WCF Using Stored Procedure In ASP.NET To Insert Records

Introduction

WCF refers to Windows Communication Foundation and is a part of .NET 3.0 Framework. WCF is a product developed by Microsoft. It is called for distributed applications.

WCF was released for the first time in 2006 as a part of the .NET framework with Windows Vista. It is also known as the Service Model. This means the Applications where parts of it are run on more than two computers. These Applications are also called inter-connected systems with one Application running on one machine and a WCF Service running on another machine.

A WCF application consists of three components, which are given below.

  1. WCF Service.
  2. WCF Service host.
  3. WCF Service client.

Three tier architecture based Applications mostly use distributed Applications. Three tier architecture based applications may need to use the Services provided by other organizations. For example, Flipkart and Amazon using Paypal and Visa service for payments. For better Security, an enterprise Web Application may have Presentation tier, Business tier, and Data Access tier. Each tier might run on two or more machines.

An Application that can be used by any other Application built on any platform and using any programming language, like C# , Java etc. is called an interoperable Application. WCF Services are interoperable.

Difference between Web Services & .NET Remote Service

Web Services can communicate with any Application built on any platform, whereas a .NET Remote Service can be consumed only by a .NET Application.

  1. Web Service to exchange messages in XML format using HTTP protocol for interoperability.
  2. A remote Service to exchange the messages in the binary format, using TCP protocol for the performance.

Real Time example for better understanding about WCF

Let’s have 2 customers and we need to build a Service a for them. 

  1. The first customer is using a PHP Application to interact with our Service, so for interoperability requirement of this customer, the messages needs to be in XML format and the protocol will be HTTP
  2. The second customers uses .NET for the better performance. AS per the requirement of this customer, the message will be in the binary format and the protocol to be TCP protocol.

You implement one Service and we can configure as many end-points as we want to support all the customers' needs. To support the two customers' requirements given above, we would configure two end points. In the endpoint configuration, we can specify the protocols and the message formats, which we want to use.

WCF = WEB SERVICES + .NET REMOTE SERVICES.

If we do not use WCF for those two clients, then for the first client, we should use Web Services i.e. ASMX Web Service.

For the second client, we should use .NET Remote Services.

In order to collaborate and bring all these technologies under single part, Microsoft has introduced a single programming model called WCF - Windows Communication Foundation.

The developers work is minimized, simple and less time consuming.

The Services are based on different transport protocols and message formats.

We should use a single WCF Service and configure different end points to support different transport protocols and message formats.

PortType

In WSDL document, there is a stuff called PortType. This portType is the interface, which the client uses to communicate with the WCF Service. When you don't set the Name property on a Service contract attribute, by default, the name attribute of the portType XML element in WSDL will be the name of the Service contract interface.

Use Name property of ServiceContractAttribute and give it an explicit name to prevent the clients from breaking when you change the Service contract interface name.

What Is DataContract and DataMember?

Both are the Attributes.

Difference Between Serialization & Deserialization

Serialization is the process of converting an object into an XML representation. The reverse process, that is reconstructing the same object from the XML is called as Deserialization.

By default, WCF uses DataContractSerializer. 

What is KnownType attribute?

If the classes related by inheritance, the WCF Service generally accepts and returns the base type. If you expect the Service to accept and return the inherited types, use KnownType attribute.

Use Microsoft Service Configuration Editor to enable tracing and message logging in WCF. This can be done either on the client or the WCF Service.

Difference Between Data Contracts & Message Contracts

With Data Contracts, we have very limited control over the SOAP XML request and response messages that are generated. Use Message Contracts, if you want to have full control over the generated XML SOAP messages. 

Important notes In WCF

Endpoint

