Wednesday, 26 March 2014

Google Chart in Asp.net

Through this article, I'll try to explain how we can use Google charts for reporting purposes in ASP.NET web applications. Report generation is something quite common and we need to generate self explanatory and good looking reports to the users almost every time. “Images always speak more than words”. So instead of just showing the figures in our reports, we can let the users see diagrammatic charts which can help the users to analyze the whole data more quickly and easily. Though Microsoft itself has its charting controls for .NET, but we integrate it with other great technology by Google.
Google has its own, very awesome and simple application for charting purposes which we will be using here. I will request you to get a brief idea of what Google charts are, by visiting the following link:
So to brief stuff down, let’s look at one example. This may give you a better understanding of Google charts. To generate charts using “Google charts”, we need to pass the proper parameters.
Visit the below link:
In the chart, you can clearly see the chart title as “Amount Collection”. If you see the URL carefully, you’ll notice that the name has been passed by the URL, similarly the other details like the type of graph, axes, data on which chart is plotted, etc. all are passed through the URL only.
Now let’s go through all the parameters that we need to pass to get the required charts.
Parameter Description
cht The chart type. Google offers around a dozen different chart types, including line charts, bar charts, pie charts, and others.
chs The chart size. This value is expressed as chs=WIDTHxHEIGHT, where WIDTH and HEIGHT are the number of pixels wide and tall to draw the chart. E.g., chs=250x100. The maximum height and width is 1,000 pixels, and the product of the height and width cannot exceed 300,000 pixels.
chtt The chart title.
chd The chart data. When using this parameter, you must specify the data format. The Google Chart API allows for different data encodings. The simplest to use is text encoding and is denoted by the letter t. Following the encoding, place a colon (Smile | :) and then a comma-delimited list of data point values. The default text encoding requires that the data points be floating point values between zero (0.0) and one hundred (100.0). To correctly scale the data, convert each data point into a percentage of the largest data point. Ergo, the largest value will have a value of 100.0, whereas the others will be expressed in terms of a percentage of the largest – 50.0 for one that’s half as large as the largest, 25.0 for one that’s 25% of the largest, and so forth. To render a chart with data points of 10, 20, and 8, you’d send: chd=t:50,100,40. Note the t:, which indicates that the data is formatted using text encoding. You can alternatively use the text encoding method with data scaling, which allows data points of any positive or negative floating point number. With this approach, you must specify a scaling parameter (chds). The examples in this article use the default text encoding, limiting all data point values between zero and one hundred.
The above mentioned parameters are just the basic ones that you will need to plot charts. There are more advanced options that you can use as per your requirements.
Till now, we were just discussing about Google charts. As you are now having an idea of what Google charts, we can go forward with how we can implement these in our web application.
You can refer the below code for much better understanding. All I have done is that I have used an image control and the image path is the Google chart path. In the below example, we are trying to generate charts as per the options selected.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Text;
namespace WebApplication1
{
    public partial class graphs : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
        }
        protected void Button1_Click(object sender, EventArgs e)
        {
            int count = 0;
            int count1 = 0;
            int maxvalue = 0;
            float amount = 0;
            string[] amounts = null;
            string[] months = null;
            string query = “”;
            if ((Convert.ToInt32(to_month.SelectedItem.Value) – 
  Convert.ToInt32(from_month.SelectedItem.Value) + 1) > 0)
            {
                amounts = new string[Convert.ToInt32(to_month.SelectedItem.Value) - 
  Convert.ToInt32(from_month.SelectedItem.Value) + 1];
                months = new string[Convert.ToInt32(to_month.SelectedItem.Value) - 
  Convert.ToInt32(from_month.SelectedItem.Value) + 1];
                query = “select * from chart_table where month>=’” + 
  from_month.SelectedItem.Value + “‘ and month }
                StringBuilder chartUrl = new StringBuilder
        (“http://chart.apis.google.com/chart?chs=500×200&chtt=Amount%20Collection”);
                string connection = 
  System.Configuration.ConfigurationManager.ConnectionStrings
   ["ApplicationServices"].ConnectionString;
                SqlConnection con = new SqlConnection(connection);
                SqlDataAdapter da = new SqlDataAdapter(query, con);
                DataSet ds = new DataSet();
                da.Fill(ds);
                GridView1.DataSource = ds.Tables[0];
                GridView1.DataBind();
                maxvalue = Convert.ToInt32(ds.Tables[0].Rows[0][1].ToString());
                while (count1 {
                  if (maxvalue < Convert.ToInt32(ds.Tables[0].Rows[count1][1].ToString()))
                  {
                      maxvalue = Convert.ToInt32(ds.Tables[0].Rows[count1][1].ToString());
                  }
                  count1++;
                }
                chartUrl.Append(“&chxt=x,y”);
                chartUrl.AppendFormat(“&chxr=1,0,{0}”, maxvalue.ToString(“0?));
                chartUrl.AppendFormat(“&cht={0}”, Server.UrlEncode
    (chart_type.SelectedValue));
                while (count{
                    amount = (Convert.ToInt32(ds.Tables[0].Rows
   [count][1].ToString()) * 100) / maxvalue;
                    amounts[count] = amount.ToString();
                    months[count] = ds.Tables[0].Rows[count][2].ToString();
                    count++;
                }
                chartUrl.AppendFormat(“&chxl=0:|{0}”, String.Join(“|”, months.ToArray()));
                chartUrl.AppendFormat(“&chd=t:{0}”, String.Join(“,”, amounts.ToArray()));
                Image1.ImageUrl = chartUrl.ToString();
                Image1.Visible = true;
         }
    }
}
 
 
Google provided an open API for generating the charts which can be used in our commercial web applications. We can generate various graphs using the Google chart API.
The Google Chart API lets you dynamically generate charts. To see the Chart API in action, open up a browser window and copy the following URL into it:
http://chart.apis.google.com/chart?cht=p3&chd=s:hW&chs=250x100&chl=Hello|World The following types of charts are available:
  • Line Chart
  • Bar Chart
  • Pie Chart
  • Venn diagram
  • Scatter Plot
The following article demonstrates the usage of graph in ASP.NET.
Use the image tag and place the source there:
<img src="http://chart.apis.google.com/chart?cht=p3&chd=s:asR&chs=400x150&chl=A|B|C" /> We can pass a variety of parameters to enhance the graph. Following are a few:
Graph Title
We can place the chart title using:
e.g.: chtt=Welcome chts
Graph Style
We can place the graph tile color and size of the font:
chts for Title Style : color,size
e.g.: chts=225ff0,20
Graph Colors
We can have different colors:
chco for colors: one or many
e.g.: chco=ff0000,00ff00,0000ff

Passing the Data

The data can be passed using various encoding techniques like simple, text, etc. I have done the simple encoding for you in C#:
public string GenerateGraph() { //Get the Data to draw the graph DataTable dt = new DataTable(); dt = dtGraphData; //Get the max vals in the Data int maxval = GetMaxVal(dt); //SAMPLE: http://chart.apis.google.com/chart? // cht=p3&chs=400x200&chd=s:asR&chl=A|B|C string GReqURL = http://chart.apis.google.com/chart?chts=+ GTitleColor+","+GTitleSize+"&chtt="+GTitle+"&chco="+GColors+ "&cht=p3&chs="+GWidth+"x"+GHeight; //chts for Title Style : color,size //chtt for title text //chco for colors: one or many string simpleEncoding = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; string chartData = string.Empty; string chartLabels = string.Empty; StringBuilder strbchartData = new StringBuilder(); StringBuilder strbchartLabels = new StringBuilder(); strbchartData.Append("&chd=s:"); strbchartLabels.Append("&chl="); int strlen = simpleEncoding.Length - 1; foreach (DataRow dr in dt.Rows) { //Generate the chart DATA int arrVal = Convert.ToInt32(dr[2]); int len = strlen * arrVal / maxval; strbchartData.Append(simpleEncoding.Substring(len, 1)); //Generate the Chart Labels strbchartLabels.Append(dr[1] + "|"); } //Converting the string builder to string chartData = strbchartData.ToString(); chartLabels = strbchartLabels.ToString(); chartLabels = chartLabels.Substring(0, chartLabels.Length - 1); return GReqURL + chartData + chartLabels; } The code is written in C#. You can assign all the properties you want to assign and finally call the GenerateGraph method which returns the string. Below is the code sample. The entire article is explained using the PIE graph example. The remaining graphs can also be achieved using the same method.
DataTable dt = new DataTable(); //Get the Data the data table and pass it dt = GetGraphData(); PieGraph pg = new PieGraph(); pg.GraphColors = "5566AA"; pg.GraphHeight="125"; pg.GraphWidth="250"; pg.GraphTitle = "Welcome to Test Graph"; pg.GraphTitleColor = "112233"; pg.GraphTitleSize = "20"; pg.dtData = dt; GGReq = pg.GenerateGraph(); this.DataBind(); } DataTable GetGraphData() { SqlConnection con = new SqlConnection(connectionstring); SqlCommand cmd = new SqlCommand("Select * from GraphSupp", con); SqlDataAdapter da = new SqlDataAdapter(cmd); DataTable dt = new DataTable(); da.Fill(dt); return dt; } I took 3 cols id, description and the count and generated a string and assigned that to the image source.
This is to show how to pass data to the PI graph, we can also perform simple encoding for other graphs...

Steps for Generation of the Graph

  1. Create a DataTable which contains column-2 as labels and column-3 as Data
  2. Create an instance of PieGraph (refer to the text doc I have attached)
  3. Assign the properties
  4. Place the return string to the source of the image tag
  5. Graph is generated

Points of Interest

  1. Easy way of generation of graphs
  2. Less effort on the web server as there is no need to render the image using Drawing name space
  3. Enhanced look and feel and open to all
 

Chart Control in Asp.net

The ASP.NET Chart server control enables you to create ASP.NET pages that include charts for complex statistical or financial analysis. The Chart control supports the following features:

  • Data series, chart areas, axes, legends, labels, and titles.
  • Data binding.
  • Data manipulation, such as copying, splitting, merging, alignment, grouping, sorting, searching, and filtering.
  • Statistical formulas and financial formulas.
  • Advanced chart appearance, such as 3-D, anti-aliasing, lighting, and perspective.
  • Events and customizations.
  • Interactivity and Ajax.
or
Heavy on the Declarative Syntax
<web:Chart ID="chart" runat="server" Width="300px" Height="150px"
    Title="Transportation" Type="Line" EnableLegend="true">
    <DataSets>
        <web:DataSet Color="ForestGreen" Label="Cars">
            <web:DataPoint Value="5" />
            <web:DataPoint Value="9" />
            <web:DataPoint Value="21" />
            <web:DataPoint Value="30" Marker="Arrow" />
            <web:DataPoint Value="25" />
            <web:DataPoint Value="36" />
        </web:DataSet>
        <web:DataSet Color="Red" Label="Trucks">
            <web:DataPoint Value="7" />
            <web:DataPoint Value="3" />
            <web:DataPoint Value="13" />
            <web:DataPoint Value="13" />
            <web:DataPoint Value="16" />
            <web:DataPoint Value="25" />
        </web:DataSet>
        <web:DataSet Color="Orange" Label="Motorcycles">
            <web:DataPoint Value="18" />
            <web:DataPoint Value="25" />
            <web:DataPoint Value="18" />
            <web:DataPoint Value="13" />
            <web:DataPoint Value="25" />
            <web:DataPoint Value="23" />
        </web:DataSet>
    </DataSets>
</web:Chart>
http://chart.apis.google.com/chart?
chd=t:5,9,21,30,25,36|7,3,13,13,16,25|18,25,18,13,25,23
&cht=lc&chs=300x150&chco=228b22,ff0000,ffa500&chm=a,000000,0,3,10&chtt=Transportation&chdl=Cars|Trucks|Motorcycles
For more information, see Chart Controls on the MSDN Web site. For examples of how to use the Chart control, see Samples Environment for Microsoft Chart Controls on the MSDN Code Gallery and Chart Controls for .NET Framework on the .NET Development Center on the MSDN Web site.
In Microsoft Visual Studio 2010, the ASP.NET Chart control is located on the Data tab of the Toolbox. You can add chart data in the control markup, or you can use data binding to populate the chart dynamically.


Exploring the ASP.NET 3.5 Chart Controls
The new Chart Controls for .NET Framework 3.5 enables ASP.NET and Windows Forms developers to easily create rich and professional-looking data visualization solutions. The Chart Controls currently contains 25 different chart types with 3-D support for most of them, and all of these, available for FREE. Amongst the other features found in 3rd party charting controls, the Chart Controls for .NET framework provides feature like DataBinding, Data Export, support for Financial and Statistical data, State Management, Streaming, Serialization and much more.
To get started, download and install the following in the order given below:
Microsoft Chart Controls for Microsoft .NET Framework 3.5 – assemblies containing the Chart Controls (ASP.NET and Windows Forms)
Microsoft Chart Controls Add-on for Microsoft Visual Studio 2008 – Add as a control in the Visual Studio toolbox and provides IntelliSense for Chart controls.
Once you have downloaded and installed these components, open Visual Studio 2008. In the Data tab on the Toolbox, observe the new ‘Chart’ control.
Chart Toolbox
To get started, let us create a sample application using the Chart control:
Step 1: Drag and drop the Chart control from the Toolbox to the Design surface of Default.aspx. You will see a ‘Column chart’ which looks similar to the following:
Sample Chart
If you click on the ‘Source’ view of the page, you find the following mark up added to the page:
<%@ Register Assembly="System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
    Namespace="System.Web.UI.DataVisualization.Charting" TagPrefix="asp" %>
        <asp:Chart ID="Chart1" runat="server">
            <Series>
                <asp:Series Name="Series1">
                </asp:Series>
            </Series>
            <ChartAreas>
                <asp:ChartArea Name="ChartArea1">
                </asp:ChartArea>
            </ChartAreas>
        </asp:Chart>
By default the ChartType is ‘Column’. In order to change the Chart Type to either Line, Bar, Pie or any of these 25 chart types; with the Chart control selected, go to the Properties window > go to ‘Series’ > Click on the ellipse button(…) > in the ‘Series Collection Editor’, click on the ‘ChartType’ to view and select a different chart type as shown below:
Series Coll Editor
For this demonstration, we will keep the ChartType to the default ‘Column’.
We will be binding the chart to some data. For this purpose, we will be using the SqlDataSource.
Step 2: Click on the smart tag or right click Chart > Show Smart Tag > Choose a DataSource > New Data Source… > Select Database. We will keep the default ID for SqlDataSource, SqlDataSource1 and click OK.
Step 3: On clicking OK, you will be presented with a ‘Configure Data Source’ wizard. Click on ‘New Connection’ to open the ‘Add Connection’. Type your ‘Server Name’ and ‘Select a database Name’ to connect to. Over here, I have typed (local) as the ServerName and the database I am connecting to is ‘Northwind’. Click on ‘Test Connection’ to make sure that there are no errors connecting to the server. Click Ok.
Step 4: In your ‘Configure Data Source’, click Next. An option will be displayed for saving the connection string to the configuration file. Select the checkbox ‘Yes, save this connection as:’ , type a name for the connectionstring ‘NorthwindConnectionString’ and click Next.
Step 5: In the ‘Configure Select Statement’ > select ‘Specify a Custom SQL Statement or stored procedure’ > click Next
SQL Data Src
Type the SQL query to ‘list the count of products in a category’ as shown below:
SELECT CategoryName, COUNT(*) AS ProductCount FROM Products JOIN Categories ON Products.CategoryID = Categories.CategoryID GROUP BY CategoryName
Query
Click Next > Finish.
Step 6: Select the Chart control > Go to the Properties window > ChartAreas property and click the ellipse (…) button to open the ChartArea collection editor. Go to the ‘Axes’ property in the ChartArea Collection Editor and click the ellipse (…) button to open the Axis collection editor as shown below:
Axis Coll Editor
Set the ‘Title’ of the X axis to ‘Categories’ and the ‘Title’ of the Y axis to ‘Product Count’. Click OK to close the Axis Collection Editor and an OK again to close the ChartArea Collection Editor.
With the Chart control selected, go to the Series property in the Properties window and click the ellipse (…) button to open the Series collection editor. Go to the Data Source section and add the XValueMember as ‘CategoryName’ and YValueMembers to ‘ProductCount’. Also set the ‘IsValueShownAsLabel’ to True to display the value of ProductCount on the columns. Click OK.
Series Coll Editor
Step 7: With the properties set, run the application. You will see a chart as displayed below:
Final Chart
I am sure all we developers who have used 3rd party Charting solutions in the past, are going to welcome this awesome control from Microsoft. The best part is that it is available for FREE. For the ASP.NET MVC developers, here’s an article that would interest you Combining ASP.NET MVC and ASP.NET Charting Controls.



I have approached this problem by trying to represent the entire chart declaratively right in the aspx code. Here is an example of a line chart:
As you can see, a chart with any sizable amount of data can become very cumbersome. The output of this chart looks like this:
Example Output
The url used to generate this chart looks like this:
You can change the type of chart being generated through the Type property. Here is an example of a bar chart:
Sample Bar Chart
A Venn Diagram:
Venn Diagram
Pie Chart:
Pie Chart
 

Tuesday, 25 March 2014

Transaction Flow in WCF

Windows Communication Foundation (WCF) provides highly flexible options for controlling transaction flow. A service's transaction flow settings can be expressed using a combination of attributes and configuration.
Transaction Flow Settings
Transaction flow settings are generated for a service endpoint as a result of the intersection of the following three values:
  • The TransactionFlowAttribute attribute specified for each method in the service contract.
  • The TransactionFlow binding property in the specific binding.
  • The TransactionFlowProtocol binding property in the specific binding. The TransactionFlowProtocol binding property enables you to choose among two different transaction protocols that you can use to flow a transaction. The following sections briefly describe each of them.

WS-AtomicTransaction Protocol

The WS-AtomicTransaction (WS-AT) protocol is useful for scenarios when interoperability with third-party protocol stacks is required.

OleTransactions Protocol

The OleTransactions protocol is useful for scenarios when interoperability with third-party protocol stacks is not required, and the deployer of a service knows in advance that the WS-AT protocol service is disabled locally or the existing network topology does not favor the usage of WS-AT.
The following table shows the different types of transaction flows that can be generated using these various combinations.

 

TransactionFlow binding TransactionFlow binding property TransactionFlowProtocol binding protocol Type of transaction flow
Mandatory
true
WS-AT
Transaction must be flowed in the interoperable WS-AT format.
Mandatory
true
OleTransactions
Transaction must be flowed in the WCF OleTransactions format.
Mandatory
false
Not applicable
Not applicable because this is an invalid configuration.
Allowed
true
WS-AT
Transaction may be flowed in the interoperable WS-AT format.
Allowed
true
OleTransactions
Transaction may be flowed in the WCF OleTransactions format.
Allowed
false
Any value
A transaction is not flowed.
NotAllowed
Any value
Any value
A transaction is not flowed.
The following table summarizes the message processing result.

Enabling Transaction Flow at the Method Level

Transaction flow requirements are not always the same for all methods in a service contract. Therefore, WCF also provides an attribute-based mechanism to allow each method's transaction flow preferences to be expressed. This is achieved by the TransactionFlowAttribute that specifies the level in which a service operation accepts a transaction header. You should mark your service contract methods with this attribute if you want to enable transaction flow. This attribute takes one of the values of the TransactionFlowOption enumeration, in which the default value is NotAllowed. If any value except NotAllowed is specified, the method is required to not be one-way. A developer can use this attribute to specify method-level transaction flow requirements or constraints at design time.

Enabling Transaction Flow at the Endpoint Level

In addition to the method-level transaction flow setting the TransactionFlowAttribute attribute provides, WCF provides an endpoint-wide setting for transaction flow to allow administrators to control transaction flow at a higher level.
This is achieved by the TransactionFlowBindingElement, which enables you to enable or disable incoming transaction flow in an endpoint’s binding settings, as well as to specify the desired transaction protocol format for incoming transactions.
If the binding has disabled transaction flow, but one of the operations on a service contract requires an incoming transaction, then a validation exception is thrown at service startup.
Most of the standing bindings WCF provides contain the transactionFlow and transactionProtocol attributes to enable you to configure the specific binding to accept incoming transactions. For more information about setting the configuration elements, see <binding>.
An administrator or deployer can use endpoint-level transaction flow to configure transaction flow requirements or constraints at deployment time using the configuration file.

Security

To ensure system security and integrity, you must secure message exchanges when flowing transactions between applications. You should not flow or disclose transaction details to any application that is not entitled to participate in the same transaction.
When generating WCF clients to unknown or untrusted Web services through the use of metadata exchange, calls to operations on these Web services should suppress the current transaction if possible. The following example demonstrates how to do this.
//client code which has an ambient transaction
using (TransactionScope scope = new TransactionScope(TransactionScopeOption.Suppress))
{
    // No transaction will flow to this operation
    untrustedProxy.Operation1(...);
    scope.Complete();
}
//remainder of client code
In addition, services should be configured to accept incoming transactions only from clients that they have authenticated and authorized. Incoming transactions should only be accepted if they come from highly trusted clients.

This defines the operations in the order they are to be processed:
  • An Add operation request must include a flowed transaction.
  • A Subtract operation request may include a flowed transaction.
  • A Multiply operation request must not include a flowed transaction through the explicit NotAllowed setting.
  • A Divide operation request must not include a flowed transaction through the omission of a TransactionFlow attribute.
To enable transaction flow, bindings with the <transactionFlow> property enabled must be used in addition to the appropriate operation attributes. In this sample, the service's configuration exposes a TCP endpoint and an HTTP endpoint in addition to a Metadata Exchange endpoint. The TCP endpoint and the HTTP endpoint use the following bindings, both of which have the <transactionFlow> property enabled.
<bindings>
  <netTcpBinding>
    <binding name="transactionalOleTransactionsTcpBinding"
             transactionFlow="true"
             transactionProtocol="OleTransactions"/>
  </netTcpBinding>
  <wsHttpBinding>
    <binding name="transactionalWsatHttpBinding"
             transactionFlow="true" />
  </wsHttpBinding>
</bindings>
noteNote:
The system-provided netTcpBinding allows specification of the transactionProtocol whereas the system-provided wsHttpBinding uses only the more interoperable WSAtomicTransactionOctober2004 protocol. The OleTransactions protocol is only available for use by Windows Communication Foundation (WCF) clients.

Monday, 24 March 2014

WCF Service Behaviors

Concurrency 
By default WCF service handles only single request at a time and all other service request threads are queued and processed one by one. Concurrency element allows clients to send multiple requests at the same time, but service implementation should be break free of scenarios like dead locks.
There are three types of Concurrency modes. 
  1. Single(Default): Concurrency mode single will allows only one at a time to the service instance. And all other pending requests will be maintained in queue and processed one by one. Whenever a new request comes dispatcher gets a lock before entering in to the code. Refer Figure 1. 

  2. Figure 1. 
    ConcurrencyMode Single is defined as follows:
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single)]
    public class VisitorCount : IVisitorCount
    {
    } 
  3. Multiple: This will allow parallel requests, and that are processed at the same time by spawning separate thread for each and every request. Refer Figure 2.

  4. Figure 2
    Here is how we would define ConcurrencyMode Multiple.
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Multiple)]
    public class VisitorCount : IVisitorCount
    {
    }
  5. Re-entrant: Whenever a client calls WCF service a thread lock will be assigned to this client call. Let us consider a scenario where Service 1 makes an external call to Service 2. Thread lock won’t be released until entire service call is completed. So all other client requests are in waiting state. Re-entrant allows the client to release the lock before making call to the external service (Service 2) and this will allow other client to use the Service 1 facilities until Service 2 process is completed. Refer Figure 3. 

  6. Figure 3 
    Decorating service class with ConcurrencyMode Reentrant.
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Reentrant)]
    public class VisitorCount : IVisitorCount
    {
    }
