/// <summary>
        /// Sends a single Get Request using $batch
        /// </summary>
        /// <param name="svc">The configured service</param>
        /// <param name="path">The relative URL of the GET request</param>
        /// <param name="headers">Any headers to be applied to the request.</param>
        /// <returns></returns>
        private static JToken SendGetAsBatch(CDSWebApiService svc, string path, Dictionary <string, string> headers = null)
        {
            var batchGet = new BatchGetRequest()
            {
                Path    = path,
                Headers = headers
            };


            var batchResponses = svc.PostBatch(new List <BatchItem> {
                batchGet
            });

            HttpResponseMessage batchResponse = batchResponses[0];

            if (batchResponse.IsSuccessStatusCode)
            {
                var responseContent = JToken.Parse(batchResponse.Content.ReadAsStringAsync().Result);

                return(responseContent);
            }
            else
            {
                throw new Exception("Error sending GET request in Batch.");
            }
        }
Exemple #2
0
        public static void Run(CDSWebApiService svc, bool deleteCreatedRecords)
        {
            Console.WriteLine("--Starting BatchOperations sample--");
            //Create an account outside of the batch to show linking.
            var parentAccount = new JObject
            {
                { "name", "Parent Account" }
            };
            Uri accountUri = svc.PostCreate("accounts", parentAccount);
            // Not technically necessary to convert to a relative Uri, but
            // it does make the JSON passed more readable in Fiddler
            var relativeAccountUri = svc.BaseAddress.MakeRelativeUri(accountUri);

            entityUris.Add(relativeAccountUri);

            Console.WriteLine("\nCreated an account record before the batch operation.");

            //Create a BatchChangeSet to include operations within the batch
            var changeset = new BatchChangeSet();

            //Compose the body for the first contact.
            var contact1 = new JObject
            {
                { "firstname", "Joe" },
                { "lastname", "Smith" },
                { "accountrolecode", 1 }, //Decision Maker
                { "jobtitle", "Manager" },
                //Related to the account
                { "*****@*****.**", relativeAccountUri.ToString() }
            };

            //Add a request to the changeset.
            changeset.Requests.Add(
                new HttpRequestMessage(HttpMethod.Post, "contacts")
            {
                Content = new StringContent(contact1.ToString())
            }
                );

            //Compose the body for the second contact.
            var contact2 = new JObject
            {
                { "firstname", "Jack" },
                { "lastname", "Jones" },
                { "accountrolecode", 2 }, //Employee
                { "jobtitle", "Assistant" },
                //Related to first contact in batch
                { "*****@*****.**", "$1" },
                //Related to the account
                { "*****@*****.**", relativeAccountUri.ToString() }
            };

            //Add another request to the changeset.
            changeset.Requests.Add(
                new HttpRequestMessage(HttpMethod.Post, "contacts")
            {
                Content = new StringContent(contact2.ToString())
            }
                );

            //Add the changeset to the list of BatchItems
            var items = new List <BatchItem>()
            {
                changeset
            };

            var includeAnnotationsHeader = new Dictionary <string, string>();

            //Adding annotations to show formatted values
            includeAnnotationsHeader.Add("Prefer", "odata.include-annotations=\"*\"");

            var query      = "?$select=name&$expand=contact_customer_accounts($select=fullname,accountrolecode)";
            var getRequest = new BatchGetRequest()
            {
                Path    = $"{relativeAccountUri.ToString()}{query}",
                Headers = includeAnnotationsHeader
            };

            //Add the GET request to the list of BatchItems
            items.Add(getRequest);

            //Send the batch request.
            var responses = svc.PostBatch(items);

            Console.WriteLine("\nCreated these contact records in the batch:");
            responses.ForEach(x => {
                if (x.Headers.Contains("OData-EntityId"))
                {
                    var contactRelativeUri = svc.BaseAddress.MakeRelativeUri(new Uri(x.Headers.GetValues("OData-EntityId").FirstOrDefault()));
                    Console.WriteLine($"\tContact: {contactRelativeUri.ToString()}");
                }
            });

            Console.WriteLine("\nInformation about the Account retrieved in the batch:");
            Console.WriteLine(JObject.Parse(responses[2].Content.ReadAsStringAsync().Result));

            if (deleteCreatedRecords)
            {
                svc.Delete(relativeAccountUri);
                Console.WriteLine("\nThe account created for this sample was deleted and the related contacts with it.");
            }

            Console.WriteLine("--BatchOperations sample complete--");
        }