How to call dynamic crm 2016 rest api from javascript? - dynamics-crm

I want to create lead in dynamic crm from my website. My website is build using HTML as this is a static site. I need to call dynamic crm (setup on premises) api from contact us page to submit data in dynamic crm.
Please suggest me a right direction.
Thanks

The SDK has lots of helpful information, have you looked at it? Here's a start:
Authenticating to CRM from JS using adal.js
Perform operations using the Web API

This is a sample code we use to submit entries from webpage to CRM. Hope this helps:
function CreateWebLeadInCRM(SourceCampaignName, Email, MobilePhone, FirstName, LastName, CompanyName){
var webLead = new Object();
//Add Source Campaing name
if(SourceCampaignName != null)
webLead.sof_sourcecampaign = SourceCampaignName;
//Add Email
if(Email != null)
webLead.sof_Email = Email;
//Add Mobile phone
if(MobilePhone != null)
webLead.sof_MobilePhone = MobilePhone;
//Add First name
if(FirstName != null)
webLead.sof_FirstName = FirstName;
//Add Last name
if(LastName != null)
webLead.sof_LastName = LastName;
//Add Company name
if(CompanyName != null)
webLead.sof_CompanyName = CompanyName;
var jsonwebLead = JSON.stringify(webLead);
var createwebLeadReq = new XMLHttpRequest();
createwebLeadReq.open("POST", "http://SERVER/ORG/XRMServices/2011/OrganizationData.svc/sof_webleadSet", true, "USERNAME", "PASSWORD");
createwebLeadReq.setRequestHeader("Accept", "application/json");
createwebLeadReq.setRequestHeader("Content-Type", "application/json; charset=utf-8");
createwebLeadReq.onreadystatechange = function () {
createwebLeadReqCallBack(this);
};
createwebLeadReq.send(jsonwebLead);
Ugly thing about this approach is that you have to save your password inside your javascript function, which is not really safe approach.. On the other hand you should only allow this user to insert entries to only one custom table without possibility to do anything else inside your CRM. This way you could manage what happens if you get spammed by the bots.

Related

Automatically map a Contact to an Account

I want to add a field to Accounts which shows the email domain for that account e.g. #BT.com. I then have a spreadsheet which lists all the Accounts and their email domains. What I want to do is when a new Contact is added to Dynamics that it checks the spreadsheet for the same email domain (obviously without the contacts name in the email) and then assigned the Contact to the Account linked to that domain. Any idea how I would do this. Thanks
Probably best chance would be to develop CRM plugin. Register your plugin to be invoked when on after contact is created or updated (so called post-event phase). And in your plugin update the parentaccountid property of the contact entity to point to account of your choice.
Code-wise it goes something like (disclaimer: not tested):
// IPluginExecutionContext context = null;
// IOrganizationService organizationService = null;
var contact = (Entity)context.InputParameters["Target"];
var email = organizationService.Retrieve("contact", contact.Id, new ColumnSet("emailaddress1")).GetAttributeValue<string>("emailaddress1");
string host;
try
{
var address = new MailAddress(email);
host = address.Host;
}
catch
{
return;
}
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
contact["parentaccountid"] = entities[0].ToEntityReference();
}
organizationService.Update(contact);
I took Ondrej's code and cleaned it up a bit, re-factored for pre-operation. I also updated the logic to only match active account records and moved the query inside the try/catch. I am unfamiliar with the MailAddress object, I personally would just use string mapping logic.
var target = (Entity)context.InputParameters["Target"];
try
{
string host = new MailAddress(target.emailaddress1).Host;
var query = new QueryExpression("account");
query.TopCount = 1;
// or whatever the name of email domain field on account is
query.Criteria.AddCondition("emailaddress1", ConditionOperator.Contains, "#" + host);
query.Criteria.AddCondition("statecode", ConditionOperator.Equals, 0); //Active records only
var entities = organizationService.RetrieveMultiple(query).Entities;
if (entities.Count != 0)
{
target["parentaccountid"] = entities[0].ToEntityReference();
}
}
catch
{
//Log error
}