Concurrency mode can increase the amount of passing through the service methods and hence overall service performance increases.
Instance Context Mode  
WCF Instancing decides how objects are created and refers to the life time of the service object. Whenever clients make request runtime will create service objects to provide the response. Through instancing we ca control how long this service instance wants to be retained. For that we are using the three instancing modes.
  1. Per Call: In this scenario, all the calls to the service become stateless. And for every thread request a new service instance will be created. This will work with all the service bindings. Refer Figure 4. 

  2. Figure 4.
    Here is how we would define InstanceContext Mode Percall.
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,
           InstanceContextMode = InstanceContextMode.PerCall)]
    public class VisitorCount : IVisitorCount
    {
    }
  3. Per Session: The life time of service object is independent of the life time of Client channels, so  this will create a new service object whenever a new communication session is established and disposed after that. Each client channel gets a dedicated service instance and the subsequent calls in the same session are handled by the same Service object. This is the default value for Instancing Context. And this will work with all bindings except basicHttpBindings. Refer Figure 5. 

  4. Figure 5.
    Here is how we would define InstanceContextMode PerSession.
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,InstanceContextMode = InstanceContextMode.PerSession)]
    public class VisitorCount : IVisitorCount
    {
    }
  5. Single: This will help us to share the data globally. We can create only one instance and the same instance will be reused on the subsequent calls. Same like Per Session this will work with all bindings except basicHttpBinding. Single ton instance will not be disposed until service host is down. Refer Figure 6.

  6. Figure 6
    Here is how we would define InstanceContext mode Single.
    [ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,InstanceContextMode = InstanceContextMode.Single)]
    public class VisitorCount : IVisitorCount
    {
    } 

