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.
- WCF Service.
- WCF Service host.
- 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.
- Web Service to exchange messages in XML format using HTTP protocol for interoperability.
- 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.
- 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
- 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
- WCF Service is defined by ServiceContract and OperationContract attributes, whereas a Web Service is defined by WebService and WebMethod attributes.
- WCF supports a range of protocols, i.e., HTTP, Named Pipes, TCP, and MSMQ, whereas a Web Service only supports HTTP protocol.
- 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.
- WCF supports a robust security, trustworthy messaging, transaction and interoperability, while a Web Service only supports security services.
- WCF Supports DataContract serializer by employing System.Runtime.Serialization, whereas a Web Service supports XML serializer by making use of System.Xml.Serialization.
- 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.
- 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.
- It is possible to serialize a Hash Table in WCF, but this is not the case in a web service.
- WCF supports several types of bindings like BasicHttpBinding, WSDualHttpBinding, WSHttpBinding, etc., while a web service supports only SOAP or XML.
- WCF supports multithreading by using the ServiceBehavior Class, whereas this is not supported in a web service.
- 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”.
- CREATE TABLE [dbo].[tblEmployees](
- [Id] [int] IDENTITY(1,1) NOT NULL,
- [Name] [nvarchar](50) NULL,
- [Gender] [nvarchar](10) NULL,
- [Salary] [int] NULL,
- PRIMARY KEY CLUSTERED
- (
- [Id] ASC
- )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
- ) ON [PRIMARY]
Step2
Create a procedure named “Sp_Insert”.
- Create PROCEDURE Sp_Insert
- (
- @Name varchar(100),
- @Gender varchar(100),
- @Salary varchar(max)
- )
- AS
- BEGIN
- SET NOCOUNT ON;
- Insert into tblEmployees(Name,Gender,Salary) values(@Name,@Gender,@Salary)
- END
To check the stored procedure, execute it by passing the parameter values.
- exec Sp_Insert 'Satyaprakash Samantaray' , 'Male' , 1000
Use SQL query given below.
- select * from tblEmployees
Step3
Create a WCF Application named “WCFService” to implement Service related stuff to the Application.
Step4
Add the connection string in Web.config file.
Code Ref
- <?xml version="1.0"?>
- <configuration>
- <connectionStrings>
- <add name="Connection" connectionString="Enter Your Connection String Here"/>
- </connectionStrings>
- <system.web>
- <compilation debug="true" targetFramework="4.0" />
- </system.web>
- <system.serviceModel>
- <behaviors>
- <serviceBehaviors>
- <behavior>
- <!-- To avoid disclosing metadata information, set the value below to false before deployment -->
- <serviceMetadata httpGetEnabled="true"/>
- <!-- 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 -->
- <serviceDebug includeExceptionDetailInFaults="false"/>
- </behavior>
- </serviceBehaviors>
- </behaviors>
- <serviceHostingEnvironment multipleSiteBindingsEnabled="true" />
- </system.serviceModel>
- <system.webServer>
- <modules runAllManagedModulesForAllRequests="true"/>
- <!--
- To browse web app root directory during debugging, set the value below to true.
- Set to false before deployment to avoid disclosing web app folder information.
- -->
- <directoryBrowse enabled="true"/>
- </system.webServer>
-
- </configuration>
Code description
- <connectionStrings>
- <add name="Connection" connectionString="Enter Your Connection String Here"/>
- </connectionStrings>
Other Service related tags like <serviceBehaviors> , <serviceDebug> are added here.
The description for the deployment purpose is given below.
Step5
There two important parts added automatically I.e. IService1.cs and Service1.svc .
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
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Runtime.Serialization;
- using System.ServiceModel;
- using System.ServiceModel.Web;
- using System.Text;
-
- namespace WCFService
- {
-
- [ServiceContract]
- public interface IService1
- {
- [OperationContract]
- void InsertMovieData(Movie objmovie);
- }
-
- [DataContract]
- public class Movie
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public string Gender { get; set; }
- [DataMember]
- public string Salary { get; set; }
- }
-
- }
Code description for IService1.cs
The two namespaces used are
- using System.ServiceModel;
This namespace provides classes related to the Service model.
- 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”.
- [ServiceContract]
- 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”.
- [OperationContract]
- void InsertMovieData(Movie objmovie);
Using “[DataContract]” attribute, I created one class named “Movie” with three data variables.
- [DataContract]
- public class Movie
- {
- [DataMember]
- public string Name { get; set; }
- [DataMember]
- public string Gender { get; set; }
- [DataMember]
- public string Salary { get; set; }
- }
You can see also use these methods and DataMembers of Movie class, using Solution Explorer.
Code Ref for Service1.svc.cs
- using System.Data;
- using System.Data.SqlClient;
- using System.Configuration;
-
- namespace WCFService
- {
- public class Service1 : IService1
- {
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
- public void InsertMovieData(Movie objmovie)
- {
- SqlCommand cmd = new SqlCommand("Sp_Insert", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Name", objmovie.Name);
- cmd.Parameters.AddWithValue("@Gender", objmovie.Gender);
- cmd.Parameters.AddWithValue("@Salary", objmovie.Salary);
- cmd.ExecuteNonQuery();
- }
- }
Code description for Service1.svc.cs
- 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.
- SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["Connection"].ToString());
Now, I build one method same as in “IService1.cs”
- public void InsertMovieData(Movie objmovie)
- {
- SqlCommand cmd = new SqlCommand("Sp_Insert", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Name", objmovie.Name);
- cmd.Parameters.AddWithValue("@Gender", objmovie.Gender);
- cmd.Parameters.AddWithValue("@Salary", objmovie.Salary);
- cmd.ExecuteNonQuery();
- }
Here, I mentioned my stored procedure and the related parameters for an insert operation.
- SqlCommand cmd = new SqlCommand("Sp_Insert", con);
- cmd.CommandType = CommandType.StoredProcedure;
- con.Open();
- cmd.Parameters.AddWithValue("@Name", objmovie.Name);
- cmd.Parameters.AddWithValue("@Gender", objmovie.Gender);
- cmd.Parameters.AddWithValue("@Salary", objmovie.Salary);
- cmd.ExecuteNonQuery();
You can also use these methods line connections string and parameters of Movie class, using Solution Explorer.
Step 6
Build the project and run.
To check WCF Service working, right click on “Service1.Svc” and view in the Browser.
Here, we can check the WCF Service URL
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,
- Service1Client client = new Service1Client();
- 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.
Here, related Movie class and parameters are defined in the stored procedure.
The “wsdl:portType” is defined in XML format.
Step7
Create ASP.NET Web Application named “Website17” under the same project “WCFService”.
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.
After doing such steps, the “ServiceReference1” will be added in “App_WebReferences” folder.
Here, you will get the earlier described XML file in “Service1.wsdl” file.
Now, you can use WCF Service freely.
Step8
Add a Web page called Default.aspx.
Add one CSS style sheet to give the layout to ASP.NET Server Controls.
Script For “Styles.css”
- body {
- font-family: Arial;
- }
-
- table {
- font-family: arial, sans-serif;
- border-collapse: collapse;
- width: 70%;
- }
-
- .button {
- background-color: #4CAF50;
- border: none;
- color: white;
- padding: 15px 32px;
- text-align: center;
- text-decoration: none;
- display: inline-block;
- font-size: 14px;
- margin: 4px 2px;
- cursor: pointer;
- }
-
- .button4 {border-radius: 14px;}
-
- .textbox {
- height: 50px;
- padding: 0 10px;
- border: none;
- background: Orange;
- background: Orange;
- box-shadow: inset 0 0 10px rgba(255, 255, 255, 0.5);
- font-family: 'Montserrat', sans-serif;
- text-indent: 10px;
- color: blue;
- text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
- font-size: 20px;
- width: 470px;
- }
- .textbox:focus {
- 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);
- outline: none;
- background: Orange;
- background: Orange;
- outline: solid 1px yellow;
- }
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”
- function Required(ctrlID, ctrlName) {
- var txtControl = document.getElementById(ctrlID);
- var string = document.getElementById(ctrlID).value;
- var spaceCount;
-
- if (txtControl.value == '') {
- alert('Enter ' + ctrlName + '.');
- txtControl.focus();
-
- return false;
- }
- else {
- spaceCount = 0;
- for (var count = 0; count < string.length; count++) {
- var ch = string.substring(count, count + 1);
-
- if (ch == ' ') {
- spaceCount++;
- }
- }
- if (spaceCount == string.length) {
- alert('Please Enter ' + ctrlName + '.');
- txtControl.value = "";
- txtControl.focus();
- return false;
- }
- }
-
- return true;
- }
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”
- <%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
-
- <!DOCTYPE html>
-
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head runat="server">
- <title>Satyaprakash Wcf Concept</title>
- <link href="Styles.css" rel="stylesheet" />
- <script language="javascript" src="../Validation.js" type="text/javascript"></script>
- <script language="javascript" type="text/javascript">
- function Validation() {
- if (Required('<%=txtname.ClientID%>', ' Name'))
- if (Required('<%=txtGender.ClientID%>', ' Gender'))
- if (Required('<%=txtsalary.ClientID%>', ' Salary'))
- return true;
- return false;
- }
- </script>
- </head>
- <body>
- <form id="form1" runat="server">
- <div>
- <h2 style="background-color: Yellow;color: Blue; text-align: center; font-style: oblique">SATYAPRAKASH's WCF CONCEPT</h2>
- <fieldset>
- <legend style="font-family:Arial Black;color:orangered">WCF INSERT USING STORED PROCEDURE</legend>
- <table align="center" border="1" cellpadding="4" cellspacing="4">
- <tr><td align="center"><asp:TextBox ID="txtname" class="textbox" runat="server" placeholder="Enter Name.."></asp:TextBox></td></tr>
- <tr><td align="center"> <asp:TextBox ID="txtGender" class="textbox" runat="server" placeholder="Enter Gender.." ></asp:TextBox></td></tr>
- <tr><td align="center"><asp:TextBox ID="txtsalary" class="textbox" runat="server" placeholder="Enter Salary.."></asp:TextBox></td></tr>
- <tr><td align="center">
- <asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" OnClick="btnsave_Click" OnClientClick="javascript:return Validation();" />
- <asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" OnClick="btnreset_Click"/>
- </td></tr>
- </table>
- </fieldset>
- </div>
- <footer>
- <p style="background-color: Yellow; font-weight: bold; color:blue; text-align: center; font-style: oblique">© <script> document.write(new Date().toDateString()); </script></p>
- </footer>
- </form>
- </body>
- </html>
Code description of “Default.aspx”
Here, I added 3 textboxes and 2 Button controls. The validation for 3 textboxes is given below.
- <table align="center" border="1" cellpadding="4" cellspacing="4">
- <tr><td align="center"><asp:TextBox ID="txtname" class="textbox" runat="server" placeholder="Enter Name.."></asp:TextBox></td></tr>
- <tr><td align="center"> <asp:TextBox ID="txtGender" class="textbox" runat="server" placeholder="Enter Gender.." ></asp:TextBox></td></tr>
- <tr><td align="center"><asp:TextBox ID="txtsalary" class="textbox" runat="server" placeholder="Enter Salary.."></asp:TextBox></td></tr>
- <tr><td align="center">
- <asp:Button ID="btnsave" runat="server" Text="Save" class="button button4" OnClick="btnsave_Click" OnClientClick="javascript:return Validation();" />
- <asp:Button ID="btnreset" runat="server" Text="Reset" class="button button4" OnClick="btnreset_Click"/>
- </td></tr>
- </table>
Step9
Code ref of “Default.aspx.cs”
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.UI;
- using System.Web.UI.WebControls;
- using ServiceReference1;
-
- public partial class _Default : System.Web.UI.Page
- {
- protected void Page_Load(object sender, EventArgs e)
- {
-
- }
-
- protected void btnsave_Click(object sender, EventArgs e)
- {
- try
- {
- Service1Client client = new Service1Client();
- Movie objmovie = new Movie();
- objmovie.Name = txtname.Text;
- objmovie.Gender = txtGender.Text;
- objmovie.Salary = txtsalary.Text;
- client.InsertMovieData(objmovie);
- Response.Write("<script>alert('Record Is Inserted Successfully');</script>");
- ClearControls();
- }
- catch (Exception ex)
- {
-
- }
- }
- protected void btnreset_Click(object sender, EventArgs e)
- {
- ClearControls();
- }
- private void ClearControls()
- {
- txtname.Text = string.Empty;
- txtGender.Text = string.Empty;
- txtsalary.Text = string.Empty;
- }
- }
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.
- protected void btnsave_Click(object sender, EventArgs e)
- {
- try
- {
- Service1Client client = new Service1Client();
- Movie objmovie = new Movie();
- objmovie.Name = txtname.Text;
- objmovie.Gender = txtGender.Text;
- objmovie.Salary = txtsalary.Text;
- client.InsertMovieData(objmovie);
- Response.Write("<script>alert('Record Is Inserted Successfully');</script>");
- ClearControls();
- }
- catch (Exception ex)
- {
-
- }
- }
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.
- Service1Client client = new Service1Client();
- Movie objmovie = new Movie();
We can assign textbox values to insert the parameters of the stored procedure.
- objmovie.Name = txtname.Text;
- objmovie.Gender = txtGender.Text;
- objmovie.Salary = txtsalary.Text;
Use the generated client class to call the Service.
- 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.
- 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.
- private void ClearControls()
- {
- txtname.Text = string.Empty;
- txtGender.Text = string.Empty;
- txtsalary.Text = string.Empty;
- }
Proceed, as shown below in both button click events.
- protected void btnreset_Click(object sender, EventArgs e)
- {
- ClearControls();
- }
Step10
In the Web.Config of Website project, you will get the WCF Service URL.
Code Ref
- <client>
- <endpoint address="http://localhost:63144/Service1.svc" binding="basicHttpBinding"
- bindingConfiguration="BasicHttpBinding_IService1" contract="ServiceReference1.IService1"
- name="BasicHttpBinding_IService1" />
- </client>
Code description
The WCF Service URL is : http://localhost:63144/Service1.svc
Output
The URL is : http://localhost:58041/Default.aspx
The validation of the textboxes will occur if empty.
Afterwards, put all the values in the textboxes and an insert will be successful.
Check, whether Reset button is working fine or not.
Check the back-end if the record is inserted or not.
Now, it is working fine.
Summary
- What is WCF Service.
- Add WCF in ASP.NET Application project.
- Add CSS and JavasSript in ASP.NET Application project.
- WCF using stored procedure.