How to get client's contact details in lync sdk c#

Which Object has the client contact information like office,company,IM, etc,. in Lync SDK 2013? I want to know the user's(client's) location/address information.
User location/office information can be obtained from contact object as given below:
LyncClient lyncClient = LyncClient.GetClient();
Contact contact = lyncClient.ContactManager.GetContactByUri("sip:contact#organization.com");
String officeLocation = contact.GetContactInformation(ContactInformationType.Office).ToString();
More information can be obtained using Contact information types Personal Note, Company, Location, Department etc.
In addition to Kannan's answer, getting the phone numbers from a contact is different and requires more work. Here's how you do it:
LyncClient lyncClient = LyncClient.GetClient();
Contact contact = lyncClient.ContactManager.GetContactByUri("sip:contact#organization.com");
List<object> endPoints = new List<object>();
var telephoneNumber = (List<object>)contact.GetContactInformation(ContactInformationType.ContactEndpoints);
endPoints = telephoneNumber.Where<object>(N => ((ContactEndpoint)N).Type == ContactEndpointType.HomePhone || ((ContactEndpoint)N).Type == ContactEndpointType.MobilePhone || ((ContactEndpoint)N).Type == ContactEndpointType.OtherPhone || ((ContactEndpoint)N).Type == ContactEndpointType.WorkPhone).ToList<object>();
foreach (var endPoint in endPoints)
{
//((ContactEndpoint)endPoint).DisplayName.ToString(); //This is the phone number in string format
}

(Windows Phone 10) Is possible to edit, add new contact programmatically in windows phone 10?

I want to implement function edit and add contact programatically in windows phone 10.
Is it possible? Has any sample about it ?
Here is a code snippet for creating the contact:
public async Task AddContact(String FirstName, String LastName)
{
var contact = new Windows.ApplicationModel.Contacts.Contact();
contact.FirstName = FirstName;
contact.LastName = LastName;
//Here you can set other properties...
//Get he contact store for the app (so no lists from outlook and other stuff will be in the returned lists..)
var contactstore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);
try
{
var contactLists = await contactstore.FindContactListsAsync();
Windows.ApplicationModel.Contacts.ContactList contactList;
//if there is no contact list we create one
if (contactLists.Count == 0)
{
contactList = await contactstore.CreateContactListAsync("MyList");
}
//otherwise if there is one then we reuse it
else
{
contactList = contactLists.FirstOrDefault();
}
await contactList.SaveContactAsync(contact);
}
catch
{
//Handle it properly...
}
}
And here is a short sample for changing an existing contact:
//you can obviusly couple the changes better then this... this is just to show the basics
public async Task ChangeContact(Windows.ApplicationModel.Contacts.Contact ContactToChange, String NewFirstName, String NewLastName)
{
var contactStore = await Windows.ApplicationModel.Contacts.ContactManager.RequestStoreAsync(Windows.ApplicationModel.Contacts.ContactStoreAccessType.AppContactsReadWrite);
var contactList = await contactStore.GetContactListAsync(ContactToChange.ContactListId);
var contact = await contactList.GetContactAsync(ContactToChange.Id);
contact.FirstName = NewFirstName;
contact.LastName = NewLastName;
await contactList.SaveContactAsync(contact);
}
And very important:
In the appxmanifest you have to add the contacts capability. Right click to it in the solution explorer and "View Code" and then under Capabilities put
<uap:Capability Name="contacts" />
There is no UI for this. See this.
Both samples are meant to be for starting point... obviously it's not production ready and you have to adapt it to your scenario.
Update
Since this came up in the comments I extend my answer a little bit.
Based on this (plus my own experimentation) the ContactListId for aggregated contacts is null (which makes sense if you think about it). Here is how to get the raw contact with ContactlLstId (code is based on the comment from the link)
public async Task IterateThroughContactsForContactListId()
{
ContactStore allAccessStore = await ContactManager.RequestStoreAsync(ContactStoreAccessType.AllContactsReadOnly);
var contacts = await allAccessStore.FindContactsAsync();
foreach (var contact in contacts)
{
//process aggregated contacts
if (contact.IsAggregate)
{
//here contact.ContactListId is "" (null....)
//in this case if you need the the ContactListId then you need to iterate through the raw contacts
var rawContacts = await allAccessStore.AggregateContactManager.FindRawContactsAsync(contact);
foreach (var rawContact in rawContacts)
{
//Here you should have ContactListId
Debug.WriteLine($"aggregated, name: {rawContact.DisplayName }, ContactListId: {rawContact.ContactListId}");
}
}
else //not aggregated contacts should work
{
Debug.WriteLine($"not aggregated, name: {contact.DisplayName }, ContactListId: {contact.ContactListId}");
}
}
}
And another important thing:
According to the documentation you won’t be able to change all the contacts which are created by other apps.
AllContactsReadWrite:
Read and write access to all app and system contacts. This value is
not available to all apps. Your developer account must be specially
provisioned by Microsoft in order to request this level of access.
In some cases, I get a System.UnauthorizedAccessException when SaveContactAsync(contact) is called. One example for this was when the contact was in the Skype Contact List.