It defines the address where a message is to be sent or received. The communication mechanism to describe how the messages will be sent along with defined the set of the messages. A structure of an endpoint related to the parts given below.

  • Address
    Address specifies the exact location to receive the messages and is specified as a Uniform Resource Identifier (URI). It is expressed as a scheme://domain[:port]/[path]. Take a look at the address mentioned below.

    net.tcp://localhost:2000/ServiceB

    Here, 'net.tcp' is the scheme for the TCP protocol. The domain is 'localhost', which can be the name of a machine or a Web domain, and the path is ' ServiceB '.
  • Binding
    It defines the way an endpoint communicates. It consists of some binding elements, which make the infrastructure for the communication. For example, a binding states the protocols used for transport like TCP, HTTP etc. and the format of the message encoding in addition to the protocols related to the security as well as reliability.

  • Contracts
    It is a collection of operations, which specifies what functionality; the endpoint exposes to the client. It generally consists of an interface name.

Hosting

WCF Service hosting, which can be done through many available options like self-hosting, IIS hosting and WAS hosting.

Metadata

It facilitates an easy interaction between a client Application and a WCF Service. Normally, metadata for a WCF Service is generated automatically when enabled and this is done by inspection of the Service and its endpoints.

Message

This is a communication unit, which consists of several parts apart from the body. Message instances are sent as well as received for all the types of communication between the client and the Service.

WCF Client

A client Application, which gets created for exposing the Service operations in the form of methods refers to a WCF client. This can be hosted by any Application and even the one that does Service hosting.

Channel

Channel is a medium through which a client communicates with a Service. Different types of channels gets stacked and are known as Channel Stacks.

SOAP

SOAP refers to ‘Simple Object Access Protocol’. SOAP is not a transport protocol; instead it is an XML document comprising of a header and body section.

Advantages of WCF

  • It is interoperable with respect to other Services. This is in sharp contrast to .NET Remote in which both the client and the Service must have .NET.
  • WCF Services offer enhanced reliability as well as security in comparison to ASMX (Active Server Methods) Web Services.
  • Implementing the security model and binding change in WCF does not require a major change in the coding. Just a few configuration changes are required to meet the constraints.
  • WCF has built-in logging mechanism whereas in other technologies, it is essential to do the requisite coding.
  • WCF has integrated AJAX and support for JSON (JavaScript object notation).
  • It offers scalability and support for up-coming Web Service standards.
  • It has a default security mechanism, which is extremely robust.

Difference Between WCF & Web Services

  1. WCF Service is defined by ServiceContract and OperationContract attributes, whereas a Web Service is defined by WebService and WebMethod attributes.
  2. WCF supports a range of protocols, i.e., HTTP, Named Pipes, TCP, and MSMQ, whereas a Web Service only supports HTTP protocol.
  3. The activation mechanisms are there for WCF hosting, i.e., IIS (Internet Information Service), WAS (Windows Activation Service), Self-hosting and Windows Service, but a web service is hosted only by IIS.
  4. WCF supports a robust security, trustworthy messaging, transaction and interoperability, while a Web Service only supports security services.
  5. WCF Supports DataContract serializer by employing System.Runtime.Serialization, whereas a Web Service supports XML serializer by making use of System.Xml.Serialization.
  6. ServiceMetadata tool (svcutil.exe) is used for client generation for a WCF service, while WSDL.EXE tool is used for generating the same for a web service.
  7. In WCF, unhandled exceptions are handled in a better way by making use of FaultContract. They do not return to the client like in a web service as SOAP faults.
  8. It is possible to serialize a Hash Table in WCF, but this is not the case in a web service.
  9. WCF supports several types of bindings like BasicHttpBinding, WSDualHttpBinding, WSHttpBinding, etc., while a web service supports only SOAP or XML.
  10. WCF supports multithreading by using the ServiceBehavior Class, whereas this is not supported in a web service.
  11. Web services have .asmx extension But WCF services have .svc extension.

Contracts are basically of four types

Service contract 
This contract provides the information to the client as well as to the outside world about the offerings of the endpoint and the protocols to be used in the communication process.