Service Throttling  

WCF allows you to throttle load on a particular service type.

This includes
  1. Maximum number of Concurrent sessions  
  2. Maximum number of Concurrent calls 
  3. Maximum number of Concurrent instances  
Whenever these values exceeded, the callers will be added to the queue and processed FIFO order. We can configure throttling behavior in application configuration file as follows.
<serviceBehaviors> 
<behavior name="visitorCountServiceBehavior"> 
<serviceThrottling maxConcurrentCalls="5" maxConcurrentInstances="10" maxConcurrentSessions="10"> 
</serviceThrottling>
</behavior> 
</serviceBehaviors>

Using the code   

Let us create a sample application to demonstrate different service behaviors. First create an interface and decorate it with  ServiceContract and OperationalContract attributes to specify that these operations of this interface can be used by the client applications.
[ServiceContract]
public interface IVisitorCount
{
[OperationContract]
int GetVisitorCount();
}
Now we have to create a service class to implement above interface method. And we have to decorate service class with different service behaviors, following code explains Concurrency Mode Single and Instance context mode single.
[ServiceBehavior(ConcurrencyMode = ConcurrencyMode.Single,InstanceContextMode = InstanceContextMode.Single)]
public class VisitorCount : IVisitorCount
{
  int _visitorCount = 0;
 
