· web viewas shown in the above code segment, the interface named iservice1 declares two members...

21
IS 460 LAB – Creating a WCF Web Service IS 460 LAB CREATING A WCF Web Service In this lab exercise you will: Create a first WCF Web Service and understand its parts Test a Web service using the WCF Test client. Understand the role of the Web.config file in configuring a WCF Web Service Create a client application to execute a Web service Understand the relevant Web.config elements and how they are used to configure the WCF Web service client. Note: This lab contains descriptive text and hands-on steps that you need to complete. Hands-on steps appear shaded. RESOURCES: WS-* FUNTIONALITY: There are many standards associated with Web services. The following (yes Wikipedia) contains a good list of those standards. We commonly refer to these standards as the WS-* (Web Service Specifications). These specifications include WSDL, SOAP. The WS* standards are characterized as WS-Addressing, WS- Discovery, WS-Federation, WS-Policy, WS-Security, and WS-Trust. https://en.wikipedia.org/wiki/Web_service WCF TUTORIAL: The following link contains an excellent introductory tutorial on the implementation of a WCF Web Service: http://www.codeproject.com/Articles/29243/A-Windows- Communication-Foundation-WCF-Overview . WCF CONFIGURATION: The following link contains a detailed discussion of the Windows Communication Foundation Configuration schema: (1) Page 1 of 21

Upload: buithuy

Post on 08-Jun-2018

218 views

Category:

Documents


0 download

TRANSCRIPT

Page 1:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

IS 460LABCREATING A WCF Web ServiceIn this lab exercise you will:

Create a first WCF Web Service and understand its parts Test a Web service using the WCF Test client. Understand the role of the Web.config file in configuring a WCF Web Service Create a client application to execute a Web service Understand the relevant Web.config elements and how they are used to configure the WCF

Web service client.

Note: This lab contains descriptive text and hands-on steps that you need to complete. Hands-on steps appear shaded.

RESOURCES:

WS-* FUNTIONALITY: There are many standards associated with Web services. The following (yes Wikipedia) contains a good list of those standards. We commonly refer to these standards as the WS-* (Web Service Specifications). These specifications include WSDL, SOAP. The WS* standards are characterized as WS-Addressing, WS-Discovery, WS-Federation, WS-Policy, WS-Security, and WS-Trust. https://en.wikipedia.org/wiki/Web_service

WCF TUTORIAL: The following link contains an excellent introductory tutorial on the implementation of a WCF Web Service: http://www.codeproject.com/Articles/29243/A-Windows-Communication-Foundation-WCF-Overview .

WCF CONFIGURATION: The following link contains a detailed discussion of the Windows Communication Foundation Configuration schema: (1) https://msdn.microsoft.com/en-us/library/ms731734(v=vs.110).aspx

WCF SYSTEM BINDINGS: The following link lists the WCF system bindings and their purpose: http://msdn.microsoft.com/en-us/library/ms730879(v=vs.110).aspx

SAMPLES: In case you are interested. http://msdn.microsoft.com/en-us/library/dd483346(v=vs.110).aspx

Page 1 of 17

Page 2:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

HANDS –ON TASK: CREATING A WCF Web Service Project

In this section, you will create a first WCF Service Application from one of the .NET defined templates. This first WCF Service application that you create will simply return a string indicating that the service function was called. You will expand the WCF service to operate with more complex data types as you progress through the lab and complete your homework.

Note that WCF services are an extension of traditional Web Services. The following table derived from www.codeproject.com highlights the differences:

Web Service WCF ServiceCommunication can happen over HTTP only

Communication can happen over HTTP, TCP, IPC, or even MSMQ.

Only simplex and request-response communication is possible

It can be configured to have simplex, request-response, or even full duplex communication.

They work in an stateless fashion over HTTP and are hosted inside a web server like IIS

These can be hosted in many ways inside IIS, inside a Windows service, or even self-hosted.

1. Start Visual Studio, if necessary. This lab assumes that you are running Visual Studio 2015.

2. Create a new Web Service project by clicking File, New Project. (Note that you are creating a project rather than a Web site). On the templates tab, select WCF. Select WCF Service Application. Create the solution in a new empty folder of your choosing. The following figure shows the New Project dialog box configured to create the WCF Service Application: Make sure to create the project in C#. VB will work but the process is a bit more difficult.

Don’t add the Application Insights features. They are used to get data about your app. They are useful, but will cloud the purpose of this exercise.

Page 2 of 17

Page 3:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

