Академический Документы
Профессиональный Документы
Культура Документы
SEN-371
DISTRIBUTED COMPUTING
LAB MANUAL
SEN-371
DISTRIBUTED COMPUTING
LIST OF EXPERIMENTS
S.No
Topic
Page
Lab 01
03
Lab 02
07
Lab 03
10
Lab 04
13
Lab 05
16
Lab 06
19
Lab 07
22
Lab 08
25
Lab 09
28
Lab 10
30
Lab 11
32
Lab 12
35
Lab 13
37
Lab 14
40
Lab 15
42
Lab 16
43
Lab 01:
Lab Objectives:
Distributed systems offer many benefits over centralized systems, including the following:
Scalability
The system can easily be expanded by adding more machines as needed.
Redundancy
Several machines can provide the same services, so if one is unavailable, work does
not stop. Additionally, because many smaller machines can be used, this redundancy
does not need to be prohibitively expensive
Many home computers are also examples of distributed computing. By using multiple processors
in the same machine, a computer can run separate processes and reach a higher level of
efficiency than otherwise. Many home computers now take advantage of multiprocessing, as
well as a similar practice known as multithreading, to achieve much higher speeds than their
single-processor counterparts.
WCF Service
Windows Communication Foundation (WCF) is a framework for building service-oriented
applications. Using WCF, you can send data as asynchronous messages from one service
endpoint to another. A service endpoint can be part of a continuously available service hosted by
IIS, or it can be a service hosted in an application. An endpoint can be a client of a service that
requests data from a service endpoint. The messages can be as simple as a single character or
word sent as XML, or as complex as a stream of binary data.
Difference between Web Service in ASP.NET & WCF Service
WCF is a replacement for all earlier web service technologies from Microsoft. It also does a lot
more than what is traditionally considered as "web services".
WCF "web services" are part of a much broader spectrum of remote communication enabled
through WCF. You will get a much higher degree of flexibility and portability doing things in
WCF than through traditional ASMX because WCF is designed, from the ground up, to
summarize all of the different distributed programming infrastructures offered by Microsoft. An
endpoint in WCF can be communicated with just as easily over SOAP/XML as it can over
TCP/binary and to change this medium is simply a configuration file mod. In theory, this reduces
the amount of new code needed when porting or changing business needs, targets, etc.
ASMX is older than WCF, and anything ASMX can do so can WCF (and more). Basically you
can see WCF as trying to logically group together all the different ways of getting two apps to
communicate in the world of Microsoft; ASMX was just one of these many ways and so is now
grouped under the WCF umbrella of capabilities.
Web Services can be accessed only over HTTP & it works in stateless environment, where WCF
is flexible because its services can be hosted in different types of applications. Common
scenarios for hosting WCF services are IIS, WAS, Self-hosting, Managed Windows Service.
What is SOA?
In software engineering, a Service-Oriented Architecture (SOA) is a set of principles and
methodologies for designing and developing software in the form of interoperable services.
These services are well-defined business functionalities that are built as software components
(discrete pieces of code and/or data structures) that can be reused for different purposes. SOA
design principles are used during the phases of systems development and integration.
SOA also generally provides a way for consumers of services, such as web-based applications, to
be aware of available SOA-based services. For example, several disparate departments within a
company may develop and deploy SOA services in different implementation languages; their
respective clients will benefit from a well-understood, well-defined interface to access them.
XML is often used for interfacing with SOA services, though this is not required. JSON is also
becoming increasingly common.
SOA defines how to integrate widely disparate applications for a Web-based environment and
uses multiple implementation platforms. Rather than defining an API, SOA defines the interface
in terms of protocols and functionality. An endpoint is the entry point for such a SOA
implementation.
Lab 02:
Introduction to Windows
Communication Foundation (WCF)
Lab Objectives:
Get an idea of WCF (API in the .NET Framework) and its applications.
Know the three key components of a WCF Service.
Understand the architecture of a WCF Service.
What is WCF?
Windows Communication Foundation (WCF) is a framework for building service-oriented
applications. Using WCF, you can send data as asynchronous messages from one service
endpoint to another. Windows Communication Foundation (WCF) is designed to offer a
manageable approach to distributed computing, broad interoperability, and direct support for
service orientation. WCF is meant for designing and deploying distributed applications
under service-oriented architecture (SOA) implementation. WCF simplifies development of
connected applications through a new service-oriented programming model.
WCF supports many styles of distributed application development by providing a layered
architecture. A WCF client connects to a WCF service via an Endpoint. Each service exposes its
contract via one or more endpoints. An endpoint has an address (which is a URL specifying
where the endpoint can be accessed) and binding properties that specify how the data will be
transferred.
1.
Contract definitions
Data contracts and data member
Service contracts
Fault contracts
Message contracts
2. End points
3.
Bindings
BasicHttpBinding
WSHttpBinding
WSDualHttpBinding
WSFederationHttpBinding
MsmqIntegrationBinding
NetMsmqBinding
NetNamedPipeBinding
NetPeerTcpBinding
NetTcpBinding
4. Hosting environments
Windows application
Console application
Windows service
IIS
WAS (Windows Activation Service), comes with IIS 7.0
Architecture of WCF
WCF is meant for designing and deploying distributed applications under service-oriented
architecture (SOA) implementation.
WCF is designed using service oriented architecture principles to support distributed
computing where services have remote consumers. Clients can consume multiple services;
services can be consumed by multiple clients. Services are loosely coupled to each other.
Services typically have a WSDL interface (Web Services Description Language) that any WCF
client can use to consume the service, regardless of which platform the service is hosted on.
WCF implements many advanced Web services (WS) standards such as WS-Addressing, WSReliable Messaging and WS-Security. With the release of .NET Framework 4.0, WCF also
provides RSS Syndication Services, WS-Discovery, routing and better support for REST
services.
WCF supports interoperability with WCF applications running on the same Windows machine or
WCF running on a different Windows machines or standard Web services built on platforms
such as Java running on Windows or other operating systems. WCF does not only support SOAP
messages, it can also be configured to support standard XML data that is not wrapped in SOAP,
or can even be used to support formats such as RSS, or JSON that makes WCF flexible for
current requirements and future changes.
Lab 03:
Lab Objectives:
Code
The Service has two parts one the function or service part second is Interface part. When we cretes a
service it automatically creates its Interface file. For Example for Service.cs it creates IService.cs
Service.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCF_Service
{
publicclassService : IService
{
publicstring helloworld(string name, string language)
{
switch (language)
{
case"en":
return"Hello" + name;
case"es":
return"Hello" + name;
case"ur":
return"Hello" + name;
default:
return"Improper language spacified";
}
}
}
}
10
IService.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
namespace WCF_Service
{
[ServiceContract]
publicinterfaceIService
{
[OperationContract]
string helloworld(string name, string language);
}
}
Screen Shots
11
Conclusion/Result:
The Service is invoked successfully.
12
Lab 04:
Lab Objectives:
An address represents the services location (also known as its endpoint), which
includes the protocol (for example, HTTP) and network address used to access the
service.
A binding specifies how a client communicates with the service (for example,
SOAP, REST, and so on). Bindings can also specify other options, such as security
constraints.
13
System;
System.Collections.Generic;
System.Linq;
System.Runtime.Serialization;
System.ServiceModel;
System.Text;
namespace WcfService1
{
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class
name "Service1" in code, svc and config file together.
public class Service1 : IService1
{
public string hello(string name, string language)
{
switch (language)
{
case "en":
return "Hello " + name;
case "es":
return "Hola " + name;
case "ar":
return "Marhaba " + name;
case "ur":
return "Adaab " + name;
default:
return "Salam " + name;
}
}
}
}
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace ClientApp
{
public partial class Form1 : Form
{
14
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string t1 = textBox1.Text;
string lang = comboBox1.Text;
Service1Client sc = new Service1Client();
textBox2.Text = sc.hello(t1, lang);
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
Snap Shot:
15
Lab 05:
Lab Objectives:
Creating a WCF Web Service:To build a SOAP-based WCF web service in Visual Web Developer, you first create a project of
type WCF Service. SOAP is the default protocol for WCF web services, so no special
configuration is required to create them. Visual Web Developer then generates files for the
WCF service code, an SVC file (Service.svc, which provides access to the service), and a
Web.config file (which specifies the services binding and behavior). Visual Web Developer also
generates code files for the WCF service class and any other code that is part of the WCF
service implementation. In the service class, you define the methods that your WCF web service
makes available to client applications.
Code for the WelcomeSOAPXMLService:// IWelcomeSOAPXMLService.cs
// WCF web service interface that returns a welcome message through SOAP
// protocol and XML data format.
public interface IWelcomeSOAPXMLService
{
// returns a welcome message
string Welcome( string yourName );
} // end interface IWelcomeSOAPXMLService
WCF web-service interface that returns a welcome message through SOAP protocol
and XML format.
// WelcomeSOAPXMLService.cs
// WCF web service that returns a welcome message using SOAP protocol and
// XML data format.
public class WelcomeSOAPXMLService :
{
// returns a welcome message
16
17
the web service. However, if you open the SVC file on disk, it contains only
to indicate the programming language in which the web services code-behind file is written,
the Debug attribute (enables a page to be compiled for debugging), the name of the
service and the code-behind files location. When you request the SVC page in a web
browser, WCF uses this information to dynamically generate the WSDL document.
Deploying the WelcomeSOAPXMLService:You can choose Build Web Site from the Build menu to ensure that the web service compiles
without errors. You can also test the web service directly from Visual Web Developer by
selecting Start Debugging from the Debug menu. The first time you do this, the Debugging Not
Enabled dialog appears. Click OK if you want to enable debugging. Next, a browser window
opens and displays information about the service. This information is generated dynamically
when the SVC file is requested. Once the service is running, you can also access the SVC page
from your browser by typing a URL of the following form in a web browser:
http://localhost:portNumber/virtualPath/Service.svc
By default, the ASP.NET Development Server assigns
a random port number to each website it hosts. You can change this behaviour by going to the
Solution Explorer and clicking on the project name to view the Properties window. Set the Use
dynamic ports property to False and set the Port number property to the port number that you
want to use, which can be any unused TCP port. Generally, you dont do this for web services
that will be deployed to a real web server. You can also change the services virtual path,
perhaps to make the path shorter or more readable.
18
Lab 06:
Lab Objectives:
Create a client application using Windows Presentation Foundation (WPF).
Consume the Web Service created in the previous lab using the client
application.
Introduction:
SOAP stands for Simple Object Access Protocol It is a communication protocol and it is for
communication between applications. SOAP is a format for sending messages. SOAP
communicates via Internet It is platform and language independent .SOAP is based on XML.
A better way to communicate between applications is over HTTP, because HTTP is supported by
all Internet browsers and servers. SOAP was created to accomplish this. SOAP provides a way to
communicate between applications running on different operating systems, with different
technologies and programming languages.
Experiment to perform:
Making a SOAP-based Web Service (using windows form application).
Software used:
Visual studio 2010
Objective:
SOAP is a simple XML-based protocol.
It lets the applications to exchange information over HTTP.SOAP is a protocol for accessing a Web
Service.
Code:
Form1.cs
using
using
using
using
System;
System.Collections.Generic;
System.ComponentModel;
System.Data;
19
using
using
using
using
System.Drawing;
System.Linq;
System.Text;
System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
private ServiceReference1.SOAPXMLServiceClient client;
public Form1()
{
InitializeComponent();
client = new ServiceReference1.SOAPXMLServiceClient();
}
Form1.cs[Design]
20
SOAPXMLService.cs
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Runtime.Serialization;
System.ServiceModel;
System.Text;
ISOAPXMLService.cs
using
using
using
using
using
using
System;
System.Collections.Generic;
System.Linq;
System.Runtime.Serialization;
System.ServiceModel;
System.Text;
[ServiceContract]
public interface ISOAPXMLService
{
[OperationContract]
int compute(int base_ , int power);
}
Service.svc
<%@ ServiceHost Language="C#" Debug="true"
Service="SOAPXML_Service"CodeBehind="~/App_Code/SOAPXML_Service.cs" %>
21
Lab 07:
Lab Objectives:
22
An HTTP request often posts data to a server-side form handler that processes the
data. For example, when a user performs a search or participates in a web-based survey, the
web server receives the information specified in the XHTML form as part of the request.
Both types of requests can be used to send form data to a web server, yet each request type
sends the information differently.
23
The URL specifies the location of the Service.svc file and uses the URI template to
invoke method Welcome with the argument Bruce. The browser displays the XML data
response from WelcomeRESTXMLService.
Task:
To invoke the REST-based Service.
24
Lab 08:
Lab Objectives:
Code
Rest.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
// NOTE: You can use the "Rename" command on the "Refactor" menu to change the class
name "REST" in code, svc and config file together.
public class REST : IREST
{
public string mannan(string value)
{
char[] arr = value.ToCharArray();
Array.Reverse(arr);
return new string(arr);
}
}
IREST.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Web;
25
[ServiceContract]
public interface IREST
{
[OperationContract]
[WebGet(UriTemplate = "/reverse/{value}")]
string mannan(string value);
}
GUI Application Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Net;
using System.Xml.Linq;
namespace RESTClient
{
public partial class MainWindow : Window
{
private WebClient mj = new WebClient();
private XNamespace xmj =
XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/");
public MainWindow()
{
InitializeComponent();
mj.DownloadStringCompleted += new
DownloadStringCompletedEventHandler(mj_DownloadStringCompleted);
}
void mj_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
if (e.Error == null)
26
{
XDocument response = XDocument.Parse(e.Result);
MessageBox.Show(response.Element(xmj + "string").Value, "Reverse String Window");
}
}
Screenshots
Task:
Invoke the REST-based Service through a client application.
27
Lab 09:
Lab Objectives:
Introduction
JavaScript Object Notation (JSON) is an alternative to XML for representing data. JSON is a
text-based data-interchange format used to represent objects in JavaScript as collections of name/value
pairs represented as Strings. It is commonly used in Ajax applications.
It is a lightweight text-based open standard designed for human-readable data interchange. It is derived
from the JavaScript scripting language for representing simple data structures and associative arrays,
called objects. Despite its relationship to JavaScript, it is language-independent, with parsers available for
most languages.
Format
JSON is a simple format that makes objects easy to read, create and parse, and allows programs
to transmit data efficiently across the Internet because it is much less verbose than XML. Each JSON
object is represented as a list of property names and values contained in curly braces, in the following
format:
{propertyName1: value1, propertyName2: value2}
Arrays are represented in JSON with square brackets in the following format:
Each value in an array can be a string, a number, a JSON object, true, false or null. To appreciate the
simplicity of JSON data, examine this representation of an array of address book entries
[value1, value2, value3]
[{first: 'Cheryl', last: Black}, {first: 'James', last: Blue}, {first: 'Mike', last: Brown},
{First: 'Meg', last: Gold}]
28
Schema
JSON Schema is a specification for a JSON-based format for defining the structure of JSON data.
JSON Schema provides a contract for what JSON data is required for a given application and how it can
be modified, much like the XML Schema provides for XML. JSON Schema is intended to provide
validation, documentation, and interaction control of JSON data.
JSON
Data types
Support for
arrays
Support for
objects
Null support
Comments
Namespaces
Formatting
decisions
Size
29
Not supported.
No concept of namespaces. Naming
collisions are usually avoided by
nesting objects or using a prefix in an
object member name (the former is
preferred in practice).
Simple. Provides a much more direct
mapping for application data. The
only exception may be the absence of
date/time literal.
Syntax is very terse and yields
formatted text where most of the
space is consumed (rightly so) by the
represented data.
Lab 10:
Lab Objectives:
Understand the two main types of REST-based Web Services. (JSON and XML)
Create a REST-based JSON Web Service.
Modify the changes in web.config file according to the requirements.
Publish the Web Service.
Environment
Operating System
Tool
Component
Windows 7
Visual Studio 2010
WCF.Net
Code
IJSON.cs
using System.ServiceModel;
using System.ServiceModel.Web;
[ServiceContract]
public interface IWelcomeRESTJSONService
{
[OperationContract]
[WebGet( ,UriTemplate = "/welcome/{yourName}" )]
TextMessage Welcome( string yourName );
}
public class TextMessage
{
public string Message {get; set; }
}
using System.Runtime.Serialization;
ResponseFormat = WebMessageFormat.Json
[DataContract]
[DataMember]
30
JSON.cs
public class WelcomeRESTJSONService : IWelcomeRESTJSONService
{
public TextMessage Welcome(string yourName)
{
message = new TextMessage();
message.Message = string.Format(
"Welcome to WCF Web Services with REST and JSON, {0}!",
yourName);
return message;
}
}
Screen Shot
Task
To create a Rest-Based JSON Web Service.
31
Lab 11:
Lab Objectives:
Environment
Operating System
Tool
Component
Windows 7
Visual Studio 2010
WCF.Net, WPF.Net
Code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.IO;
using System.Runtime.Serialization;
using System.Net;
using System.Runtime.Serialization.Json;
namespace Json_client
{
32
[Serializable]
public class TextMessage
{
public string Message;
}
private void Invoke_Click(object sender, RoutedEventArgs e)
{
client.DownloadStringAsync(new
Uri("http://localhost:49750/RESTservice/REST.svc/reverse/" + Revstring.Text));
}
}
}
33
Screen Shot
Task
To invoke a REST-Based JSON Web Service with a WPF Application.
34
Lab 12:
Lab Objectives:
Environment
Operating System
Tool
Language
Windows 7
Visual Studio 2010
WCF.Net
Code
IEQRSET.cs
using System.ServiceModel;
using System.ServiceModel.Web;
public interface IEquationGeneratorService
{
// method to generate a math equation
Equation GenerateEquation( string operation, string level );
} // end interface IEquationGeneratorService
[ServiceContract]
[OperationContract]
[WebGet( UriTemplate = "equation/{operation}/{level}" )]
Equation GenerateEquation( string operation, string level );
}
EQRSET.cs
using System;
public class EquationGeneratorService : IEquationGeneratorService
{
// method to generate a math equation
public Equation GenerateEquation( string operation, string level )
{
// calculate maximum and minimum number to be used
35
int maximum =
Convert.ToInt32( Math.Pow( 10, Convert.ToInt32( level ) ) );
int minimum =
Convert.ToInt32( Math.Pow( 10, Convert.ToInt32( level ) - 1 ) );
Random randomObject = new Random(); // generate random numbers
// create Equation consisting of two random
// numbers in the range minimum to maximum
Equation newEquation = new Equation(
randomObject.Next(minimum, maximum),
randomObject.Next(minimum, maximum), operation);
return newEquation;
}
}
Task
To create a REST-based XML Equation Generator.
36
Lab 13:
Lab Objectives:
Learn how to process web service response and to check if any errors occurred in
retrieving service data.
Know how a new equation can be generated.
Create a client application for the Web Service.
Consume the Equation Generator Web Service using the client application.
.
Environment
Operating System
Tool
Component
Windows 7
Visual Studio 2010
WCF.Net
Code
using System;
using System.Net;
using System.Windows.Forms;
using System.Xml.Linq;
namespace MathTutorXML
{
public partial class MathTutor : Form
{
private string operation = "add";
private int level = 1;
private string leftHandSide;
private int result;
37
service.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(
service_DownloadStringCompleted );
}
private void generateButton_Click( object sender, EventArgs e )
{
38
{
MessageBox.Show( "Incorrect. Try again.", "Result" );
}
}
}
private void additionRadioButton_CheckedChanged( object sender,EventArgs e )
{
if ( additionRadioButton.Checked )
operation = "add";
}
private void subtractionRadioButton_CheckedChanged( object sender,EventArgs e )
{
if ( subtractionRadioButton.Checked )
operation = "subtract";
}
private void multiplicationRadioButton_CheckedChanged(object sender, EventArgs e )
{
if ( multiplicationRadioButton.Checked )
operation = "multiply";
}
private void levelOneRadioButton_CheckedChanged( object sender,EventArgs e )
{
if ( levelOneRadioButton.Checked )
level = 1;
}
private void levelTwoRadioButton_CheckedChanged(object sender,EventArgs e)
{
if (levelTwoRadioButton.Checked)
level = 2;
}
private void levelThreeRadioButton_CheckedChanged(object sender,EventArgs e)
{
if (levelThreeRadioButton.Checked)
level = 3;
}
}
}
Task
To consume the generator service with a client application.
39
Lab 14:
Introduction
As the Microsoft .NET platform and its supporting languages C# and VB have matured, it has
become apparent that one of the more troublesome areas still remaining for developers is that of
accessing data from different data sources. In particular, database access and XML manipulation
are often cumbersome at best and problematic at worst.
For the most part, LINQ is all about queries, whether they are queries returning a set of matching
objects, a single object, or a subset of fields from an object or set of objects. In LINQ, this
returned set of objects is called a sequence. Most LINQ sequences are of type IEnumerable<T>,
where T is the data type of the objects stored in the sequence. For example, if you have a
sequence of integers, they would be stored in a variable of type IEnumerable<int>.
using System;
using System.Linq;
string[] greetings = {"hello world", "hello LINQ", "hello Apress"};
var items =
from s in greetings
where s.EndsWith("LINQ")
select s;
foreach (var item in items)
Console.WriteLine(item);
Query XML
using System;
using System.Linq;
using System.Xml.Linq;
XElement books = XElement.Parse(
@"<books>
<book>
<title>Distributed Computing</title>
<author>Joe Rattz</author>
</book>
<book>
<title>Visual Programming</title>
<author>Adam Freeman</author>
</book>
<book>
40
<title>Discrete Mathematics</title>
<author>Andrew Troelsen</author>
</book>
</books>");
var titles =
from book in books.Elements("book")
where (string) book.Element("author") == "Joe Rattz"
select book.Element("title");
foreach(var title in titles)
Console.WriteLine(title.Value);
41
Lab 15:
Lab Objectives:
Create a Service which fetches record from a database.
Create a Client which invokes the Service and gets the result from the database.
Environment
Operating System
Tool
Component
Windows 7
Visual Studio 2010
WCF.Net
Code
[ServiceContract]
public interface IService1
{
[OperationContract]
string GetEname(int empID);
}
public class Service1 : IService1
{
public string GetEname(int emp_ID)
{
empDataContext db = new empDataContext();
string ename="";
var rows = from e in db.emps
where e.emp_id == emp_ID
select e;
foreach (var row in rows)
{
ename = row.emp_name;
}
return ename;
}
}
42
Lab 16:
Introduction:
This lab outlines the basic steps required to create a Windows Communication Foundation
(WCF) service that is hosted by a Windows Service. The scenario is enabled by the managed
Windows service hosting option that is a long-running WCF service hosted outside of Internet
Information Services (IIS) in a secure environment that is not message activated. The lifetime of
the service is controlled instead by the operating system. This hosting option is available in all
versions of Windows.
The service code includes a service implementation of the service contract, a Windows Service
class, and an installer class. The service implementation class, CalculatorService, is a WCF
service. The CalculatorWindowsService is a Windows service. To qualify as a Windows service,
the class inherits from ServiceBase and implements the OnStart and OnStop methods. In
OnStart, a ServiceHost is created for the CalculatorService type and opened. In OnStop, the
service is stopped and disposed. The host is also responsible for providing a base address to the
service host, which has been configured in application settings. The installer class, which inherits
from Installer, allows the program to be installed as a Windows service by the Installutil.exe tool.
43
using System.Configuration.Install;
6. Define the ICalculator service contract as shown in the following code.
// Define a service contract.
[ServiceContract(Namespace = "http://Microsoft.ServiceModel.Samples")]
public interface ICalculator
{
[OperationContract]
double Add(double n1, double n2);
[OperationContract]
double Subtract(double n1, double n2);
[OperationContract]
double Multiply(double n1, double n2);
[OperationContract]
double Divide(double n1, double n2);
}
44
9.
Override the OnStart method by creating and opening a new ServiceHost instance as shown in
the following code.
// Start the Windows service.
protected override void OnStart(string[] args)
{
if (serviceHost != null)
{
serviceHost.Close();
}
// Create a ServiceHost for the CalculatorService type and
// provide the base address.
serviceHost = new ServiceHost(typeof(CalculatorService));
// Open the ServiceHostBase to create listeners and start
// listening for messages.
serviceHost.Open();
}
10. Override the OnStop method closing the ServiceHost as shown in the following code.
protected override void OnStop()
{
if (serviceHost != null)
{
serviceHost.Close();
serviceHost = null;
}
}
45
11. Create a new class called ProjectInstaller that inherits from Installer and that is marked
with the RunInstallerAttribute set to true. This allows the Windows service to be installed by the
Installutil.exe tool.
// Provide the ProjectInstaller class which allows
// the service to be installed by the Installutil.exe tool
[RunInstaller(true)]
public class ProjectInstaller : Installer
{
private ServiceProcessInstaller process;
private ServiceInstaller service;
public ProjectInstaller()
{
process = new ServiceProcessInstaller();
process.Account = ServiceAccount.LocalSystem;
service = new ServiceInstaller();
service.ServiceName = "WCFWindowsServiceSample";
Installers.Add(process);
Installers.Add(service);
}
}
12. Remove the Service class that was generated when you created the project.
13. Add an application configuration file to the project. Replace the contents of the file with the
following configuration XML.
XML
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<system.serviceModel>
<services>
<!-- This section is optional with the new configuration model
introduced in .NET Framework 4. -->
<service name="Microsoft.ServiceModel.Samples.CalculatorService"
behaviorConfiguration="CalculatorServiceBehavior">
<host>
<baseAddresses>
<add baseAddress="http://localhost:8000/ServiceModelSamples/service"/>
</baseAddresses>
</host>
<!-- this endpoint is exposed at the base address provided by host: http:/
/localhost:8000/ServiceModelSamples/service -->
<endpoint address=""
binding="wsHttpBinding"
contract="Microsoft.ServiceModel.Samples.ICalculator" />
<!-- the mex endpoint is exposed at http://localhost:8000/ServiceModelSamp
les/service/mex -->
<endpoint address="mex"
binding="mexHttpBinding"
contract="IMetadataExchange" />
</service>
46
</services>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceMetadata httpGetEnabled="true"/>
<serviceDebug includeExceptionDetailInFaults="False"/>
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
</configuration>
2.
Open the Visual Studio 2010 command prompt and navigate to the project directory.
Type installutil bin\service.exe at the command prompt to install the Windows
service.
Type services.msc at the command prompt to access the Service Control Manager
(SCM). The Windows service should appear in Services as
"WCFWindowsServiceSample". The WCF service can only respond to clients if the
Windows service is running. To start the service, right-click it in the SCM and select
"Start", or type net start WCFWindowsServiceSample at the command prompt.
3.
If you make changes to the service, you must first stop it and uninstall it. To stop the
service, right-click the service in the SCM and select "Stop", or type net stop
WCFWindowsServiceSample at the command prompt. Note that if you stop the
Windows service and then run a client, an EndpointNotFoundException exception
occurs when a client attempts to access the service. To uninstall the Windows service
type installutil /u bin\service.exe at the command prompt.
47