Data contract
The data exchanged by a Service is defined by a data contract. Both the client and the Service has to be in agreement with the data contract.

Message contract
A data contract is controlled by a message contract. It primarily does the customization of the type formatting of the SOAP message parameters. Here, it should be mentioned that WCF employs SOAP format for the purpose of communication. SOAP stands for Simple Object Access Protocol.

Policy and Binding
There are certain pre-conditions for communication with a service, and such conditions are defined by policy and binding contract. A client needs to follow this contract.

There are many types of behaviors that can undergo configuration and come under the service runtime.

Throttling Behavior
Manages the number of the messages processed.

Error Behavior
Defines the result of any internal service error occurrence.

Metadata Behavior
Specifies the availability of the metadata to the outside world.

Instance Behavior
Defines the number of instances, which needs to be created to make them available for the client.

Transaction Behavior
Enables a change in the transaction state in case of any failure.

Dispatch Behavior
Controls the way by which a message gets processed by the infrastructure of WCF.

Concurrency Behavior
Controls the functions, which runs parallel during a client-Server communication.

Parameter Filtering
Features the process of validation of the parameters to a method before it gets invoked.

The two major types of channels that comprise the channel stack are the following ones

Transport Channels
These channels are present at the bottom of a stack and are accountable for sending and receiving messages using transport protocols like HTTP, TCP, Peer-to-Peer, Named Pipes, and MSMQ.

Protocol Channels
Present at the top of a stack, these channels also known as layered channels, implement wire-level protocols by modifying messages.

The WCF Activation and Hosting is done by various mechanisms discussed below in brief.

IIS
IIS stands for Internet Information Service. It offers a myriad of advantages using the HTTP protocol by a service. Here, it is not required to have the host code for activating the service code; instead, the service code gets activated automatically.

Windows Activation Service
This is popularly known as WAS and comes with IIS 7.0. Both HTTP and non-HTTP based communication is possible here by using TCP or Namedpipe protocols.

Self-hosting
This is a mechanism by which a WCF service gets self-hosted as a console application. This mechanism offers amazing flexibility in terms of choosing the desired protocols and setting own addressing scheme.

Windows Service
Hosting a WCF service with this mechanism is advantageous, as the services then remain activated and accessible to the client due to no runtime activation.

Steps to create a simple application using WCF

Step1

