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>





Saturday 26 September 2015

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

What is Serialization in C#.Net ?

Object Serialization is a process through which an object's state is transformed
into some serial data format, such as XML or binary format, in order to be stored
for some later use.

Use of Serialization
Passing an object from on application to another.
Passing an object from one domain to another.

Types of Serialization
1.Binary Serialization
2.SOAP Serialization
3.XML Serialization



XML Serialization:-

Required namespace for XML Serialization
using System.Xml;
using System.Xml.Serialization;


How Do We Achieve This
For serialization and deserialization, we need to use 
System.Xml.Serialization, because we need to use XmlSerialization class
which is provided in System.Xml.Serialization.

To understand this, we assume one example of Author and Books. We have two classes.
One is Author and another is Books. Author has Author ID, Author Name and Array
of Books. While Books has Books ID, Books Name, Books Price and Books Quantity in Stock.


// Author Class . 
public class Author
    {
        private int _AuthID;
        private string _AuthName;
        private Books[] _Books;

        public int AuthorID
        {
            getreturn _AuthID;}
            set{  _AuthID = value;}
        }

        public string AuthorName
        {
            get { return _AuthName; }
            set { _AuthName = value; }
        }


        public Books[] Books
        {
            get {return _Books;}
            set{ _Books = value;}
        }

    }


// Books Class . 
public class Books
    {
        private int _BookID;
        private string _BookName;
        private int _BookPrice;
        private int _BookQtyInStock;

        public int BookID
        {
            getreturn _BookID; }
            set{  _BookID = value;}
        }

        public string BookName
        {
            get{return _BookName;}
            set{   _BookName = value;}
        }

        public int BookPrice
        {
            get{   return _BookPrice;}
            set  {   _BookPrice = value; }
        }

        public int BookQtyInStock
        {
            get { return _BookQtyInStock; }
            set{ _BookQtyInStock = value; }
        }


First we will Understand Serialization

In our application, we have serialization function which is called by our click event or
 whenever this is required. In serialization, we have created one object of Author class
 and another is Books. Author holds one test Author “Phone” and then it creates an array
 of Books class and stores to Author.Books.


private void Serialization()
        {
            Author Auth = new Author();
            Auth.AuthorID = 1;
            Auth.AuthorName = "Auhtor";
            Books[] book = new Books[5];
            for (int i = 0; i < 5; i++)
            {
                book[i] = new Books();
                book[i].BookID = i;
                book[i].BookPrice = i * 10;
                book[i]._BookQtyInStock = i + 10;
                book[i].BookName = " Book Name : " + i.ToString();

            }
            Auth.Books = book;
            XmlSerializer ser = new XmlSerializer(Auth.GetType());
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.StringWriter writer = new System.IO.StringWriter(sb);
            ser.Serialize(writer, Auth);
            // Here Classes are converted to XML String.
            // This can be viewed in SB or writer.
            // Above XML in SB can be loaded in XmlDocument object
            XmlDocument doc = new XmlDocument();
            doc.LoadXml(sb.ToString());
        }

  


Now we will look at Deserialization

In our application, we have Deserialization function which is called by our click event 
or whenever this is required. In deserialization, we have created one object of Author 
class.


        protected void DeSerialize(string XmlString)
        {
        Author Auth = new Author();
        XmlDocument doc = new XmlDocument();
        doc.LoadXml (XmlString);
        XmlNodeReader reader = new XmlNodeReader(doc.DocumentElement);
        XmlSerializer ser = new XmlSerializer(Auth.GetType());
        object obj = ser.Deserialize(reader);
        // Then you just need to cast obj into whatever type it is, e.g.:
        Author myObj = (Author)obj;
      
       }


In the above method, we are passing one XML string. This will be converted into a form of 
object. Here XML string is loaded into XmlDocument object and then XmlNodeReader is 
reading from it. Now XmlSerialize object is created and we let it know the type of 
object by Auth.GetType(). Now Ser object knows that it has to convert XML into an object 
of Author Type. Now ser.Deserialize(reader) takes XML from reader object and converts 
into an Object. Later this object is cast into Author. If we add this object into watch 
and view, we will find that it has created the class hierarchy.


In the above post I have explained only XML serialization, hope its very useful to you. Please your feedback and comments.