  public VisitorCount()
  {           
      Console.WriteLine("New Service Instance Created");
  }
 
  public int GetVisitorCount()
  {
 
   _visitorCount++;
 
   return _visitorCount;
   }
}
Now let us see how we can make this service available to client applications, Configuration file App.Config contents are given below.
<configuration>
  <system.web>
    <compilation debug="true">
  </compilation></system.web>
  <system.servicemodel>
    <services>
      <service name="InstanceContextModeService.VisitorCount">
        <endpoint binding="wsHttpBinding" contract="InstanceContextModeService.IVisitorCount">
          <identity>
            <dns value="localhost">
          </dns></identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange">
        <host>
          <baseAddresses>
            <add baseaddress="http://localhost:8732/InstanceContextModeService/VisitorCount/">
          </baseAddresses>
        </add></host>
      </endpoint></service>
    </services>
    <behaviors>
      <servicebehaviors>
          <behavior>
          <servicemetadata httpgetenabled="True">
          <servicedebug includeexceptiondetailinfaults="False">
          <servicethrottling maxconcurrentcalls="5" maxconcurrentinstances="10" maxconcurrentsessions="10">
        </servicethrottling></servicedebug></servicemetadata><</behavior>
      </servicebehaviors>
    </behaviors>
  </system.servicemodel>
