Friday 4 December 2015

Serialization of .NET classes into JSON object in C#.Net ?

What is Serialization  ?

Serialization is a programming technique that converts an object in memory to a sequence of bytes. The serialized data is suitable for storage in files and databases, and can be sent to other computer systems across network protocols.

you will see how to use features built-in to the .NET framework to serialize objects to JavaScript object notation (JSON). JSON stores objects and collections of objects in a human-readable, structured text format, and is commonly used in client/server architectures because of its high level of compatibility across a wide range of client programming languages.

.NET Framework Classes

In version 3.5 (and in later versions) of the .NET framework, classes for serializing and deserializing to JSON are included in the framework. The main classes you will use are in System.Runtime.Serialization and System.Runtime.Serialization.Json.

The general process for serializing and deserializing JSON from C# is:


  • Add a reference to the System.Runtime.Serialization library.
  • Add using directives for System.Runtime.Serialization and System.Runtime.Serialization.Json.
  • Define classes for the objects represented using DataContract and DataMember attributes.
  • Create an instance of DataContractJsonSerializer.
  • Use WriteObject() to serialize an object to a stream.
  • Use ReadObject() to deserialize an object from a JSON stream.



Classes and Service Contracts

DataContracts are agreements between clients and servers that describe the information that is to be exchanged between them. Windows Communication Foundation (WCF) uses these extensively, however, you only need a small familiarity with them to use the DataContractJsonSerializer.


The DataContract attribute is used to mark a class as suitable for serialization/deserialization by the DataContractJsonSerializer. The example below defines a class with the minimum attributes needed to work with the serializer.



The attribute DataMember can also be used to control certain elements in the serialization and deserialization process. It has five properties:


Property Name


  1. EmitDefaultValue:- Sets whether or not to serialize the default values for the fields and properties being serialized.
  2. IsRequired:-  Whether the member must be present in the JSON code when deserializing.
  3. Name :- The name of the member when serialized.
  4. Order:- The order of the serialization or  deserialization.
  5. TypeId :-  With derived classes, TypeId is a unique  identifier for this attribute.
Attribute properties are included in the DataMember attribute by specifying the property name and value in parenthesis as shown in this modified version of the UserReg class.




[DataContract]
    class UserReg
    {
        [DataMember(IsRequired = true)]
        public String FirstName;

        [DataMember]
        public String LastName;

        [DataMember(IsRequired = true)]
        public String Gender;

        [DataMember(Name = "EmailAddress", IsRequired = true)]
        public String EmailID;

        [DataMember(IsRequired = true)]
        public String MobileNo;

        [DataMember]
        public String Country;

        [DataMember]
        public String State;

        [DataMember]
        public String City;

        [DataMember]
        public String Address;

        [DataMember]
        public int PinCode;
    }




The example above uses the name property to change how the member EmailID appears in the serialized output. It also marks all members, apart from icon, as required.

Specifying the attribute properties can be useful when building a contract to an existing service that uses names that cannot be used in your class. When serialized,


Serialization with the DataContractJsonSerializer

To serialize a .NET object to JSON, you must create an instance of DataContractJsonSerializer. The constructor for this class has one parameter: a reference to the type of .NET object that is to be serialized or deserialized.

Use the method WriteObject() to perform the serialization and send the output to the specified stream. It can work with most streams that are derived from System.IO.Stream – such as file streams, memory streams, and network streams.



class TestSerialization
    {
        static void Main(string[] args)
        {
            UserReg userReg = new UserReg()
            {
                FirstName = "Rampal",
                LastName = "Singh",
                Gender = "Male",
                EmailID = "rampal.singh0586@gmail.com",
                MobileNo = "8861447949",
                Country = "India",
                State = "Uttar Pradesh",
                City = "Moradbad",
                Address = "Prakash Nagar",
                PinCode = 244255
            };

            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserReg));
            MemoryStream ms = new MemoryStream();
            js.WriteObject(ms, userReg);

            Console.WriteLine("\r\nSerializing of .NET Class into JSON Object in C#\r\n");
            ms.Position = 0;
            StreamReader sr = new StreamReader(ms);
            Console.WriteLine(sr.ReadToEnd());
            sr.Close();
            ms.Close();
            Console.ReadKey();

        }
    }




The code above produces the following JSON output:
















Deserialization with the DataContractJsonSerializer

Deserialization takes JSON-formatted data and converts it into a .NET object in memory. As with serialization, this relies on using an instance of DataContractJsonSerializer. Generally speaking, you will be loading JSON data from a stream (most likely a network stream from communicating with a web server), however, in this example the JSON is hardcoded into a string and then accessed through a MemoryStream.

To deserialize JSON from a stream, use the method ReadObject(). This returns an Object type that you can cast to the desired class.


class TestSerialization
    {
        static void Main(string[] args)
        {

String userData = "{ \"FirstName\": \"Rampal\", \"LastName\": \"Singh\", \"Gender\": \"Male\", \"EmailAddress\": \"rampal.singh0586@gmail.com\", \"MobileNo\": \"8861447949\", \"Country\": \"India\", \"State\": \"Uttar Pradesh\" , \"City\": \"Moradabad\" , \"Address\": \"Prakash Nagar\", \"PinCode\": \"244255\"}";

            DataContractJsonSerializer js = new DataContractJsonSerializer(typeof(UserReg));
            MemoryStream ms = new MemoryStream(System.Text.ASCIIEncoding.ASCII.GetBytes(userData));

            UserReg userreg = (UserReg)js.ReadObject(ms);
            Console.WriteLine("\r\nDeserializing JSON object into .NET class Object in C#\r\n");
            Console.WriteLine("User Name: " + userreg.FirstName + "' '" + userreg.LastName);
            Console.WriteLine("Address: " + userreg.Address);
            ms.Close();

            Console.ReadKey();
       }
  }