Create a table named “tblEmployees”. 

  1. CREATE TABLE [dbo].[tblEmployees](  
  2.     [Id] [int] IDENTITY(1,1) NOT NULL,  
  3.     [Name] [nvarchar](50) NULL,  
  4.     [Gender] [nvarchar](10) NULL,  
  5.     [Salary] [intNULL,  
  6. PRIMARY KEY CLUSTERED   
  7. (  
  8.     [Id] ASC  
  9. )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ONON [PRIMARY]  
  10. ON [PRIMARY]   

Step2

Create a procedure named “Sp_Insert”. 

  1. Create PROCEDURE Sp_Insert  
  2. (  
  3. @Name varchar(100),  
  4. @Gender varchar(100),  
  5. @Salary varchar(max)  
  6. )  
  7. AS  
  8. BEGIN  
  9. SET NOCOUNT ON;  
  10. Insert into tblEmployees(Name,Gender,Salary) values(@Name,@Gender,@Salary)  
  11. END   

To check the stored procedure, execute it by passing the parameter values. 

  1. exec Sp_Insert 'Satyaprakash Samantaray' , 'Male' , 1000   

Use SQL query given below. 

  1. select * from tblEmployees   

ASP.NET

Step3

Create a WCF Application named “WCFService” to implement Service related stuff to the Application.

ASP.NET

Step4

Add the connection string in Web.config file.

Code Ref 

  1. <?xml version="1.0"?>  
  2. <configuration>  
  3.   <connectionStrings>  
  4.     <add name="Connection" connectionString="Enter Your Connection String Here"/>  
  5.   </connectionStrings>  
  6.   <system.web>  
  7.     <compilation debug="true" targetFramework="4.0" />  
  8.   </system.web>  
  9.   <system.serviceModel>  
  10.     <behaviors>  
  11.       <serviceBehaviors>  
  12.         <behavior>  
  13.           <!-- To avoid disclosing metadata information, set the value below to false before deployment -->  
  14.           <serviceMetadata httpGetEnabled="true"/>  
  15.           <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->  
  16.           <serviceDebug includeExceptionDetailInFaults="false"/>  
  17.         </behavior>  
  18.       </serviceBehaviors>  
  19.     </behaviors>  
  20.     <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />  
  21.   </system.serviceModel>  
  22.  <system.webServer>  
  23.     <modules runAllManagedModulesForAllRequests="true"/>  
  24.     <!--  
  25.         To browse web app root directory during debugging, set the value below to true.  
  26.         Set to false before deployment to avoid disclosing web app folder information.  
  27.       -->  
  28.     <directoryBrowse enabled="true"/>  
  29.   </system.webServer>  
  30.   
  31. </configuration>   

Code description 

  1. <connectionStrings>  
  2.     <add name="Connection" connectionString="Enter Your Connection String Here"/>  
  3. </connectionStrings>   

Other Service related tags like <serviceBehaviors> , <serviceDebug> are added here.

The description for the deployment purpose is given below.

ASP.NET

Step5

There two important parts added automatically I.e. IService1.cs and Service1.svc .

ASP.NET

Difference Between IService1.cs and Service1.svc

In WCF Service Applications, we have a Service contract i.e. IService1 for the Service implementation and Service1 as a Web.config file setting configuration. In WCF Service Library, we also have a Service contract i.e. IService1 for the Service implementation and Service1 as an App.config file for the configuration instead of web.config as in the Service Application.

The major difference is that the WCF Service Application has a .svc file, whereas the Service Library does not have a .svc file. Suppose , we want to host this WCF Service Application in IIS, then you need to specify for IIS the execution runtime environment requirements.

Code Ref for IService1.cs 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Runtime.Serialization;  
  5. using System.ServiceModel;  
  6. using System.ServiceModel.Web;  
  7. using System.Text;  
  8.   
  9. namespace WCFService  
  10. {  
  11.       
  12.     [ServiceContract]  
  13.     public interface IService1  
  14.     {  
  15.         [OperationContract]  
  16.         void InsertMovieData(Movie objmovie);  
  17.     }  
  18.   
  19.     [DataContract]  
  20.     public class Movie  
  21.     {  
  22.         [DataMember]  
  23.         public string Name { get; set; }  
  24.         [DataMember]  
  25.         public string Gender { get; set; }  
  26.         [DataMember]  
  27.         public string Salary { get; set; }  
  28.     }  
  29.   
  30. }   

Code description for IService1.cs

The two namespaces used are 

  1. using System.ServiceModel;   

This namespace provides classes related to the Service model. 

  1. using System.ServiceModel.Web;   

This namespace provides classes related to using the Service model on the Web.

Using “[ServiceContract]” attribute, I declared one interface called “IService1”. 

  1. [ServiceContract]  
  2. public interface IService1   

Using “[OperationContract]” attribute inside interface called “IService1” , I called one method from “Service1.svc.cs” called “InsertMovieData” by passing Movie class object “Movie objmovie”. 

  1. [OperationContract]  
  2. void InsertMovieData(Movie objmovie);   

Using “[DataContract]” attribute, I created one class named “Movie” with three data variables. 

  1. [DataContract]  
  2.     public class Movie  
  3.     {  
  4.         [DataMember]  
  5.         public string Name { get; set; }  
  6.         [DataMember]  
  7.         public string Gender { get; set; }  
  8.         [DataMember]  
  9.         public string Salary { get; set; }  
  10.     }   

You can see also use these methods and DataMembers of Movie class, using Solution Explorer.

ASP.NET

Code Ref for Service1.svc.cs 

  1. using System.Data;  
  2. using System.Data.SqlClient;  
  3. using System.Configuration;  
  4.   
  5. namespace WCFService  
  6. {  
  7.     public class Service1 : IService1  
  8.     {  
  9.         SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());  
  10.         public void InsertMovieData(Movie objmovie)  
  11.         {  
  12.             SqlCommand cmd = new SqlCommand("Sp_Insert", con);  
  13.             cmd.CommandType = CommandType.StoredProcedure;  
  14.             con.Open();  
  15.             cmd.Parameters.AddWithValue("@Name", objmovie.Name);  
  16.             cmd.Parameters.AddWithValue("@Gender", objmovie.Gender);  
  17.             cmd.Parameters.AddWithValue("@Salary", objmovie.Salary);  
  18.             cmd.ExecuteNonQuery();  
  19.         }  
  20.     }     

Code description for Service1.svc.cs

  1. using System.Data.SqlClient;  

Using this namespace, I used the Ado.net objects like “SqlConnection” & “SqlCommand” .

Here “Service1.svc.cs” inherits all class properties and methods from “IService1.cs”.

public class Service1 : IService1

Here, I need to add the name of the connection string named “Connection” in Web.Config file. 

  1. SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());   

Now, I build one method same as in “IService1.cs” 

  1. public void InsertMovieData(Movie objmovie)  
  2.         {  
  3.             SqlCommand cmd = new SqlCommand("Sp_Insert", con);  
  4.             cmd.CommandType = CommandType.StoredProcedure;  
  5.             con.Open();  
  6.             cmd.Parameters.AddWithValue("@Name", objmovie.Name);  
  7.             cmd.Parameters.AddWithValue("@Gender", objmovie.Gender);  
  8.             cmd.Parameters.AddWithValue("@Salary", objmovie.Salary);  
  9.             cmd.ExecuteNonQuery();  
  10.         }   

Here, I mentioned my stored procedure and the related parameters for an insert operation. 

  1. SqlCommand cmd = new SqlCommand("Sp_Insert", con);  
  2.             cmd.CommandType = CommandType.StoredProcedure;  
  3.             con.Open();  
  4.             cmd.Parameters.AddWithValue("@Name", objmovie.Name);  
  5.             cmd.Parameters.AddWithValue("@Gender", objmovie.Gender);  
  6.             cmd.Parameters.AddWithValue("@Salary", objmovie.Salary);  
  7.             cmd.ExecuteNonQuery();   

You can also use these methods line connections string and parameters of Movie class, using Solution Explorer.

ASP.NET

Step 6

Build the project and run.

To check WCF Service working, right click on “Service1.Svc” and view in the Browser.

ASP.NET

Here, we can check the WCF Service URL

ASP.NET

I have already created a Service.

To test this WCF Service, you need to create a client and use it to call the Service. You can do this, using the svcutil.exe tool from the command line with the syntax given below.

svcutil.exe http://localhost:63144/Service1.svc?wsdl

You can also access the Service description as a single file.

http://localhost:63144/Service1.svc?singleWsdl

This will generate a configuration file and a code file, which contains the client class. Add the two files to your client Application and use the generated client class to call the Service. For example, 

  1. Service1Client client = new Service1Client();  
  2. client.Close();   

Use the 'client' variable to call operations on the service.

By click on the link : http://localhost:63144/Service1.svc?singleWsdl

You will get the details of “InsertMovieData” method in XML format.

ASP.NET

Here, related Movie class and parameters are defined in the stored procedure.

ASP.NET

The “wsdl:portType” is defined in XML format.

ASP.NET

Step7

Create ASP.NET Web Application named “Website17” under the same project “WCFService”.

ASP.NET

After creating new Website, go to Solution Explore and Right click on Website >> ADD >> Click on Service reference. On clicking Add Service reference, pop up will open. Copy the URL of WCF Service and paste it in the displaying input. Enter the namespace and click Go button. In this Website, ServiceReference1 is the namespace.

ASP.NET

After doing such steps, the “ServiceReference1” will be added in “App_WebReferences” folder.

ASP.NET

Here, you will get the earlier described XML file in “Service1.wsdl” file.

ASP.NET

Now, you can use WCF Service freely.

Step8

Add a Web page called Default.aspx.

ASP.NET

Add one CSS style sheet to give the layout to ASP.NET Server Controls.

Script For “Styles.css” 

  1. body {  
  2.     font-family: Arial;  
  3. }  
  4.   
  5. table {  
  6.             font-family: arial, sans-serif;  
  7.             border-collapse: collapse;  
  8.             width: 70%;  
  9.       }  
  10.   
  11. .button {  
  12.     background-color: #4CAF50;   
  13.     border: none;  
  14.     color: white;  
  15.     padding: 15px 32px;  
  16.     text-align: center;  
  17.     text-decoration: none;  
  18.     display: inline-block;  
  19.     font-size: 14px;  
  20.     margin: 4px 2px;  
  21.     cursor: pointer;  
  22. }  
  23.   
  24. .button4 {border-radius: 14px;}  
  25.   
  26. .textbox {  
  27.     height: 50px;  
  28.     padding: 0 10px;  
  29.     border: none;  
  30.     background: Orange;  
  31.     background: Orange;  
  32.     box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5);  
  33.     font-family: 'Montserrat', sans-serif;  
  34.     text-indent: 10px;  
  35.     color: blue;  
  36.     text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);  
  37.     font-size: 20px;  
  38.     width: 470px;  
  39. }  
  40.  .textbox:focus {  
  41.     box-shadow: 0 1px 0 rgba(255, 255, 255, 0.2), inset 0 1px 1px rgba(0, 0, 0, 0.1), 0 0 0 3px rgba(255, 255, 255, 0.15);  
  42.     outline: none;  
  43.     background: Orange;  
  44.     background: Orange;  
  45.     outline: solid 1px yellow;  
  46. }   

