Top Banner
Introduction to WCF - WCF tutorial | WCF Tutorial - Windows Communication Foundation | WCF Example | WCF Sample code in asp.net 3.5 | Basic WCF Tutorial for Beginners What is WCF (windows communication foundation) Service ? 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 feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for all .NET communication. Advantages of WCF 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. 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 [ServiceContract] attribute has to be
35
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
Page 1: wcf

Introduction to WCF - WCF tutorial | WCF Tutorial - Windows Communication Foundation | WCF Example | WCF Sample code in asp.net 3.5 | Basic WCF Tutorial for BeginnersWhat is WCF (windows communication foundation) Service?

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

feature of Web Service, Remoting, MSMQ and COM+. WCF provides a common platform for

all .NET communication.

Advantages of WCF1)    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.

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

[ServiceContract] 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

OperationOne-way, Request- Response are the different operations supported in web service

One-Way, Request-Response, Duplex are different type of operations supported in WCF

XMLSystem.Xml.serialization name space is used for serialization

System.Runtime.Serialization namespace is used for serialization

EncodingXML 1.0, MTOM(Message Transmission Optimization Mechanism), DIME, Custom

XML 1.0, MTOM, Binary, Custom

Transports Can be accessed through Can be accessed through

Page 2: wcf

HTTP, TCP, Custom HTTP, TCP, Named pipes, MSMQ,P2P, Custom

Protocols Security Security, Reliable messaging, Transactions

A WCF Service is composed of three components parts viz,

1) Service Class - A WCF service class implements some service as a set of methods.

2) Host Environment - A Host environment can be a Console application or a Windows Service or a Windows Forms application or IIS as in case of the normal asmx web service in .NET.

