Thursday, 19 January 2012

Complex Data Types And DataContractJsonSerializer:-

XmlSerializer is the serializer in .NET for many years.The Serialize and Deserialize methods of XmlSerializer are used to Serialization and Deserialization respectively.

DataContractSerializer is new in .NET 3.0.The WCF services by default uses the DataContractSerializer for Serialization.It is faster than XmlSerializer.


namespace Serialization
{
    public class Main
    {
        //convert the object to json
        public void Serialize()
        {
            //create class object
            ClassRoom objClass = new ClassRoom();

            //assign name
            objClass.Name = "MCA";

            //list of students
            List<Student> objList = new List<Student>();

            //create student object
            Student objStudent = new Student();

            //assign name
            objStudent.Name = "Sekhar";

            //assign Age
            objStudent.Age = 24;

            //student birthday
            objStudent.DOB = DateTime.Now;

            //student status
            objStudent.Status = Status.UnEmployed;

            //adding student to list
            objList.Add(objStudent);

            //assign student object
            objClass.Students = objList.ToArray();

            //json serializer
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ClassRoom));

            //memory stream
            MemoryStream ms = new MemoryStream();

            //write object to stream
            ser.WriteObject(ms, objClass);

            //read the json string from stream
            string json = Encoding.Default.GetString(ms.ToArray());
        }

        //convert the json to object
        public void DeSerialize()
        {
            //json string
            string Json = "{\"Name\":\"MCA\",\"Students\":[{\"Age\":24,\"DOB\":\"\\/Date(1326975142299+0530)\\/\",\"Name\":\"Sekhar\",\"Status\":2}]}";

            //json serializer
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(ClassRoom));

            //memory stream for json string
            MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(Json));

            //read object from strem
            ClassRoom objClassRoom = (ClassRoom)ser.ReadObject(ms);
        }
    }

    [DataContract]
    public class ClassRoom
    {
        //class name
        [DataMember]
        public string Name { get; set; }

        //list of students
        [DataMember]
        public Student[] Students { get; set; }
    }

    [DataContract]
    public class Student
    {
        //student name
        [DataMember]
        public string Name { get; set; }

        //student age
        [DataMember]
        public int Age { get; set; }

        //student birthday
        [DataMember]
        public DateTime DOB { get; set; }

        //student status
        [DataMember]
        public Status Status { set; get; }

    }

    //enum for student status
    public enum Status { Employed, UnEmployed, Student };
}



Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com





Tuesday, 17 January 2012

Wcf webHttpBinding And XMLHttpRequest:-

WcfService:-
namespace WebHttpBindingXmlHttpRequestWcf
{
 [ServiceContract(Namespace = "WebHttpBindingXmlHttpRequestWcf")]
 public interface IService
  {
    [OperationContract]
          string GetData(string input);
   }
}    


namespace WebHttpBindingXmlHttpRequestWcf
{ 
   public class Service : IService
    {  
     public string GetData(string input)
          
{
  
       string output = "You Enter "+ input;
        return output;
          
}
      
}
}

<system.serviceModel>
   <services>
     <service name="WebHttpBindingXmlHttpRequestWcf.Service">
       <endpoint address="webHttpBinding" 
binding="webHttpBinding" 
contract="WebHttpBindingXmlHttpRequestWcf.IService"
behaviorConfiguration="webHttpBindingEndpointBehavior">
       </endpoint>
     </service>
   </services>
    <behaviors>
       <endpointBehaviors>
         <behavior name="webHttpBindingEndpointBehavior">
           <enableWebScript/>
         </behavior>
       </endpointBehaviors>
   </behaviors>
 </system.serviceModel>



JavaScript File:-

//calling wcf service
function callservice(){

//create XMLHttpRequest object
var xmlHttp = new XMLHttpRequest();

//event handler for getting result
xmlHttp.onreadystatechange = function () {
    //check the status of the request(if the status is 4 then all the data is received)
      
if (xmlHttp.readyState == 4) 
       
{
      //here you  get the data.      
         
//alert the result   
          
alert(xmlHttp.responseText);
       
}
};


//error event handler 
xmlHttp.onerror = function (e) {
    //alert the user
    alert('error occurred…');
};


//url of the service
var url = "http://localhost:1094/Service.svc/webHttpBinding/";

//method name
url = url + "GetData";


//here we are passing data to wcf service
var body = '{"input":"1"}';
                                                        
//here we are passing the method type,url and operation type(true for async,false for sync)
xmlHttp.open("POST", url, true);

//adding  header for sending data type(json)
xmlHttp.setRequestHeader("Content-type", "application/json");

//calling service function
xmlHttp.send(body);
} 





Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Friday, 6 January 2012

