I am Raghuveer

In my opinion programming means thinking, and it is fun. My vision is to teach programming in more understandable manner to the students from rural background. I support programming for everyone

WCF Architecture

The following figure illustrates the major components of WCF.

Figure 1: WCF Architecture

Contracts

Contracts layer are next to that of Application layer. Developer will directly use this contract to develop the service. We are also going to do the same now. Let us see briefly what these contracts will do for us and we will also know that WCF is working on message system.

Service contracts

- Describe about the operation that service can provide. Example, Service provided to know the temperature of the city based on the zip code, this service we call as Service contract. It will be created using Service and Operational Contract attribute.

Data contract

- It describes the custom data type which is exposed to the client. This defines the data types, are passed to and from service. Data types like int, string are identified by the client because it is already mention in XML schema definition language document, but custom created class or datatype cannot be identified by the client e.g. Employee data type. By using DataContract we can make client aware that we are using Employee data type for returning or passing parameter to the method.

Message Contract

- Default SOAP message format is provided by the WCF runtime for communication between Client and service. If it is not meeting your requirements then we can create our own message format. This can be achieved by using Message Contract attribute.

Policies and Binding

- Specify conditions required to communicate with a service e.g security requirement to communicate with service, protocol and encoding used for binding.

Service Runtime

- It contains the behaviors that occur during runtime of service.

  • Throttling Behavior- Controls how many messages are processed.
  • Error Behavior - Specifies what occurs, when internal error occurs on the service.
  • Metadata Behavior - Tells how and whether metadata is available to outside world.
  • Instance Behavior - Specifies how many instance of the service has to be created while running.
  • Transaction Behavior - Enables the rollback of transacted operations if a failure occurs.
  • Dispatch Behavior - Controls how a message is processed by the WCF Infrastructure.

Messaging

- Messaging layer is composed of channels. A channel is a component that processes a message in some way, for example, by authenticating a message. A set of channels is also known as a channel stack. Channels are the core abstraction for sending message to and receiving message from an Endpoint. Broadly we can categories channels as

  • Transport Channels

    Handles sending and receiving message from network. Protocols like HTTP, TCP, name pipes and MSMQ.

  • Protocol Channels

    Implements SOAP based protocol by processing and possibly modifying message. E.g. WS-Security and WS-Reliability.

Activation and Hosting

- Services can be hosted or executed, so that it will be available to everyone accessing from the client. WCF service can be hosted by following mechanism

  • IIS

    Internet information Service provides number of advantages if a Service uses Http as protocol. It does not require Host code to activate the service, it automatically activates service code.

  • Windows Activation Service

    (WAS) is the new process activation mechanism that ships with IIS 7.0. In addition to HTTP based communication, WCF can also use WAS to provide message-based activation over other protocols, such as TCP and named pipes.

  • Self-Hosting

    WCF service can be self hosted as console application, Win Forms or WPF application with graphical UI.

  • Windows Service

    WCF can also be hosted as a Windows Service, so that it is under control of the Service Control Manager (SCM).

Introdution to WCF 4.0

This article explains about the new features introduced in WCF 4.0.

.Net framework comes with new features and improved areas of WCF. It was mainly focused on simplifying the developer experience, enabling more communication scenario and providing rich integration with WWF.

The following items specifies the new features of WCF 4.0

Simplified configuration

This new feature shows simplification of WCF configuration section by providing default endpoint, binding and behavior configuration. It is not mandatory to provide endpoint while hosting service. Service will automatically create new endpoint if it does find any endpoint while hosting service. These changes make it possible to host configuration-free services.

Discovery service

There are certain scenario in which endpoint address of the service will be keep on changing. In that kind of scenario, client who consume this service also need to change the endpoint address dynamically to identify the service. This can be achieved using WS-Discovery protocol.

Routing service

This new feature introduces routing service between client and actual business service. This intermediated service Act as broker or gateways to the actual business services and provides features for content based routing, protocol bridging and error handling

