Wednesday 28 October 2015

What is Message contract in wcf?


Message is a packet of data which contains important information. WCF use this message to transfer from source to destination path.

WCF uses a SOAP message for communication. SOAP message contain message Envelop, Header and body.

Message contract is used to control the structure of a message body and serialization process. It is used to send/access the information over SOAP. Using message contract you can customize the parameter sent using a SOAP message between the client and the server.
How to Define/Declare MessageHeader and MessageBody?

MessageHeader:-
A Message Header is applied to a member of a message contract to declare the member within the message header.
 
[MessageContract(IsWrapped = true)]
public class EmpRequest
{

  [MessageHeader(Name = "EmpIdentity")]
  public string EmpId;

}


Message Body:-
A Message Body Member is applied to a member of a message contract to declare the member within the message body.




[MessageContract(IsWrapped = true)]

public class EmpResponse

{

    [MessageBodyMember]

    public Employee EmpINfo;

}
 
 
Example:-
Create WCF Service application.
 
Code for IService.cs :-
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
 
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService" in both code and config file together.
[ServiceContract]
public interface IService
{
 
    [OperationContract]
    [FaultContract(typeof(string))]
    EmpResponse GetEmpInfo(EmpRequest request);
 
 
            // TODO: Add your service operations here
}
 
// Use a data contract as illustrated in the sample below to add composite types to service operations.
 
[MessageContract(IsWrapped = true)]
public class EmpRequest
{
    [MessageHeader(Name = "EmpIdentity")]
    public string EmpId;
}
 
[MessageContract(IsWrapped = true)]
public class EmpResponse
{
    [MessageBodyMember]
    public Employee EmpINfo;
}
 
[DataContract]
public class Employee
{
    [DataMember(Name = "FirstName", Order = 1)]
    public string FirstName;
 
    public string firstName
    {
        get { return firstName; }
        set { firstName = value; }
    }
 
    [DataMember(Name = "LastName", Order = 2)]
    public string LastName;
 
    public string lastName
    {
        get { return lastName; }
        set { lastName = value; }
    }
 
    [DataMember(Name = "Address", Order = 3)]
    public string Address;
 
    public string address
    {
        get { return address; }
        set { address = value; }
    }
}
 
Code for Service.cs :-
 
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;
 
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service" in code, svc and config file together.
public class Service : IService
{
            public string GetData(int value)
            {
                        return string.Format("You entered: {0}", value);
            }
            public CompositeType GetDataUsingDataContract(CompositeType composite)
            {
                        if (composite == null)
                        {
                                    throw new ArgumentNullException("composite");
                        }
                        if (composite.BoolValue)
                        {
                                    composite.StringValue += "Suffix";
                        }
                        return composite;
            }
    private const string EmpId = "d2nf@5";
    public EmpResponse GetEmpInfo(EmpRequest request)
    {
        EmpResponse response = new EmpResponse();
 
        if (request.EmpId != EmpId)
        {
            string error = "Invalid Emp Id";
            throw new FaultException<string>(error);
  }
       response.EmpINfo = new Employee();
        response.EmpINfo.firstName = "Sushil";
        response.EmpINfo.lastName = "Modi";
        response.EmpINfo.address = "Bangalore"
        return response;
    }
}
 


Now deploy the Service on IIS or Local Server.

Create one Windows or Console application.

Add service reference into your application.
After adding service reference, create an object of Service Client proxy class and call the GetEmpInfo method and display the Employee info as given below.


class Program

