public async Task<HttpResponseMessage> ForwardAndGetResponseAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var serialized = new HttpMessageContent(request).ReadAsByteArrayAsync().Result; var ms = new MemoryStream(serialized); var request2 = new HttpRequestMessage(); request2.Content = new ByteArrayContent(ms.ToArray()); request2.Content.Headers.Add("Content-Type", "application/http;msgtype=request"); var r3 = request2.Content.ReadAsHttpRequestMessageAsync().Result; var serviceAddress = new Uri(_baseurl + "IoT/rest_requests"); var client = _bus.CreateRequestClient<string, string>(serviceAddress, TimeSpan.FromSeconds(50)); var reply = await client.Request("HI!", cancellationToken); /* await endpoint.Send("HI!", Console.WriteLine(request.ToString()); Console.WriteLine(r3.ToString()); Console.WriteLine(r3.Content.ReadAsStringAsync().Result); */ var response = new HttpResponseMessage(HttpStatusCode.Accepted); return response; }
public HttpContent Build() { HttpMessageContent messageContent = new HttpMessageContent(RawRequest); messageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/http"); messageContent.Headers.Add("Content-Transfer-Encoding", "binary"); return messageContent; }
public Task SerializeAsync(HttpRequestMessage request, Stream stream) { if (request.Content != null) { return request.Content.LoadIntoBufferAsync() .Then(() => { var httpMessageContent = new HttpMessageContent(request); // All in-memory and CPU-bound so no need to async httpMessageContent.ReadAsByteArrayAsync().Then( buffer => { return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent); }); }); } else { var httpMessageContent = new HttpMessageContent(request); // All in-memory and CPU-bound so no need to async return httpMessageContent.ReadAsByteArrayAsync().Then( buffer => { return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent); } ); } }
public static HttpMessageContent CreateODataRequestContent(HttpRequestMessage request) { var changeSetMessageContent = new HttpMessageContent(request); changeSetMessageContent.Headers.ContentType.Parameters.Clear(); changeSetMessageContent.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", "binary"); return changeSetMessageContent; }
protected override async Task<HttpResponseMessage> SendAsync( HttpRequestMessage request, CancellationToken token) { HttpMessageContent requestContent = new HttpMessageContent(request); string requestMessage = requestContent.ReadAsStringAsync().Result; return await base.SendAsync(request, token); }
public static HttpMessageContent CreateODataRequestContent(HttpRequestMessage request) { var changeSetMessageContent = new HttpMessageContent(request); changeSetMessageContent.Headers.ContentType.Parameters.Clear(); changeSetMessageContent.Headers.TryAddWithoutValidation("Content-Transfer-Encoding", "binary"); changeSetMessageContent.Headers.TryAddWithoutValidation( "Content-ID", Guid.NewGuid().GetHashCode().ToString(CultureInfo.InvariantCulture)); return changeSetMessageContent; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, System.Threading.CancellationToken cancellationToken) { // we convert the request to a multipart content HttpMessageContent content = new HttpMessageContent(request); this.Parts.Add(content); // create a new promise for this one var promise = new TaskCompletionSource<HttpResponseMessage>(); this.Promises.Add(promise); if (this.Parts.Count >= this.ExpectedRequests) { this.operationsQueued.SetResult(true); } return promise.Task; }
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken) { var serialized = new HttpMessageContent(request).ReadAsByteArrayAsync().Result; var ms = new MemoryStream(serialized); var request2 = new HttpRequestMessage(); request2.Content = new ByteArrayContent(ms.ToArray()); request2.Content.Headers.Add("Content-Type", "application/http;msgtype=request"); var r3 = request2.Content.ReadAsHttpRequestMessageAsync(cancellationToken).Result; Console.WriteLine(request.ToString()); Console.WriteLine(r3.ToString()); Console.WriteLine(r3.Content.ReadAsStringAsync().Result); var response = new HttpResponseMessage(HttpStatusCode.Accepted); return Task.FromResult(response); }
public HttpContent Build(string boundary) { if (boundary == null) { throw new ArgumentNullException("boundary"); } if (string.IsNullOrWhiteSpace(boundary)) { throw new ArgumentException("The provided boundary value is invalid", "boundary"); } MultipartContent content = new MultipartContent("mixed", boundary); foreach (var request in Requests) { HttpMessageContent messageContent = new HttpMessageContent(request); messageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/http"); messageContent.Headers.Add("Content-Transfer-Encoding", "binary"); content.Add(messageContent); } return content; }
public Task SerializeAsync(Task<HttpResponseMessage> response, Stream stream) { return response.Then(r => { if (r.Content != null) { TraceWriter.WriteLine("SerializeAsync - before load", TraceLevel.Verbose); return r.Content.LoadIntoBufferAsync() .Then(() => { TraceWriter.WriteLine("SerializeAsync - after load", TraceLevel.Verbose); var httpMessageContent = new HttpMessageContent(r); // All in-memory and CPU-bound so no need to async return httpMessageContent.ReadAsByteArrayAsync(); }) .Then( buffer => { TraceWriter.WriteLine("SerializeAsync - after ReadAsByteArrayAsync", TraceLevel.Verbose); return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent); } ); ; } else { TraceWriter.WriteLine("Content NULL - before load", TraceLevel.Verbose); var httpMessageContent = new HttpMessageContent(r); // All in-memory and CPU-bound so no need to async var buffer = httpMessageContent.ReadAsByteArrayAsync().Result; return Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent); } } ); }
public static Task <HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, int bufferSize, int maxHeaderSize) { if (content == null) { throw Error.ArgumentNull("content"); } if (bufferSize < MinBufferSize) { throw Error.ArgumentMustBeGreaterThanOrEqualTo("bufferSize", bufferSize, MinBufferSize); } if (maxHeaderSize < InternetMessageFormatHeaderParser.MinHeaderSize) { throw Error.ArgumentMustBeGreaterThanOrEqualTo("maxHeaderSize", maxHeaderSize, InternetMessageFormatHeaderParser.MinHeaderSize); } HttpMessageContent.ValidateHttpMessageContent(content, false, true); return(content.ReadAsHttpResponseMessageAsyncCore(bufferSize, maxHeaderSize)); }
public async Task SerializeAsync(Task<HttpResponseMessage> response, Stream stream) { var r = await response; if (r.Content != null) { await r.Content.LoadIntoBufferAsync(); var httpMessageContent = new HttpMessageContent(r); // All in-memory and CPU-bound so no need to async var buffer = await httpMessageContent.ReadAsByteArrayAsync(); await Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent); } else { var httpMessageContent = new HttpMessageContent(r); // All in-memory and CPU-bound so no need to async var buffer = await httpMessageContent.ReadAsByteArrayAsync(); await Task.Factory.FromAsync(stream.BeginWrite, stream.EndWrite, buffer, 0, buffer.Length, null, TaskCreationOptions.AttachedToParent); } }
public void SerializeRequestWithEntityAsync() { for (int cnt = 0; cnt < iterations; cnt++) { HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, true); HttpMessageContent instance = new HttpMessageContent(request); ValidateRequest(instance, true); } }
public void SerializeRequestWithPortAndQueryAsync() { for (int cnt = 0; cnt < iterations; cnt++) { HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUriWithPortAndQuery, false); HttpMessageContent instance = new HttpMessageContent(request); string message = ReadContentAsync(instance); Assert.Equal(ParserData.HttpRequestWithPortAndQuery, message); } }
public void SerializeResponseMultipleTimes() { HttpResponseMessage response = CreateResponse(false); HttpMessageContent instance = new HttpMessageContent(response); for (int cnt = 0; cnt < iterations; cnt++) { ValidateResponse(instance, false); } }
public void SerializeRequestMultipleTimes() { HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false); HttpMessageContent instance = new HttpMessageContent(request); for (int cnt = 0; cnt < iterations; cnt++) { ValidateRequest(instance, false); } }
public void SerializeRequestWithExistingHostHeader() { HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false); string host = ParserData.HttpHostName; request.Headers.Host = host; HttpMessageContent instance = new HttpMessageContent(request); string message = ReadContentAsync(instance); Assert.Equal(ParserData.HttpRequestWithHost, message); }
private static async Task ExecuteBatchRequest() { HttpClient client = new HttpClient(); HttpRequestMessage request; HttpResponseMessage response; request = new HttpRequestMessage(HttpMethod.Get, serviceUrl + "/Customers"); response = await client.SendAsync(request); if (!response.IsSuccessStatusCode) { Console.WriteLine("Couldn't get the list of Customers"); return; } IList<Customer> customers = await response.Content.ReadAsAsync<IList<Customer>>(); Customer updatedCustomer = customers.First(); updatedCustomer.Name = "Peter"; Customer removedCustomer = customers.ElementAt(1); Customer addedCustomer = new Customer { Id = 10, Name = "Name " + 10 }; JsonMediaTypeFormatter formatter = new JsonMediaTypeFormatter(); //Create a request to query for customers HttpRequestMessage queryCustomersRequest = new HttpRequestMessage(HttpMethod.Get, serviceUrl + "/Customers"); //Create a message to add a customer HttpRequestMessage addCustomerRequest = new HttpRequestMessage(HttpMethod.Post, serviceUrl + "/Customers"); addCustomerRequest.Content = new ObjectContent<Customer>(addedCustomer, formatter); //Create a message to update a customer HttpRequestMessage updateCustomerRequest = new HttpRequestMessage(HttpMethod.Put, string.Format(serviceUrl + "/Customers/{0}", updatedCustomer.Id)); updateCustomerRequest.Content = new ObjectContent<Customer>(updatedCustomer, formatter); //Create a message to remove a customer. HttpRequestMessage removeCustomerRequest = new HttpRequestMessage(HttpMethod.Delete, string.Format(serviceUrl + "/Customers/{0}", removedCustomer.Id)); //Create the different parts of the multipart content HttpMessageContent queryContent = new HttpMessageContent(queryCustomersRequest); HttpMessageContent addCustomerContent = new HttpMessageContent(addCustomerRequest); HttpMessageContent updateCustomerContent = new HttpMessageContent(updateCustomerRequest); HttpMessageContent removeCustomerContent = new HttpMessageContent(removeCustomerRequest); //Create the multipart/mixed message content MultipartContent content = new MultipartContent("mixed", "batch_" + Guid.NewGuid().ToString()); content.Add(queryContent); content.Add(addCustomerContent); content.Add(updateCustomerContent); content.Add(removeCustomerContent); //Create the request to the batch service HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, serviceUrl + "/batch"); //Associate the content with the message batchRequest.Content = content; //Send the message HttpResponseMessage batchResponse = await client.SendAsync(batchRequest); //Check that the batch response is correct if (!batchResponse.IsSuccessStatusCode) { Console.WriteLine("There was an error executing the batch request."); Console.WriteLine(await batchResponse.Content.ReadAsStringAsync()); } //Check that the content in the response is multipart/mixed if (!batchResponse.Content.IsMimeMultipartContent("mixed")) { Console.WriteLine("The returned content is not multipart/mixed"); Console.WriteLine(await batchResponse.Content.ReadAsStringAsync()); } //Reads the individual parts in the content and loads them in memory MultipartMemoryStreamProvider responseContents = await batchResponse.Content.ReadAsMultipartAsync(); if (!(responseContents.Contents.Count == 4)) { Console.WriteLine("There wrong number of responses came back."); } HttpResponseMessage queryResponse = await responseContents.Contents[0].ReadAsHttpResponseMessageAsync(); if (!queryResponse.IsSuccessStatusCode || queryResponse.Content == null) { Console.WriteLine("The query for the customers failed"); Console.WriteLine(); } else { Console.WriteLine("Query result:"); Console.WriteLine(await queryResponse.Content.ReadAsStringAsync()); Console.WriteLine(); } HttpResponseMessage addResponse = await responseContents.Contents[1].ReadAsHttpResponseMessageAsync(); if (!addResponse.IsSuccessStatusCode || addResponse.Content == null) { Console.WriteLine("The add customer operation failed"); Console.WriteLine(); } else { Console.WriteLine("Add result:"); Console.WriteLine(await addResponse.Content.ReadAsStringAsync()); Console.WriteLine(); } HttpResponseMessage updateResponse = await responseContents.Contents[2].ReadAsHttpResponseMessageAsync(); if (!updateResponse.IsSuccessStatusCode || updateResponse.Content == null) { Console.WriteLine("The update customer operation failed"); Console.WriteLine(); } else { Console.WriteLine("Update result:"); Console.WriteLine(await updateResponse.Content.ReadAsStringAsync()); Console.WriteLine(); } HttpResponseMessage removeResponse = await responseContents.Contents[3].ReadAsHttpResponseMessageAsync(); if (!removeResponse.IsSuccessStatusCode) { Console.WriteLine("The delete customer operation failed"); } else { Console.WriteLine("The delete operation was successful"); } }
public void DisposeInnerHttpResponseMessage() { HttpResponseMessage response = CreateResponse(false); HttpMessageContent instance = new HttpMessageContent(response); instance.Dispose(); Assert.ThrowsObjectDisposed(() => { response.StatusCode = HttpStatusCode.OK; }, typeof(HttpResponseMessage).FullName); }
public void RoundtripClientRequest(IEnumerable<string> message) { HttpContent content = CreateContent(true, message, null); HttpRequestMessage httpRequest = content.ReadAsHttpRequestMessageAsync().Result; HttpMessageContent httpMessageContent = new HttpMessageContent(httpRequest); MemoryStream destination = new MemoryStream(); httpMessageContent.CopyToAsync(destination).Wait(); destination.Seek(0, SeekOrigin.Begin); string destinationMessage = new StreamReader(destination).ReadToEnd(); string sourceMessage = content.ReadAsStringAsync().Result; Assert.Equal(sourceMessage, destinationMessage); }
public async Task Run(Authentication auth, Configuration config) { try { using (WebAPIPreviewService webAPIPreviewService = new WebAPIPreviewService(auth, config)) { //Demonstrates how to retrieve a list of entities #region Get entity list JArray entities = await webAPIPreviewService.GetEntityList(); Console.WriteLine("{0} entities returned.", entities.Count); JArray sortedEntities = new JArray(entities.OrderBy(obj => obj["name"].ToString().ToLower())); foreach (var item in sortedEntities) { Console.WriteLine(item["name"]); } #endregion Get entity list //Demonstrates how to associate and disassociate using the single-valued navigation property. #region Add and Remove Reference //Create a contact JObject contactA = new JObject(); contactA.Add("firstname", "Tom"); contactA.Add("lastname", "Test"); Uri contactAUri = await webAPIPreviewService.Create("contacts", contactA); //Create an account JObject accountA = new JObject(); accountA.Add("name", "Tom's Company"); Uri accountAUri = await webAPIPreviewService.Create("accounts", accountA); //Set the contact as the primary contact for the account await webAPIPreviewService.AddReference(accountAUri, "account_primary_contact", contactAUri); //Retrieve the account accountA = await webAPIPreviewService.Retrieve(accountAUri, new String[] { "name" }, new String[] { "account_primary_contact($select=fullname)" }, true); //Get the fullname property of the primary contact - it should have a value String primaryContactValue = (accountA["account_primary_contact"] == null) ? "null" : accountA["account_primary_contact"]["fullname"].ToString(); //Show the primary contact value - it should be 'Tom Test' Console.WriteLine("Primary contact for {0} is {1}.", accountA["name"], primaryContactValue); //Remove the contact as the primary contact for the account await webAPIPreviewService.RemoveReference(accountAUri, "account_primary_contact"); //Retrieve the account again accountA = await webAPIPreviewService.Retrieve(accountAUri, new String[] { "name" }, new String[] { "account_primary_contact($select=fullname)" }, true); //Get the fullname property of the primary contact - it should be null primaryContactValue = (accountA["account_primary_contact"] == null) ? "null" : accountA["account_primary_contact"]["fullname"].ToString(); //Show the primary contact value - it should be null Console.WriteLine("Primary contact for {0} is {1}.", accountA["name"], primaryContactValue); //Delete the account and contact created await webAPIPreviewService.Delete(accountAUri); await webAPIPreviewService.Delete(contactAUri); #endregion Add and Remove Reference //Demonstrates the use of Upsert with options to prevent create or update #region Upsert Contact //Create a new contact with a specific contactid Uri newContactUri = new Uri("/api/data/contacts(80db55c7-a16b-4851-b5c8-24186f3d86b6)", UriKind.Relative); JObject contact = new JObject(); contact.Add("firstname", "Joe"); contact.Add("lastname", "Jones"); await webAPIPreviewService.Upsert(newContactUri, contact); String fullName = await webAPIPreviewService.RetrievePropertyValue<String>(newContactUri, "fullname"); Console.WriteLine("New Contact fullname returned: {0}", fullName); //Do not update the contact if it already exists JObject doNotUpdateContact = new JObject(); doNotUpdateContact.Add("firstname", "Joseph"); doNotUpdateContact.Add("lastname", "Jones"); await webAPIPreviewService.Upsert(newContactUri, doNotUpdateContact, false, true); String sameFullName = await webAPIPreviewService.RetrievePropertyValue<String>(newContactUri, "fullname"); Console.WriteLine("New Contact fullname returned: {0}", sameFullName); //Do not create the contact if it doesn't already exist Uri doNotCreateContactUri = new Uri("/api/data/contacts(ebeefeb4-c3aa-4d7b-a094-43288d3ccf95)", UriKind.Relative); JObject doNotCreateContact = new JObject(); doNotCreateContact.Add("firstname", "Bob"); doNotCreateContact.Add("lastname", "Burns"); await webAPIPreviewService.Upsert(doNotCreateContactUri, doNotCreateContact, true); try { JObject noContact = await webAPIPreviewService.Retrieve(doNotCreateContactUri, new String[] { "fullname" }, null, false); } catch (Exception ex) { if (!ex.Message.EndsWith("Does Not Exist")) { throw ex; } Console.WriteLine("Expected Error: {0}", ex.Message); } //Delete the contact await webAPIPreviewService.Delete(newContactUri); Console.WriteLine("Contact Deleted"); #endregion Upsert Contact //Demonstrates creating new entity #region Create New Account Uri newAccountUri = null; String newAccountId = null; JObject account = new JObject(); //Application Required String account.Add("name", "Sample Account"); //Boolean account.Add("creditonhold", false); // Double account.Add("address1_latitude", 47.6395830); //Memo account.Add("description", "This is the description of the full account"); //Money account.Add("revenue", 5000000); //Picklist account.Add("accountcategorycode", 1); //Preferred Customer newAccountUri = await webAPIPreviewService.Create("accounts", account); Console.WriteLine("New account created with Uri = {0}", newAccountUri); #endregion Create New Account //Demonstrates how to retrieve individual properties #region Retrieve individual properties //Retrieve individual properties from the new account DateTime createdOn = await webAPIPreviewService.RetrievePropertyValue<DateTime>(newAccountUri, "createdon"); Console.WriteLine("Returned createdon: {0}", createdOn.ToLongDateString()); String createdby = await webAPIPreviewService.RetrievePropertyValue<String>(newAccountUri, "createdby"); Console.WriteLine("Returned createdby: {0}", createdby); Int32 statusCode = await webAPIPreviewService.RetrievePropertyValue<Int32>(newAccountUri, "statuscode"); Console.WriteLine("Returned statusCode: {0}", statusCode); //CreditLimit is null Decimal? creditLimit = await webAPIPreviewService.RetrievePropertyValue<Decimal?>(newAccountUri, "creditlimit"); Console.WriteLine("Returned creditLimit: {0}", (creditLimit == null) ? "null" : creditLimit.ToString()); //Capture this value to use with QueryEntitySet filter example; newAccountId = await webAPIPreviewService.RetrievePropertyValue<String>(newAccountUri, "accountid"); #endregion Retrieve individual properties //Demonstrates how to update individual properties #region Update individual properties await webAPIPreviewService.UpdatePropertyValue(newAccountUri, "name", "New Improved Account Name"); //Then retrieve to verify it was set String newName = await webAPIPreviewService.RetrievePropertyValue<String>(newAccountUri, "name"); Console.WriteLine("Updated name: {0}", newName); #endregion Update individual properties //Demonstrates how to associate entities using a collection-valued navigation property #region Create Parent Account JObject parentAccount = new JObject(); parentAccount.Add("name", "Parent Account"); Uri parentAccountUri = await webAPIPreviewService.Create("accounts", parentAccount); Console.WriteLine("New Parent Account created with Uri = {0}", parentAccountUri); #region Associate accounts await webAPIPreviewService.Associate(parentAccountUri, "Referencedaccount_parent_account", newAccountUri); Console.WriteLine("Accounts Associated"); #endregion Associate accounts #endregion Create Parent Account //Demonstrates associating records on create using @odata.bind #region Add 3 related tasks DateTime now = DateTime.Now; DateTime tomorrow = now.AddDays(1); for (int i = 1; i < 4; i++) { JObject task = new JObject(); task.Add("scheduledstart", tomorrow); task.Add("*****@*****.**", newAccountUri); task.Add("subject", String.Format("Task: {0}", i.ToString())); await webAPIPreviewService.Create("tasks", task); } #endregion Add 3 related tasks //Demonstrates the use of batch operations #region Batch // Add 2 related tasks in a batch Guid batchId = Guid.NewGuid(); List<JObject> tasks = new List<JObject>(); JObject firstTask = new JObject(); firstTask.Add("subject", "Task 1 in batch"); firstTask.Add("*****@*****.**", newAccountUri); tasks.Add(firstTask); JObject secondTask = new JObject(); secondTask.Add("subject", "Task 2 in batch"); secondTask.Add("*****@*****.**", newAccountUri); tasks.Add(secondTask); List<HttpContent> payload = new List<HttpContent>(); String changeSetId = Guid.NewGuid().ToString(); MultipartContent changeSet = new MultipartContent("mixed", "changeset_" + changeSetId); int taskNumber = 1; tasks.ForEach(t => { HttpRequestMessage message = new HttpRequestMessage(HttpMethod.Post, config.ServiceUrl + "/api/data/tasks"); message.Content = new StringContent(JsonConvert.SerializeObject(t)); message.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); HttpMessageContent messageContent = new HttpMessageContent(message); messageContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/http"); messageContent.Headers.Add("Content-Transfer-Encoding", "binary"); messageContent.Headers.Add("Content-ID", taskNumber.ToString()); changeSet.Add(messageContent); taskNumber++; }); payload.Add(changeSet); HttpRequestMessage retrieveTasks = new HttpRequestMessage(HttpMethod.Get, newAccountUri + "/Account_Tasks?$select=subject"); HttpMessageContent retrieveTasksContent = new HttpMessageContent(retrieveTasks); retrieveTasksContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/http"); retrieveTasksContent.Headers.Add("Content-Transfer-Encoding", "binary"); payload.Add(retrieveTasksContent); String batchResponse = await webAPIPreviewService.ExecuteBatch(payload, batchId); Console.WriteLine("Batch Response START"); Console.WriteLine(batchResponse); Console.WriteLine("Batch Response END"); #endregion Batch //Demonstrates a simple update #region Update JObject accntObj = new JObject(); accntObj.Add("name", "Updated Account Name"); accntObj.Add("description", "Sample Account Description Updated."); await webAPIPreviewService.Update(newAccountUri, accntObj); Console.WriteLine("Account Updated"); #endregion Update //Demonstrates retrieve with related entities #region Retrieve String[] properties = { "accountcategorycode", "accountclassificationcode", "accountid", "accountnumber", "accountratingcode", "businesstypecode", "creditonhold", "createdon", "lastusedincampaign", "address1_latitude", "address1_longitude", "numberofemployees", "parentaccountid", "description", "name", "revenue"}; String[] navigationProperties = { "Referencingaccount_parent_account($select=createdon,name)", //Data from parent account "Account_Tasks($select=subject,scheduledstart)" //Data from related tasks }; JObject retrievedAccount = await webAPIPreviewService.Retrieve(newAccountUri, properties, navigationProperties, true); Console.WriteLine("Account retrieved"); Console.WriteLine("Account accountcategorycode value: {0}", retrievedAccount.GetValue("accountcategorycode")); //Access formatted value String formattedAccountCategoryCodeValue = (String)retrievedAccount.GetValue("*****@*****.**"); Console.WriteLine("Account accountcategorycode formatted value: {0}", formattedAccountCategoryCodeValue); Console.WriteLine("Parent Account name: {0}", retrievedAccount.GetValue("Referencingaccount_parent_account")["name"]); //Access related tasks Console.WriteLine("Related tasks subject values:"); retrievedAccount.GetValue("Account_Tasks").ToList().ForEach(delegate(JToken relatedTask) { Console.WriteLine(" Task Subject: {0}", relatedTask.ToObject<JObject>().GetValue("subject")); }); #endregion Retrieve //Demonstrates querying an entity set and retrieving additional pages #region QueryEntitySet String query = String.Format("$filter=regardingobjectid eq {0}&$select=subject", newAccountId); Boolean includeFormattedValues = true; uint maxPageSize = 2; JObject QueryEntitySetActivitiesResponse = await webAPIPreviewService.QueryEntitySet("activitypointers", query, includeFormattedValues, maxPageSize); Console.WriteLine("First page of activities retrieved using QueryEntitySet:"); QueryEntitySetActivitiesResponse.GetValue("value").ToList().ForEach(delegate(JToken relatedActivity) { Console.WriteLine(" Activity Subject: {0}", relatedActivity.ToObject<JObject>().GetValue("subject")); }); Uri nextPageQuery = (Uri)QueryEntitySetActivitiesResponse.GetValue("@odata.nextLink"); if (nextPageQuery != null) { JObject QueryEntitySetActivitiesNextPageResponse = await webAPIPreviewService.GetNextPage(nextPageQuery, includeFormattedValues, maxPageSize); Console.WriteLine("Second page of activities retrieved using QueryEntitySet:"); QueryEntitySetActivitiesNextPageResponse.GetValue("value").ToList().ForEach(delegate(JToken relatedActivity) { Console.WriteLine(" Activity Subject: {0}", relatedActivity.ToObject<JObject>().GetValue("subject")); }); } #endregion QueryEntitySet //Demonstrates disassociation using a collection-valued navigation property #region Disassociate await webAPIPreviewService.Disassociate(parentAccountUri, "Referencedaccount_parent_account", newAccountUri); Console.WriteLine("Accounts disassociated"); #endregion Disassociate //Demonstrates deleteing an individual property #region Delete Property Value Decimal? beforeRevenueValue = await webAPIPreviewService.RetrievePropertyValue<Decimal?>(newAccountUri, "revenue"); Console.WriteLine("Before revenue value: {0}", beforeRevenueValue); await webAPIPreviewService.DeletePropertyValue(newAccountUri, "revenue"); Decimal? afterRevenueValue = await webAPIPreviewService.RetrievePropertyValue<Decimal?>(newAccountUri, "revenue"); Console.WriteLine("After revenue value: {0}", afterRevenueValue); #endregion Delete Property Value //Demonstrates deleteing entities #region Delete await webAPIPreviewService.Delete(newAccountUri); Console.WriteLine("Account Deleted"); //Tasks are deleted with the Account await webAPIPreviewService.Delete(parentAccountUri); Console.WriteLine("Parent Account Deleted"); #endregion Delete //Demonstrates using an unbound function : WhoAmI #region WhoAmI String UserId; //Used in a following RetrieveUserQueues sample JObject WhoAmIResponse = await webAPIPreviewService.InvokeUnboundFunction("WhoAmI", null); Console.WriteLine("Results from WhoAmI function:"); UserId = (String)WhoAmIResponse.GetValue("UserId"); Console.WriteLine(" UserId: {0}", WhoAmIResponse.GetValue("UserId")); Console.WriteLine(" BusinessUnitId: {0}", WhoAmIResponse.GetValue("BusinessUnitId")); Console.WriteLine(" OrganizationId: {0}", WhoAmIResponse.GetValue("OrganizationId")); #endregion WhoAmI //Demonstrates using an unbound function : GetAllTimeZonesWithDisplayName #region GetAllTimeZonesWithDisplayName JArray lcidParams = new JArray(); lcidParams.Add("LocaleId=1033"); JObject GATZWDNResponse = await webAPIPreviewService.InvokeUnboundFunction("GetAllTimeZonesWithDisplayName", lcidParams); Console.WriteLine("GetAllTimeZonesWithDisplayName Function Response values:"); foreach (var item in GATZWDNResponse.GetValue("value").Children()) { Console.WriteLine(" {0}", item["userinterfacename"].ToString()); } #endregion GetAllTimeZonesWithDisplayName //Demonstrates using an unbound function : RetrieveUserQueues #region RetrieveUserQueues JArray parameters = new JArray(); parameters.Add(String.Format("UserId={0}", UserId)); parameters.Add("IncludePublic=true"); JObject RetrieveUserQueuesResponse = await webAPIPreviewService.InvokeUnboundFunction("RetrieveUserQueues", parameters); Console.WriteLine("Returned {0} user queues.", RetrieveUserQueuesResponse.GetValue("value").Children().Count()); #endregion RetrieveUserQueues //Demonstrates using a bound function : mscrm.GetSavedQueries #region mscrm.GetSavedQueries JArray queries = await webAPIPreviewService.InvokeBoundFunction("accounts", "mscrm.GetSavedQueries"); if (queries.Count > 0) { Console.WriteLine("These are the saved queries for the account entity."); foreach (var item in queries.Children()) { Console.WriteLine(" {0}", item["name"].ToString()); } } else { Console.WriteLine("There are no saved queries for this entity."); } #endregion mscrm.GetSavedQueries //Demonstrates using an unbound action : WinOpportunity #region WinOpportunity action //Create an Account to own the Opportunity JObject winOppAccount = new JObject(); winOppAccount.Add("name", "Win Opp Account"); Uri winOppAccountUri = await webAPIPreviewService.Create("accounts", winOppAccount); //Create an associated opportunity to win JObject winOpp = new JObject(); winOpp.Add("name", "Opportunity to Win"); winOpp.Add("*****@*****.**", winOppAccountUri); Uri winOppUri = await webAPIPreviewService.Create("opportunities", winOpp); //Create Opportunityclose object to pass with the parameters JObject opportunityClose = new JObject(); opportunityClose.Add("@odata.type", "#mscrm.opportunityclose"); //Essential to describe the type of entity opportunityClose.Add("subject", "Won Opp Activity"); opportunityClose.Add("description", "We won this opportunity."); opportunityClose.Add("*****@*****.**", winOppUri); //Prepare Parameter object JObject winOppParams = new JObject(); winOppParams.Add("Status", 3); winOppParams.Add("OpportunityClose", opportunityClose); //Invoke the action JObject winOppResponse = await webAPIPreviewService.InvokeUnboundAction("WinOpportunity", winOppParams); Console.WriteLine("Opportunity Closed as Won."); //Delete Account await webAPIPreviewService.Delete(winOppAccountUri); Console.WriteLine("Account deleted and all related records with it."); #endregion WinOpportunity action } } catch (Exception ex) { DisplayException(ex); } }
public static async Task<Stream> ToRawHttpResponseStream(this HttpResponseMessage response, Stream stream) { var httpMessageContent = new HttpMessageContent(response); await httpMessageContent.CopyToAsync(stream); return stream; }
public void SerializeResponseWithEntityAsync() { for (int cnt = 0; cnt < iterations; cnt++) { HttpResponseMessage response = CreateResponse(true); HttpMessageContent instance = new HttpMessageContent(response); ValidateResponse(instance, true); } }
public void DisposeInnerHttpRequestMessage() { HttpRequestMessage request = CreateRequest(ParserData.HttpRequestUri, false); HttpMessageContent instance = new HttpMessageContent(request); instance.Dispose(); Assert.ThrowsObjectDisposed(() => { request.Method = HttpMethod.Get; }, typeof(HttpRequestMessage).FullName); }
public async Task HttpHeader_TryAddWithoutValidation_does_not_validates_the_value_but_preserves_it() { var request = new HttpRequestMessage(HttpMethod.Get, "http://some.uri"); Assert.True(request.Headers.TryAddWithoutValidation("Date", "invalid-date")); Assert.Equal(null, request.Headers.Date); Assert.Equal("invalid-date", request.Headers.First(h => h.Key == "Date").Value.First()); var content = new HttpMessageContent(request); var s = await content.ReadAsStringAsync(); Assert.True(s.Contains("Date: invalid-date")); }
public static Task <HttpResponseMessage> ReadAsHttpResponseMessageAsync(this HttpContent content, int bufferSize, int maxHeaderSize) { if (content == null) { throw Error.ArgumentNull("content"); } if (bufferSize < MinBufferSize) { throw Error.ArgumentMustBeGreaterThanOrEqualTo("bufferSize", bufferSize, MinBufferSize); } if (maxHeaderSize < InternetMessageFormatHeaderParser.MinHeaderSize) { throw Error.ArgumentMustBeGreaterThanOrEqualTo("maxHeaderSize", maxHeaderSize, InternetMessageFormatHeaderParser.MinHeaderSize); } HttpMessageContent.ValidateHttpMessageContent(content, false, true); return(content.ReadAsStreamAsync().Then(stream => { HttpUnsortedResponse httpResponse = new HttpUnsortedResponse(); HttpResponseHeaderParser parser = new HttpResponseHeaderParser(httpResponse, HttpResponseHeaderParser.DefaultMaxStatusLineSize, maxHeaderSize); ParserState parseStatus; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; int headerConsumed = 0; while (true) { try { bytesRead = stream.Read(buffer, 0, buffer.Length); } catch (Exception e) { throw new IOException(Properties.Resources.HttpMessageErrorReading, e); } try { parseStatus = parser.ParseBuffer(buffer, bytesRead, ref headerConsumed); } catch (Exception) { parseStatus = ParserState.Invalid; } if (parseStatus == ParserState.Done) { // Create and return parsed HttpResponseMessage return CreateHttpResponseMessage(httpResponse, stream, bytesRead - headerConsumed); } else if (parseStatus != ParserState.NeedMoreData) { throw Error.InvalidOperation(Properties.Resources.HttpMessageParserError, headerConsumed, buffer); } } })); }
public void ResponseConstructor() { HttpResponseMessage response = new HttpResponseMessage(); HttpMessageContent instance = new HttpMessageContent(response); Assert.NotNull(instance); Assert.Same(response, instance.HttpResponseMessage); Assert.Null(instance.HttpRequestMessage); }
private static void WriteComplete(IAsyncResult result, HttpMessageContent thisPtr, Stream stream, TaskCompletionSource<object> writeTask) { Contract.Assert(result != null, "result cannot be null"); Contract.Assert(thisPtr != null, "thisPtr cannot be null"); Contract.Assert(stream != null, "stream cannot be null"); Contract.Assert(writeTask != null, "writeTask cannot be null"); try { stream.EndWrite(result); } catch (Exception e) { writeTask.TrySetException(e); } thisPtr.PrepareContentAsync().Then(content => { if (content != null) { content.CopyToAsync(stream) .CopyResultToCompletionSource(writeTask, completionResult: null); } else { writeTask.TrySetResult(null); } }); }
public static Task <HttpRequestMessage> ReadAsHttpRequestMessageAsync(this HttpContent content, string uriScheme, int bufferSize) { if (content == null) { throw new ArgumentNullException("content"); } if (uriScheme == null) { throw new ArgumentNullException("uriScheme"); } if (!Uri.CheckSchemeName(uriScheme)) { throw new ArgumentException(RS.Format(Properties.Resources.HttpMessageParserInvalidUriScheme, uriScheme, typeof(Uri).Name), "uriScheme"); } if (bufferSize < MinBufferSize) { throw new ArgumentOutOfRangeException("bufferSize", bufferSize, RS.Format(Properties.Resources.ArgumentMustBeGreaterThanOrEqualTo, MinBufferSize)); } HttpMessageContent.ValidateHttpMessageContent(content, true, true); return(content.ReadAsStreamAsync().Then(stream => { HttpUnsortedRequest httpRequest = new HttpUnsortedRequest(); HttpRequestHeaderParser parser = new HttpRequestHeaderParser(httpRequest); ParserState parseStatus; byte[] buffer = new byte[bufferSize]; int bytesRead = 0; int headerConsumed = 0; while (true) { try { bytesRead = stream.Read(buffer, 0, buffer.Length); } catch (Exception e) { throw new IOException(Properties.Resources.HttpMessageErrorReading, e); } try { parseStatus = parser.ParseBuffer(buffer, bytesRead, ref headerConsumed); } catch (Exception) { parseStatus = ParserState.Invalid; } if (parseStatus == ParserState.Done) { return CreateHttpRequestMessage(uriScheme, httpRequest, stream, bytesRead - headerConsumed); } else if (parseStatus != ParserState.NeedMoreData) { throw new IOException(RS.Format(Properties.Resources.HttpMessageParserError, headerConsumed, buffer)); } } })); }
public void RoundtripServerResponse(IEnumerable<string> message) { HttpContent content = CreateContent(false, message, @"<html><head><title>Object moved</title></head><body><h2>Object moved to <a href=""/en-us/"">here</a>.</h2></body></html>"); HttpResponseMessage httpResponse = content.ReadAsHttpResponseMessageAsync().Result; HttpMessageContent httpMessageContent = new HttpMessageContent(httpResponse); MemoryStream destination = new MemoryStream(); httpMessageContent.CopyToAsync(destination).Wait(); destination.Seek(0, SeekOrigin.Begin); string destinationMessage = new StreamReader(destination).ReadToEnd(); string sourceMessage = content.ReadAsStringAsync().Result; Assert.Equal(sourceMessage, destinationMessage); }
static void BatchRequest() { string tpl = "http://localhost.fiddler:3333" + "/odata/{0}/{1}"; HttpClient client = new HttpClient(); //Create a request to query for customers HttpRequestMessage AspNetUsers = new HttpRequestMessage(HttpMethod.Get, string.Format(tpl, _DataSourceName, "AspNetUsers")); //Create a message to add a customer HttpRequestMessage AspNetRoles = new HttpRequestMessage(HttpMethod.Get, string.Format(tpl, _DataSourceName, "AspNetRoles")); string b = Guid.NewGuid().ToString(); //Create the different parts of the multipart content HttpMessageContent queryContent1 = new HttpMessageContent(AspNetUsers); HttpMessageContent queryContent2 = new HttpMessageContent(AspNetRoles); if (queryContent1.Headers.Contains("Content-Type")) queryContent1.Headers.Remove("Content-Type"); queryContent1.Headers.Add("Content-Type", "application/http"); queryContent1.Headers.Add("client-request-id", "1"); queryContent1.Headers.Add("return-client-request-id", "True"); queryContent1.Headers.Add("Content-ID", "1"); queryContent1.Headers.Add("DataServiceVersion", "3.0"); queryContent1.Headers.Add("Content-Transfer-Encoding", "binary"); if (queryContent2.Headers.Contains("Content-Type")) queryContent2.Headers.Remove("Content-Type"); queryContent2.Headers.Add("Content-Type", "application/http"); queryContent2.Headers.Add("client-request-id", "2"); queryContent2.Headers.Add("return-client-request-id", "True"); queryContent2.Headers.Add("Content-ID", "2"); queryContent2.Headers.Add("DataServiceVersion", "3.0"); queryContent2.Headers.Add("Content-Transfer-Encoding", "binary"); //Create the multipart/mixed message content MultipartContent content = new MultipartContent("mixed", "batch_" + b); content.Add(queryContent1); content.Add(queryContent2); //Create the request to the batch service HttpRequestMessage batchRequest = new HttpRequestMessage(HttpMethod.Post, "http://localhost:3333" + "/odata/$batch"); //Associate the content with the message batchRequest.Content = content; var response = client.SendAsync(batchRequest).Result; Console.WriteLine("\r\nResult:"); Console.WriteLine(response.StatusCode.ToString()); Console.WriteLine(response.Content.ReadAsStringAsync().Result); }