3. Click OK to create the WCF Service Application from the template.

Look closely at the Solution Explorer. The following files were created:

Properties/AssemblyInfo.cs is the assembly information file. This file contains attributes that describe the assembly. These attributes are compiled into the application itself. If you look at the file, you will see that it describes the application’s owner / creator, and versioning information. Note that all application types have an AssemblyInfo.cs file used to describe the assembly.

IService1.cs contains the interface for the service. This interface describes the [ServiceContract] and the operations performed by the service [OperationContract]. Remember that the [ServiceContract] defines the name of the service itself. The [OperationContract] describes the members supported by the service. These members are the exposed methods of the service. It also contains a template for the [DataContract]. The [DataContract] is necessary when the service operates with composite types in addition to primitive types.

Page 3 of 17

Page 4:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

As shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always (by convention) start with the letter “I”. The first method accepts an integer as an argument and returns a string. These are primary types so no data contract is needed. The second method accepts a complex type (CompositeType) as an argument and returns the same complex type. The data type CompositeType is just a class. The class template is declared later next in this file.

The interface also describes the [DataContract] and data members of the contract [DataMember]. The [DataContract] describes complex data members that will be passed by the service. In other words, the [DataContract] is a formal definition of the data types that can be processed by both the service (service endpoints).

In this case, the data type is named CompositeType and exposes two read/write properties

Page 4 of 17

Page 5:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

named BoolValue and StringValue. This data type could be anything such as a customer or payroll record, or anything else. In addition, the class name CompositeType could also be named something else.

