Wednesday 23 April 2014

JSON Date input to WCF Rest service

what's the problem .....in passing date using ajax/JSON method to wcf rest service ,you can read it here ....from Scott and problem here

now you got to pass a date(JSON FORMAT) using ajax/JSON call from asp.net page. ,

I have taken bits of code and modified to my needs from here


using System;
using System.Collections.Generic;
using System.Runtime.Serialization;

namespace SomeNameSpace
{
/// <summary>
/// Class describes the Entities for Persons
/// </summary>
[DataContract(Namespace = "")]
public class Person
{
private int _personId;
private string _emailAddress;
private string _IP;
private DateTime _CreatedOn;
private DateTime _ModifiedOn;
private DateTime _subscribedOn;
private string _statusCD;
private string _sourceCD;


[DataMember]
public virtual int PersonId
{
get
{
return _personId;
}
set
{
_personId = value;
}
}
[DataMember]
public virtual string EmailAddress
{
get
{
return _emailAddress;
}
set
{
_emailAddress = value;
}
}
[DataMember]
public virtual string IP
{
get
{
return _IP;
}
set
{
_IP = value;
}
}
[DataMember]
public virtual DateTime CreatedOn
{
get
{
return _CreatedOn;
}
set
{
_CreatedOn = value;
}
}
[DataMember]
public virtual DateTime ModifiedOn
{
get
{
return _ModifiedOn;
}
set
{
_ModifiedOn = value;
}
}
/// <summary>
/// Gets or sets the subscriptione date.
/// </summary>
/// <value>
/// The subscribed on.
/// </value>
[DataMember]
public virtual DateTime SubscribedOn
{
get
{
return _subscribedOn;
}
set
{
_subscribedOn = value;
}
}
/// <summary>
/// Gets or sets the status cd.this is null when a user unsubscribes
/// </summary>
/// <value>
/// The status cd.
/// </value>
[DataMember]
public virtual string StatusCD
{
get
{
return _statusCD;
}
set
{
_statusCD = value;
}
}
/// <summary>
/// Gets or sets the source cd.To Identify whether a user is valid
/// </summary>
/// <value>
/// The source cd.
/// </value>
[DataMember]
public virtual string SourceCD
{
get
{
return _sourceCD;
}
set
{
_sourceCD = value;
}
}

}
}


                 [OperationContract()]
[WebInvoke(Method = "POST", UriTemplate = "AddUser")]
bool AddUser(Person user);



       
      [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple, InstanceContextMode = InstanceContextMode.PerCall)]
public class TestService : ISubscriberService
{

       public bool AddUser(Person user)
{
            return true;
//Do what ever you want
}
    }


download ww.jquey.js from here

under your aspx page refer <script src="scripts/ww.jquery.js"></script>


<script type="text/javascript">

        var date = new Date();

        EmailAddress = 'varunpathak123@gmail.com';
        SourceCD = 'testapp';

       

        var person =
                        {
                            'IP': "12.22.434",
                            'CreatedOn': date,
                            'ModifiedOn': date,
                            'SubscribedOn': date,
                            'StatusCD': "ACTV",
                            'EmailAddress': EmailAddress,
                            'SourceCD': SourceCD,
                           
                        };







                        person = JSON.stringifyWcf(person);

        function PostData() {
            $.ajax(
                        {
                            type: "POST",
                            url: "http://localhost:9234/AddUser",
                            contentType: "application/json; charset=utf-8",
                            data: person,
                            dataType: "json",
                            success: function (result) {
                             
                                alert("Success");
                            },
                            failure: function (result) {
                                alert("Failure");
                            }
                        });
        }
                   

                 

    </script>

I want to give a vote of thanks again to Rick Strahl. There are plenty of post out there which I tried but did not work for me....apart from this one .
I could have changed my wcf service ,but dates have always been a problem be it any world.

I have highlighted the function JSON.stringifyWCF which looks like this

 JSON.stringifyWcf = function(json) {
        /// <summary>
        /// Wcf specific stringify that encodes dates in the
        /// a WCF compatible format ("/Date(9991231231)/")
        /// Note: this format works ONLY with WCF.
        ///       ASMX can use ISO dates as of .NET 3.5 SP1
        /// </summary>
        /// <param name="key" type="var">property name</param>
        /// <param name="value" type="var">value of the property</param>        
        return JSON.stringify(json, function(key, value) {
            if (typeof value == "string") {
                var a = reISO.exec(value);
                if (a) {
                    var val = '/Date(' + new Date(Date.UTC(+a[1], +a[2] - 1, +a[3], +a[4], +a[5], +a[6])).getTime() + ')/';
                    this[key] = val;
                    return val;
                }
            }
            return value;
        })
    };

one can make out it is specifically targeting dates format.which is always a issue with JSON to WCF


I hope this post will help some one.