Discussions

Ask a Question
Back to All

Unsupported Media Error -- Can we get a simple C# PUT example that uses something other than REST SHARP?

I couldn't resist formatting my question in the Bruce Wilson style (that he hat-tipped back to me. Thanks Bruce ha)...

Can we get a simple C# REST PUT example that does not use REST Sharp. Maybe something that uses HttpClient?

I get Unsupported Media Type no matter what I do. I think it has to do with Encoding or Charset but I don't know which one to send....

This code is the latest I produced to get the Unsupported Media Error
static async Task createEvent(string id)
{
//ZEX18AB197
//ZPEX182820
var settings = new JsonSerializerSettings();
settings.TypeNameHandling = TypeNameHandling.Objects;

        // Create the client
        using (var client = new HttpClient())
        {
            // Format headers
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            //client.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("UTF8"));
            // Request token, and append to headers
            await AddTokenToHeaders(client);

            EventData eventNew = new EventData();
            var responseEvent = await client.GetAsync(baseUrl + EVENT_REST_QUERY + "/" + id);
            if (responseEvent.IsSuccessStatusCode)
            {
                // Deserialize response to DataContract
                eventNew = await responseEvent.Content.ReadAsAsync<EventData>();
            }
            EventFunctionData eventFunction = new EventFunctionData();
            eventFunction.Description = "TestFunc3";
            eventFunction.EventFunctionCode = "TestFunc3";
            eventFunction.EventFunctionId = "TestFunc3";
            eventNew.Functions.Add(eventFunction);


            string Serialized = JsonConvert.SerializeObject(eventNew);               
            HttpContent content = new StringContent(Serialized, System.Text.Encoding.Unicode, "application/json");
            //byte[] encodedBytes = System.Text.Encoding.UTF8.GetBytes(json);
            //System.Text.Encoding.Convert(System.Text.Encoding.UTF8, System.Text.Encoding.Unicode, encodedBytes);

            var response = await client.PutAsync(baseUrl + EVENT_REST_QUERY + "/" + id, content);
            if (response.IsSuccessStatusCode)
            {
                // Deserialize response to DataContract
                eventNew = await response.Content.ReadAsAsync<EventData>();
            }
            }
    }

This results in a Unsported Media Type error on PUT

Thanks

Good afternoon Jack,

Have you tried out the simple starter boilerplates shown here?

https://developer.imis.com/docs/accessing-the-rest-api#section-direct-access-oauth-20

Those, although narrow in scope, might be more up your alley.

Thanks,

  • Jeremy

This is the actual error in the EventViewer

Could it be that there are required fields or required DataContracts on an event when adding a function that are not documented? Or is this object not serializable?

2018-09-12 17:25:38,928 [70] ERROR SVR-GAMMA:IMIS [(null)] - Error occured at Uri: https://customer.uspta.org/asi.scheduler_imis/api/event/ZPEX182820
System.InvalidCastException: Unable to cast object of type 'Newtonsoft.Json.Linq.JObject' to type 'Asi.Soa.Events.DataContracts.EventData'.
at Asi.Services.Core.EntityServiceToCommonServiceAdapter1.Update(Object dataContract) at Castle.Proxies.Invocations.ICommonService_Update.InvokeMethodOnTarget() at Castle.DynamicProxy.AbstractInvocation.Proceed() at Asi.Shared.Aspects.CacheAspect.Intercept(IInvocation invocation) in C:\Builds\208\ScrumV3\sp137_Main10\Sources\MainFoundation\imis.net\Packages\Platform\Asi.Shared\Aspects\CacheAspect.cs:line 62 at Castle.DynamicProxy.AbstractInvocation.Proceed() at Asi.Services.Core.Interceptors.CommonSecurityAspect.Intercept(IInvocation invocation) at Castle.DynamicProxy.AbstractInvocation.Proceed() at Asi.Services.Core.Interceptors.ServiceTaskTriggerInterceptor.Intercept(IInvocation invocation) at Castle.DynamicProxy.AbstractInvocation.Proceed() at Asi.Shared.Aspects.PerformanceAspect.Intercept(IInvocation invocation) in C:\Builds\208\ScrumV3\sp137_Main10\Sources\MainFoundation\imis.net\Packages\Platform\Asi.Shared\Aspects\PerformanceAspect.cs:line 55 at Castle.DynamicProxy.AbstractInvocation.Proceed() at Castle.Proxies.ICommonService1Proxy_28.Update(Object dataContract)
at Asi.Scheduler.Controllers.CommonServiceController.Put(String entityName, String entityId, Object entity)

Jeremy, yes the code uses the boilerplate options your suggest. I really need the PUT option. I get an Unsupported Media Type every time. I can POST, I can GET, I can delete...but I cannot serialize to JSON the EventData

My goal is to Create an EventFunction but I cannot get past UnsupportedMediaType after days and weeks of trying.

I posted code, but I believe it is a server-side issue with Encoding or Charset or something...
Jack

Jack,

You can try to use postman and the asi examples.

  1. Install Postman [1]: https://www.getpostman.com/
    2 Use the examples from the ASI github iMISRESTCollection repository [1]: https://github.com/Advsol/iMISRESTCollection

-Daryl

Admin(edited)

Jack,

Would a PUT example using another entity such as PartyData work for your example or are you really most interested in EventData and EventFucntionData. We're tracking down all the initialization that is required in this event function case but wanted to see if a simpler example would suffice in the short term.