REST Service

There are few features helps while developing RESTful service.

  • Automatic help page that describes REST services to consumer
  • Support for declarative HTTP catching

Workflow service

  • Improves development experience
  • Entire service definition can be define in XAML
  • Hosting workflow service can be done from .xamlx file, without using .svc file
  • Introduce new “Context” bindings like BasicHttpContextBinding, WSHttpContextBinding, or NetTcpContextBinding
  • In .Net4.0, WorkflowServiceHost class for hosting workflow services was redesigned and it is available inSystem.ServiceModel.Activities assembly. In .Net3.5, WorkflowServiceHost class is available inSystem.WorkflowServices assembly
  • New messaging activities SendReply and ReceiveReply are added in .Net4.0

Difference between WCF and Web service

Web service is a part of WCF. WCF offers much more flexibility and portability to develop a service when comparing to web service. Still we are having more advantages over Web service, following table provides detailed difference between them.

Features Web Service WCF
Hosting It can be hosted in IIS It can be hosted in IIS, windows activation service, Self-hosting, Windows service
Programming [WebService] attribute has to be added to the class [ServiceContraact] attribute has to be added to the class
Model [WebMethod] attribute represents the method exposed to client [OperationContract] attribute represents the method exposed to client
Operation One-way, Request- Response are the different operations supported in web service One-Way, Request-Response, Duplex are different type of operations supported in WCF
XML System.Xml.serialization name space is used for serialization System.Runtime.Serialization namespace is used for serialization
Encoding XML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom XML 1.0, MTOM, Binary, Custom
Transports Can be accessed through HTTP, TCP, Custom Can be accessed through HTTP, TCP, Named pipes, MSMQ,P2P, Custom
Protocols Security Security, Reliable messaging, Transactions

Introduction to WCF

Windows Communication Foundation (Code named Indigo) is a programming platform and runtime system for building, configuring and deploying network-distributed services. It is the latest service oriented technology; Interoperability is the fundamental characteristics of WCF. It is unified programming model provided in .Net Framework 3.0. WCF is a combined features of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication.

Below figures shows the different technology combined to form WCF.

Advantage
  1. WCF is interoperable with other services when compared to .Net Remoting,where the client and service have to be .Net.
  2. WCF services provide better reliability and security in compared to ASMX web services.
  3. In WCF, there is no need to make much change in code for implementing the security model and changing the binding. Small changes in the configuration will make your requirements.
  4. WCF has integrated logging mechanism, changing the configuration file settings will provide this functionality. In other technology developer has to write the code.
Disadvantage

Making right design for your requirement is little bit difficult.

ASP.NET GridView Mouseover Hover Effect using JQuery

JQuery API has many CSS related functions, which can be used to create many UI effects in the modern web applications. The most common of those methods are addClass, removeClass and toggleClass, which add, remove or toggle CSS classes to any matched element. In this Tutorial, I will show you how you can create a simple mouseover hover effect on ASP.NET GridView Rows using JQuery CSS related methods.

To get things started, create an ASP.NET website and add a GridView control to the page from the Data Category in Toolbox. The following code shows the GridView control I am using for the demonstration of this tutorial. Please set the appropriate properties as shown in the code snippet below.

<form id="form1" runat="server">
<asp:GridView ID="GridView1" runat="server" BackColor="White" Font-Size="10"
Font-Names="Verdana" BorderColor="#000000" BorderStyle="Solid" BorderWidth="1px"
CellPadding="3" Width="400px" CellSpacing="0" GridLines="Horizontal">
</asp:GridView>

</form>

Next I am binding the GridView with a DataTable object that I created in the Page Load event in the code behind file. To keep things simple I am not connecting any database as it is not the purpose of this tutorial. I created a DataTable object with three columns and filled it with some rows using for loop. The complete code of the Page Load event is shown below:

protected void Page_Load(object sender, EventArgs e)
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
if (GridView1.Rows.Count > 0)
{
GridView1.UseAccessibleHeader = true;
GridView1.HeaderRow.TableSection = TableRowSection.TableHeader;

}
}