Output Result:-
















In the above post I explain with example how to Serialization  the .NET classes into JSON objects and Deserialization back into .NET classes as objects. I hove this post very useful to you. I request you to please comments your feedback and questions here. Thamk Your

Thursday 1 October 2015

WCF REST sample web service

I  this post will explain very basic sample WCF REST Service with example for beginers.

What is WCF :-
.NET provides various options for creating services under .NET Framework. Before WCF, ASP.NET Web Services are used to ceate service in .NET Framework. Now WCF is the latest programming model for building and developing service-oriented application. WCF allows applications to communicate with each other in distributed environment. WCF is a set of technologies that covers ASMX web services, Web Services Enhancements (WSE), .NET Remoting and MSMQ. In this article, you will learn How to create and consume your WCF application from client app.

Task List

  • WCF application (REST)
  • 1 Database Table, 1 Stored Procedure to fetch Employee salary.
  • Client Application(ASP.NET app)

Creating WCF app:-

Open your Visual Studio go to file menu then select new project one window  will open. Now in left tab Select WCF and in right tab select WCF Service Application and choose your app name, location then clock on OK button. See below




Now your WCF application is ready. It contains one Interface IService1.cs and one Service class Service1.cs .





using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace WCF_Sample_REST_Service
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface
    //name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {
        [OperationContract]
        [FaultContract(typeof(string))]

        // UriTemplate for REST Service
        // UriTemplate = "formate?Param1={EmpId}&Param1={EmpName}"
        [WebInvoke(Method = "POST", UriTemplate = "Json?EmpId={EmpId}&EmpName={EmpName}",
        RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Wrapped)]
        string GetEmpSalary(string EmpId, string EmpName);
    }

}


Service class:-

In below Service class I implimented above method see below


using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
using System.Web.Configuration;
using System.Data;
using System.Data.SqlClient;

namespace WCF_Sample_REST_Service
{
   // REST WCF sevice...
    public class Service1 : IService1
    {
            // first I will create an Instance of SqlConnection
        static String conString = WebConfigurationManager.ConnectionStrings["TestWebCon"].ConnectionString;
        static SqlConnection con = new SqlConnection(conString);

        public string GetEmpSalary(string EmpId, string EmpName)
        {
            string result = string.Empty;
            SqlCommand cmd = new SqlCommand("[dbo].[getEmployeeSalary]", con);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("@EmpId ", EmpId);
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataSet ds = new DataSet();
            da.Fill(ds);
            if (ds.Tables[0].Rows.Count > 0)
            {
                result = ds.Tables[0].Rows[0].ItemArray[0].ToString();
            }

            else
            {
                result = "Record not found!";
            }
            return result;
        }
     
    }
}



Note:- You can replace your Interface and service class code  by above code.



Now I will Create a database table  tblEmpMaster.

CREATE TABLE [dbo].[tblEmpMaster](
       [EmpID] [int] NOT NULL,
       [EmpName] [varchar](100) NOT NULL,
       [EmpSalary] [int] NULL,
       [Age] [int] NULL

) ON [PRIMARY]

Let me Insert some records in the above table 

USE [Employee]
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (101, N'Ram', 50000, 28)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (102, N'Naveen', 22000, 25)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (103, N'Neetu Singh', 17000, 27)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (104, N'R. P Singh', 62000, 23)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (105, N'Mohit', 27000, 24)
GO
INSERT [dbo].[tblEmpMaster] ([EmpID], [EmpName], [EmpSalary], [Age])
 VALUES (106, N'Amit', 15000, 26)

GO

And let me create Stored Procedure also

USE [Employee]
GO
Create Procedure [dbo].[getEmployeeSalary]
as
begin
SELECT [EmpSalary] FROM [Employee].[dbo].[tblEmpMaster]

end

Now see final table  with data is below




















Now its time to create client application .

Creating Asp.net Application:-


I hope you are familiar with asp.net application so here I will not tell you how to create it.


.ASPX file

<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"
     CodeBehind="Default.aspx.cs" Inherits="ClientApp._Default" %>
<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <center>
    <div class="jumbotron">
        <h3>Demo App</h3>
        <p class="lead">Client App to Consume WCF service</p>
    </div>
    </center>
<div>
  <table align="center"  width="50%">
      <tr><td>Enter Emp Id</td><td><asp:TextBox ID="TextBox1" runat="server" Width="300px"></asp:TextBox></td></tr>
       <tr><td></td><td></td></tr>
       <tr><td></td><td><asp:Button ID="tbnSubmit" runat="server" Text="Show my Salary"  Width="200px"
            OnClick="tbnSubmit_Click"/></td></tr>

  </table>
    </div>
    <div class="">
        <table align="center"  width="500px"><tr><td>
        <asp:Label ID="lbltxt" runat="server" Text="" style="font-weight: 700"></asp:Label>
            </td></tr></table>

    </div>

</asp:Content>