Script description of Styles.css

Follow my link to describe how it is applied in Server controls

http://www.c-sharpcorner.com/blogs/apply-css-in-asp-net-server-controls-in-real-time-scenario

Add one JavaScript file to perform validation to ASP.NET Server Controls.

Script For “Validation.js” 

  1. function Required(ctrlID, ctrlName) {  
  2.     var txtControl = document.getElementById(ctrlID);  
  3.     var string = document.getElementById(ctrlID).value;  
  4.     var spaceCount;  
  5.   
  6.     if (txtControl.value == '') {  
  7.         alert('Enter ' + ctrlName + '.');  
  8.         txtControl.focus();  
  9.   
  10.         return false;  
  11.     }  
  12.     else {  
  13.         spaceCount = 0;  
  14.         for (var count = 0; count < string.length; count++) {  
  15.             var ch = string.substring(count, count + 1);  
  16.   
  17.             if (ch == ' ') {  
  18.                 spaceCount++;  
  19.             }  
  20.         }  
  21.         if (spaceCount == string.length) {  
  22.             alert('Please Enter ' + ctrlName + '.');  
  23.             txtControl.value = "";  
  24.             txtControl.focus();  
  25.             return false;  
  26.         }  
  27.     }  
  28.   
  29.     return true;  
  30.  

Script description of Validation.js

Follow my link to describe how TextBox Validation is done, using JavaScript In ASP.NET in real time scenario.

http://www.c-sharpcorner.com/blogs/textbox-validation-using-javascript-in-asp-net-in-real-time-scenario

Code ref of “Default.aspx” 

  1. <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>  
  2.   
  3. <!DOCTYPE html>  
  4.   
  5. <html xmlns="http://www.w3.org/1999/xhtml">  
  6. <head runat="server">  
  7.     <title>Satyaprakash Wcf Concept</title>  
  8.     <link href="Styles.css" rel="stylesheet" />  
  9.     <script language="javascript" src="../Validation.js" type="text/javascript"></script>  
  10.     <script language="javascript" type="text/javascript">  
  11.         function Validation() {  
  12.             if (Required('<%=txtname.ClientID%>'' Name'))  
  13.                 if (Required('<%=txtGender.ClientID%>'' Gender'))  
  14.                     if (Required('<%=txtsalary.ClientID%>'' Salary'))  
  15.                         return true;  
  16.             return false;  
  17.         }  
  18.     </script>  
  19. </head>  
  20. <body>  
  21.     <form id="form1" runat="server">  
  22.     <div>  
  23.          <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYAPRAKASH's  WCF CONCEPT</h2>  
  24.         <fieldset>  
  25.             <legend style="font-family:Arial Black;color:orangered">WCF INSERT USING STORED PROCEDURE</legend>  
  26.             <table align="center" border="1" cellpadding="4" cellspacing="4">  
  27.             <tr><td align="center"><asp:TextBox ID="txtname" class="textbox" runat="server" placeholder="Enter Name.."></asp:TextBox></td></tr>  
  28.             <tr><td align="center"> <asp:TextBox ID="txtGender" class="textbox" runat="server" placeholder="Enter Gender.." ></asp:TextBox></td></tr>  
  29.             <tr><td align="center"><asp:TextBox ID="txtsalary" class="textbox" runat="server" placeholder="Enter Salary.."></asp:TextBox></td></tr>    
  30.             <tr><td align="center">  
  31.                 <asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" OnClick="btnsave_Click" OnClientClick="javascript:return Validation();" />  
  32.                 <asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" OnClick="btnreset_Click"/>  
  33.             </td></tr>                  
  34.          </table>  
  35.        </fieldset>  
  36.     </div>  
  37.     <footer>  
  38.         <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>  
  39.     </footer>  
  40.     </form>    
  41. </body>  
  42. </html>   

Code description of “Default.aspx”

Here, I added 3 textboxes and 2 Button controls. The validation for 3 textboxes is given below. 

  1. <table align="center" border="1" cellpadding="4" cellspacing="4">  
  2.             <tr><td align="center"><asp:TextBox ID="txtname" class="textbox" runat="server" placeholder="Enter Name.."></asp:TextBox></td></tr>  
  3.             <tr><td align="center"> <asp:TextBox ID="txtGender" class="textbox" runat="server" placeholder="Enter Gender.." ></asp:TextBox></td></tr>  
  4.             <tr><td align="center"><asp:TextBox ID="txtsalary" class="textbox" runat="server" placeholder="Enter Salary.."></asp:TextBox></td></tr>    
  5.             <tr><td align="center">  
  6.                 <asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" OnClick="btnsave_Click" OnClientClick="javascript:return Validation();" />  
  7.                 <asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" OnClick="btnreset_Click"/>  
  8.             </td></tr>                  
  9.          </table>  

ASP.NET

Step9

Code ref of “Default.aspx.cs” 

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.UI;  
  6. using System.Web.UI.WebControls;  
  7. using ServiceReference1;  
  8.   
  9. public partial class _Default : System.Web.UI.Page  
  10. {  
  11.     protected void Page_Load(object sender, EventArgs e)  
  12.     {  
  13.   
  14.     }  
  15.   
  16.     protected void btnsave_Click(object sender, EventArgs e)  
  17.     {  
  18.         try  
  19.         {  
  20.             Service1Client client = new Service1Client();  
  21.             Movie objmovie = new Movie();  
  22.             objmovie.Name = txtname.Text;  
  23.             objmovie.Gender = txtGender.Text;  
  24.             objmovie.Salary = txtsalary.Text;  
  25.             client.InsertMovieData(objmovie);  
  26.             Response.Write("<script>alert('Record Is Inserted Successfully');</script>");  
  27.             ClearControls();  
  28.         }  
  29.         catch (Exception ex)  
  30.         {  
  31.             //;  
  32.         }  
  33.     }  
  34.     protected void btnreset_Click(object sender, EventArgs e)  
  35.     {  
  36.         ClearControls();  
  37.     }  
  38.     private void ClearControls()  
  39.     {  
  40.         txtname.Text = string.Empty;  
  41.         txtGender.Text = string.Empty;  
  42.         txtsalary.Text = string.Empty;  
  43.     }  
  44. }   

Code description of “Default.aspx.cs”

using ServiceReference1;

Here, I used WCF URL Reference namespace.

Inside button, Save click event. I added some code to Insert operation. 

  1. protected void btnsave_Click(object sender, EventArgs e)  
  2.     {  
  3.         try  
  4.         {  
  5.             Service1Client client = new Service1Client();  
  6.             Movie objmovie = new Movie();  
  7.             objmovie.Name = txtname.Text;  
  8.             objmovie.Gender = txtGender.Text;  
  9.             objmovie.Salary = txtsalary.Text;  
  10.             client.InsertMovieData(objmovie);  
  11.             Response.Write("<script>alert('Record Is Inserted Successfully');</script>");  
  12.             ClearControls();  
  13.         }  
  14.         catch (Exception ex)  
  15.         {  
  16.             //;  
  17.         }  
  18.     }   

This will generate a configuration file and a code file, which contains the client class named “Service1Client”.

Here, Class “Movie” creates a object called objmovie. 

  1. Service1Client client = new Service1Client();  
  2. Movie objmovie = new Movie();   

We can assign textbox values to insert the parameters of the stored procedure. 

  1. objmovie.Name = txtname.Text;  
  2. objmovie.Gender = txtGender.Text;  
  3. objmovie.Salary = txtsalary.Text;   

Use the generated client class to call the Service. 

  1. client.InsertMovieData(objmovie);   

Pass the class movie object name with all textbox values to insert operation.

If there is a success, then a message popup will be generated. 

  1. Response.Write("<script>alert('Record Is Inserted Successfully');</script>");   

For “ClearControls();” function, I added some code to reset ASP.NET Server control values inside button reset click event. 

  1. private void ClearControls()  
  2.     {  
  3.         txtname.Text = string.Empty;  
  4.         txtGender.Text = string.Empty;  
  5.         txtsalary.Text = string.Empty;  
  6.     }   

Proceed, as shown below in both button click events. 

  1. protected void btnreset_Click(object sender, EventArgs e)  
  2.     {  
  3.         ClearControls();  
  4.     }  

ASP.NET

Step10

In the Web.Config of Website project, you will get the WCF Service URL.

Code Ref 

  1. <client>  
  2.             <endpoint address="http://localhost:63144/Service1.svc" binding="basicHttpBinding"  
  3.                 bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"  
  4.                 name="BasicHttpBinding_IService1" />  
  5.         </client>   

Code description

The WCF Service URL is : http://localhost:63144/Service1.svc

ASP.NET

Output
ASP.NET

The URL is : http://localhost:58041/Default.aspx

The validation of the textboxes will occur if empty.

ASP.NET

ASP.NET

ASP.NET

Afterwards, put all the values in the textboxes and an insert will be successful.

ASP.NET

ASP.NET

Check, whether Reset button is working fine or not.

ASP.NET

Check the back-end if the record is inserted or not.

ASP.NET

Now, it is working fine.

Summary

  1. What is WCF Service.
  2. Add WCF in ASP.NET Application project.
  3. Add CSS and JavasSript in ASP.NET Application project.
  4. WCF using stored procedure.