none
json v5 RRS feed

  • Question

  • Hi All

    I have upgraded to WCF DataServices 5.0.2 and want to return JSON (for size of data being returned) the service will only be used by a windows forms application. So no AJAX.

    Now I have followed http://blogs.msdn.com/b/astoriateam/archive/2012/04/11/what-happened-to-application-json-in-wcf-ds-5-0.aspx, if I add the accept header below it throws a NOTSupportedException  "The content type 'application/json' is not currently supported."

      Request.Accept = "application/json;odata=verbose";

    Service code to show V3 support


        public static void InitializeService(DataServiceConfiguration config)
        {
          config.SetEntitySetAccessRule("*", EntitySetRights.All);
          config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);

          config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
        }

    Client code

       var DataSource = ConfigurationManager.AppSettings["DataSource"].ToString();
            var ctx = new MyEntities(new Uri(Url));
            ctx.IgnoreResourceNotFoundException = true;
            ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;

    ctx.SendingRequest += delegate(object sender, SendingRequestEventArgs args)
              {
                var Request = ((HttpWebRequest)args.Request);
                Request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;

                Request.Accept = "application/json;odata=verbose";

                Request.Headers.Add("MaxDataServiceVersion", "3.0");

                Request.Proxy = null;
              };

    Friday, September 7, 2012 11:33 AM

Answers

  • Cheers Chris

    That worked, Lesson learnt there that NuGet doesn't install all the Toolsets

    Now all I have to overcome is a the ReadEnitity issue which is not supported yet for json but I'm tracking in another thread.

    Thank for your help

    Ian.

    • Marked as answer by Watty45 Monday, January 28, 2013 9:05 AM
    Monday, January 28, 2013 8:55 AM

