{"id":2552,"date":"2016-03-31T18:23:08","date_gmt":"2016-03-31T12:53:08","guid":{"rendered":"https:\/\/www.inogic.com\/blog\/?p=2552"},"modified":"2021-12-15T16:07:35","modified_gmt":"2021-12-15T10:37:35","slug":"programming-using-webapi-through-c-in-dynamics-crm-2016","status":"publish","type":"post","link":"https:\/\/www.inogic.com\/blog\/2016\/03\/programming-using-webapi-through-c-in-dynamics-crm-2016\/","title":{"rendered":"Programming using WebAPI through C# in Dynamics CRM 2016"},"content":{"rendered":"<h2><strong>Introduction:<\/strong><\/h2>\n<p>Stepping towards the enhancement, Dynamics CRM 2016 introduced <strong>\u2018Web API\u2019<\/strong> as the new concept which delivers a unique development experience across a wide variety of programming languages, devices, and platforms.<\/p>\n<p>We have earlier explored using WEB API through scripting from within Dynamics CRM environment in this <a href=\"https:\/\/www.inogic.com\/blog\/2016\/02\/set-values-of-all-data-types-using-web-api-in-dynamics-crm\/\" target=\"_blank\" rel=\"noopener noreferrer\">blog<\/a>.<\/p>\n<p>We noticed quite a few queries coming up in forums about using WEB API through C# in code executed outside of CRM like a portal or other integration apps.<\/p>\n<h2><strong>What is the difference?<\/strong><\/h2>\n<p>The key difference lies in authentication. When we use scripts and execute from within Dynamics CRM using web resources, the authentication is automatically passed and we do not have to supply the authentication token header there.<\/p>\n<p>But when we are connecting from outside of CRM context, it is important to authenticate the access credentials before they can connect and perform actions in Dynamics CRM.<\/p>\n<blockquote><p><strong><em>Note: Some part of the code provided below has been taken from the Authentication library supplied in the SDK and that was the starting point for us to understand and get this working. We were however not able to get the code to execute as is and we try to explain the issues and resolutions to those through this blog.<\/em><\/strong><\/p><\/blockquote>\n<h2><strong>Connecting using C# from a windows forms application<\/strong><\/h2>\n<p>Here again, the method to pass authentication token varies depending on whether it is CRM On-Premises or CRM Online or IFD enabled deployment of Microsoft Dynamics CRM 2016.<\/p>\n<p>When using windows forms, we realized that it was important to initiate the code as an async task to establish connection. If you do not initiate an async task, the code block to authenticate fails since that action is async.<\/p>\n<p>So first in the form load, we initiate the Start() asynchronously.<\/p>\n<pre class=\"lang:default decode:true \">private void CRUD_Load(object sender, EventArgs e)\r\n{ \r\n   Task.WaitAll(Task.Run(async () =&gt; await Start()));\r\n}<\/pre>\n<h3><strong>On-Premises Deployment<\/strong><\/h3>\n<p>The following details are set in the config file for On-Premises connection<\/p>\n<pre class=\"lang:default decode:true\">  &lt;appSettings&gt;\r\n    &lt;!-- FOR CRM OnPremise--&gt;\r\n    &lt;add key=\"EndPointType\" value=\"OnPremise\"\/&gt;\r\n    &lt;add key=\"Username\" value=\"username\"\/&gt;\r\n    &lt;add key=\"Password\" value=\"password\"\/&gt;\r\n    &lt;add key=\"Domain\" value=\"domainname\"\/&gt;\r\n    &lt;add key=\"ServerAddress\" value=\"http:\/\/ad10:5555\/Testing2016\/\"\/&gt;\r\n    &lt;!--CRM ONPremise End--&gt;\r\n  &lt;\/appSettings&gt;\r\n<\/pre>\n<p>You need to execute your WEB API requests through the HttpClient object. When creating the object of HttpClient, pass the credentials along as shown in the code block below;<\/p>\n<pre class=\"lang:default decode:true\">HttpClient httpClient = (new HttpClientHandler() { Credentials = new NetworkCredential(_userName, _passWord, _domain) });\r\n\/\/Base url of the CRM For e.g. http:\/\/servername:port\/orgname\r\nhttpClient.BaseAddress = new Uri(_serviceUri);\r\n<\/pre>\n<p>Suppose you want to create a record in CRM then we need to create an HttpRequestMessage which needs to be sent.<\/p>\n<p>\/\/Http Request needed to be sent by the HttpClient<br \/>\nHttpRequestMessage request = null;<br \/>\ntry<br \/>\n{<br \/>\nrequest = new HttpRequestMessage(HttpMethod.Post, \u201capi\/data\/v8.0\/accounts\u201d); \/\/uri to accounts<br \/>\nrequest.Content = new StringContent(content.ToString()); \/\/JObject of the data to be posted.<br \/>\nrequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse(\u201capplication\/json\u201d);<\/p>\n<p>\/\/Send the HttpRequest<\/p>\n<p>Task&lt;HttpResponseMessage&gt; response = httpClient.SendAsync(requestMessage);<\/p>\n<p>\/\/Wait till the Response Execution is complete<br \/>\nresponse.Wait();<\/p>\n<p>\/\/If the response is Successfully executed then it will return the value true<br \/>\nif (response.Result.IsSuccessStatusCode)<br \/>\n{<br \/>\n}<br \/>\n}<br \/>\ncatch (Exception err)<br \/>\n{<br \/>\nthrow new Exception(err.Message);<br \/>\n}<\/p>\n<h3><strong>CRM Online<\/strong><\/h3>\n<p>The key to establishing connection in CRM Online, is getting the authentication context and acquiring the token<\/p>\n<pre class=\"lang:default decode:true\">        AuthenticationResult result = null;\r\n        AuthenticationContext authContext;\r\n<\/pre>\n<p>In CRM Online, the OAuth authentication is performed through the Azure Active Directory. With OAuth the user is presented with the login page to type in the credentials manually, once the user is successfully authenticated, the control is redirected to the application that had invoked the authentication.<\/p>\n<p>The following details are set in the config file for CRM Online connection<\/p>\n<pre class=\"lang:default decode:true \">    &lt;!-- FOR CRM Online--&gt;\r\n    &lt;add key=\"EndPointType\" value=\"OnlineFederation\"\/&gt;\r\n    &lt;add key=\"Username\" value=\"username@myorg.onmicrosoft.com\"\/&gt;\r\n    &lt;add key=\"Password\" value=\"password\"\/&gt;\r\n    &lt;add key=\"ServerAddress\" value=\"https:\/\/myorg.crm.dynamics.com\"\/&gt;\r\n    &lt;add key=\"RedirectUrl\" value=\"http:\/\/localhost\/CrmWebApi\"\/&gt;\r\n    &lt;add key=\"ClientId\" value=\"3b12fde5-d0c1-4bed-b1c2-73b0f336d777\"\/&gt; \r\n    &lt;!--CRM Online End--&gt;\r\n<\/pre>\n<p>You need to pass the authority to the AuthContext<\/p>\n<pre class=\"lang:default decode:true \">private void DiscoverAuthority(String serviceUri)\r\n {\r\n            try\r\n            {\r\n                \/\/Authentication parameters received from Resource Server\r\n                AuthenticationParameters ap = AuthenticationParameters.CreateFromResourceUrlAsync(new Uri(serviceUri + \"\/api\/data\/\")).Result;\r\n\r\n                if (!String.IsNullOrEmpty(ap.Resource))\r\n                {\r\n                    _serviceUri = ap.Resource;\r\n                }\r\n                _authority = ap.Authority;\r\n            }\r\n            catch (HttpRequestException e)\r\n            {\r\n                throw new Exception(\"An HTTP request exception occurred during authority discovery.\", e);\r\n            }\r\n        }<\/pre>\n<p>#region If you want to get the Authenticationresult at runtime by manually entering the username &amp; password<\/p>\n<pre class=\"lang:default decode:true \">\/\/ Authenticate the registered application with Azure Active Directory.\r\nauthContext = new AuthenticationContext(Authority, false);\r\n\r\n\/\/Result to get the AccessToken\r\nresult = authContext.AcquireToken(_serviceUri, _clientId, new Uri(_redirectUrl)); \r\n#endregion\r\n<\/pre>\n<p>If you see in the above code, we pass the<\/p>\n<p>_serviceUri &#8211; CRM Online URL,<\/p>\n<p>_clientId &#8211; the client id that is generated for your app when you register it in Azure.<\/p>\n<p>_redirectUrl \u2013 The URL that the control should be redirected to once the user is successfully authenticated<\/p>\n<p>We can also pass the credentials of a valid CRM user if we do not want the login prompt to show up.<\/p>\n<pre class=\"lang:default decode:true\">#region Code to pass the Username &amp; Password through Appconfig\r\n\/\/\/\/ Authenticate the registered application with Azure Active Directory.\r\nauthContext = new AuthenticationContext(Authority, false);\r\n\r\n\/\/User Credentials from the AppConfig\r\nUserCredential cred = new UserCredential(_userName, _passWord);\r\n\r\n\/\/\/\/Result to get the AccessToken\r\nresult = authContext.AcquireToken(_serviceUri, _clientId, cred);\r\n#endregion\r\n<\/pre>\n<p>Once you have the Authentication Result, you can prepare the <strong>HttpClient<\/strong> as below:<\/p>\n<pre class=\"lang:default decode:true \">HttpClient httpClient= null;\r\nhttpClient = new HttpClient();\r\n \/\/Default Request Headers needed to be added in the HttpClient Object\r\nhttpClient.DefaultRequestHeaders.Add(\"OData-MaxVersion\", \"4.0\");\r\nhttpClient.DefaultRequestHeaders.Add(\"OData-Version\", \"4.0\");\r\nhttpClient.DefaultRequestHeaders.Accept.Add(new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue(\"application\/json\"));\r\n\r\n \/\/Set the Authorization header with the Access Token received specifying the Credentials\r\n httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue(\"Bearer\", _result.AccessToken);\r\n<\/pre>\n<h2><strong>Steps for registering the App in Azure to get the ClientID:<\/strong><\/h2>\n<p>For Online CRM deployment models, it seems to be a tricky process as we need to use OAuth to authenticate the user to Azure Active Directory and hence we need to register the App on Azure to get the ClientId &amp; Redirect URL which will be used for Azure authentication.<\/p>\n<h2><strong>Steps for registering the App in Azure:<\/strong><\/h2>\n<p>If you have a trial online CRM then you also need to have an Azure subscription. You may get the trial account for Azure using the credentials for Office 365 by signing up from this <a href=\"https:\/\/azure.microsoft.com\/en-in\/pricing\/free-trial\/\" target=\"_blank\" rel=\"noopener noreferrer\">link<\/a>. \u00a0Make sure to sign up in the same tenant.<\/p>\n<p>After you have signed up for Azure go to the Azure portal i.e. <a href=\"https:\/\/portal.azure.com\/\" target=\"_blank\" rel=\"noopener noreferrer\">https:\/\/portal.azure.com\/<\/a> and navigate to <strong>\u2018Browse\u2019<\/strong> and click <strong>\u2018Active Directory\u2019<\/strong>. You are then directed to the page as shown in the screenshot below.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2561\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api.png\" alt=\"Web API through C#\" width=\"530\" height=\"304\" \/><\/a><\/p>\n<p>From the left-hand side after selecting <strong>\u2018ACTIVE DIRECTORY\u2019, <\/strong>you are able to find the Active Directory which is created for the Organization. Click and open the active directory.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-through-c.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2559\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-through-c.png\" alt=\"web api through c#\" width=\"503\" height=\"325\" \/><\/a><\/p>\n<p>At the bottom click <strong>\u2018ADD\u2019<\/strong> to add the application. A pop up would then get displayed on the screen.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/connecting-crm-to-web-api.png\"><img decoding=\"async\" class=\"aligncenter wp-image-2555 size-full\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/connecting-crm-to-web-api.png\" alt=\"connecting crm to web api\" width=\"437\" height=\"212\" \/><\/a><\/p>\n<p>Give a name for the App and select <strong>\u2018NATIVE CLIENT APPLICATION<\/strong>\u2019 and proceed to the next step.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-throgh-c-in-crm.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2558\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-throgh-c-in-crm.png\" alt=\"web api throgh c# in crm\" width=\"431\" height=\"267\" \/><\/a><\/p>\n<p>You then need to specify the <strong>Redirect Url<\/strong> which can be used in the Code later as above.<\/p>\n<p>Your App as seen in the screenshot below is now ready.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/configure-web-api.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2554\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/configure-web-api.png\" alt=\"configure web api\" width=\"486\" height=\"209\" \/><\/a><\/p>\n<p>Next, click <strong>\u2018CONFIGURE ACCESS TO WEB APIS IN OTHER APPLICATIONS\u2019<\/strong> followed <strong>by \u2018Configure it Now<\/strong>\u2019<\/p>\n<p>You will then get directed to the screen as shown below:<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/configure-web-api-in-crm.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2553\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/configure-web-api-in-crm.png\" alt=\"configure web api in crm\" width=\"477\" height=\"211\" \/><\/a><\/p>\n<p>Here you can see the Client ID and Redirect URL which needs to be used in the code further.<\/p>\n<p>As you scroll down, you can view the web page as shown below.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-using-c.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2560\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-using-c.png\" alt=\"web api using c#\" width=\"466\" height=\"109\" \/><\/a><\/p>\n<p>After clicking <strong>\u2018Add application\u2019<\/strong> you would be directed to a screen which displays the list of Microsoft Apps.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-in-Dynamics-CRM-through-C.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2557\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/web-api-in-Dynamics-CRM-through-C.png\" alt=\"web api in Dynamics CRM through C#\" width=\"488\" height=\"303\" \/><\/a><\/p>\n<p>Select the <strong>Dynamics CRM Online<\/strong> option and add it. Next, the screenshot as below lets you provide the access to the user you wish.<a href=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/Web-API-C.png\"><img decoding=\"async\" class=\"aligncenter size-full wp-image-2556\" src=\"https:\/\/www.inogic.com\/blog\/wp-content\/uploads\/2016\/03\/Web-API-C.png\" alt=\"Web API - C#\" width=\"492\" height=\"254\" \/><\/a><\/p>\n<h2><strong>Conclusion:<\/strong><\/h2>\n<p>Hope the above code snippets along with the logic helps you to perform various operations through the Web API using C#. We have referred to the <a href=\"https:\/\/code.msdn.microsoft.com\/Basic-Operations-with-web-67fc1d8f\" target=\"_blank\" rel=\"noopener noreferrer\">blog<\/a> posted under Microsoft\u2019s Developer Network for creating our WebApiHandler class.<\/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\">Cut short 90% of your manual work and repetitive data entry!<\/div><\/div><\/h2>\n<p style=\"text-align: left;\"><em>Get 1 Click apps and say goodbye to all repetitive data entry in CRM &#8211;<\/em><br \/>\n<em><strong><a href=\"https:\/\/bit.ly\/3oH7dYw\" target=\"_blank\" rel=\"noopener noreferrer\">Click2Clone<\/a> <\/strong>\u2013 Clone\/Copy Dynamics 365 CRM records in 1 Click<\/em><br \/>\n<em><strong><a href=\"https:\/\/bit.ly\/3EPjAYc\" target=\"_blank\" rel=\"noopener noreferrer\">Click2Export<\/a><\/strong> \u2013 Export Dynamics 365 CRM Report\/CRM Views\/Word\/Excel template in 1 Click<\/em><br \/>\n<em><strong><a href=\"https:\/\/bit.ly\/3EN8h2v\" target=\"_blank\" rel=\"noopener noreferrer\">Click2Undo<\/a><\/strong> \u2013 Undo &amp; Restore Dynamics 365 CRM data in 1 Click<\/em><\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction: Stepping towards the enhancement, Dynamics CRM 2016 introduced \u2018Web API\u2019 as the new concept which delivers a unique development experience across a wide variety of programming languages, devices, and platforms. We have earlier explored using WEB API through scripting from within Dynamics CRM environment in this blog. We noticed quite a few queries coming\u2026 <span class=\"read-more\"><a href=\"https:\/\/www.inogic.com\/blog\/2016\/03\/programming-using-webapi-through-c-in-dynamics-crm-2016\/\">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":[16,24,25,65],"tags":[178,663,709,1145,1822,1825],"class_list":["post-2552","post","type-post","status-publish","format-standard","hentry","category-dynamics-365","category-dynamics-crm-2016","category-dynamics-crm-2016-update-1","category-webapi","tag-authenticate-microsoft-dynamics-crm-with-web-api","tag-dynamics-crm-online","tag-dynamics-crm-web-api-using-c","tag-microsoft-dynamics-crm-web-api","tag-web-api-functions-in-dynamics-crm-2016","tag-web-api-in-dynamics-crm"],"aioseo_notices":[],"_links":{"self":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/2552","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=2552"}],"version-history":[{"count":0,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/posts\/2552\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/media?parent=2552"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/categories?post=2552"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.inogic.com\/blog\/wp-json\/wp\/v2\/tags?post=2552"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}