</configuration>
Following service host code will host VisitorCounter service to the client applications.
class Program
{
  private static ServiceHost host = null;
  static void Main(string[] args)
  {
     host = new ServiceHost(typeof(InstanceContextModeService.VisitorCount));
     host.Opened += new EventHandler(host_Opened);
     host.Closed += new EventHandler(host_Closed);
     host.Open();
     Console.ReadKey();
     host.Close();
     Console.ReadKey();
  }
 
  static void host_Closed(object sender, EventArgs e)
  {
     Console.WriteLine("Service Closed");
  }
 
  static void host_Opened(object sender, EventArgs e)
  {
    Console.WriteLine("Service Started");
  }
}
We have our service is hosted and defined. Following code explains how clients utilize service and service behaviors.
static class Program
{
 static void Main(string[] args)
 {            
    VisitorCountClient client = new VisitorCountClient();
    Console.WriteLine("First Call-->" + client.GetVisitorCount());
    Console.ReadKey();
    Console.WriteLine("Second Call-->" + client.GetVisitorCount());
    Console.ReadKey();
    Console.WriteLine("Third Call-->" + client.GetVisitorCount());
    Console.ReadKey();
    Console.WriteLine("Forth Call-->" + client.GetVisitorCount());
    Console.ReadKey();
 }
}

