Client OData Patch without retrieving object first? - c#

I am using a C# OData 4 client as described here:
http://www.asp.net/web-api/overview/odata-support-in-aspnet-web-api/odata-v4/create-an-odata-v4-client-app
I have a product class and it has an Id, Name, Price and Category. I'd like to do something like:
var product = new ProductService.Models.Product {
Id = 2,
Price = 4
};
container.AttachTo("Products", product);
container.UpdateObject(product);
So that I can update only the price property and ignore all the rest of them. I can see that this won't work because Name and Category are Created as null when Product object is created so they will be sent in the resulting request as null.
Is there a way of doing this without first retrieving the object that I want to update? (I'm guessing that I need to go down the HttpClient route).

One workaround is to use HttpClient directly:
HttpRequestMessage request = new HttpRequestMessage(new HttpMethod("PATCH"), requestUri);
request.Content = new StringContent(#"{{""#odata.type"":""#ProductService.Models.Product"",""Price"":3000}}");
request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json");
HttpResponseMessage response = new HttpClient.SendAsync(request).Result;

Related

Simple PUT request to API endpoint

I'm trying to PUT JSON to the ElasticSearch api in an effort to index/insert a document in an existing index but I can't find any code examples that will actually work. I've looked at httpClient, httpWebRequests and the elastic .net plugin - NEST.
Everything works fine in something like Postman. How would the below translate to C#?
Here is an example of what I'm trying to PUT in ARC(Advanced Rest Client):
Something like this?
public void PutAPI(string basicAuth, string json)
{
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Add("authorization", $"Basic {basicAuth}");
client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = client.PutAsync("https://mydankapi.com/v1/put", new StringContent(json, Encoding.UTF8, "application/json")).Result;
if (!response.IsSuccessStatusCode)
throw new Exception(response.ReasonPhrase);
}
}
Why didn't NEST meet your requirements? According to their Getting Started - Indexing, you can index a document like this:
var tweet = new Tweet
{
Id = 1,
User = "kimchy",
PostDate = new DateTime(2009, 11, 15),
Message = "Trying out NEST, so far so good?"
};
var response = client.Index(tweet, idx => idx.Index("mytweetindex")); //or specify index via settings.DefaultIndex("mytweetindex");
All you have to do is to create a POCO class for your document type (DataMetadata?) and set the index name to data_metadata I believe.

ACUMATICA: I want to invoke a simple API when a field is updated

I am trying to invoke a simple web request (restful API) when a specific field is updated in Acumatica (when one field in Contact entity is updated on the screen), I know where exactly to put the code, I guess here:
protected void Contact_RowUpdated(PXCache cache, PXRowUpdatedEventArgs e)
{
var row = (Contact)e.Row;
}
How do I invoke this web request, and how can I access the value of a certain custom field from the contact entity?
I tried the following code:
System.Net.Http.HttpClient client = new System.Net.Http.HttpClient();
client.BaseAddress = new System.Uri("....");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept.Add(
new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue("application/json"));
var res = await client.PostAsync(
"", new System.Net.Http.StringContent("...", System.Text.Encoding.UTF8, "application/json"));
But I've got an error that HttpClient doesn't exist in System.Net.Http namespace.
using (var client = new HttpClient(new HttpClientHandler())
I used System.Net.WebClient instead at the end.

Create Master Category Via Microsoft Graph API

Im Trying to create a new category via an event for outlook. Below is what I have so far.
using (var client = new HttpClient())
{
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", AdviserBearerToken);
client.DefaultRequestHeaders.Accep.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var categoryName = new List<string>();
categoryName.Add("New Event");
var startTime = new Time();
var endTime = new Time();
startTime.DateTime = "2016-07-15T15:00:00.0000000";
startTime.TimeZone = "UTC";
endTime.DateTime = "2016-07-15T15:30:00.0000000";
endTime.TimeZone = "UTC";
var eventModel = new EventModelForGraph
{
categories = categoryName,
subject = "This is an event",
Start = startTime,
End = endTime
};
var serializedObject = JsonConvert.SerializeObject(eventModel);
var createBody = new StringContent(serializedObject, System.Text.Encoding.UTF8, "application/json");
var response = await client.PostAsync("https://graph.microsoft.com/v1.0/me/calendar/events", createBody);
var responseString = await response.Content.ReadAsStringAsync();
}
The event shows up in the calendar and the category as the header but it is not listed under the categorize tab which leads me to my question.
Is it possible to create such a category using the API?
I know this is an older question, but I was looking into the same thing and figured I'd post an update. This is now possible with the current version of the Graph API. You can see the documentation here from MSDN. You can create categories by sending a POST API request:
POST https://graph.microsoft.com/beta/me/outlook/masterCategories
Content-type: application/json
Content-Length: 70
{
"displayName":"Project expenses",
"color":"preset9"
}
After the category is created, you can assign it when you create your event by adding the category's displayName property to the categories collection of the item.
You can find more details about when these API endpoints were added here and more details about categories here.
No, you cannot add categories to the master category list via the REST API. You cannot add them directly via any API.
However, you CAN modify the list if you're willing to manipulate the XML directly. The gory details are documented in MS-OXOCFG. You can use EWS for example to access the config item.
This would be a great feature to add to the REST API. You should suggest it on UserVoice.

C# HttpClient send multiform post data

I'm having some issues with calling an API.
I need to send post data containing 2 things: an ID and an array of strings.
I have tried a lot of things, all resulting in errors or simply not sending data in the right way.
All answers I found, do not handle the fact that I want to send 2 different data types.
My current C# code is like this:
HttpClient client = new HttpClient();
client.BaseAddress = new Uri(SERVER_URI);
var content = ; //This is where I need help
HttpResponseMessage response = client.PostAsync("API URL", content).Result;
The API function is set up like this:
public ActionResult Function(int Id, string[] array)
{
// Contents are not relevant
}
The problem here is that I need to be able to set the names for the values.
I have tried serializing the required data to Json with the following code:
StringContent content = new System.Net.Http.StringContent(TypeSerializer.SerializeToString(new { Id = Id, array = array }));
Of course, Id and Array in this example are filled variables.
This results in a successful call to the server, but the server does not receive the data correctly (both variables stay null)
I've also tried doing it with MultiPartContent, but once again I don't see any way to actually give the right names to the values (Every attempt once again results in the API receiving null values)
Edit:
I got it to send the Id using MultipartFormDataContent instead.
MultipartFormDataContent content = new MultipartFormDataContent();
content.Add(new StringContent(Id), "Id");
I still can't seem to get it to send an array to the server though.
Wrap things into an object like this
public class MyPostObject
{
public int Id{get;set;}
public IEnumerable<string> Array{get;set;}
}
then send it as json
using (var client = new HttpClient())
{
var myObject = new MyPostObject(){Id =XXXX, Array = YYYYY};
using (var response = await client.PostAsJsonAsync("api/CONTROLLER/METHOD", myObject))
using (var content = response.Content)
{
var result = content.ReadAsAsync<LoginModelResponse>().Result;
}
}
and receive it as json like this in the server
[HttpPost]
public dynamic METHOD([FromBody] MyPostObject mydata)
{
//Do whatever
}

Retrieve list object from HttpClient call to web api

I am trying to retrieve a list object from Web api via code behind. I have the following code:
var update = new Update();
using (var client = new HttpClient())
{
client.BaseAddress = new Uri("http://localhost:xxxxx/");
client.DefaultRequestHeaders.Accept.Clear();
client.DefaultRequestHeaders.Accept
.Add(new MediaTypeWithQualityHeaderValue("application/json"));
var response = await client.GetAsync("yada yada yada");
var result = response.Content.ReadAsStringAsync();
Where I'm getting confused is how to handle the data coming in so that it is in List<> format. I want to be able to enumerate through the List so I can manipulate the individual updates. When I hit the service with Fiddler, I get either a json or xml array depending on what I set the content-type to, so it works at that point. I just need some help figuring out some content negotiation. Any help is appreciated.

Categories