PartyData is great at this point.

Hey Jack,

Jeremy here, just wanted to give you a verbose update on your attempt to create and tie event functions to an existing event. Admittedly, it's a bit cumbersome relative to other entity updates due to the amount of structure inherent to it, but hopefully I can put you on the right path as much as possible.

For event functions in particular, we'll need to chain a few calls to iMIS to ensure we've got every bit of data filled out for the application to utilize it safely throughout the various scenarios that entity might find itself in. This involves POSTing to both the Product and Product_Function endpoints prior to PUTting to the Event endpoint. You can take advantage of of the GenericEntityData contract with iMIS for the first two calls, which I'll demonstrate below as two simple REST calls to their respective endpoints -

POST to /api/Product with a payload much like the one here. The important fields here to keep in mind would be the initial identity value (in this case, ANNCONF/DINNER, our new function tied to the Annual Conference event), as well as the PRODUCT_CODE, PRODUCT_MAJOR, and PRODUCT_MINOR fields, as varying representations of the aforementioned ID. Programatically, we'll also have to ensure ProductKey is a unique GUID.

POST to /api/Product_Function/[Event ID here, such as ANNCONF] with a payload much like one here. Much like before, we'll tie this to the previously made product with the ANNCONF/DINNER identity value being passed in, as well as the PRODUCT_CODE with the same value.

I've then merged a bit of the boilerplate code I mentioned prior along with some of the code you had written out utilizing our client library to create the following class that you can find here. The pertinent method begins at line 71. I've set some of the event function fields to newer values to showcase the PUT working as intended. I've neglected to add the first two POSTS as code within this class, although if you'd like me to look into some recipes or best practices when working with that kind of data, please let me know.

Admin

Jack, here is an example of a simple put where I show how to make a minor update to a person. Note one difference between your example and mine. In your example I see you initialize JsonSerializerSettings but I don't see you pass it in your call to JsonConvert.SerializeObject. See my example, line 106. I hope this helps.

Stacey and Jeremy

I haven't tried either solution yet - but thank you (in caps) in advance for the samples and for re-engineering my code. I don't want to clutter up this post with "thank-you's" that might spoil the reading for others -- until I can provide a solution. But, should all go well I will post a solution here with commented code for all to use and share.

I'm sure I have passed settings in one of my versions in that add and remove the $type designation...but, if this works on your end - I can say we have a REST configuration problem on my end! And that - would be great to know as well.

I can then move to the Event and Event_Function creates...which definitely needed further explanation from a long-time iMIS user-perspective here. I was obviously not clear on the Product table POST's and PUT's. You obviously see they are completely missing.

Thanks again in advance and I'll post again....

Jack Donahue

Hi Stacey.
Your POST for Token never returns

So this statement does not work for me at least in VS 2013 which is admittedly old - but I have new HttpClient packages installed. We may need to compare versions - but do you have any thoughts?

        // POST to the iMIS token endpoint with form-encoded data set, which should be modified to
        // correspond to your iMIS instance's MANAGER/RemoteService user
        var response = Client.PostAsync("token", new FormUrlEncodedContent(new[]
        {
            new KeyValuePair<string, string>("grant_type", "password"),
            new KeyValuePair<string, string>("username", "XXXXXXX"),
            new KeyValuePair<string, string>("password", "XXXXXXX")
        })).Result;
Admin

Jack, I had left off a trailing / in the BaseAddress. I've updated it online. To update yours, it should be as follows (on line 22):
BaseAddress = new Uri("https://testapi.imis.com/Asi.Scheduler_SDKDemo/")
Try that and see if it fixes the problem.

I did that before and still no luck.
I noticed that early on

Admin

Hmm, that was taken from the other boilerplate code examples. Did that work for you in your example project that you derived from the boilerplate? Just trying to understand if you are only seeing the problem with my example or all of the boilerplate examples? BTW, my project is VS 2017 with target framework 4.62. System.Net.Http version is 4.0.30319.

I am going to load this to VS 2017 and try again.

I had been afraid to migrate this particular code piece from 2013 (B.C) ... but Friday is one fine day for an Upgrade.

Be back shortly- I'm somewhat positive we will find success here today.... with all of your help.

Jack

I built this project with a total solution from REST I obtained (somehow) from ASI. That ASI_SAMPLE namespace was written and much of the code was provided. I had major problems early on.

The solution also tries the boilerplate code in VS2013 to no avail.

However, I have some good working VS 2017 at another client...

THIS ATTEMPT (which fails with HttpClient for one reason or another):
Visual Studio 2013 (with major Web updates)
Target ASPNET 4.62

OK - we have some movement.

The code provided above by Jeremy for the Simple PUT works PERFECTLY in 2017 - but probably everyone already knew that.

Don't try to do what I did and use VS 2013 for this process... hindsight being 20/20 (and not wanting or hoping to modify all of the other existing 2013 code - I did not try 2017).

To be continued Monday.

Thanks to everyone for the support this week. Truly... genuine... Thanks.

Jack D.

WOW. Commentary and a few changes and comments forthcoming.

Austin/Houston - We have working Event Function creation code....

To be continued...

Jack Donahue

Marked as answered by Jeremy Cantu

ο»Ώ

Contact us
Copyright Β© Advanced Solutions International, All rights reserved.