Introduction:
With the release of Microsoft Dynamics CRM 2016, Web API which was introduced offers a development experience across many devices, languages and platforms.
In this blog we will take a look at how to set the all the datatypes in the CRM using C# through a windows application and using Web API.
You may refer this blog for connecting the CRM through the Web API.
Sample code to create an Account Entity Record with all Data Types:
//Initialize the WebAPIHandler class on Load of the Form as seen below:
//Global Variable of Class WebApiHandler WebApiHandler _webAPIHandler=null; //Method which Waits for all of the provided Task objects(i.e. Start Method in our case) to complete execution private void CRUD_Load(object sender, EventArgs e) { Task.WaitAll(Task.Run(async () => await Start())); } private async Task Start() { //Initialize the WebAPIHandler class webAPIHandler = new WebApiHandler(); } //Button click code which creates the Account record. private void btnCreate_Click(object sender, EventArgs e) { string recordId = string.Empty; //A Json Object used to create account record JObject account = null; //Request Uri to store the accounts path string requestUri = "api/data/v8.0/accounts"; try { //Get the Account Object account = CreateAccountRecordObject(); //WebAPI Handler method call to Create Record recordId = _webAPIHandler.CreateRecord(account, requestUri); } catch (Exception err) { throw new Exception(err.Message); } } /// <summary> /// Create Account Record Object /// </summary> /// <returns></returns> private JObject CreateAccountRecordObject() { JObject account = null; try { account = new JObject(); //String Value account["name"] = "Sid Test Co";//Account Name //Optionset account["accountcategorycode"] = "2"; //Category : 1--> Preferred Customer, 2--> Standard //Two Options account["donotsendmm"] = false; //Marketing Materials : 0-->False/Send, 1-->True/Do Not Send //Whole number account["numberofemployees"] = 100;//Number of Employees //Custom Decimal Field account["new_creditrate"] = 2.25;//Decimal Number (Custom Field) //Lookup //Setting the Primary Contact account["primarycontactid@odata.bind"] = "/contacts(E15C03BA-10EC-E511-80E2-C4346BAD87C8)"; //Primary Contact //setting the Transaction Currency account["transactioncurrencyid@odata.bind"] = "/transactioncurrencies(63D588A2-10EC-E511-80E2-C4346BAD87C8)"; //Currency //Currency/Money Field account["creditlimit"] = 1000; //Currency Limit //Custom Date Only Field account["new_effectivedate"] = DateTime.Now; //Date Only (Custom Field) } catch (Exception error) { throw new Exception(error.Message); } return account; }
Sample code to create an Activity & set Activity Party:
/// <summary> /// To Create the Phone Call Record /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnCreatePhoneCall_Click(object sender, EventArgs e) { //Request Uri to store the accounts path string requestUri = "api/data/v8.0/phonecalls"; string recordId = string.Empty; try { //Create Phone Call Object JObject phoneCall = CreatePhoneCall(); //WebAPI Handler method call to Create Record recordId = _webAPIHandler.CreateRecord(phoneCall,requestUri); } catch (Exception error) { throw new Exception(error.Message); } } /// <summary> /// Create PhoneCall Object /// </summary> /// <returns></returns> private JObject CreatePhoneCall() { //create activity party collection JArray parties = new JArray(); //create JSON object JObject jsonPhoneCall = new JObject(); try { //set fields using JSON object //Single line of text jsonPhoneCall["subject"] = "Test Phone Call" + DateTime.Now.ToShortDateString(); //Subject //Single line of text & format of phone jsonPhoneCall["phonenumber"] = "4565898756"; //Phone Number //Multiple Line of Text jsonPhoneCall["description"] = "Phone Call Activity for Testing Purpose only...!"; //Description //Date and Time jsonPhoneCall["scheduledend"] = DateTime.Now; //Due //Lookup jsonPhoneCall["regardingobjectid_account@odata.bind"] = "/accounts(4B47AA19-88F3-E511-80E6-C4346BACF5C0)"; //Regarding is an account //ActivityParty (From) JObject sender = new JObject(); sender["partyid_systemuser@odata.bind"] = "/systemusers(2e68e212-c82d-4bc6-9493-fbd80204a763)"; sender["participationtypemask"] = 1; //From //ActivityParty (To) JObject receiver1 = new JObject(); receiver1["partyid_account@odata.bind"] = "/accounts(4B47AA19-88F3-E511-80E6-C4346BACF5C0)"; receiver1["participationtypemask"] = 2; //To JObject receiver2 = new JObject(); receiver2["partyid_systemuser@odata.bind"] = "/systemusers(2e68e212-c82d-4bc6-9493-fbd80204a763)"; receiver2["participationtypemask"] = 2; //From //Add this to collection parties.Add(sender); parties.Add(receiver1); parties.Add(receiver2); //pass parties[] to phonecall_activity_parties jsonPhoneCall["phonecall_activity_parties"] = parties; //Whole Number jsonPhoneCall["actualdurationminutes"] = 25; //Duration //Two Options jsonPhoneCall["directioncode"] = true;//Direction : 0-->False/Incoming, 1-->True/Outgoing } catch (Exception error) { throw new Exception(error.Message); } return jsonPhoneCall;
The __webAPIHandler.CreateRecord() method is in WebApiHandler class.
It is as below:
/// <summary> /// Method to Return the record ID after creating it in CRM /// </summary> /// <param name="record"></param> /// <param name="requestUrl"></param> /// <returns></returns> public string CreateRecord(JObject record, string requestUrl) { string recordId = string.Empty; try { //Create HttpClient object to send and receive Http Requests and Response using (HttpClient httpClient = GetHttpClientObject()) { //Http Request needed to be sent by the HttpClient HttpRequestMessage requestMessage = GetHttpRequestMessage(HttpMethod.Post, requestUrl, record); //Send the HttpRequest Task<HttpResponseMessage> response = httpClient.SendAsync(requestMessage); //Wait till the Response Execution is complete response.Wait(); //If the response is Successfully executed then it will return the value true if (response.Result.IsSuccessStatusCode) { _recordUrl = response.Result.Headers.GetValues("OData-EntityId").FirstOrDefault(); splitRetrievedData = _recordUrl.Split('[', '(', ')', ']'); recordId = splitRetrievedData[1]; } } } catch (Exception error) { throw new Exception(error.Message); } return recordId; }
For the methods GetHttpClientObject(),GetHttpRequestMessage you may refer this blog.
To get the JObject, JArray i.e Json Objects you need to add reference to the Newtonsoft.Json.You may add it through Nuget using this command Install-Package Newtonsoft.Json.
Conclusion:
Hope the above code helps to set all the data types in Dynamics CRM.
One Pic = 1000 words! Analyze data 90% faster with visualization apps!
Get optimum visualization of Dynamics 365 CRM data with –
Kanban Board – Visualize Dynamics 365 CRM data in Kanban view by categorizing entity records in lanes and rows as per their status, priority, etc.
Map My Relationships – Map My Relationships – Visualize connections and relationships between Dynamics 365 CRM entities or related records in a Mind Map view.