distributed computing _ lab manual

Upload: vicky-malik

Post on 09-Jan-2016

12 views

Category:

Documents


0 download

DESCRIPTION

Data comunication Network

TRANSCRIPT

  • 1 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Faculty of Computer and Software Engineering

    SEN-371 DISTRIBUTED COMPUTING

    LAB MANUAL

  • 2 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    SEN-371 DISTRIBUTED COMPUTING

    LIST OF EXPERIMENTS

    S.No Topic Page

    Lab 01 Introduction to Distributed Computing & Web Services 03

    Lab 02 Introduction to Windows Communication Foundation (WCF) 07

    Lab 03 Creating a Simple Web Service 10

    Lab 04 Consuming a WCF Service with Console & GUI Client App 13

    Lab 05 Publishing a SOAP-based Web Service 16

    Lab 06 Consuming a SOAP-based Web Service 19

    Lab 07 Publishing a REST-based XML Web Service 22

    Lab 08 Consuming a REST-based XML Web Service 25

    Lab 09 JavaScript Object Notation (JSON) 28

    Lab 10 Creating a REST-based JSON Web Service 30

    Lab 11 Consuming a REST-based JSON Web Service 32

    Lab 12 Creating a REST-based XML Equation Generator 35

    Lab 13 Consuming a REST-based XML Equation Generator 37

    Lab 14 Accessing tables in Database via LINQ 40

    Lab 15 Creating and Consuming a Database Service 42

    Lab 16 Host a WCF Service in a Managed Windows Service 43

  • 3 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 01: Introduction to Distributed Computing

    & Web Services

    Lab Objectives:

    Understand what distributed computing is.

    Differentiate between a service and a web-service.

    Know what kind of Web-services are there.

    Understand the basics of Service Oriented Architecture (SOA)

    What distributed computing is?

    A distributed computer system consists of multiple software components that are on multiple

    computers, but run as a single system. The computers that are in a distributed system can be

    physically close together and connected by a local network, or they can be geographically distant

    and connected by a wide area network. A distributed system can consist of any number of

    possible configurations, such as mainframes, personal computers, workstations, minicomputers,

    and so on. The goal of distributed computing is to make such a network work as a single

    computer.

  • 4 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

    Difference between service & web service.

    Web Service

    A Web Service is programmable application logic accessible via standard Web protocols. One of

    these Web protocols is the Simple Object Access Protocol (SOAP). SOAP is a W3C submitted

    note that uses standards based technologies (XML for data description and HTTP for transport)

    to encode and transmit application data.

    Consumers of a Web Service do not need to know anything about the platform, object model, or

    programming language used to implement the service; they only need to understand how to send

    and receive SOAP messages (HTTP and XML).

  • 5 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

  • 6 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

  • 7 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

    Key Components of WCF WCF is based upon the following key components that are used to build a WCF service. Each component is covered in detail in the following sections.

  • 8 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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

  • 9 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Windows presentation foundation

    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, WS-

    Reliable 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.

  • 10 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 03: Creating a Simple Web Service

    Lab Objectives:

    Create a WCF Web Service.

    Deploy the WCF Web Service.

    Invoke the Service using WCF Test Client.

    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";

    } } } }

  • 11 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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

  • 12 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Conclusion/Result:

    The Service is invoked successfully.

  • 13 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 04: Consuming a WCF Service with Console

    & GUI Client App

    Lab Objectives:

    Create a console-based client application that consumes the web service.

    Create a GUI-based client application that also consumes the web service.

    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.

    A contract is an interface representing the services methods and their return types. The services contract allows clients to interact with the service.

    Microsofts Windows Communication Foundation (WCF) was created as a single platform to encompass many existing communication technologies. WCF increases productivity,

    because you learn only one straightforward programming model. Each WCF service

    has three key componentsaddresses, bindings and contracts (usually called the ABCs of a WCF service):

    First of all we create a service. so this means we are making a function in it. then we follow

    above steps(ABCs) of WCF service.

    The next step is to create a service client. for this we have to add a service reference named as

    System.Service.Model. so we create an object of service client.

    Now using this object as reference we call the service from client which can be either in console

    or in GUI.

    in console there is no GUI, to interact with user you have to display line by line of code. But in

    GUI there are form components which help us in interacting with user.

  • 14 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Code for service

    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using 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; } } } }

    Code for Client

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace ClientApp { public partial class Form1 : Form {

  • 15 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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:

  • 16 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 05: Publishing a SOAP Based Web Service

    Lab Objectives:

    Understand the basics of XML

    Understand how SOAP message is encrypted and decrypted using XML.

    Know how a SOAP-based Web Service can be published.

    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

  • 17 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    public string Welcome( string yourName ) {

    return string.Format( "Welcome to WCF Web Services with SOAP and XML, {0}!", yourName );

    } // end method Welcome } // end class WelcomeSOAPXMLService Building a SOAP WCF Web Service

    In the following steps, you create a WCF Service project for the WelcomeSOAPXMLService and test it using the built-in ASP.NET Development Server that comes with Visual Web Developer Express and Visual Studio. Step 1: Creating the Project To create a project of type WCF Service, select File > New Web Site to display the New Web Site dialog . Select the WCF Service template. Select File System from the Location drop-down list to indicate that the files should be placed on your local hard disk. By default, Visual Web Developer places files on the local machine in a directory named WCFService1. Rename this folder to WelcomeSOAPXMLService. Click OK to create the project. Step 2: Examining the Newly Created Project After you create the project, the code-behind file Service.cs, which contains code for a simple web service, is displayed by default. If the code-behind file is not open, open it by double clicking the file in the App_Code directory listed in the Solution Explorer. By default, a new code-behind file implements an interface named IService. This interface (in the file IService.cs) is marked with the ServiceContract and OperationContract attributes. In addition, the IService.cs file defines a class named CompositeType with a DataContract attribute. The interface contains two sample service methods named GetData and GetDataUsingContract. The Service.cs contains the code that defines these methods. Step 3: Modifying and Renaming the Code-Behind File To create the WelcomeSOAPXMLService service developed in this section, modify IService. cs and Service.cs by replacing the sample code provided by Visual Web Developer with the code from the IWelcomeSOAPXMLService and WelcomeSOAPXMLService files. Then rename the files to IWelcomeSOAPXMLService.cs and WelcomeSOAPXMLService.cs by right clicking each file in the Solution Explorer and choosing Rename. Step 4: Examining the SVC File The Service.svc file, when accessed through a web browser, provides information about

  • 18 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

  • 19 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 06: Consuming SOAP-Based Web Service

    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 System; using System.Collections.Generic; using System.ComponentModel; using System.Data;

  • 20 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace WindowsFormsApplication1 { public partial class Form1 : Form { private ServiceReference1.SOAPXMLServiceClient client; public Form1() { InitializeComponent(); client = new ServiceReference1.SOAPXMLServiceClient(); } private void button1_Click(object sender, EventArgs e) { textBox3.Text= client.compute(Int32.Parse(textBox1.Text), Int32.Parse(textBox2.Text)).ToString(); } } }

    Form1.cs[Design]

  • 21 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    SOAPXMLService.cs

    using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.ServiceModel; using System.Text; public class SOAPXMLService : ISOAPXMLService { public int compute(int base_,int power) { int result = base_; for(int i=1; i

  • 22 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 07: Publishing a REST-Based Web Service

    Lab Objectives:

    Create a client application using Windows Presentation Foundation (WPF).

    Consume the Web Service created in the previous lab using the client application.

    Representational State Transfer (REST) Representational State Transfer (REST) refers to an architectural style for implementing

    web services. Such web services are often called RESTful web services. Though REST

    itself is not a standard, RESTful web services are implemented using web standards.

    Each operation in a RESTful web service is identified by a unique URL. Thus, when the

    server receives a request, it immediately knows what operation to perform. Such web

    services can be used in a program or directly from a web browser. The results of a

    particular operation may be cached locally by the browser when the service is invoked

    with a GET request. This can make subsequent requests for the same operation faster

    by loading the result directly from the browsers cache. Amazons web services are

    RESTful, as are many others. RESTful web services are alternatives to those

    implemented with SOAP. Unlike SOAP-based web services, the request and response of

    REST services are not wrapped in envelopes. REST is also not limited to returning data in

    XML format. It can use a variety of formats, such as XML, JSON, HTML, plain text and

    media files.

    Publishing and Consuming REST-Based XML Web Services In the previous section, we used a proxy object to pass data to and from a WCF web

    service using the SOAP protocol. In this section, we access a WCF web service using the REST

    architecture. We modify the IWelcomeSOAPXMLService example to return data in plain XML

    format.

    HTTP get and post Requests The two most common HTTP request types (also known as request methods) are get

    and post. A get request typically gets (or retrieves) information from a server. Common

    uses of get requests are to retrieve a document or an image, or to fetch search results based

    on a user-submitted search term. A post request typically posts (or sends) data to a server.

    Common uses of post requests are to send form data or documents to a server.

  • 23 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

    Creating a REST-Based XML WCF Web Service

    using System.ServiceModel;

    using System.ServiceModel.Web;

    [ServiceContract]

    public interface IWelcomeRESTXMLService

    {

    // returns a welcome message

    [OperationContract]

    string Welcome( string yourName );

    } // end interface IWelcomeRESTXMLService

    public class WelcomeRESTXMLService : IWelcomeRESTXMLService

    {

    // returns a welcome message

    public string Welcome( string yourName )

    {

    return string.Format( "Welcome to WCF Web Services" + " with REST

    and XML, {0}!", yourName );

    } // end method Welcome

    } // end class WelcomeRESTXMLService

    Modifying the Web.config File

  • 24 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Default Web.config file is modified to use REST architecture. The endpointBehaviors

    element in the behaviors element indicates that this web service endpoint will be accessed using

    the web programming model (REST).

    The nested webHttp element specifies that clients communicate with this service using

    the standard HTTP request/response mechanism. The protocolMapping element in the

    system.serviceModel element, changes the default protocol for communicating with this web

    service (normally SOAP) to webHttpBinding, which is used for RESTbased HTTP requests.

    It tests the WelcomeRESTXMLServices Welcome method in a web browser.

    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.

    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.

  • 25 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 08: Consuming a REST-Based XML Web Service

    Lab Objectives:

    Create a client application for the REST-based XML Web Service.

    Know how the response from Web Service is parsed and saved in XDocument.

    Test and consume the Web Service using the client application in WPF.

    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;

  • 26 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    [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)

  • 27 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    { XDocument response = XDocument.Parse(e.Result); MessageBox.Show(response.Element(xmj + "string").Value, "Reverse String Window"); } } private void call_Click(object sender, RoutedEventArgs e) { mj.DownloadStringAsync(new Uri(@"http://localhost:49750/RESTservice/REST.svc\reverse\" + revstring.Text)); } } }

    Screenshots

    Task: Invoke the REST-based Service through a client application.

  • 28 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 09: JavaScript Object Notation (JSON)

    Lab Objectives:

    Understand the difference between XML and JSON.

    Identify how JSON is efficient than XML in transmitting data across the internet.

    Know the format of JSON objects.

    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}]

  • 29 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

    Difference between JSON and XML

    Characteristic

    Characteristic XML JSON Data types Does not provide any notion of data types.

    One must rely on XML Schema for adding

    type information.

    Provides scalar data types and the

    ability to express structured data

    through arrays and objects.

    Support for

    arrays Arrays have to be expressed by conventions,

    for example through the use of an outer

    placeholder element that models the arrays

    contents as inner elements. Typically, the

    outer element uses the plural form of the

    name used for inner elements.

    Native array support.

    Support for

    objects Objects have to be expressed by conventions,

    often through a mixed use of attributes and

    elements.

    Native object support.

    Null support Requires use of xsi:nil on elements in an XML instance document plus an import of

    the corresponding namespace.

    Natively recognizes the null value.

    Comments Native support and usually available through APIs.

    Not supported.

    Namespaces Supports namespaces, which eliminates the risk of name collisions when combining

    documents. Namespaces also allow existing

    XML-based standards to be safely extended.

    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).

    Formatting

    decisions Complex. Requires a greater effort to decide

    how to map application types to XML

    elements and attributes. Can create heated

    debates whether an element-centric or

    attribute-centric approach is better.

    Simple. Provides a much more direct

    mapping for application data. The

    only exception may be the absence of

    date/time literal.

    Size Documents tend to be lengthy in size, especially when an element-centric approach

    to formatting is used.

    Syntax is very terse and yields

    formatted text where most of the

    space is consumed (rightly so) by the

    represented data.

  • 30 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 10: Creating a REST-based JSON Web Service

    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 Windows 7

    Tool Visual Studio 2010

    Component 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]

  • 31 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

  • 32 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 11: Consuming a REST-based JSON Web Service

    Lab Objectives:

    Understand what Serializable classes are.

    Know the difference between synchronous and asynchronous DownloadString methods.

    Create a client application for the REST-based JSON Web Service.

    Consume the Web Service using the REST-based client application.

    Environment

    Operating System Windows 7

    Tool Visual Studio 2010

    Component 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 {

  • 33 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    public partial class MainWindow : Window { private WebClient client = new WebClient();

    public MainWindow() { InitializeComponent(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { DataContractJsonSerializer jsonserial = new DataContractJsonSerializer(typeof(TextMessage)); TextMessage texts = (TextMessage)jsonserial.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(e.Result))); MessageBox.Show(texts.Message, "Bila"); } } [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)); } } }

  • 34 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Screen Shot

    Task

    To invoke a REST-Based JSON Web Service with a WPF Application.

  • 35 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 12: Creating a REST-based XML Equation

    Generator

    Lab Objectives:

    Create randomly generated Equations.

    Modify web.config file to enable REST support.

    Understand how the Equation is serialized as XML by default before sending it to the

    client.

    Environment

    Operating System Windows 7

    Tool Visual Studio 2010

    Language 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

  • 36 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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.

  • 37 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 13: Consuming a REST-based XML Equation

    Generator

    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 Windows 7

    Tool Visual Studio 2010

    Component 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; private XNamespace xmlNamespace = XNamespace.Get( "http://schemas.datacontract.org/2004/07/" ); private WebClient service = new WebClient(); public MathTutor() { InitializeComponent();

  • 38 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    service.DownloadStringCompleted += new DownloadStringCompletedEventHandler( service_DownloadStringCompleted ); } private void generateButton_Click( object sender, EventArgs e ) { service.DownloadStringAsync( new Uri( "http://localhost:49732/EquationGeneratorService+"/Service.svc/equation/" + operation + "/" + level ) ); } private void service_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e ) { if ( e.Error == null ) { XDocument xmlResponse = XDocument.Parse( e.Result ); leftHandSide = xmlResponse.Element(xmlNamespace + "Equation" ).Element(xmlNamespace + "LeftHandSide" ).Value; result = Convert.ToInt32( xmlResponse.Element(xmlNamespace + "Equation" ).Element(xmlNamespace + "Result" ).Value ); questionLabel.Text = leftHandSide; okButton.Enabled = true; answerTextBox.Enabled = true; } } private void okButton_Click( object sender, EventArgs e ) { if ( !string.IsNullOrEmpty( answerTextBox.Text ) ) { int userAnswer = Convert.ToInt32( answerTextBox.Text ); if ( result == userAnswer ) { questionLabel.Text = string.Empty; answerTextBox.Clear(); okButton.Enabled = false; MessageBox.Show( "Correct! Good job!", "Result" ); } // end if else

  • 39 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    { 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.

  • 40 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 14: Accessing tables in Database via LINQ

    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,

    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.

    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(

    @"

    Distributed Computing Joe Rattz

    Visual Programming Adam Freeman

  • 41 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Discrete Mathematics Andrew Troelsen

    ");

    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);

    Query a SQL Server Database

    using System; using System.Linq; using System.Data.Linq; empDataContext db = new empDataContext();

    IQueryable dpt = from d in db.depts

    where d.dname == "Isb"

    select d;

    foreach (dept d in dpt)

    Console.WriteLine("\n" + "{0} office has {1} dept.",d.dloc,d.dname);

  • 42 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 15: Creating and Consuming a Database

    Service

    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 Windows 7

    Tool Visual Studio 2010

    Component 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; } } Task: Create a Client applications which consumes the database Service.

  • 43 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Lab 16: Host a WCF Service in a Managed Windows

    Service

    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.

    Construct the service and provide the hosting code

    1. Create a new Visual Studio Console Application project called "Service".

    2. Rename Program.cs to Service.cs.

    3. Change the namespace to Microsoft.ServiceModel.Samples.

    4. Add references to the following assemblies.

    System.ServiceModel.dll

    System.ServiceProcess.dll

    System.Configuration.Install.dll

    5. Add the following using statements to Service.cs.

    using System.ComponentModel;

    using System.ServiceModel;

    using System.ServiceProcess;

    using System.Configuration;

  • 44 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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); }

    7. Implement the service contract in a class called CalculatorService as shown in the following code.

    // Implement the ICalculator service contract in a service class. public class CalculatorService : ICalculator { // Implement the ICalculator methods. public double Add(double n1, double n2) { double result = n1 + n2; return result; } public double Subtract(double n1, double n2) { double result = n1 - n2; return result; } public double Multiply(double n1, double n2) { double result = n1 * n2; return result; } public double Divide(double n1, double n2) { double result = n1 / n2; return result; } }

  • 45 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    8. Create a new class called CalculatorWindowsService that inherits from the ServiceBase class. Add a local variable called serviceHost to reference

    theServiceHost instance. Define the Main method that calls ServiceBase.Run(new

    CalculatorWindowsService)

    public class CalculatorWindowsService : ServiceBase { public ServiceHost serviceHost = null; public CalculatorWindowsService() { // Name the Windows Service ServiceName = "WCFWindowsServiceSample"; } public static void Main() { ServiceBase.Run(new CalculatorWindowsService()); }

    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; } }

  • 46 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    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

  • 47 BAHRIA UNIVERSITY ISLAMABAD CAMPUS

    Install and run the service

    1. Build the solution to create the Service.exe executable.

    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.