All replies

  • The client library of WCF DS currently doesn't support JSON (yet). The only option for the WCF DS client is still ATOM.

    Thanks,


    Vitek Karas [MSFT]

    Friday, September 7, 2012 3:08 PM
    Moderator
  • Hi Vitek

    Ok thanks.

    Is it coming any time soon ? ( it makes such a differnce about half the data transfer )

    Many thanks

    Monday, September 10, 2012 1:30 PM
  • Hi,

    Did you try enabling HTTP compression for the ATOM responses? That should solve the problem as well. The compressed version of ATOM versus JSON difference is usually pretty small (compressed ATOM is still a bit bigger, but it's definitely not twice as big as compressed JSON).

    Thanks,


    Vitek Karas [MSFT]

    Monday, September 10, 2012 2:01 PM
    Moderator
  • The WCF Data Services team is currently working on adding 'Json Light' support to both the server and client. If you are writing a V3 service and looking to cut payload size down, then the upcoming release of WCF DS will help you significantly.

    There is already a NuGet prerelease that includes partial Json Light support on the client (and more on the server).  In NuGet package manager for VS, you need to click the "Include Prereleases" checkbox to see this.  There will be another prerelease very soon that will enable the majority of client's functionality with Json Light. Also, the full release isn't too far out either.

    If you haven't looked at the new 'Json Light' format yet, this is a good starting point: http://www.bitwhys.com/odata-101-what-is-json-light/

    As far as Verbose Json is concerned, we haven't prioritized adding support for it in the client yet, as we foresee Json Light eclipsing Verbose Json moving forward. If there is demand for the old Json format on the client, we can certainly consider supporting it. Since you mention above that you are already on V3, Json Light will likely be right for you. 


    -Ian

    Monday, September 10, 2012 9:54 PM
  • Hi Ian

    Fantastic have downloaded 5.1(rc)

    I get error below

    "Invalid JSON. A comma character ',' was expected in scope 'Object'. Every two elements in an array and properties of an object must be separated by commas."

    Also

    The ReadingEntity and WritingEntity events are only supported when using the Atom format. Use the Atom format or remove all registered handlers for these events before enabling another format

    Do you also have any approximate dates for the release ?

    Regards





    • Edited by Watty45 Tuesday, September 11, 2012 10:13 AM
    Tuesday, September 11, 2012 7:44 AM
  • Hi Ian

    Any update on prevous thread please ?

    Regards

    Paul

    Friday, September 14, 2012 11:46 AM
  • Hi Paul,

    As far as the first bit goes ('Invalid JSON...') I'd more context to be able to help you there. The error message is pretty clear but I'm not sure what led you to it with more more context. Could you show the code that led you to this?

    For the second part, are you listening on the ReadingEntity and WritingEntity events? They are specifically for Atom and not applicable for JSON of any kind, since they give you an XElement which is an XML only concept. In the future we can consider adding similar events for JSON if that's something valuable to our users.

    The 5.1 RC2 should be very soon, so stay tuned :-)


    -Ian

    Friday, September 14, 2012 5:33 PM
  • Hi Ian

    Looking forward to 5.1 rc2

    This is the code below that causes the error, works fine using ATOM.

    Also using Casinni JSON light is returned ok, but in IIS 7.5 I get the following.

    <?xml version="1.0" encoding="utf-8"?><m:error xmlns:m="<m:code">http://schemas.microsoft.com/ado/2007/08/dataservices/metadata"><m:code /><m:message xml:lang="en-GB">Unsupported media type requested.</m:message><m:innererror><m:message>A supported MIME type could not be found that matches the acceptable MIME types for the request. The supported type(s) 'application/atom+xml;type=feed, application/atom+xml, application/json;odata=verbose' do not match any of the acceptable MIME types 'application/json;odata=light'.</m:message><m:type>Microsoft.Data.OData.ODataContentTypeException</m:type><m:stacktrace>   at Microsoft.Data.OData.MediaTypeUtils.GetContentTypeFromSettings(ODataMessageWriterSettings settings, ODataPayloadKind payloadKind, MediaTypeResolver mediaTypeResolver, MediaType&amp; mediaType, Encoding&amp; encoding)&#xD;
       at Microsoft.Data.OData.ODataMessageWriter.EnsureODataFormatAndContentType()&#xD;
       at Microsoft.Data.OData.ODataMessageWriter.SetHeaders(ODataPayloadKind payloadKind)&#xD;
       at Microsoft.Data.OData.ODataUtils.SetHeadersForPayload(ODataMessageWriter messageWriter, ODataPayloadKind payloadKind)&#xD;
       at System.Data.Services.ContentTypeUtil.DetermineResponseFormat(DataServiceHostWrapper host, ODataPayloadKind kind, ODataVersion version, Boolean throwIfNoMatch)</m:stacktrace></m:innererror></m:error>

    Code

     var aList = (from w in r.List<InspectionItem>()
                              where w.Id == O.Id
                              orderby w.Reference ascending
                              select new LookupBinder
                              {
                                Id = w.Id,
                                Code = w.Reference,
                                Description = string.Format("{0} {1}", w.Reference, string.IsNullOrEmpty(w.Description) == false ? string.Format("( {0} )", w.Description) : "")
                              }
                             );

    Monday, September 17, 2012 8:04 AM
  • Hi,

    5.1 RC2 has been released: http://blogs.msdn.com/b/astoriateam/archive/2012/09/26/wcf-data-service-5-1-0-rc2-released.aspx

    Let me know if you have any troubles with the new bits. Code generation and the client itself support most features in JSON Light now.

    With regards to the error above, the message is pretty straight forward; the server only has Atom and Verbose JSON as acceptable MIME types. My guess is that somehow the newer DLLs you are using aren't being referenced correctly when using IIS, but Casinni somehow did pick up the newer DLLs. Take a look at this and make sure your DLL references are correct across the board: http://blogs.msdn.com/b/astoriateam/archive/2012/08/29/odata-101-bin-deploying-wcf-data-services.aspx


    -Ian

    Thursday, September 27, 2012 4:48 PM
  • Hi Ian

    Thanks for the reply, apologies this was the wrong error message. See below

    I flip using Request.Accept = "application/json;odata=verbose"; and get error, remove and run again to use atom and it works fine.

    There is a type mismatch between the client and the service. Type 'System.Nullable`1[[System.Int32, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]' is not an entity type, but the type in the response payload represents an entity type. Please ensure that types defined on the client match the data model of the service, or update the service reference on the client.
       at System.Data.Services.Client.Materialization.ODataMaterializer.CreateMaterializerForMessage(IODataResponseMessage responseMessage, ResponseInfo responseInfo, Type materializerType, QueryComponents queryComponents, ProjectionPlan plan, ODataPayloadKind payloadKind)
       at System.Data.Services.Client.MaterializeAtom..ctor(ResponseInfo responseInfo, QueryComponents queryComponents, ProjectionPlan plan, IODataResponseMessage responseMessage, ODataPayloadKind payloadKind)
       at System.Data.Services.Client.DataServiceRequest.Materialize(ResponseInfo responseInfo, QueryComponents queryComponents, ProjectionPlan plan, String contentType, IODataResponseMessage message, ODataPayloadKind expectedPayloadKind)
       at System.Data.Services.Client.QueryResult.CreateMaterializer(ProjectionPlan plan, ODataPayloadKind payloadKind)
       at System.Data.Services.Client.QueryResult.ProcessResult[TElement](ProjectionPlan plan)
       at System.Data.Services.Client.DataServiceRequest.Execute[TElement](DataServiceContext context, QueryComponents queryComponents)


    Friday, September 28, 2012 7:15 AM
  • So, first off, the new bits are enabling the new JSON format (JSON Light) on the client. The accept header for that would be application/json;odata=minimalmetadata in usual circumstances (you can also specify odata=nometadata or odata=fullmetadata, but that is probably not important to you).

    However, to use JSON on the client, you do not override the accept header like this. Instead call context.Format.UseJson(). Additionally, you must provide an IEdmModel so the lightweight JSON format can be deserialized. The new bits include an upgrade to code generation that includes that model, so if you use Add Service Reference in VS, then all you need to do is call context.UseJsonFormatWithDefaultServiceModel(), and JSON light will start working out of the box with the service that you generated client classes for.

    Please note that we are still making some tweaks to the APIs here to make them as friendly as possible for the RTW, so expect a change in how you enable JSON light on the client between from the RC2 to RTW. 


    -Ian

    Monday, October 1, 2012 5:03 PM
  • Hi

    We have upgraded to 5.2 rtm. How do we now use the client library use JSON ?

    Regards

    Paul


    • Edited by Watty45 Friday, January 4, 2013 12:08 PM
    Friday, January 4, 2013 12:01 PM
  • As Ian noted above: call context.UseJsonFormatWithDefaultServiceModel().

    Thanks,


    Vitek Karas [MSFT]

    Friday, January 4, 2013 1:09 PM
    Moderator
  • This was actually changed between 5.1/5.2rc1 and 5.2 RTM you should now call context.Format.UseJson(), this will use the JSON (light) format with the default model.

    Regards

    Uffe



    Friday, January 4, 2013 1:48 PM
  • Thanks Uffe for the right information... and sorry for the wrong one (I just checked an old sample).

    Vitek Karas [MSFT]

    Friday, January 4, 2013 4:21 PM
    Moderator
  • Hi

    we tried below

            ctx.Format.LoadServiceModel();
            ctx.Format.UseJson();

    we get the error below, how do we get the IedmModel into the LoadServiceModel() ?

    When you call the UseJson method without a parameter, you must use the LoadServiceModel property to provide a valid IEdmModel instance.

    Also tried this http://www.bitwhys.com/odata-101-enabling-json-light-from-the-wcf-ds-5-1-0-rc1-client/ but now doesn't compile

    Regards

    Ian

    Tuesday, January 22, 2013 11:26 AM
  • Hey Ian,

    The edmModel for the service can be retrieved from the Service.svc/$metadata endpoint.

    If you want you can use the $metadata endpoint to regenerate the client layer. What we do is embed the $metadata edm document into the generated file and then use this so that you can call UseJson() without a model specified.

    I'm not sure why things don't compile, but you should use the newly released 5.2 instead.

    Thanks,

    Chris Robinson - Wcf Data Services


    This posting is provided "AS IS" with no warranties, and confers no rights.

    Tuesday, January 22, 2013 10:00 PM
    Moderator
  • Hi Chris,

    Just to clarify, I'm using 5.2, I tried rebuilding the service from the $metadata but to no avail

    our code is as follows

    if we included the LoadServiceModal it fails with NullReferenceException Object reference not set to an instance of an object.

    if we don't include it the UseJSON line fails with an InvalidOperationException
    When you call the UseJson method without a parameter, you must use the LoadServiceModel property to provide a valid IEdmModel instance.
    Catch 22 as we don't have the modal

    static public Reference.Entities Context
    {
     get
     {
      .
      .
      .
      var ctx = new Entities(new Uri(Url));
      ctx.IgnoreResourceNotFoundException = true;
      ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
      ctx.Format.LoadServiceModel();
      ctx.Format.UseJson();

            .
      .
      .
      return ctx;
     }
    }

    I've also check all the assemblies and they are 5.2, also can you refer me to any update documentation relating to this.

    Thanks for Help

    Ian

    Wednesday, January 23, 2013 10:39 AM
  • Hey Ian,

    Can you post the exact stack of the error that occurs for you? Also if possible can you send me an email with the model the code that is generated to my email so that I can investigate this further?

    Thanks,

    Chris Robinson  - WCF Data Services Team


    This posting is provided "AS IS" with no warranties, and confers no rights.

    Wednesday, January 23, 2013 5:22 PM
    Moderator
  • Yo Chris

    LoadServiceModel = null so comes back with "Object reference not set to an instance of an object." , so no stack.

    UseJson = "When you call the UseJson method without a parameter, you must use the LoadServiceModel property to provide a valid IEdmModel instance" , there no inner exception

    Just to clarify
    I used NuGet to get all the 5.2 package
    I am using Visual Studio 2010 SP 1 and .net 4
    I’ve updated the service reference using the Meta
     
    Can you verify our code is fundamentally right
    var ctx = new PIMSEntities(new Uri(Url));
    ctx.IgnoreResourceNotFoundException = true;
    ctx.Credentials = System.Net.CredentialCache.DefaultCredentials;
    ctx.Format.LoadServic
    eModel();
    ctx.Format.UseJson();

    when you said regenerate the client layer , I update the service from the $MetaData endpoint, was that correct.

    I can email the modal as requested but are we talking the entity modal, the service generate code or endpoint metadata.

    Thank you for your assistance.

    Ian

     

    Thursday, January 24, 2013 3:15 PM
  • Did you install the 5.2 msi on your development machine? There is an update to the code generation tool set. When you use the correct version of code generation the useJson works. I suspect that you are using an older version and what is generated is not correct or complete. You shouldn't have to call LoadServiceModel() on a correctly generated code gen file.

    Thanks,

    Chris Robinson - WCF Data Services


    This posting is provided "AS IS" with no warranties, and confers no rights.

    Thursday, January 24, 2013 3:30 PM
    Moderator
  • Cheers Chris

    That worked, Lesson learnt there that NuGet doesn't install all the Toolsets

    Now all I have to overcome is a the ReadEnitity issue which is not supported yet for json but I'm tracking in another thread.

    Thank for your help

    Ian.

    • Marked as answer by Watty45 Monday, January 28, 2013 9:05 AM
    Monday, January 28, 2013 8:55 AM
  • Hi,

    I have also faced same issue while using REST service with visual studio 2012 while the service using linq to sql server. the DataServiceProtocolVersion is the issue it should be synchronised

    Monday, July 1, 2013 7:22 AM