Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Send JQuery JSON to WCF REST using date

I know that are a lot of posts about consuming a WCF REST through JQuery/JSON, but I can't get it to work. I'm currently stuck at a date parameter. Below is my C# method:

[OperationContract]
[WebInvoke]
[TransactionFlow(TransactionFlowOption.Allowed)]
string GoodRegister(DateTime pDtTimeStampTransac, Int32 pIDResource, Decimal pQty, enQtyLogType pQtyGoodLogType);

Below is my JavaScript code:

/// <reference path="../Scripts/jquery-1.4.1-vsdoc.js" />
/// <reference path="json.js" />

Date.prototype.toMSJSON = function () {
  var date = '\\\/Date(' + this.getTime() + ')\\\/';
  return date;
};

function botaoclick() {
  var date = new Date().toMSJSON();
  var datavar = {
    'pDtTimeStampTransac': date,
    'pIDResource': 1,
    'pQty': 1
  };
  $.ajax(
  {
    type: "POST",
    contentType: "application/json; charset=utf-8",
    url: "http://desk01:9876/ShopFloorService/script/GoodRegister",
    dataType: "json",
    data: JSON.stringify(datavar),
    //data: '{"pDtTimeStampTransac":date, "pIDResource":"teste", "pQty":"3"}',
    error: jqueryError,
    success: function (msg) {
      alert("back");
      var divForResult = document.getElementById("test");
      divForResult.innerHTML = "Result: <b>" + msg.d + "</b>";
    }
  }
  )
}

function jqueryError(request, status, error) {
  alert(request.responseText + " " + status + " " + error);
}

My first problem is that I keep getting a date serialization error:

{"ExceptionDetail":{"HelpLink":null,"InnerException":{"HelpLink":null,"InnerException":{"HelpLink":null,"InnerException":null,"Message":"DateTime content '\\\/Date(1292616078638)\\\/' does not start with '\\\/Date(' and end with ')\\\/' as required for JSON.","StackTrace":"   at System.Runtime.Serialization.Json.JsonReaderDelegator.ParseJsonDate(String originalDateTimeValue)\u000d\u000a   at 

It says it doesn't start/end the way it's starting and ending.

My second question is: Will I have to get ride of the enumerator, or is there a way to send it?

like image 593
Pascal Avatar asked Dec 17 '10 20:12

Pascal


2 Answers

I pulled out a lot of hair and shed plenty a tear over this but this worked. I modified the date formatting in your toMSJSON function. WCF accepts this format which I realised thanks to Rick Strahl.

Date.prototype.toMSJSON = function () {
    var date = '/Date(' + this.getTime() + ')/'; //CHANGED LINE
    return date;
};

You also need to convert the dates to UTC time or you get all kinds of funny stuff, so:

  var dt = ...;
  var dt1 = new Date(Date.UTC(dt.getFullYear(), dt.getMonth(), dt.getDate(),   dt.getHours(), dt.getMinutes(), dt.getSeconds(), dt.getMilliseconds()));
  var wcfDateStr = dt1.toMSJSON();

Hope this helps.

like image 131
Vas Avatar answered Nov 10 '22 12:11

Vas


According to: http://msdn.microsoft.com/en-us/library/bb412170.aspx

DateTime Wire Format

DateTime values appear as JSON strings in the form of "/Date(700000+0500)/", where the first number (700000 in the example provided) is the number of milliseconds in the GMT time zone, regular (non-daylight savings) time since midnight, January 1, 1970. The number may be negative to represent earlier times. The part that consists of "+0500" in the example is optional and indicates that the time is of the Local kind - that is, should be converted to the local time zone on deserialization. If it is absent, the time is deserialized as Utc. The actual number ("0500" in this example) and its sign (+ or -) are ignored.

When serializing DateTime, Local and Unspecified times are written with an offset, and Utc is written without.

The ASP.NET AJAX client JavaScript code automatically converts such strings into JavaScript DateTime instances. If there are other strings that have a similar form that are not of type DateTime in .NET, they are converted as well.

The conversion only takes place if the "/" characters are escaped (that is, the JSON looks like "\/Date(700000+0500)\/"), and for this reason WCF's JSON encoder (enabled by the WebHttpBinding) always escapes the "/" character.

Your enumerator should be fine.

like image 2
Stever B Avatar answered Nov 10 '22 11:11

Stever B