By default, The GridView control doesn’t render the <th> tags for the header row which can be an issue for sites where standard compliance and accessibility are important. When we set the property UseAccessibleHeader = true, it replaces the <td> elements of the header row with the correct <th> element. The HeaderRow.TableSection property of GridView control generates <thead> and <tbody> tags to make generated code more accessible. Build and run your project, and you will see the following output.

GridView without Highlighting

Although the above output looks very simple but the important thing to note is the HTML generated by the GridView control. Please check the source code of the page from the browser View Source option and see the HTML table code is generated. Next you need to add following CSS style rules inside the <head> section of the page. We will use the headerRow, highlightRow and selectedRow CSS classes in JQuery code in few minutes.

<style type="text/css">
th
{
text-align:left;
}
.headerRow
{
background-color: #000000;
color:White;
font-weight:bold;
}
.highlightRow
{
background-color: #dadada;
cursor: pointer;
border:solid 1px black;
}
.selectedRow
{
background-color: #808080;
cursor: pointer;
border:solid 1px black;
color:White;
}
</style>

Next add the JQuery script file reference inside the <head> section of the page depending on the script file location and JQuery version you are using.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>

Next add the following JQuery code inside a script block in<head>section of the page.

<script type="text/javascript">
$(document).ready(function () {
$('#GridView1 thead').addClass('headerRow');
$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

});
</script>

The code defines typical JQuery ready method, which is used to access and manipulate DOM elements when they are loaded by the browser. The first line of code uses a JQuery selector to select<thead>section of the html table and adds a CSS class to the element using JQuery APIaddClass method.

$('#GridView1 thead').addClass('headerRow');

Next I am adding a sequence of three JQuery events mouseover, mouseout and click to the table rows<tr>elements.

$('#GridView1 tbody tr').mouseover(function () {
$(this).addClass('highlightRow');
}).mouseout(function () {
$(this).removeClass('highlightRow');
}).click(function () {
$(this).toggleClass('selectedRow');
});

Each one of these events takes a function handler as a parameter in which you can write code you want to execute when these events occur on table rows. I am using addClass method to add CSS class inside mouseover event handler and removing the same CSS class using theremoveClass method inside mouseout event handler. This will give you hover effect when you will move the mouse on table rows. The clickevent handler uses JQuery API toggleClass method which adds or removes CSS classes based on the class presence. You can read more about these methods at the following URL on JQuery website.
http://api.jquery.com/category/css
If you have followed the complete tutorial with me you will see the GridView with mouseover hover and click effects as shown in the following figure.

GridView with mouseover hover and click effect

I hope you have enjoyed this tutorial as much as I have enjoyed writing it. You can download the full source code of this tutorial by clicking theDownload Source Code button at the top of this page. You can also watch the live demo by clicking the Live Demo button.

Download Source Code

Calling ASP.NET Web Services using JQuery AJAX

AJAX has changed the way we developed web sites in the past by giving them responsiveness similar to Desktop applications. In Plain English, AJAX means that instead of waiting for the whole web page to load you can load and display only what you need to. Technically speaking, it’s a technique to communicate with servers through JavaScript asynchronously and handle external data. In this tutorial, I will show you how you can call ASP.NET web service using JQuery, which is the most popular and widely used JavaScript library.

To start communicating with ASP.NET web service through JQuery we first need to implement our web service. Create an ASP.NET web site project in Visual Studio and add an ASP.NET Web Service by right clicking the project name and choosing Add New Item option as shown in the figure below.

Add New Item Dialog

Once the Add New Item dialog box appears, select Web Service (.asmx) item from the list and give web service a suitable name such asDateWebService.asmx. Visual Studio will create a web service (.asmx) and related code behind files in the project. You need to add a method GetDateTime in web service code behind file but keep in mind that we will call this web service from JavaScript so you need to remove comments from the attribute System.Web.Script.Services.ScriptService of your class. The complete code of the web service class is shown below.

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class DateWebService : System.Web.Services.WebService {
public DateWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetDateTime() {
return DateTime.Now.ToString();
}

}