{

static void Main(string[] args)

{

Try

{

   ServiceReference2.ServiceClient ref2 = new ServiceClient();

   ServiceReference2.Author a = ref2.GetAuthorInfo("d2nf@5");

   Console.WriteLine("First Name: " + a.firstName + "\t" + "Last Name" +                a.lastName + "\t" + "Address : " + a.address);

}

 catch (FaultException<string> ex)

 {

   Console.Write(ex.Detail + "<br/>");

 }

}

If you pass wrong EmpId the it show “Invalid Emp Id”.
 
 

Monday 26 October 2015

What is endpoint in WCF.What is ABC in WCF?

All communication with the windows communication foundation (WCF) service occurs through the endpoints of the service. Endpoints provide client access to the functionality offered by a WCF Service.
WCF Service exposes a collection of endpoints and each endpoint is a way for communicating with the world.
 Each Endpoint consists of four points: -
• Address
• Binding
• Contact
• Behavior
Address: - It is uniquely identifies the endpoint and tells client where the service is located. Address is basically a URL ex.
http://localhost:8090/MyService/Service.svc
Client use this address to connect the WCF Service.
Binding: - Binding specifies how to communicate with service. There are different protocols available for WCF Serv . This includes:-
• The transport protocol to use (ex. TCP or HTTP).
• The encoding to use for the message (for ex. Text or binary)
• The necessary security requirement (for ex. SSL or SOAP message).
Contracts:-  The contract outline what functionality the endpoint expose to the client. A contract Specifies
• What the operation called by client
• The form of message
• The type of input parameter or data required  to call the operation
• What type of processing or response message the client can expect
 Behaviors:- You can use endpoint behaviors to customize the local behavior of the service endpoint.  Endpoint behavior achieves this by participating in the process of building WCF runtime. An example of endpoint behavior is the ListenURI property, which allows you to specify a different listening address than the SOAP or WSDL address.

HitCounts on website or Number of Users Online on website in asp.net.


If have a web site on World Wide Web, you may be interested to know how many users are online and how many numbers of users visited website. For analyzing this thing you will go for log file on web server but that information is usually difficult to read.

Please follow the steps to count No. of hits on web site or no. of users online in asp.net using c#.
Step:-

1. Create new web site in VS 2008 or VS2010.
2. Add one Global.asax file.

3. Code for Global.asax.cs:-
 
using System;
using System.Data;
using System.Configuration;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.IO;
 
/// <summary>
/// Summary description for Global
/// </summary>
public class Global : System.Web.HttpApplication
{
    private static int totalNoOfUsers = 0;
    private static int currentNoOfUsers = 0;
 
    /// <summary>
    /// Required designer variable.
    /// </summary>
    private System.ComponentModel.IContainer components = null;
 
    public Global()
    {
        InitializeComponent();
    }
 
    protected void Application_Start(Object sender, EventArgs e)
    {
        int counterValue = 0;
        string counterFile = Server.MapPath("~/Counter.txt");
 
        if (File.Exists(counterFile))
        {
            using (StreamReader sr = new StreamReader(counterFile))
            {
                string result = sr.ReadLine();
                if (result != null)
                {
                    string delimStr = "\t";
                    char[] delimiter = delimStr.ToCharArray();
                    string[] arrResult = null;
                    arrResult = result.Split(delimiter);
                    if (arrResult.Length == 2)
                    {
                        counterValue = Convert.ToInt32(arrResult[1]);
                    }
                }
            }
        }
        totalNoOfUsers = counterValue;
    }
 
    protected void Session_Start(Object sender, EventArgs e)
    {
        totalNoOfUsers += 1;
        currentNoOfUsers += 1;
 
        string counterFile = Server.MapPath("~/Counter.txt");
 
        if (File.Exists(counterFile))
        {
            //File.Delete(counterFile);
        }
        StreamWriter sw = File.CreateText(counterFile);
        sw.WriteLine("Total\t" + totalNoOfUsers);
        sw.Close();
    }
 
    protected void Application_BeginRequest(Object sender, EventArgs e)
    {
 
    }
 
    protected void Application_EndRequest(Object sender, EventArgs e)
    {
 
    }
 
    protected void Application_AuthenticateRequest(Object sender, EventArgs e)
    {
 
    }
 
    protected void Application_Error(Object sender, EventArgs e)
    {
 
    }
 
    protected void Session_End(Object sender, EventArgs e)
    {
        currentNoOfUsers -= 1;
    }
 
    protected void Application_End(Object sender, EventArgs e)
    {
 
    }
 
    public static int TotalNumberOfUsers
    {
        get
        {
            return totalNoOfUsers;
        }
    }
 
    public static int CurrentNumberOfUsers
    {
        get
        {
            return currentNoOfUsers;
        }
    }
 
    #region Web Form Designer generated code
    /// <summary>
    /// Required method for Designer support - do not modify
    /// the contents of this method with the code editor.
    /// </summary>
    private void InitializeComponent()
    {
        this.components = new System.ComponentModel.Container();
    }
    #endregion
}
 
 4. Code for Default.aspx :-
 
<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
        Total No of Users:- <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
        No. Of Users Online :- <asp:Label ID="Label2" runat="server" Text="Label"></asp:Label>
</div>
  </form>
</body>
</html>
5. Default.aspx.cs:-
protected void Page_Load(object sender, EventArgs e)
{
int currentNumberOfUsers = Global.CurrentNumberOfUsers;
int totalNumberOfUsers = Global.TotalNumberOfUsers;
Label2.Text = currentNumberOfUsers.ToString();
Label1.Text = totalNumberOfUsers.ToString();
}
6. Create one text file in root folder with a name Counter.txt.
Run the code.