DynamicsCRM2015WebAPI: Perform CRUD operations on clients.
After introducing two more conceptual articles, let's take a look at some specific Web API programming examples today. In this article, I will introduce how to call the CRM Web API to complete basic CRUD operations under the heavy client. What is a heavy client? Haha, this word was invented by myself and used to represent API consumers who are not browser scripts, such as data interfaces and intermediate services using C # code.
So what are the essential differences between heavy clients and light clients (Browser scripts? In my opinion, the biggest difference is that we need to consider API authentication and authorization in heavy client programming, but we don't need it in light client. Those who have used the REST interface in Dynamics CRM for programming may have realized that if we only call the API in browser scripts (not cross-origin, we do not need to involve any permission verification or granting process.
There are two difficulties in using Web APIs to perform transaction operations on CRM in a heavy client: one is to construct input parameters in JSON format, and the other is to construct an Odata URL that complies with the rules. For the former, we can use the JSON serialization class library for operations. For the latter, we can refer to the official SDK for URL construction.
Before programming, make sure that the following class libraries have been referenced in your project. If not, you can use NuGet for installation (search for the ID name, such as Newtonsoft. Json)
Before implementing specific functions, you need to use the verification helper class in the previous blog to generate an AccessToken. Then, we can implement specific services.
First, we generate an AccessToken and assign it to the HttpClient object so that the server can identify the request as an authorization request. The following code snippet is used to Create an Account.
Authentication auth = new Authentication(clientId, service, redirectUrl, username, password); //create an account JObject acc = new JObject(); acc.Add("name", "this account was created by WEB API"); HttpRequestMessage createReq = new HttpRequestMessage(HttpMethod.Post, string.Format("api/data/accounts")); createReq.Content = new StringContent(JsonConvert.SerializeObject(acc), Encoding.UTF8, "application/json"); createReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken); HttpResponseMessage createResponse = await client.SendAsync(createReq).ConfigureAwait(false); string accountUri = string.Empty; if (createResponse.IsSuccessStatusCode) { var result = await createResponse.Content.ReadAsStringAsync(); accountUri = createResponse.Headers.GetValues("OData-EntityId").FirstOrDefault(); }
The read operation is also very simple, basically the same as the rest query url, but this new API simplifies some complicated URL formats, such as querying customer records by ID: Old API-http: // server/AccountSet (guid 'xxxxx-xxxx-xxx-xxxx'), new API-http: // server/AccountSet ('xxxx-xxxx-XXX '). Isn't it easy? Big Love: D
//read an account if (!string.IsNullOrEmpty(accountUri)) { HttpRequestMessage getReq = new HttpRequestMessage(HttpMethod.Get, accountUri); getReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken); HttpResponseMessage getResp = await client.SendAsync(getReq); if (getResp.IsSuccessStatusCode) { JObject retrievedAcc = JsonConvert.DeserializeObject
(await getResp.Content.ReadAsStringAsync()); if (retrievedAcc != null) { Console.WriteLine(retrievedAcc["name"]); } } }
The update operation has also been greatly improved. The new API abandons some of the previous inexplicable client data types, such as Mony and OptionsSetValue. Instead, the basic data structure is concise and clear: integer and floating point. Another major change is the EntityReference type. In this set of APIS, we use a data structure like 'navigation', which is really awkward.
//update an account if (!string.IsNullOrEmpty(accountUri)) { HttpRequestMessage uptReq = new HttpRequestMessage(new HttpMethod("PATCH"), accountUri); JObject uptAcc = new JObject(); uptAcc.Add("telephone1", "12345"); //text uptAcc.Add("[email protected]", "https://server/api/data/contacts(d870721c-bf64-e511-80f0-c4346bc43f98)"); //lookup uptAcc.Add("donotemail", false); //bool uptAcc.Add("address1_shippingmethodcode", 3); //optionset uptAcc.Add("new_testcurrency", 500.51); uptAcc.Add("new_testdecimal", 1000.1); uptAcc.Add("new_testfloat", 2000.2); uptAcc.Add("new_testtime", DateTime.Now); uptAcc.Add("new_testwholenumber", 5000); uptReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer",auth.AcquireToken().AccessToken); uptReq.Content = new StringContent(JsonConvert.SerializeObject(uptAcc), Encoding.UTF8, "application/json"); HttpResponseMessage uptResp = await client.SendAsync(uptReq); if (uptResp.IsSuccessStatusCode) { Console.WriteLine("Update Successfully"); } }
Delete operation, concise, here the accountUrl format is this type of 'https: // server/api/data/contacts (d870721c-bf64-e511-80f0-c4346bc43f98)
//delete an account if (!string.IsNullOrEmpty(accountUri)) { HttpRequestMessage delReq = new HttpRequestMessage(HttpMethod.Delete, accountUri); delReq.Headers.Authorization = new AuthenticationHeaderValue("Bearer", auth.AcquireToken().AccessToken); HttpResponseMessage delResp = await client.SendAsync(delReq); if (delResp.IsSuccessStatusCode) { Console.WriteLine("Delete Successfully"); } }