The web service code is pretty straight forward as there is only one method GetDateTime defined returning the current Date and Time using DateTime.Now property. Before calling the service method using JQuery you need to keep in mind few restrictions on calling service methods from JavaScript. To preventing some security vulnerabilities, ASP.NET service validation layer checks for following two things when service methods are called from JavaScript.

  1. Only POST method can be used to call a web service method. You cannot use HTTP GET.
  2. The HTTP content-type header should be set to the value "application/json".
For those of you who are not familiar with JSON may be wondering what is json and where it came from. So don’t worry I have some basic introduction for you in this tutorial as we will use it in few minutes using JQuery AJAX. In modern AJAX based web applications, when web services are called from client applications, they normally return XML formatted response, which can be parsed and use in JavaScript, but it complicates things for developers. They need a simple data structure which can be used more easily than XML. This is where JavaScript Object Notation (JSON) comes to help us with the following major features.
  1. Lightweight data-interchange format.
  2. Easy for humans to read and write.
  3. Easy for machines to parse and generate.
  4. JSON can be parsed trivially using the JavaScript eval() procedure or using some useful methods in JQuery API.
  5. JSON supports almost all modern languages such as ActionScript, C, C#, ColdFusion, Java, JavaScript, Perl, PHP, Python, Ruby and many more.

Any .NET object you return from web service methods can be serialized in JSON format. To get some familiarity with JSON format, let’s say you have following custom Product object initialized with some properties.

Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };


If you will serialize the object in JSON format it will produce the following output:

{
"Name": "Apple",
"Expiry": new Date(1230422400000),
"Price": 3.99,
"Sizes": [
"Small",
"Medium",
"Large"
]
}


You can see from the above output that JSON data structure is very easy to read and understand. If you are a .NET developer and want to learn more about serialization and de-serialization of .NET objects into JSON, I will recommend you to use free JSON.NET library available atjson.codeplex.com.
Let’s come back to our tutorial, we have implemented web service so it’s time to create a web page and call that service using JQuery. Create an ASP.NET web form (.aspx) in your project and add the following button and span tag in web form.

<form id="form1" runat="server">
<input id="Button1" type="button" value="Get Date and Time" />
<br />
<br />
<span id="output" />
</form>


Next add the JQuery library reference and the following JQuery script in the head section of the page.

<script src="Scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#Button1").click(function() {
$.ajax({
type: "POST",
url: "/ASPNET_WebServices_JQuery/DateWebService.asmx/GetDateTime",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg)
{
$("#output").text(msg.d);
}
});

});
});
</script>

The important lines in the above code are when the $.ajax() method is called inside the Button1 click event handler. $.ajax() method performs an asynchronous HTTP AJAX request and can be customized with many parameters. Some of the parameters I used in the above code are explained below:
type: The type of request you want to make "POST" or "GET". The default value of this parameter is "GET"
url: A string containing the URL to which the request is sent. In the code above, I put the website project name followed by the service file name with extension and then the web method name.
data: This parameter contains the data to be sent to the server. For the GET requests it will be appended to the url although you can change this behavior using processData parameter (not used in the above example). I am using empty braces in the above example as I am not passing any parameters to service methods.
contentType: When sending data to the server, use this content-type. Default is "application/x-www-form-urlencoded". Data will always be transmitted to the server using UTF-8 charset. In the above code, I am explicitly using application/json as the contentType.
dataType: The type of data that you're expecting back from the server. If none is specified, JQuery will intelligently try to get the results, based on the MIME type of the response. The available types are xml, html, script, json, jsonp and text.
success: JQuery $.ajax() method also supports many callback functions, which are invoked at the appropriate during the request process. One of them is a success which is called if the request succeeds.
In this tutorial, I have explained all the options used in this example code above but there are more parameters and options available, and If you are interested to read more about JQuery $.ajax() method please visit the JQuery API documentation available athttp://api.jquery.com/jQuery.ajax.
Build and test your page in the browser, and you will see the server time displayed on the page when you will click the button. If you are using FireFox you can even see the JSON formatted response came from the server in my favorite FireFox plug-in Firebug.