3) Endpoints - All communications with the WCF service will happen via the endpoints. The endpoint is composed of 3 parts (collectively called as ABC's of endpoint) as defines below:

Address: The endpoints specify an Address that defines where the endpoint is hosted. It’s basically url.

Ex:http://localhost/WCFServiceSample/Service.svc

Binding: The endpoints also define a binding that specifies how a client will communicate with the service and the address where the endpoint is hosted. Various components of the WCF are depicted in the figure below.

"A" stands for Address: Where is the service? "B" stands for Binding: How can we talk to the service? "C" stands for Contract: What can the service do for us?

Different bindings supported by WCF

Binding Description

BasicHttpBinding Basic Web service communication. No security by default

WSHttpBinding Web services with WS-* support. Supports transactions

WSDualHttpBinding Web services with duplex contract and transaction support

WSFederationHttpBinding Web services with federated security. Supports transactions

MsmqIntegrationBinding Communication directly with MSMQ applications. Supports transactions

NetMsmqBinding Communication between WCF applications by using queuing. Supports transactions

NetNamedPipeBindingCommunication between WCF applications on same computer. Supports duplex contracts and transactions

NetPeerTcpBindingCommunication between computers across peer-to-peer services. Supports duplex contracts

NetTcpBindingCommunication between WCF applications across computers. Supports duplex contracts and transactions

BasicHttpBinding Basic Web service communication. No

Page 3: wcf

security by default

WSHttpBinding Web services with WS-* support. Supports transactions

Contract: The endpoints specify a Contract that defines which methods of the Service class will be accessible via the endpoint; each endpoint may expose a different set of methods.

Different contracts in WCF

Service Contract

Service contracts describe the operation that service can provide. For Eg, a Service provide to know the temperature of the city based on the zip code, this service is called as Service contract. It will be created using Service and Operational Contract attribute.

Data Contract

Data contract describes the custom data type which is exposed to the client. This defines the data types, which 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 data types cannot be identified by the client e.g. Employee data type. By using DataContract we can make client to be aware of Employee data type that are 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.

Fault Contract

Suppose the service I consumed is not working in the client application. I want to know the real cause of the problem. How I can know the error? For this we are having Fault Contract. Fault Contract provides documented view for error occurred in the service to client. This helps us to easy identity, what error has occurred.

Overall Endpoints will be mentioned in the web.config file for WCF service like this

<system.serviceModel><services><service name="Service" behaviorConfiguration="ServiceBehavior"><!-- Service Endpoints --><endpoint address="http://localhost:8090/MyFirstWcfService/SampleService.svc" binding="wsHttpBinding" contract="IService"><identity><dns value="localhost"/></identity></endpoint><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/></service></services><behaviors>

Page 4: wcf

<serviceBehaviors><behavior name="ServiceBehavior"><serviceMetadata httpGetEnabled="true"/><serviceDebug includeExceptionDetailInFaults="false"/></behavior></serviceBehaviors></behaviors></system.serviceModel>

Creating simple application using WCF

First open Visual Studio and click file --> Select New --> Website Under that select WCF Service and give name for WCF Service and click OK 

Once you created application you will get default class files including Service.cs and IService.cs

Page 5: wcf

Here IService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.

Now open IService.cs write the following code

[ServiceContract]public interface IService{[OperationContract]string Welcome(string Name);}After that open Service.cs class file and write the following code 

public class Service : IService{public string SampleMethod(string Name){return "First WCF Sample Program " + Name;}}

Here we are using basicHttpBinding for that our web.config file system.serviceModel code should be like this and I hope no need to write any code because this code already exists in your web.config file in system.serviceModel

<system.serviceModel><services><service name="Service" behaviorConfiguration="ServiceBehavior"><!-- Service Endpoints --><endpoint address="" binding="wsHttpBinding" contract="IService"><identity><dns value="localhost"/></identity></endpoint><endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/></service></services><behaviors><serviceBehaviors><behavior name="ServiceBehavior"><serviceMetadata httpGetEnabled="true"/><serviceDebug includeExceptionDetailInFaults="false"/></behavior></serviceBehaviors></behaviors></system.serviceModel>Our WCF service ready to use with basicHttpBinding. Now we can call this WCF Service method console applications

After completion of WCF service creation publish or deploy your WCF Service in your system. If you don’t’ have idea on deploy check this post publish or deploy website

Page 6: wcf

After completion of deploy webservice now we can see how to use WCF Service in our console application

Calling WCF Service using Console Application

To call WCF service we have many ways like using console app, windows app and web app but here I am going for console application.

Create new console app from visual studio select project type as console application gives some name as you like.

After Creation Console application now we need to add WCF reference to our console application for that right click on your windows application and select Add Service Reference

Page 7: wcf

Now one wizard will open in that give your WCF service link and click Go after add your service click OK button.

Page 8: wcf

After completion of adding WCF Service write the following code in Program.cs class file Main method

static void Main(string[] args){ServiceReference1.ServiceClient objService = new ServiceClient();Console.WriteLine("Please Enter your Name");string Message = objService.SampleMethod(Console.ReadLine());Console.WriteLine(Message);Console.ReadLine();}After that open your app.config file and check your endpoint connection for WCF Service reference that should be like this

<endpoint address=" http://localhost/WCFServiceSample/Service.svc"binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"contract="ServiceReference1.IService" name="WSHttpBinding_IService"><identity><dns value="localhost" /></identity>

Page 9: wcf

</endpoint>Now everything is ready run your application that output should be like this

Asp.net WebService or Creating and Consuming WebService in asp.net or Create and call webservice in asp.net or how to create webservice and how to use webservice in asp.net

What is Web Service?

Web Service is an application that is designed to interact directly with other applications over the internet. In simple sense, Web Services are means for interacting with objects over the Internet. The Web serivce consumers are able to invoke method calls on remote objects by using SOAP and HTTP over the Web. WebService is language independent and Web Services communicate by using standard web protocols and data formats, such as

HTTP XML SOAP

Advantages of Web Service

Web Service messages are formatted as XML, a standard way for communication between two incompatible system. And this message is sent via HTTP, so that they can reach to any machine on the internet without being blocked by firewall.

Examples for Web Service

Weather Reporting: You can use Weather Reporting web service to display weather information in your personal website.

Stock Quote: You can display latest update of Share market with Stock Quote on your web site.

Page 10: wcf

News Headline: You can display latest news update by using News Headline Web Service in your website.

In summary you can any use any web service which is available to use. You can make your own web service and let others use it. Example you can make Free SMS Sending Service with footer with your advertisement, so whosoever use this service indirectly advertise your company... You can apply your ideas in N no. of ways to take advantage of it.

Frequently used word with web services

What is SOAP?

SOAP (simple object access protocol) is a remote function calls that invokes method and execute them on Remote machine and translate the object communication into XML format. In short, SOAP are way by which method calls are translate into XML format and sent via HTTP.

What is WSDL? 

WSDL stands for Web Service Description Language, a standard by which a web service can tell clients what messages it accepts and which results it will return.WSDL contains every detail regarding using web service and Method and Properties provided by web service and URLs from which those methods can be accessed and Data Types used.

What is UDDI?

UDDI allows you to find web services by connecting to a directory.

What is Discovery or .Disco Files?

Discovery files are used to group common services together on a web server. Discovery files .Disco and .VsDisco are XML based files that contains link in the form of URLs to resources that provides discovery information for a web service. Disco File contains URL for the WSDL, URL for the documentation and URL to which SOAP messages should be sent.

Before start creating web service first create one table in your database and give name UserInformation in my code I am using same name and enter some dummy data for our testing purpose

Column Name Data Type Allow NullsUserId Int(Set Identity=true) NoUserName Varchar(50) YesFirstName Varchar(50) YesLastName Varchar(50) YesLocation Varchar(50) Yes

Now we will see how to create new web service application in asp.net

Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Service

Page 11: wcf

Now our new web service ready our webservice website like this

Now open your Service.cs file in web service website to write the code to get the user details from database

Before writing the WebMethod in Service.cs first add following namespaces

using System.Xml;using System.Configuration;using System.Data;using System.Data.SqlClient;After adding namespaces write the following method GetUserDetails in Service.cs page

Page 12: wcf

[WebMethod]public XmlElement GetUserDetails(string userName){SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["dbconnection"].ToString());con.Open();SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName like @userName+'%'", con);cmd.Parameters.AddWithValue("@userName", userName);cmd.ExecuteNonQuery();SqlDataAdapter da = new SqlDataAdapter(cmd);// Create an instance of DataSet.DataSet ds = new DataSet();da.Fill(ds);con.Close();// Return the DataSet as an XmlElement.XmlDataDocument xmldata = new XmlDataDocument(ds);XmlElement xmlElement = xmldata.DocumentElement;return xmlElement;}Here we need to remember one point that is adding [WebMethod] before method definition because we need to access web method pulically otherwise it’s not possible to access method publically. If you observe above code I converted dataset to XmlElement t because sometimes we will get error like return type dataset invalid type it must be either an IListSource, IEnumerable, or IDataSource to avoid this error I converted dataset to XmlElement.

Here we need to set the database connection in web.config because here I am getting database connection from web.config

<connectionStrings><add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/></connectionStrings>Now run your web service it would be like this

Our web service is working fine now we need to know how we can use webservice in our application? Before to know about using web service in application first Deploy your webservice application in your local system if you want to know how to deploy application in your local system check this link deploy application in local system

How to Use Web service in web application?

By using this webservice we can get the user details based on username. For that first create one new web application

Open visual studio ---> Select File ---> New ---> Web Site ---> select ASP.NET Web Site

Page 13: wcf

After creation of new website right click on solution explorer and choose “Add web reference” that would be like this

After select Add Web reference option one window will open like this 

Page 14: wcf

Now enter your locally deployed web service link and click Go button after that your web service will found and window will looks like this

Page 15: wcf

Now click on Add Reference button web service will add successfully. Now open your Default.aspx page and design like this

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title>Getting Data from WebService</title></head><body><form id="form1" runat="server"><div><table><tr><td><b>Enter UserName:</b> </td><td><asp:TextBox ID="txtUserName" runat="server"></asp:TextBox></td><td><asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /></td></tr></table></div><div><asp:GridView ID="gvUserDetails" runat="server" EmptyDataText="No Record Found"><RowStyle BackColor="#EFF3FB" /><FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /><PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /><HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /><AlternatingRowStyle BackColor="White" /></asp:GridView></div></form></body></html>Now in code behind add following namespaces

using System.Data;using System.Xml;

After adding namespaces write the following code in code behind

protected void Page_Load(object sender, EventArgs e){if(!IsPostBack){BindUserDetails("");}}

Page 16: wcf

protected void BindUserDetails(string userName){localhost.Service objUserDetails = new localhost.Service();DataSet dsresult = new DataSet();XmlElement exelement = objUserDetails.GetUserDetails(userName);if(exelement!=null){XmlNodeReader nodereader = new XmlNodeReader(exelement);dsresult.ReadXml(nodereader, XmlReadMode.Auto);gvUserDetails.DataSource = dsresult;gvUserDetails.DataBind();}else{gvUserDetails.DataSource = null;gvUserDetails.DataBind();    }}protected void btnSubmit_Click(object sender, EventArgs e){BindUserDetails(txtUserName.Text);}Now run your application and check output

how to consume (or) use wcf service in web application | how to consume (or) use wcf service in asp.net | wcf tutorial with examples for beginners

Creating simple application using WCF

Here I am going to do WCF sample to insert new userdetails and display Userdetails based on UserName for that first create table in your database like this

Column Name Data Type Allow NullsUserId Int(Set Identity=true) NoUserName nvarchar(MAX) YesFirstName varchar(50) YesLastName varchar(50) YesLocation varchar(50) YesAfter that First open Visual Studio and click file ---> Select New ---> Website Under that select WCF Service and give name for WCF Service and click OK

Page 17: wcf

Once you created application you will get default class files including Service.cs and IService.cs

Here IService.cs is an interface it does contain Service contracts and Data Contracts and Service.cs is a normal class inherited by IService where you can all the methods and other stuff.

Now open IService.cs add the following namespaces

using System.Collections.Generic;using System.Runtime.Serialization;using System.ServiceModel;

After that write the following code in IService.cs file

[ServiceContract]public interface IService{[OperationContract]List<UserDetails> GetUserDetails(string Username);

Page 18: wcf

[OperationContract]string InsertUserDetails(UserDetails userInfo);}

// Use a data contract as illustrated in the sample below to add composite types to service operations.[DataContract]public class UserDetails{string username = string.Empty;string firstname = string.Empty;string lastname = string.Empty;string location = string.Empty;

[DataMember]public string UserName{get { return username; }set { username = value; }}[DataMember]public string FirstName{get { return firstname; }set { firstname = value; }}[DataMember]public string LastName{get { return lastname; }set { lastname = value; }}[DataMember]public string Location{get { return location; }set { location = value; }}}After that open Service.cs class file and add the following namespaces