Wcf basicHttpBinding And XMLHttpRequest

We can access the wcf basicHttpBinding service in the XMLHttpRequest,but we must now the SOAP format of the service methods.To know the SOAP format of wcf service mathods we can use wcftestclient which is exist in wcf sdk.

WcfService:-
namespace BasicHttpBindingXmlHttpRequestWcf
{
 [ServiceContract(Namespace = "BasicHttpBindingXmlHttpRequestWcf")]
 public interface IService
  {
      [OperationContract]
          string GetData(string input);
   }
}   


namespace BasicHttpBindingXmlHttpRequestWcf
{
   public class Service : IService
    { 
     public string GetData(string input)
          {
         string output = "You Enter "+ input;
        return output;
          }
      }
}

<system.serviceModel>
   <services>
     <service name=" BasicHttpBindingXmlHttpRequestWcf.Service">
       <endpoint address="" binding="basicHttpBinding" contract=" BasicHttpBindingXmlHttpRequestWcf.IService">
       </endpoint>
         </service>
   </services>
</system.serviceModel>

JavaScript File:-

//calling wcf service
function callservice(){

//create XMLHttpRequest object
var xmlHttp = new XMLHttpRequest();

//event handler for getting result
xmlHttp.onreadystatechange = function () {
    //check the status of the request(if the status is 4 then all the data is received)
      if (xmlHttp.readyState == 4)
       {
      //here you  get the data in SOAP(xml) format.we have to iterate through xml to get the result.      
        //alert the result  
        alert(xmlHttp.responseText);
       }
};


//error event handler
xmlHttp.onerror = function (e) {
    //alert the user
    alert('error occurred…');
};


//url of the service
var url = “http://localhost:4040/Service.svc”;


//here we are constructing the request in SOAP format
var body="<s:Envelope xmlns:s='http://schemas.xmlsoap.org/soap/envelope/'>"
                 + "<s:Body>"
                + "<GetData xmlns='BasicHttpBindingXmlHttpRequestWcf'>"
                + "<input>123</input>"
                + "</GetData>"
       + "</s:Body>"
       + "</s:Envelope>";

                                                        
//here GetData is service method name.xmlns is the namespace name in ServiceContract .   The parameter name(input) must match with parameter name in OperationContract.

//here we are passing the method type,url and operation type(true for async,false for sync)
xmlHttp.open("POST", url, true);

//adding  header for sending data type(xml)
xmlHttp.setRequestHeader("Content-type", "text/xml; charset=utf-8");

//adding  header for SOAPAction(Avialable In WSDL with  Same Name.)
xmlHttp.setRequestHeader("soapAction","BasicHttpBindingXmlHttpRequestWcf/IService/GetData");

//calling service function
xmlHttp.send(body);
} 





Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com

Crossdomain Calls Using Jsonp:-

Using the XMLHttpRequest we can't make crossdomain calls.For crossdomain calls in javascript we have to use jsonp approach.

JavaScript File:-
 
 //jquery's document ready event
$(document).ready(function () {
      //url of server page
      var url='http://localhost:2437/CrossDomainServerPage.aspx';

      //callback function name
      var cbfunction='callback';

      //here we are passing the callback function name in the querystring parameter jsonp.     

      call(url + "?jsonp=" + cbfunction);


});
  //function which is used to make the crossdomain request.

 function call(url) {
                 //create the script element
                 var script = document.createElement('script');
              
                 //add the attribute type
                 script.type = 'text/javascript';

                 //add the attribute url
                 script.src = url;
          
                //here we are using the jquery to add the script element to body
                $("body").append(script);
      }

//function which is called from cross domain server page
 function callback(res) {
      //the res is result coming from the cross domain server page
      //alert the result
      alert(res.x + ' : ' + res.y);
}

CrossDomainServerPage.aspx File:-

//the page load event
protected void Page_Load(object sender, EventArgs e){


 //checks whether the jsonp variable is null or not
 if (!string.IsNullOrEmpty(Request.QueryString["jsonp"]))
  {

    //here we get the callbak function name
   

    string Callback = Request.QueryString["jsonp"];   
  
    //call the javascript callback function      
         Response.Write(Callback +"( {\"x\":10 , \"y\":100} );");

    //ends the response
    Response.End();
  }
}



Let me know, if you have any feedback. Mail me for source code. Enjoy reading my articles…
sekhartechblog@gmail.com