JQuery AJAX ASPNET Web Service

In this tutorial, I tried to give you the basic introduction of calling ASP.NET web service using JQuery AJAX along with some explanation of JSON format. In my future tutorials, I will show you more complex interaction between client and server using JQuery AJAX so please keep visiting my website to learn more about the tips and tricks of latest technologies.

Download Source Code

Using JQuery, AJAX, JSON and ASP.NET Web Services

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Due to the latest paradigm shift in web development, more and more websites are loading and displaying all types of dynamic contents on the web pages. Web 2.0 based websites such as Gmail. Facebook and Twitter have not only changed the user’s expectations but also forced developers to learn more dynamic and exciting ways to build web applications. Client side web technologies like AJAX, XHTML, DOM, JavaScript and JQuery are now mandatory ingredients of every web developer resume. In my previous tutorial, I have shown you how you can call ASP.NET web services using JQuery AJAX capabilities. In this tutorial, I will show you how you can pass parameters to web services and how you can use JSON data returned from web services to display dynamic contents on web page.

Create a new ASP.NET website in the visual studio and add following Employee.cs class in App_Code folder of your project. I will be using this class from the web service to return the list of Employee class objects to the clients.

public class Employee
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Salary { get; set; }
}


Next, add an ASP.NET web service EmployeeWebService.asmx in the project by using Add New Item dialog box. The complete web service code is shown below:

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class EmployeeWebService : System.Web.Services.WebService {
List<Employee> list = new List<Employee>();
public EmployeeWebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

}
[WebMethod]
public List<Employee> GetAllEmployees() {
return list;
}

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}

}

In start, the web service declares a list of Employee objects which I will be using to store employee objects for this tutorial.

List<Employee> list = new List<Employee>();


I have added five employee objects to the list in the constructor of the web service. I am using this approach only for simplifying this tutorial as in a real world application these records are normally stored in the database.

list.Add(new Employee { Id = 1, Name = "Peter", Salary = 22000 });
list.Add(new Employee { Id = 2, Name = "Mark", Salary = 24000 });
list.Add(new Employee { Id = 3, Name = "James", Salary = 28000 });
list.Add(new Employee { Id = 4, Name = "Simon", Salary = 29000 });
list.Add(new Employee { Id = 5, Name = "David", Salary = 19000 });

A web method GetAllEmployees returns the list of employees to the clients.

[WebMethod]
public List GetAllEmployees()
{
return list;
}


Another simple web method GetEmployeeDetails will filter and return a single Employee object based on employee id.

[WebMethod]
public Employee GetEmployeeDetails(string employeeId)
{
int empId = Int32.Parse(employeeId);
Employee emp = list.Single( e => e.Id == empId);
return emp;
}


Next add the following code in your web page in HTML source. It has a DropDownList to display all employees and an HTML table to display single employee details.

<form id="form1" runat="server">
Select Employee:
<asp:DropDownList ID="DropDownList1" runat="server" Width="150">
<asp:ListItem Text="Select" Value="-1" />
</asp:DropDownList>

<br />
<br />
<table style="border: solid 1px black; width: 300px; display: none; background-color: #f3f3f3"
cellpadding="4" cellspacing="0" id="outputTable">
<tr>
<td>Employee ID:</td>
<td><span id="spnEmployeeId" /></td>
</tr>
<tr>
<td>Employee Name:</td>
<td><span id="spnEmployeeName" /></td>
</tr>
<tr>
<td>Salary:</td>
<td><span id="spnSalary" /></td>
</tr>
</table>
</form>