using System.Collections.Generic;using System.Configuration;using System.Data;using System.Data.SqlClient;After that write the following code

public class Service : IService{private string strConnection = ConfigurationManager.ConnectionStrings["dbconnection"].ToString();public List<UserDetails> GetUserDetails(string Username){List<UserDetails> userdetails = new List<UserDetails>();

Page 19: wcf

using (SqlConnection con=new SqlConnection(strConnection)){con.Open();SqlCommand cmd = new SqlCommand("select * from UserInformation where UserName Like '%'+@Name+'%'", con);cmd.Parameters.AddWithValue("@Name", Username);SqlDataAdapter da = new SqlDataAdapter(cmd);DataTable dtresult = new DataTable();da.Fill(dtresult);if(dtresult.Rows.Count>0){for(int i=0;i<dtresult.Rows.Count;i++){UserDetails userInfo = new UserDetails();userInfo.UserName = dtresult.Rows[i]["UserName"].ToString();userInfo.FirstName = dtresult.Rows[i]["FirstName"].ToString();userInfo.LastName = dtresult.Rows[i]["LastName"].ToString();userInfo.Location = dtresult.Rows[i]["Location"].ToString();userdetails.Add(userInfo);}}con.Close();}return userdetails;}public string InsertUserDetails(UserDetails userInfo){string strMessage = string.Empty;using (SqlConnection con=new SqlConnection(strConnection)){con.Open();SqlCommand cmd = new SqlCommand("insert into UserInformation(UserName,FirstName,LastName,Location) values(@Name,@FName,@LName,@Location)", con);cmd.Parameters.AddWithValue("@Name", userInfo.UserName);cmd.Parameters.AddWithValue("@FName", userInfo.FirstName);cmd.Parameters.AddWithValue("@LName", userInfo.LastName);cmd.Parameters.AddWithValue("@Location", userInfo.Location);int result= cmd.ExecuteNonQuery();if(result==1){strMessage = userInfo.UserName+ " Details inserted successfully";}else{strMessage = userInfo.UserName + " Details not inserted successfully";}con.Close();}return strMessage;}}