The file Service1.cs contains the implementation of the contract. Note that the service must implement all of the methods defined by the contract, which in this case are GetData and GetDataUsingContract. The methods must have exactly the same signature as those declared in the interface. It’s also possible to declare and use hidden methods and data that are not exposed by the service. However, these hidden methods are internal to the service (part of the implementation), rather than part of the service interface. It is these two methods (GetData and GetDataUsingDataContract that will be called by the service client

The code in the GetData method is simple. It simply returns a string containing the number passed as an argument.

The code in the GetDataUsingContract methods accepts in instance of the class named CompositeType as its argument. The code in this method checks that the argument is not null. If the BoolValue property is true, then the StringValue property is updated.

Web.config is the standard web.config file with which you have been working. However, there are additional options in this version that configure the WCF Web Service. The details of the Web.config file will be discussed later in this lab.

The following figure shows the Solution Explorer with the relevant folders expanded. Note that some of the folders are not physical folders. Some of these are new feature so Visual Studio 2012, which include parts of the Class Designer into Visual Studio.

Page 5 of 17

Page 6:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

HANDS-ON TASK: Running a First Test

There are different ways to host a WCF Service when using the Visual Studio development environment, and for final deployment. The hosting behavior has evolved significantly with successive versions of Web Services and WCF. And there are many other ways of doing this than I have shown in this lab.

If you run a WCF project, Visual Studio will automatically try to use the WCF Test client application allowing you to interactively call the service methods. You will use this test client in this section.

1. In the Solution Explorer, make sure to select the service named Service1.svc. Run the project (Press F5). If you do not select the service, the browser will display the file system since it does not know which program to run. The WCF Test Client will not start.

The WCF Test client should appear as shown in the following Figure:

Page 6 of 17

Page 7:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

As you can see from the above figure. The WCF Test Client displays the service members named GetData() and GetDataUsingDataContract(). It also shows that the service is running at localhost at port number 2976. Your port number will likely differ. Note that the errors appears because asynchronous versions of the service methods have not been implemented.

2. Double-click on the GetData() method in the left window. Here, you are getting ready to invoke the method. Note that the right window pane changes to display the request and response parameters expected by the service. The request argument named value corresponds to the argument of the GetData() method having a data type of int (System.Int32)

Page 7 of 17

Page 8:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

3. Enter an integral value of 10 and click the Invoke button. If a warning dialog appears, click OK to accept the security risk and run the client.

4. The service runs and returns the value (response) as shown in the following figure. This response is generated by executing the following service code:

Page 8 of 17

Page 9:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

5. Click the XML tab to display the information shown in the following Figure.

What you are looking at is the XML for the request and response. As you can see, the information is contained in a SOAP envelope.

6. Test the other method named GetDataUsingContract by clicking the method name in the left window. Select True for the BoolValue argument. Select Hello for the StringValue argument. Click the Invoke button.

Page 9 of 17

Page 10:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

If you take a look at the formatted XML, you will see the composite type and the data requested and returned by the service.

7. End the program.

Page 10 of 17

Page 11:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

Much could be said about the XML in the SOAP envelope. The following W3Schools link describes the syntax of SOAP messages.: http://www.w3schools.com/xml/xml_soap.asp .

HANDS-ON TASK: CONFIGURING A SERVICE FOR CONSUMPTION

At this point, you have seen how to implement a WCF service and test it using the WCF Test Client. In this section, you will see how the Web.config file (for the service itself) is used to configure your service for consumption by a client application. This “client application” could be any Web or Desktop program, developed on any platform, in any language.

The following are important to configure the client

A

Remember that a Web service has endpoints that provide the service address. In addition, a service has a contract and behaviors. All of this information is stored in the Web.config file and is used by the ASP.NET runtime to support the service.

First, note that all of the following configuration elements appear inside of the <system.serviceModel> element (namespace). Second, note that most of the configuration options were created for you automatically when you created the service. When the service is deployed to an IIS server, this file is read and the service automatically initialized.

The <services> elements (class) is used to describe the service and the service endpoints as shown in the following code segment:

o Each <service> element describes a service in the <services> collection. If this program supported multiple services, then there would be multiple <service> tags.

o The name attribute of the service tag contains the fully qualified class name of the service. The service you have been creating uses the Service1 class of the HelloService namespace. Thus, the fully qualified named of the service is HelloService.Service1.

o The behaviorConfiguration attribute points to a “behavior”. This name points to a <behavior> in the <serviceBehaviors> section of the document. This section will be discussed in a moment.

o The <endpoint> element describes a service endpoint. It is the endpoint that describes the address, binding, and contract

The address attribute is used to specify the Uniform Resource Indicator (URI) of the service. This can either be an absolute address or a relative address. If the string is empty, it indicates that the endpoint is the base address that is specified when creating the ServiceHost for the service. As you will see later in the course, we can use these addresses to implement RESTful applications and perform URL mapping

The binding attribute defines the type of transport, security and encoding. While built-in bindings are typically used, it is possible to create custom

Page 11 of 17

Page 12:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

bindings. The different types of bindings are discussed in more detail later in this lab.

The contract attribute points to contract interface. Note that the name must be fully qualified. In this case, the contract interface is named HelloService.IService1. This is the name of the interface appearing in the file IService1.cs.

The <behaviors> element is a container for the <serviceBehaviors>. There is typically one <behavior> per service, although multiple services can share the same behavior.

o The name attribute is a string that uniquely identifies the behavior. Note that in this example, the behavior is named Service1Behavior. This name matches the behaviorConfiguration attribute of the <service> element discussed previoiusly.

o The <serviceMetadata> element describes how the metadata for the service is published. In other words, this element describes how clients can access the necessary metadata to run the service.

The httpGetEnabled attribute contains a Boolean value that specifies whether to publish service metadata for retrieval using an HTTP/Get . This attribute works with the httpGetUrl attribute which contains the address where the metadata is published.

The httpsGetEnabled attribute does the same thing as the httpGetEnabled attribute but is applied to secure HTTP.

Xo The <serviceDebug> element is used to configure a variety of debugging features

that assist in the debugging of services. Note that once deployed, debugging should be disabled as it exposes a security risk.

The includeExceptionDetailInFaults attribute, when set to true, writes debugging (error) information to the SOAP message.

The <protocolMapping> element provides a mapping between transport protocol schemes.

The <serviceHostingEnvironment> element defines the type of service the hosting environment instantiates for a particular transport.

o The aspNetCompatibilityEnabled attribute o The multipleSiteBindingsEnabled attribute

HANDS –ON TASK: Creating a Client Program to Consume a Web Service

Page 12 of 17

Page 13:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

In this next task, you will create an ASP.NET Web project in this solution. This ASP.NET project will provide a more realistic illustration of how to test a WCF Web Service. This ASP.NET project could just as well be a desktop or any other project.

These steps will also help you to understand the mechanics of hooking up the client program to the WCF Web Service. Before getting started, realize that there are different ways that you can connect the client with the service.

Create a service reference which updates the Web.config file for an ASP.NET application. Note that much of this process is done for you when you create the WCF service application.

Create the references with code.

Combine hybrid models of code configuration and the Web.config file.

1. In the Solution Explorer, right-click the Solution named HelloService. From the context menu, click Add, New Website to display the Add New Web Site dialog box:

Many of you have not worked with multi-project solutions. Multi-project solutions are commonly used to build complex projects. For example, you might have an executable program that has one or more class libraries. The executable program and each class library might be configured as individual projects. Or you might have a solution that has several executable programs. I.e. Office is made up of several applications. Each application would be configured as a separate project intended to be deployed as one package.

In this case, you will have a WCF Service Project and an ASP.NET project designed to test the service.

2. Create an ASP.NET Empty Web Site. Name the application (project) ServiceTest. The second project should be added to the solution as shown in the following Figure:

Just as the References dialog is used to add references to .NET Framework and other libraries, you can also add references to WCF Services. In this case, the WCF Service is operating locally.

Page 13 of 17

Page 14:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

This same dialog is also used to reference WCF Services that have been deployed to the Web.

3. MAKE SURE THAT THE ServiceTest PROJECT IS ACTIVE. IF IT IS NOT, YOU WILL TRY TO ADD THE SERVICE REFERENCE TO THE WRONG PROJECT.

Using the main menu, click Website, Add Service Reference. The following dialog box appears:

4. Click the Discover button. The system will find the local service from your project and fill in the URL (address) of the service. Your port number will vary. Set the namespace to HelloServiceReference as shown in the following Figure:

5. Click OK to save the reference and close the dialog box. Note that the HelloServiceReference appears in the ServiceTest project (the ASP.NET project) You should see the reference appear in the Solution Explorer as follows:

Page 14 of 17

Page 15:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

6. Expand the Solution Explorer. Add a new blank Web page to the application.

7. Name page Default.aspx.

Before writing the first line of code to reference the service, take a look at the code that was inserted to the Web.config file. Note that this is the Web.config file for the client that will be consuming the WCF service.

The <system.serviceModel> namespace contains all of the configuration options relevant to WCF services. You saw this on the server configuration side. Multiple services are supported. Each service will have its own configuration section.

The <bindings> element can contain a number of system or custom bindings. In this example, we are binding to a single service.

A <binding> specifies the communication vehicle with which messages are sent to an endpoint. A binding contains a protocol stack, a transport (TCP, HTTP, etc.), and an encoding scheme (text, XML, binary, MTOM). Generally speaking, you should use system bindings where possible as they hide much of the complexity of WCF application and protocol stack.

Page 15 of 17

Page 16:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

In the above code, we are saying that the service will use the <basicHttpBinding> to bind to the endpoint named BasicHttpBinding_IService1.

o The <basicHttpBinding> uses the HTTP transport and text/XML as the message encoding scheme. This binding conforms to the WS-1 Basic profile. Refer to the Wikipedia article.

o The <wsHttpBinding> uses HTTP transport and supports secure channels and supports WS-* functionality.

o The <netTCPBinding> provides a reliable secure binding between .NET client and .NET server (service) applications.

o The <netMsmqBinding> provides support for the Microsoft Message Queuing System (MSMQ)

o There are many other bindings but they are not listed here for brevity.

The <client> element contains a list of endpoints (<endpoint> elements).

The <endpoint> element, in turn contains the list of endpoints. Each endpoint has an address (relative or fully qualified URI).

o The address attribute contains the URI (address) of the service.The binding attribute contains the type of binding (from the previous list) that the endpoint will use.

o The bindingConfiguration attribute defines which binding to use. In this case the basicHttpBinding named BasicHttBinding_IService1.

o The contract attribute contains the fully qualified name of the contract, which is again HelloServiceReference.IService1. Remember that this is the name that you used when you created the service reference.

Next, you will write a first statement that will call the GetData() Service member.

1. Using the project named ServiceTest, the page named Default.aspx, and the Page_Load procedure, enter the following statements:

2. Run the program. The service procedure is called and the following results are returned.

Page 16 of 17

Page 17:  · Web viewAs shown in the above code segment, the interface named IService1 declares two members named GetData and GetDataUsingDataContract. Remember that interface names always

IS 460 LAB – Creating a WCF Web Service

TASK: EXPAND THE SERVICE.

In this section, you will add an additional method to get the server date and time. While nonsensical, it will illustrate how to add a member to the service and consume that service.

1. Create a service method named GetDate that will get the current date form the server and return it. The return data type should be DateTime. This is a primary data type so you need to create a data contract.

2. In the client project, you will need to update the service. In the Solution Explorer, right click the service reference named HelloServiceReference and select UpdateServiceReference.

3. In the client program, make the necessary call to the GetDate method that you just created.

4. Now, in the client program, try to call the GetDataContract method that you created.

Page 17 of 17