Before staring JQuery AJAX code make sure you have JQuery file available in the scripts folder of your website, and you have added file reference in the page <head> element.
<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Next add a JavaScript code block and typical JQuery ready function to get things started when the document is ready and DOM tree is loaded by the browser. The first statement is a call to another JavaScript function GetAllEmployees which is declared just after ready function. This function will call GetAllEmployees web service method, and then it will populate the DropDownList control from the JSON data returned from the web service method. Next the DropDownList change event function handler is defined, which first gets the selected employee id from theDropDownList using JQuery val method and then pass that employee id to another JavaScript function GetEmlployeeDetails which will retrieve details of that particular employee by calling web service GetEmployeeDetails method and then will display details in HTML table.

<script type="text/javascript">
$(document).ready(function () {
// Load Employees
GetAllEmployees();
var DropDownList1 = $("#DropDownList1");
DropDownList1.change(function (e) {
var employeeId = DropDownList1.val();
if (employeeId != -1) {
// Get Employee Details
GetEmployeeDetails(employeeId);
} else {
$("#outputTable").hide();
}
});
});
function GetAllEmployees() {
// JQuery AJAX Code Here
}
function GetEmployeeDetails(employeeId) {
// JQuery AJAX Code Here
}

</script>


As you can see in the above code, I didn’t define the GetAllEmployees and GetEmployeeDetails functions so that you can focus on ready function implementation and can understand more easily what is going on in JQuery ready function. To complete this tutorial, I need to show you the code required inside the above two functions to call web services methods and to update controls and user interface elements. Following is the implementation of GetAllEmployees function:

function GetAllEmployees()
{
var DropDownList1 = $("#DropDownList1");
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetAllEmployees",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
var Employees = response.d;
$.each(Employees, function (index, employee) {
DropDownList1.append('<option value="' + employee.Id + '">' + employee.Name + '</option>');
});

},
failure: function (msg) {
alert(msg);
}
});
}


In the above code snippet, JQuery ajax() method is used to send AJAX request to ASP.NET web service method GetAllEmployees. From the parameters, you can easily guess the service method url, request type (POST) and data type (JSON). If you are not familiar with the ajax()method parameters, I will recommend you to read my tutorial Calling ASP.NET Web Services using JQuery AJAX for more detailed understanding of the ajax() method and JSON.
Inside the success function handler of ajax() method, I have used JQuery each() method to loop through all the employees I received in JSON response (response.d) and I appended the HTML elements inside DropDownList to display all employees. If you will build and test your page in the browser you will see DropDownList populate with employee names as shown in the following figure. You can also see the JSON response inFireBug just below to the DropDownList.

JQuery AJAX JSON Response

The following is the code required for the GetEmployeeDetails function. The code is almost similar to the GetAllEmployees function as it is also using JQuery ajax() method to call web service method but there are two differences. First, I am passing employee id as a parameter in JSON format using the data option of JQuery ajax() method. Second, inside success method I am not using any loop to iterate employees as there is only one employee to receive from the web service method. Note the Employee class properties Id, Name and Salary are used to display values inside span elements declared in HTML table above.

function GetEmployeeDetails(employeeId)
{
$.ajax({
type: "POST",
url: "EmployeeWebService.asmx/GetEmployeeDetails",
data: "{'employeeId':'" + employeeId + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response)
{
var Employee = response.d;
$("#spnEmployeeId").html(Employee.Id);
$("#spnEmployeeName").html(Employee.Name);
$("#spnSalary").html(Employee.Salary);
$("#outputTable").show();

},
failure: function (msg)
{
alert(msg);
}
});
}

That’s all we need to call web service methods using JQuery AJAX and to display single or multiple records coming from web service method in JSON format. Build and run your web page, and you will see output similar to following figure:

JQuery AJAX JSON Response

 

Download Source Code Download Source Code Live Demo Live Demo

Select Deselect GridView Rows using a Checkbox in JQuery