Now set the database connection string in web.config file because in above I am getting the connection string from web.config file

Page 20: wcf

<connectionStrings><add name="dbconnection" connectionString="Data Source=SureshDasari;Integrated Security=true;Initial Catalog=MySampleDB"/></connectionStrings>Our WCF service ready to use with basicHttpBinding. Now we can call this WCF Service method console applications

After completion of WCF service creation publish or deploy your WCF Service in your system. If you don’t’ have idea on deploy check this post publish or deploy website

After completion of deploy webservice now we can see how to use WCF Service in our console application

Calling WCF Service using Web Application

To call WCF service we have many ways like using console app, windows app and web app in previous post I explained how to call (or) consume WCF service in console application. Now I will explain how to consume WCF service in web application.

Create new website from visual studio select New---> Website and give some name as you like.

After Creation Website now we need to add WCF reference to our web application for that right click on your web application and select Add Service Reference

Page 22: wcf

After completion of adding WCF Service first open Default.aspx page and write the following code

<html xmlns="http://www.w3.org/1999/xhtml"><head runat="server"><title>Untitled Page</title><style type="text/css">.style1 {height: 26px;}</style></head><body><form id="form1" runat="server"><div><table align="center"><tr><td colspan="2" align="center"><b>User Registration</b></td></tr><tr><td>UserName:</td><td><asp:TextBox ID="txtUserName" runat="server"/></td></tr><tr><td>FirstName:</td><td><asp:TextBox ID="txtfname" runat="server"/></td></tr><tr><td>LastName:</td><td><asp:TextBox ID="txtlname" runat="server"/></td></tr><tr><td class="style1">Location:</td><td class="style1"><asp:TextBox ID="txtlocation" runat="server"/></td></tr><tr><td>