unable to parse the xml query using Linq

I am developing a sample Twitter app for Windows phone 7. In my code to display some details of user, used the following code.
void ShowProfile()
{
WebClient client = new WebClient();
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(Profile_DownloadCompleted);
client.DownloadStringAsync(new Uri("http://api.twitter.com/1/users/show.xml?user_id=" + this.id));
}
void Profile_DownloadCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error != null)
{ return; }
if (e.Result == null) MessageBox.Show("NUlllllllllll");
XElement Profile = XElement.Parse(e.Result);
var ProfileDetails = (from profile in Profile.Descendants("user")
select new UserProfile
{
UserName = profile.Element("screen_name").Value,
ImageSource = profile.Element("profile_image_url").Value,
Location = profile.Element("location").Value,
TweetsCount = profile.Element("statuses_count").Value,
}).FirstOrDefault();
LayoutRoot.DataContext = ProfileDetails;
}
Here, LayoutRoot is the Grid name. But the data binding doesn't work.
Infact, when kept a Break point it seems there is no data in the ProfileDetails object. But I could observe that e.Result contains the required data in the XML format.
Can any body figureout where I am going wrong??
Thanks in advance.
You have used XElement.Parse so Profile represents the single root <user> that API request would have returned. You are then trying to look for user elements inside it which of course makes no sense.
Try XDocument.Parse instead. Also does it really make any sense assigning a IEnumerable<UserProfile> to the data context when that list can only ever contain 1 entry?

Invoke Webservice with yield return on windows phone

i'm developing a Windows Phone 7 app and I use Windows Live authentication to access the user contacts. I have a webservice, with the following method:
public IEnumerable<LiveIDContact> GetContactsInformationYield(string LocationID, string DelegationToken)
{
string uriTemplate = "https://livecontacts.services.live.com/#L#{0}/rest/LiveContacts/Contacts";
var xdoc = WindowsLiveContactAPIRequest(LocationID, DelegationToken, uriTemplate);
var contacts = (from contact in xdoc.Descendants("Contact")
select contact).ToArray();
foreach (var con in contacts)
{
RetrieveCID(LocationID, DelegationToken, con);
LiveIDContact c = new LiveIDContact()
{
ID = con.Element("ID").Value,
DisplayName = con.Element("Profiles").Element("Personal").Element("DisplayName").Value,
CID = (con.Element("CID") != null ? con.Element("CID").Value : "")
};
yield return c;
}
}
How i invoke the methode in the app:
public void GetContactInformationAsync()
{
LiveIDClient.GetContactsInformationYieldAsync(LocationID, ConsentToken);
}
Here is the problem, when I invoke this methode and i wait on the complete event. It takes 4 to 5 minutes to update the list of contacts in my app.(Performance issue). Is there any way that an event occurs on every yield return ? So i can update my list from that event?
I couldn't find the answer anywhere so lets hope somebody knows the answer.
Is this making a separate HTTP call for every single contact? If so, then I think you simply need to redesign the webservice so that it makes a call for, say, every hundred contacts.

Resources