Many websites require functionality for letting their site visitors to select and deselect all the rows in GridView using a single checkbox normally available in the header row. You may have seen the examples of such functionality in Yahoo Mail or Hotmail inbox where you can select all the emails by clicking the single Checkbox on top of the email's grid. In this tutorial, I will show you how you can provide this functionality in ASP.NET GridView control using few lines of JQuery code.

Select Unselect GridView Rows

To get started, create an ASP.NET website and drag a GridView control on the page. For this tutorial, I am using ID, Name and Salary columns, so I added three bound fields and one TemplateField that will contain the checkboxes in the header as well as in the individual row. Following is the complete HTML source for the GridView control.

<asp:GridView ID="GridView1" runat="server" Font-Size="10pt"
Font-Names="Verdana" CellPadding="4" Width="400px" GridLines="None"
ForeColor="#333333" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:TemplateField>
<HeaderTemplate>
<asp:CheckBox ID="chkHeader" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<asp:CheckBox ID="chkRow" runat="server" />
</ItemTemplate>
</asp:TemplateField>
<asp:BoundField DataField="ID" HeaderText="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />
</Columns>
</asp:GridView>

To keep this tutorial simple, I am not connecting my GridView with the database and showing some sample data in the GridView. Add the following code in the Page Load event of the page to add few rows of data.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData();
}
}
private void LoadData()
{
DataTable table = new DataTable();
table.Columns.Add("ID", typeof(int));
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Salary", typeof(decimal));
for (int i = 1; i < 8; i++)
{
DataRow row = table.NewRow();
row["ID"] = i;
row["Name"] = "Name " + i;
row["Salary"] = 10000 * i;
table.Rows.Add(row);
}
GridView1.DataSource = table;
GridView1.DataBind();
}


Now we need only few lines of JQuery code to provide the functionality of selecting or deselecting rows using the checkbox added in the header of the GridView. Add the JQuery script file reference in the head element of the page.

<script src="scripts/jquery-1.4.3.min.js" type="text/javascript"></script>
Add the following JavaScript block inside the head element of the page.
<script type="text/javascript">
$(document).ready(function() {
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});

});
</script>


The above code is using typical JQuery ready function to add some JQuery statements or code. The first line access the checkbox available in the header row of the GridView using JQuery selector.
var headerCheckbox = $('#GridView1 > tbody > tr > th > input:checkbox');
Once we have the reference of header checkbox, we are using the click event function handler that will allow us to run some code every time user will click the header checkbox. Inside click event function handler, the first line stores the current state of the header checkbox in aheaderChecked variable. The second line gets the reference of all the checkboxes in all the rows in GridView and then set their state to the same state as the header checkbox using JQuery attr function.

headerCheckbox.click(function() {
var headerChecked = $(this).attr('checked');
var rowCheckboxes = $('#GridView1 > tbody > tr > td > input:checkbox');
rowCheckboxes.attr('checked', headerChecked);
});


Build and test your web page and click the checkbox in the header row, and you will be able to select or deselect all checkboxes in GridView rows. You can click the Live Demo button to see the working example of this tutorial.

Download Source Code Download Source Code Live Demo Live Demo

Saving images in database using ASP.NET FileUpload Control

Saving and displaying images in database tables is a common requirement in ASP.NET projects. There are two ways to store images in database either you store image URLs in database as normal string or you store image as binary data. In this tutorial I will show you how you can upload and save images directly in SQL Server database table as binary data.

For this tutorial I have created a table in SQL Server database called Products with three columns, ID, ProductName and ProductImage as shown in the figure below. Note the data type of ProductImage column is varbinary not image. This is because image data type will be removed in future versions of SQL Server database so avoid using image data type.

Sample Table to Store Images

Now let’s take a look at the form I am going to use, to upload images to the above table.

<form id="form1" runat="server">
Product Name:
<asp:TextBox id="txtProductName" runat="server" />
<br />
Product Image:
<asp:FileUpload id="FileUpload1" runat="server" />
<asp:Button id="btnSave" runat="server" Text="Save Product" onclick="btnSave_Click" />
<br /><br />
<asp:Label id="lblMessage" runat="server" />
</form>