Page 23: wcf

</td><td><asp:Button ID="btnSubmit" runat="server" Text="Submit" onclick="btnSubmit_Click" /></td></tr><tr><td colspan="2"><asp:Label ID="lblResult" runat="server"/></td></tr><tr><td colspan="2"><asp:GridView runat="server" ID="gvDetails" AutoGenerateColumns="false"><RowStyle BackColor="#EFF3FB" /><FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /><PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /><HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /><AlternatingRowStyle BackColor="White" /><Columns><asp:BoundField HeaderText="UserName" DataField="UserName" /><asp:BoundField HeaderText="FirstName" DataField="FirstName" /><asp:BoundField HeaderText="LastName" DataField="LastName" /><asp:BoundField HeaderText="Location" DataField="Location" /></Columns></asp:GridView></td></tr></table></div></form></body></html>Now open Default.aspx.cs file and add following namespaces

using System;using System.Collections.Generic;using ServiceReference1;After adding namespaces write the following code in codebehind

ServiceReference1.ServiceClient objService = new ServiceClient();protected void Page_Load(object sender, EventArgs e){if(!IsPostBack){BindUserDetails();}}protected void BindUserDetails(){IList<UserDetails> objUserDetails = new List<UserDetails>();objUserDetails = objService.GetUserDetails("");gvDetails.DataSource = objUserDetails;gvDetails.DataBind();}

Page 24: wcf

protected void btnSubmit_Click(object sender, EventArgs e){UserDetails userInfo = new UserDetails();userInfo.UserName = txtUserName.Text;userInfo.FirstName = txtfname.Text;userInfo.LastName = txtlname.Text;userInfo.Location = txtlocation.Text;string result=  objService.InsertUserDetails(userInfo);lblResult.Text = result;BindUserDetails();txtUserName.Text = string.Empty;txtfname.Text = string.Empty;txtlname.Text = string.Empty;txtlocation.Text = string.Empty;}After completion of adding code check your endpoint connection for WCF Service reference that should be like this

<endpoint address=" http://localhost/WCFServiceSample/Service.svc"binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IService"contract="ServiceReference1.IService" name="WSHttpBinding_IService"><identity><dns value="localhost" /></identity></endpoint>Now everything is ready run your application that output should be like this