Sunday, 23 March 2014

Difference between WCF and ASP.NET Web Service

Difference between WCF and ASP.NET Web Service

.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 the differences between ASP.NET Web Service and WCF.

WCF
ASP.NET Web Service
ServiceContract and OperationContract attributes are used for defining WCF service.
WebService and WebMethod attributes are used for defining web service.
Supports various protocols like HTTP, HTTPS, TCP, Named Pipes and MSMQ.
Supports only HTTP, HTTPS protocols.
Hosted in IIS, WAS (Windows Activation Service), Self-hosting, Windows Service.
Hosted only in IIS.
Supports security, reliable messaging, transaction and AJAX and REST supports.
Support security but is less secure as compared to WCF.
Supports DataContract serializer by using System.Runtime.Serialization.
Supports XML serializer by using System.Xml.Serialization.
Supports One-Way, Request-Response and Duplex service operations.
Supports One-Way and Request-Response service operations.
WCF are faster than Web Services.
Web Services are slower than WCF
Hash Table can be serialized.
Hash Table cannot be serialized. It can serializes only those collections which implement IEnumerable and ICollection.
Unhandled Exceptions does not return to the client as SOAP faults. WCF supports better exception handling by using FaultContract.
Unhandled Exceptions returns to the client as SOAP faults.
Supports XML, MTOM, Binary message encoding.
Supports XML and MTOM (Message Transmission Optimization Mechanism) message encoding.
Supports multi-threading by using ServiceBehaviour class.
Doesn’t support multi-threading.