The above code looks pretty straightforward as it is just showing one TextBox, one ASP.NET 2.0 FileUpload control and a Button to Save Product Name and Image in database as shown in the following figure:

Following is the C# code for Save Product button click event.

protected void btnSave_Click(object sender, EventArgs e)
{
if(FileUpload1.HasFile)
{
string productName = txtProductName.Text;
byte[] productImage = FileUpload1.FileBytes;
string constr = "Server=TestServer; Database=SampleDB; uid=sa; pwd=abc123";
string query = "INSERT INTO Products(ProductName, ProductImage) VALUES(@ProductName, @ProductImage)";
SqlConnection con = new SqlConnection(constr);
SqlCommand com = new SqlCommand(query, con);
com.Parameters.Add("@ProductName", SqlDbType.NVarChar).Value = productName;
com.Parameters.Add("@ProductImage", SqlDbType.VarBinary).Value = productImage;
con.Open();
int result = com.ExecuteNonQuery();
con.Close();
if (result > 0)
{
lblMessage.Text = "Product Saved Successfully";
}
}
else
{
lblMessage.Text = "Please Select Product Image File";
}
}


The above code is running simple SQL Insert query to store images in database table. FileUpload control HasFile property checks whether user has selected a file or not. FileBytes property returns the image file as the array of bytes.
If you want to upload the image file to a File System then you can also use FileUpload SaveAs method that requires the server path to upload the file. If you want to verify the file size and its type then you can use FileUpload.PostedFile.ContentLength andFileUpload.PostedFile.ContentType properties.

Export ASP.NET GridView to Excel

Many developers use GridView control to display web reports in their ASP.NET websites. GridView control render data in a tabular form just like HTML tables but it lack the functionality of exporting its contents to any other format such as Excel of PDF file. It is very common requirements of many clients to export web report data to Excel file so that they can perform some analysis using Excel built in features. In this Tutorial I will show you how to export GridView control as Excel File.

For the purpose of this tutorial, I setup a sample ASP.NET page showing products from Northwind database using GridView control. I hope the data binding code will not be new for you if you have already read some of the articles related to GridView control on my website. Following is the preview of the page I am going to use to export to excel.

Export to Excel Page

Following Code shows how you can bind data to GridView control in the Page_Load event. Please keep in mind that for brevity I am storing connection string in the code. You should always store your database connection strings in web.config.

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
BindData();
}
}
private void BindData()
{
string constr = @"Server=SampleServer;Database=NORTHWND;uid=test; Password=test;";
string query = "SELECT ProductID, ProductName, UnitPrice FROM Products";
SqlDataAdapter da = new SqlDataAdapter(query, constr);
DataTable table = new DataTable();
da.Fill(table);
GridView1.DataSource = table;
GridView1.DataBind();
}


As you can guess from the above screen shot that the button “Export to Excel” will implement the main export functionality. The code below is the button click event handler code to export GridView control contents to excel but you can use similar code to export to other formats by changing the ContentType property.

Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=Products.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.xls";
StringWriter stringWriter = new StringWriter();
HtmlTextWriter htmlWriter = new HtmlTextWriter(stringWriter);
GridView1.RenderControl(htmlWriter);
Response.Write(stringWriter.ToString());
Response.End();


Sometimes, when you render any asp.net control dynamically as I am doing with the GridView control in this tutorial, you can get HttpExceptionwith the following message:
Control 'GridView1' of type 'GridView' must be placed inside a form tag with runat=server.
The problem can be solved by overriding Page class VerifyRenderingInServerForm method which confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.

public override void VerifyRenderingInServerForm(Control control)
{ }


When you will click the Export to Excel button you will see the following dialog box asking you to open or save dynamically generated Excel file.

Open/Save Excel File Dialog Box

Following screen shot shows you how the data is saved in Excel file.

export_to_excel_preview.JPG