how to create Windows Service in c# or windows service sample in c#

What is Windows Service?

Windows Services are applications that run in the background and perform various tasks.

The applications do not have a user interface or produce any visual output. Windows

Services are started automatically when computer is booted. They do not require a logged in

user in order to execute and can run under the context of any user including the system.

Windows Services are controlled through the Service Control Manager where they can be

stopped, paused, and started as needed.

Create a Windows Service 

Creating Windows Service is very easy with visual studio just follow the below steps to

create windows service Open visual studio --> Select File --> New -->Project--> select Windows Service And give name as WinServiceSample

Page 25: wcf

After give WinServiceSample name click ok button after create our project that should like this

In Solution explorer select Service1.cs file and change Service1.cs name to ScheduledService.cs because in this project I am using this name if you want to use another name for your service you should give your required name.

Page 26: wcf

After change name of service open ScheduledService.cs in design view right click and select Properties now one window will open in that change Name value to ScheduledService and change ServiceName to ScheduledService. Check below properties window that should be like this

After change Name and ServiceName properties again open ScheduledService.cs in design view and right click on it to Add Installer files to our application.

The main purpose of using Windows Installer is an installation and configuration service provided with Windows. The installer service enables customers to provide better corporate deployment and provides a standard format for component management.

After click on Add installer a designer screen added to project with 2 controls: serviceProcessInstaller1 and ServiceInstaller1

Now right click on serviceProcessInstaller1 and select properties in that change Account to LocalSystem

Page 27: wcf

After set those properties now right click on ServiceInstaller1 and change following StartType property to Automatic and give proper name for DisplayName property

After completion of setting all the properties now we need to write the code to run the windows services at scheduled intervals.

If you observe our project structure that contains Program.cs file that file contains Main() method otherwise write the Main() method like this in Program.cs file

/// <summary>/// The main entry point for the application./// </summary>static void Main(){ServiceBase[] ServicesToRun;ServicesToRun = new ServiceBase[] { new ScheduledService() };ServiceBase.Run(ServicesToRun);}After completion of adding Main() method open ScheduledService.cs file and add following namespaces in codebehind of ScheduledService.cs file

using System.IO;using System.Timers;If you observe code behind file you will find two methods those are

protected override void OnStart(string[] args){}

protected override void OnStop()

Page 28: wcf

{}We will write entire code in these two methods to start and stop the windows service. Write the following code in code behind to run service in scheduled intervals   //Initialize the timerTimer timer = new Timer();public ScheduledService(){InitializeComponent();}//This method is used to raise event during start of serviceprotected override void OnStart(string[] args){//add this line to text file during start of serviceTraceService("start service");

//handle Elapsed eventtimer.Elapsed += new ElapsedEventHandler(OnElapsedTime);

//This statement is used to set interval to 1 minute (= 60,000 milliseconds)

timer.Interval = 60000;

//enabling the timertimer.Enabled = true;}//This method is used to stop the serviceprotected override void OnStop(){timer.Enabled = false;TraceService("stopping service");}private void OnElapsedTime(object source, ElapsedEventArgs e){TraceService("Another entry at "+DateTime.Now);}private void TraceService(string content){

//set up a filestreamFileStream fs = new FileStream(@"d:\ScheduledService.txt",FileMode.OpenOrCreate, FileAccess.Write);

//set up a streamwriter for adding textStreamWriter sw = new StreamWriter(fs);

//find the end of the underlying filestreamsw.BaseStream.Seek(0, SeekOrigin.End);

//add the textsw.WriteLine(content);//add the text to the underlying filestream

Page 29: wcf

sw.Flush();//close the writersw.Close();}If you observe above code in OnStart method I written event ElapsedEventHandler this event is used to run the windows service for every one minute

After completion code writing build the application and install windows service. To install windows service check this post here I explained clearly how to install windows service and how to start windows service. 

Now the service is installed. To start and stop the service, go to Control Panel --> Administrative Tools --> Services.  Right click the service and select Start. 

Now the service is started, and you will be able to see entries in the log file we defined in the code.

Now open the log file in your folder that Output of the file like this