{"id":2583,"date":"2016-04-13T18:22:37","date_gmt":"2016-04-13T12:52:37","guid":{"rendered":"https:\/\/www.inogic.com\/blog\/?p=2583"},"modified":"2021-12-06T15:00:15","modified_gmt":"2021-12-06T09:30:15","slug":"set-values-of-all-data-types-using-web-api-in-dynamics-crm-through-c","status":"publish","type":"post","link":"https:\/\/www.inogic.com\/blog\/2016\/04\/set-values-of-all-data-types-using-web-api-in-dynamics-crm-through-c\/","title":{"rendered":"Set Values of all Data Types using Web API in Dynamics CRM Through C#"},"content":{"rendered":"<p><strong>Introduction:<\/strong><\/p>\n<p>With the release of Microsoft Dynamics CRM 2016, Web API which was introduced offers a development experience across many devices, languages and platforms.<\/p>\n<p>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.<\/p>\n<p>You may refer this <a href=\"https:\/\/www.inogic.com\/blog\/2016\/03\/programming-using-webapi-through-c-in-dynamics-crm-2016\/\" target=\"_blank\" rel=\"noopener noreferrer\">blog<\/a> for connecting the CRM through the Web API.<\/p>\n<p><strong>Sample code to create an Account Entity Record with all Data Types:<\/strong><\/p>\n<p><strong>\/\/Initialize the WebAPIHandler class on Load of the Form as seen below:<\/strong><\/p>\n<pre class=\"lang:default decode:true \">\/\/Global Variable of Class WebApiHandler\r\nWebApiHandler _webAPIHandler=null;\r\n\/\/Method which Waits for all of the provided Task objects(i.e. Start Method in our case) to complete execution\r\nprivate void CRUD_Load(object sender, EventArgs e)\r\n{         \r\n  Task.WaitAll(Task.Run(async () =&gt; await Start()));\r\n}\r\n\r\nprivate async Task Start()\r\n{\r\n  \/\/Initialize the WebAPIHandler class\r\n webAPIHandler    = new WebApiHandler();\r\n}\r\n\r\n\/\/Button click code which creates the Account record.\r\nprivate void btnCreate_Click(object sender, EventArgs e)\r\n{\r\n            string recordId = string.Empty;\r\n\r\n            \/\/A Json Object used to create account record\r\n            JObject account = null;\r\n\r\n            \/\/Request Uri to store the accounts path \r\n            string requestUri = \"api\/data\/v8.0\/accounts\";\r\n\r\n            try\r\n            {\r\n                \/\/Get the Account Object\r\n                account = CreateAccountRecordObject();\r\n\r\n                \/\/WebAPI Handler method call to Create Record\r\n                recordId = _webAPIHandler.CreateRecord(account, requestUri);         \r\n     }\r\n            catch (Exception err)\r\n            {\r\n\r\n                throw new Exception(err.Message);\r\n            }\r\n\r\n        }\r\n\r\n    \t \/\/\/ &lt;summary&gt;\r\n        \/\/\/ Create Account Record Object\r\n        \/\/\/ &lt;\/summary&gt;\r\n        \/\/\/ &lt;returns&gt;&lt;\/returns&gt;\r\n        private JObject CreateAccountRecordObject()\r\n        {\r\n            JObject account = null;\r\n            try\r\n            {\r\n                account = new JObject();\r\n\r\n                \/\/String Value\r\n                account[\"name\"] = \"Sid Test Co\";\/\/Account Name\r\n\r\n                \/\/Optionset\r\n                account[\"accountcategorycode\"] = \"2\"; \/\/Category : 1--&gt; Preferred Customer, 2--&gt; Standard\r\n\r\n                \/\/Two Options\r\n                account[\"donotsendmm\"] = false; \/\/Marketing Materials : 0--&gt;False\/Send, 1--&gt;True\/Do Not Send\r\n\r\n                \/\/Whole number\r\n                account[\"numberofemployees\"] = 100;\/\/Number of Employees\r\n\r\n                \/\/Custom Decimal Field\r\n                account[\"new_creditrate\"] = 2.25;\/\/Decimal Number (Custom Field) \r\n\r\n                \/\/Lookup\r\n                \/\/Setting the Primary Contact\r\n                account[\"primarycontactid@odata.bind\"] = \"\/contacts(E15C03BA-10EC-E511-80E2-C4346BAD87C8)\"; \/\/Primary Contact\r\n\r\n                \/\/setting the Transaction Currency\r\n                account[\"transactioncurrencyid@odata.bind\"] = \"\/transactioncurrencies(63D588A2-10EC-E511-80E2-C4346BAD87C8)\"; \/\/Currency\r\n\r\n                \/\/Currency\/Money Field\r\n                account[\"creditlimit\"] = 1000; \/\/Currency Limit\r\n\r\n                \/\/Custom Date Only Field\r\n                account[\"new_effectivedate\"] = DateTime.Now; \/\/Date Only (Custom Field)\r\n\r\n\r\n               \r\n            }\r\n            catch (Exception error)\r\n            {\r\n\r\n                throw new Exception(error.Message);\r\n            }\r\n            return account;\r\n        }<\/pre>\n<p><strong>Sample code to create an Activity &amp; set Activity Party:<\/strong><\/p>\n<pre class=\"lang:default decode:true \">\/\/\/ &lt;summary&gt;\r\n        \/\/\/ To Create the Phone Call Record\r\n        \/\/\/ &lt;\/summary&gt;\r\n        \/\/\/ &lt;param name=\"sender\"&gt;&lt;\/param&gt;\r\n        \/\/\/ &lt;param name=\"e\"&gt;&lt;\/param&gt;\r\n        private void btnCreatePhoneCall_Click(object sender, EventArgs e)\r\n        {\r\n            \/\/Request Uri to store the accounts path \r\n            string requestUri = \"api\/data\/v8.0\/phonecalls\";\r\n            string recordId = string.Empty;\r\n            try\r\n            {\r\n                \/\/Create Phone Call Object\r\n                JObject phoneCall = CreatePhoneCall();\r\n                \/\/WebAPI Handler method call to Create Record\r\n                recordId = _webAPIHandler.CreateRecord(phoneCall,requestUri);\r\n            }\r\n            catch (Exception error)\r\n            {\r\n\r\n                throw new Exception(error.Message);\r\n            }\r\n\r\n        }\r\n\r\n\r\n        \/\/\/ &lt;summary&gt;\r\n        \/\/\/ Create PhoneCall Object\r\n        \/\/\/ &lt;\/summary&gt;\r\n        \/\/\/ &lt;returns&gt;&lt;\/returns&gt;\r\n        private JObject CreatePhoneCall()\r\n        {\r\n            \/\/create activity party collection\r\n            JArray parties = new JArray();\r\n\r\n            \/\/create JSON object \r\n            JObject jsonPhoneCall = new JObject();\r\n\r\n\r\n            try\r\n            {\r\n                \/\/set fields using JSON object\r\n                \/\/Single line of text\r\n                jsonPhoneCall[\"subject\"] = \"Test Phone Call\" + DateTime.Now.ToShortDateString(); \/\/Subject\r\n\r\n                \/\/Single line of text &amp; format of phone \r\n                jsonPhoneCall[\"phonenumber\"] = \"4565898756\"; \/\/Phone Number\r\n\r\n                \/\/Multiple Line of Text\r\n                jsonPhoneCall[\"description\"] = \"Phone Call Activity for Testing Purpose only...!\"; \/\/Description\r\n\r\n                \/\/Date and Time\r\n                jsonPhoneCall[\"scheduledend\"] = DateTime.Now; \/\/Due\r\n\r\n                \/\/Lookup\r\n                jsonPhoneCall[\"regardingobjectid_account@odata.bind\"] = \"\/accounts(4B47AA19-88F3-E511-80E6-C4346BACF5C0)\"; \/\/Regarding is an account\r\n\r\n                \/\/ActivityParty (From)\r\n                JObject sender = new JObject();\r\n                sender[\"partyid_systemuser@odata.bind\"] = \"\/systemusers(2e68e212-c82d-4bc6-9493-fbd80204a763)\";\r\n                sender[\"participationtypemask\"] = 1; \/\/From\r\n\r\n                \/\/ActivityParty (To)\r\n                JObject receiver1 = new JObject();\r\n                receiver1[\"partyid_account@odata.bind\"] = \"\/accounts(4B47AA19-88F3-E511-80E6-C4346BACF5C0)\";\r\n                receiver1[\"participationtypemask\"] = 2; \/\/To\r\n                 JObject receiver2 = new JObject();\r\n                receiver2[\"partyid_systemuser@odata.bind\"] = \"\/systemusers(2e68e212-c82d-4bc6-9493-fbd80204a763)\";\r\n                receiver2[\"participationtypemask\"] = 2; \/\/From\r\n\r\n\r\n                \/\/Add this to collection\r\n                parties.Add(sender);\r\n                parties.Add(receiver1);\r\n                parties.Add(receiver2);\r\n\r\n\r\n                \/\/pass parties[] to phonecall_activity_parties\r\n                jsonPhoneCall[\"phonecall_activity_parties\"] = parties;\r\n\r\n                \/\/Whole Number\r\n                jsonPhoneCall[\"actualdurationminutes\"] = 25; \/\/Duration\r\n\r\n                \/\/Two Options\r\n                jsonPhoneCall[\"directioncode\"] = true;\/\/Direction : 0--&gt;False\/Incoming, 1--&gt;True\/Outgoing \r\n            }\r\n            catch (Exception error)\r\n            {                \r\n                throw new Exception(error.Message);\r\n            }\r\n\r\n            return jsonPhoneCall;<\/pre>\n<p>The __webAPIHandler.CreateRecord() method is in WebApiHandler<strong> class.<\/strong><\/p>\n<p><strong>It is as below:<\/strong><\/p>\n<pre class=\"lang:default decode:true \">   \/\/\/ &lt;summary&gt;\r\n   \/\/\/ Method to Return the record ID after creating it in CRM\r\n   \/\/\/ &lt;\/summary&gt;\r\n   \/\/\/ &lt;param name=\"record\"&gt;&lt;\/param&gt;\r\n        \/\/\/ &lt;param name=\"requestUrl\"&gt;&lt;\/param&gt;\r\n        \/\/\/ &lt;returns&gt;&lt;\/returns&gt;\r\n        public string CreateRecord(JObject record, string requestUrl)\r\n        {\r\n            string recordId = string.Empty;\r\n            try\r\n            {\r\n                \/\/Create HttpClient object to send and receive Http Requests and Response\r\n                using (HttpClient httpClient = GetHttpClientObject())\r\n                {\r\n                    \/\/Http Request needed to be sent by the HttpClient\r\n                    HttpRequestMessage requestMessage = GetHttpRequestMessage(HttpMethod.Post, requestUrl, record);\r\n\r\n                    \/\/Send the HttpRequest\r\n                    Task&lt;HttpResponseMessage&gt; response = httpClient.SendAsync(requestMessage);\r\n\r\n                    \/\/Wait till the Response Execution is complete\r\n                    response.Wait();\r\n\r\n                    \/\/If the response is Successfully executed then it will return the value true\r\n                    if (response.Result.IsSuccessStatusCode)\r\n                    {\r\n                        _recordUrl = response.Result.Headers.GetValues(\"OData-EntityId\").FirstOrDefault();\r\n                        splitRetrievedData = _recordUrl.Split('[', '(', ')', ']');\r\n\r\n                        recordId = splitRetrievedData[1];\r\n\r\n                    }\r\n                }\r\n            }\r\n            catch (Exception error)\r\n            {\r\n\r\n                throw new Exception(error.Message);\r\n            }\r\n\r\n            return recordId;\r\n        }\r\n<\/pre>\n<p>For the methods GetHttpClientObject(),GetHttpRequestMessage you may refer this <a href=\"https:\/\/www.inogic.com\/blog\/2016\/03\/programming-using-webapi-through-c-in-dynamics-crm-2016\/\" target=\"_blank\" rel=\"noopener noreferrer\">blog<\/a>.<\/p>\n<p>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 <strong>Install-Package Newtonsoft.Json.<\/strong><\/p>\n<p><strong>Conclusion:<\/strong><\/p>\n<p>Hope the above code helps to set all the data types in Dynamics CRM.<\/p>\n<h2 style=\"text-align: left;\"><div class=\"su-heading su-heading-style-default su-heading-align-center\" id=\"\" style=\"font-size:15px;margin-bottom:5px\"><div class=\"su-heading-inner\">One Pic = 1000 words! Analyze data 90% faster with visualization apps!<\/div><\/div><\/h2>\n<p style=\"text-align: left;\"><em>Get optimum visualization of Dynamics 365 CRM data with &#8211;<\/em><br \/>\n<em><strong><a href=\"https:\/\/bit.ly\/3lYvozZ\" target=\"_blank\" rel=\"noopener noreferrer\">Kanban Board<\/a> <\/strong>\u2013 Visualize Dynamics 365 CRM data in Kanban view by categorizing entity records in lanes and rows as per their status, priority, etc.<\/em><br \/>\n<em><strong><a href=\"https:\/\/bit.ly\/3lCSBaA\" target=\"_blank\" rel=\"noopener noreferrer\">Map My Relationships<\/a><\/strong> \u2013 Map My Relationships \u2013 Visualize connections and relationships between Dynamics 365 CRM entities or related records in a Mind Map view.<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>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\u2026 <span class=\"read-more\"><a href=\"https:\/\/www.inogic.com\/blog\/2016\/04\/set-values-of-all-data-types-using-web-api-in-dynamics-crm-through-c\/\">Read More &raquo;<\/a><\/span><\/p>\n","protected":false},"author":13,"featured_media":0,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"om_disable_all_campaigns":false,"_monsterinsights_skip_tracking":false,"_monsterinsights_sitenote_active":false,"_monsterinsights_sitenote_note":"","_monsterinsights_sitenote_category":0,"footnotes":""},"categories":[15,19,65],"tags":[708,709,1821],"class_list":["post-2583","post","type-post","status-publish","format-standard","hentry","category-development","category-dynamics-crm","category-webapi","tag-dynamics-crm-web-api","tag-dynamics-crm-web-api-using-c","tag-web-api-functions-in-dynamics-crm"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/2583","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/users\/13"}],"replies":[{"embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/comments?post=2583"}],"version-history":[{"count":0,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/2583\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/media?parent=2583"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/categories?post=2583"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/tags?post=2583"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}