Wcf Crm

  • June 2020
  • PDF

This document was uploaded by user and they confirmed that they have the permission to share it. If you are author or own the copyright of this book, please report to us by using this DMCA report form. Report DMCA


Overview

Download & View Wcf Crm as PDF for free.

More details

  • Words: 7,896
  • Pages: 28
Microsoft Virtual Labs ®

A Server Scenario Lab with Windows Communication Foundation

A Server Scenario Lab with Windows Communication Foundation

Table of Contents A Server Scenario Lab with Windows Communication Foundation....................................... 1 Exercise 1 Fabrikam CRM Application Walkthrough and Overview ...........................................................................2 Exercise 2 Creating a Windows Communication Foundation Service and Client .........................................................6 Exercise 3 Windows Communication Foundation Manageability............................................................................... 14 Exercise 4 Windows Activation Service and Security................................................................................................. 21 Exercise 5 Extending Windows Communication Foundation Services ....................................................................... 25

A Server Scenario Lab with Windows Communication Foundation

A Server Scenario Lab with Windows Communication Foundation Objectives

Scenario

Estimated Time to Complete This Lab Computer used in this Lab

After completing this lab, you will be better able to:  Fabrikam CRM Application Walkthrough and Overview  Creating a Windows Communication Foundation Service and Client  Windows Communication Foundation Manageability  Windows Activation Service and Security  Extending Windows Communication Foundation Services This document is intended to familiarize you with the Fabrikam sample application that will serve as the basis for the included hands-on labs. The steps in this document will help you gain an understanding of how the application works and introduce you to some concepts of Windows Workflow Foundation and Windows Communication Foundation. At the completion of this document, you will be ready to start the individual labs on each of these technologies. 120 Minutes CON312354

Page 1 of 26

A Server Scenario Lab with Windows Communication Foundation

Exercise 1 Fabrikam CRM Application Walkthrough and Overview Scenario Fabrikam has created a custom CRM application using the Microsoft .NET Framework 3.0 technologies including Windows Presentation Foundation, Windows Workflow Foundation and Windows Communication Foundation. The application consists of a smart client application which provides the user interface and a set of services that provide the processing logic and business rules. In this scenario, Fabrikam is a web hosting provider that provides server web site, mail, and database hosting services. As the user, you will play the role of an account manager working with a client to get them setup with a server running Windows Vista, IIS 7 and the .NET 3.0 Framework technologies included. Tasks

Detailed Steps

Complete the following task on:

a. Log in to the virtual machine using the Administrator account with a password of Pass@word1.

CON312354 1. Run the application and services

b. In Windows Explorer, navigate to c:\Fabrikam\ and double-click the Start Demo – Services.bat shortcut file to begin the demonstration. You should see a console application begin running. Wait for the console to indicate the services are ready, and then double-click back in Windows Explorer, double-click the Start Demo – UI.bat shortcut. You should then be presented with the Fabrikam user interface.

c. In the user interface, notice that Windows Presentation Foundation has been used to create a rich user experience with a carousel style menu of options on the left hand side of the window. d. Click to choose the Products button at the top of the list and view the products that are available. e. You are presented with a list of products that Fabrikam has available. Notice that there are no options using Longhorn Server, so you’ll need to create a customized

Page 2 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps quote. Click the button labeled Create Customized Quote in the Actions pane.

f. In the customized quote screen, click the Autofill checkbox in the lower-left portion of the screen to fill in the data for you so you do not have to type it all in. g. Review the quote information and notice the comments indicating that we want a virtual server with Longhorn Server, IIS 7 and the .NET Framework 3.0. h. Click the button labeled Submit Quote to begin the quote process. i. A message box will be displayed once the quote request has been submitted. Click OK and you will be taken to the quote management screen where you should see your new quote at the bottom of the list.

j. Click on the quote to highlight it and click the View Workflow Status button. Page 3 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps This will show you the workflow and all of its states along with color coded highlighting to indicate which states have already completed and what state the workflow is currently in. k. The process has already completed the QuoteVerification state and is waiting in the QuoteReview state. As part of the quote verification, emails were sent to engineering and marketing asking them to approve or reject the quote. The system is currently waiting for one of those departments to reply to the review request before proceeding.

l. Being sure to leave the Fabrikam application open, click the Windows Start button, and select E-mail (Windows Mail) to open the email reader.and initiate a receive process to check for new mail. You should find mail to both Engineering ([email protected]) and the Sales Manager ([email protected]). Note: In order to make the sample easier to use, the e-mail client is configured to receive mail for all of the demo accounts. m. Open either email (the subject will start with Review Quote). Click the information bar below the subject to download pictures. Review the content to see that the data has come from the quote you recently entered. n. Click on the Approve Quote Request button which will open a URL in your web browser which will submit the approval into the service layer. If an Information Bar warning is displayed, close it and review the web page. o. Return to the Fabrikam user interface application and notice that the status of the workflow has been updated in the user interface to indicate that the review was approved and the legal review has begun. As part of this process, an email was sent to the legal department for approval or rejection. p. Return to Windows Mail and initiate another receive. You should receive an email to [email protected] which is similar to the previous emails and asks for approval. Open the e-mail and click the information bar to download pictures. q. Click the Approve Quote Request button which will again open a URL to submit an approval for the quote.

Page 4 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps r. Return to the Fabrikam user interface and you will notice that the process has completed and that the appropriate states that have completed in the workflow are all highlighted in green. Close all open windows and applications before continuing.

Page 5 of 26

A Server Scenario Lab with Windows Communication Foundation

Exercise 2 Creating a Windows Communication Foundation Service and Client Scenario In this exercise, you will get to develop a full service including definition, implementation and hosting. You will be building the customer service which returns a collection of customers to the caller. In order to build a service, you must first define the contracts, and then provide the implementation. Then you will need to configure and host the service. After the service is created, you will update the Fabrikam client to consume the service and bind the results to a grid view in the UI. The project files for this lab are in the c:\Fabrikam\Labs\before\ folder. Tasks

Detailed Steps

Complete the following 6 tasks on:

Note: The first step in creating a service is to define the messages that the service will exchange. In the case of the customer service, you need to define a structural contract that represents a customer. Structural contracts provide the WCF runtime with the information it needs to serialize and deserialize objects to create SOAP messages. The contracts are also used in the metadata for the service, which allows client applications to build proxies to communicate with the service. Note: The Windows Communication Foundation allows you to define structural contracts implicitly, simply by defining a class and having that class passed around as a message. The class will be serialized using the familiar .NET XmlSerializer. It is preferable, though, to define structural contracts explicitly using a new syntax provided by the Windows Communication Foundation. By so doing, not only is the nature of the contract made explicit, but also serialization is accelerated by the new, high-performance Windows Communication Foundation DataContractSerializer. In this task, you will be defining your structural contracts explicitly.

CON312354 1. Create the structural contract

a. Navigate to c:\Fabrikam\Labs\before\ and double-click the Fabrikam Workflow and Services.sln file to open the solution. b. In the Solution Explorer, expand the Fabrikam.Contracts project. This is where all of the structural contracts for the WCF services reside. c. Right-click the Fabrikam.Contracts project and choose Add | Class. d. Name the new class Customer.cs and click OK in the dialog. e. Make the class public by adding the public keyword to the beginning of the class declaration. f. To start programming structural contracts in the customer class, you need to add using statements to two namespaces: System.ServiceModel and System.Runtime.Serialization. Add both of these using statements to the list at the beginning of the class file: using System.ServiceModel; using System.Runtime.Serialization;

g. In order to be a WCF contract, the class must be marked with the DataContract attribute. Add this attribute to your class now. The class definition should look like the one shown below. [DataContract()]

Page 6 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps public class Customer { }

h. Now that the class is defined as a contract, the members of the class must be defined and those that should be included in the exposed WCF contract should be marked with the DataMember attribute. Add the following properties to the Customer class. [Snippet: Lab 02 Exercise 01 Task 01 DataContract] [DataMember] public Guid CustomerId; [DataMember] public string ContactName; [DataMember] public string CompanyName; [DataMember] public string ContactEmail; [DataMember] public DateTime LastContact;

i. For simplicity, add a constructor that provides a way to instantiate an instance of a customer with the core state initialized. [Snippet: Lab 02 Exercise 01 Task 01 Constructor] public Customer(Guid customerId, string contactName, string companyName, string contactEmail) { CustomerId = customerId; ContactName = contactName; CompanyName = companyName; ContactEmail = contactEmail; }

j. Finally, we want the customer class to be able to handle the scenario where the LastContact property has not been set. We use the OnSerializing attribute to indicate a method to run when the customer is serialized. In this method we set the value of the LastContact property to the current date and time. [Snippet: Lab 02 Exercise 01 Task 01 OnSerializing] [OnSerializing] internal void InitializeData(StreamingContext context) { LastContact = DateTime.Now; }

k. Now you have a class that represents the data or messages you will be exchanging with the service. The attributes you have used, DataContract and DataMember, will guide the WCF runtime as to how to serialize and deserialize your objects properly between CLR types and XML. 2. Create the behavioral

contract

Note: In addition to the structural contracts required for your service, a behavioral contract provides the definition of the exposed operations for your service. The behavioral contract uses the classes that were defined as data contracts in the method Page 7 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps signatures. In this task, you will create the Service Contract for the customer service by defining and attributing a .NET interface. a. Right-click the Fabrikam.Contracts project and choose Add | New Item. b. In the new item dialog box, select Interface and name the new file ICustomerService.cs. c. When the interface file opens, make the interface public by adding the public access modifier to the declaration. d. Add a using statement for System.ServiceModel to the top of the file so that you will have easy access to the types needed for declaring a service contract. using System.ServiceModel;

e. In order to use the interface as a service contract, it must be attributed with the ServiceContract attribute. Add the attribute to the interface declaration including a parameter to specify a unique namespace for your service. The code below shows the interface declaration at this point. [ServiceContract(Namespace = "http://Fabrikam.Services")] public interface ICustomerService {}

f. Add an operation to the interface named GetCustomers which returns a generic list of customer objects. g. Add the OperationContract attribute to the GetCustomers operation to indicate that it is part of the service contract and not just part of the interface. [OperationContract] List GetCustomerList();

h. Build the Fabrikam.Contracts project by right-clicking it and choosing Build. Fix any compiler errors that you find. 3. Implement the

service

Note: Service implementation with Windows Communication Foundation is meant to allow you to focus on the business of your service and not having to write a lot of infrastructure code. To that end, implementing your service involves implementing the .NET interface you used as your service contract. In this task you will provide the logic to query the list of customers and return them by implementing the ICustomerService interface that you created in the previous task. a. Right click the Fabrikam.Services project and choose Add | Class. Name the class CustomerService.cs and click the OK button to exit the dialog. b. Make the class public by adding the public access modifier to the class declaration. c. Add using statements for the namespaces related to WCF as well as the data namespaces as we will be querying SQL Server for the customer information. [Snippet: Lab 02 Exercise 01 Task 03 Using] using using using using using

System.ServiceModel; System.Data; System.Data.SqlClient; Fabrikam.Contracts; System.Configuration;

d. Implement the ICustomerService interface in your class. Note: You can use the smart tags on the interface name, after you have typed it in, to

Page 8 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps have Visual Studio generate the interface stub for you. e. Add a private string field named connectionString to hold the database connection string and a parameterless constructor to initialize the value by reading from the configuration file [Snippet: Lab 02 Exercise 01 Task 03 Constructor]. f. The class declaration should now look like the following: public class CustomerService : ICustomerService { private string connectionString; public CustomerService() { connectionString = ConfigurationManager.ConnectionStrings ["Fabrikam"].ConnectionString; }

List ICustomerService.GetCustomerList() {} }

g. Now implement the service by accessing the data in the database and using it to create a list of customer objects to return. The code below provides the implementation of the GetCustomers operation. Insert the code as the body of the GetCustomerList method. [Snippet: Lab 02 Exercise 01 Task 03 GetCustomers] List custList = new List(); string queryString = @"SELECT [IdCustomer] ,[ContactName] ,[CustomerName] ,[CustomerEmail] FROM [dbo].[Customers]"; using (SqlConnection connection = new SqlConnection(this.connectionString)) { SqlCommand command = new SqlCommand(queryString,connection); connection.Open(); SqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { custList.Add( new Customer(reader.GetGuid(0), reader.GetString(1), reader.GetString(2), reader.GetString(3)));

Page 9 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps } reader.Close(); return custList; }

h. Finally, add a behavior to your service to control the instancing model used by WCF when creating instances of your service. Add the following attribute to the class declaration. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerCall)]

Note: Behaviors impact the local execution of the service and do not impact the contract of the service. Common behaviors include the instancing behavior used here and transactional behavior. Custom behaviors can also be written to inject your code into the contract building process or the runtime processes of the service or client. Because these behaviors do not impact the contract, they are placed on the implementation class instead of the interface. This also allows different implementations to exhibit different local behavior. i. Build the Fabrikam.Services project by right-clicking on it and choosing Build. Fix any compiler errors that you find. 4. Configure the service

bindings

Note: Now that the service is defined and built, the last step is to configure the bindings and address for the service. The bindings provide the definition of the various protocols that the service will use and the transport. Examples of protocols include WS-Reliable Messaging and WS-Security. Default transports include HTTP, TCP, MSMQ, Named Pipes. In this task you will use the service configuration utility to define the binding and address for the service. a. Open the Service Configuration Editor found in Start | All Programs | Microsoft Windows SDK | Tools. b. From the File menu, choose Open | Config File and browse to open the FabrikamHost\App.Config file at C:\Fabrikam\Labs\before\FabrikamHost. c. Expand the Advanced node and then select the Service Behaviors node. d. In the tasks pane, click New Service Behavior Configuration. e. In the Behavior configuration pane, name the configuration MetadataBehavior and then click the Add button. f. Choose the serviceMetadata item from the Available elements list and click Add. g. In the explorer node on the left hand side, notice the addition of the serviceMetadata node under the MetadataBehavior node. Click to highlight this item so it can be edited. h. Change the HttpGetEnabled property to True. i. In the tasks pane, click the link to Create a New Service. j. When prompted to specify the Service Type, click the Browse button and find the Fabrikam.Services.dll assembly in the C:\Fabrikam\Labs\before\bin directory. k. Choose the Fabrikam.Services.CustomerService type that you created in the last task and choose Open. Back in the wizard, click Next. l. The correct interface should be chosen for you, but if it is not, use the same method as the previous step choosing the Fabrikam.Contracts.dll assembly and the Fabrikam.Contracts.ICustomerService interface. Click Next to move to the

Page 10 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps next step of the wizard. m. For the communication type, choose HTTP and click Next. n. Leave the default setting of Basic Web Services Interoperability and click Next. o. When prompted for the address, enter: http://localhost:8081/Fabrikam/CustomerService and press Next. p. Complete the wizard by clicking Finish and then examine the configuration. You should now have a new entry in the Configuration tree view for the Fabrikam.Services.CustomerService service. You should be able to expand the node and see the single endpoint that was added for the service and the review the settings that were made for you. q. Highlight the Fabrikam.Contracts.CustomerService service node and then set the BehaviorConfiguration to MetadataBehavior. r. Choose File | Save and then exit the configuration tool. s. Back in Visual Studio 2005, open the App.config file in the FabrikamHost project and notice that addition of the new configuration item for the service. <service behaviorConfiguration="MetadataBehavior" name="Fabrikam.Services.CustomerService"> <endpoint address="http://localhost:8081/Fabrikam/CustomerService" binding="basicHttpBinding" bindingConfiguration="" contract="Fabrikam.Contracts.ICustomerService" />

5. Host the service

Note: Now that the service is built and configured, the final step to publish the service is to host the service is an application domain. The ServiceHost class provides the means to host a service in any .NET application domain. In this task, you will update the FabrikamHost application to host the customer service. a. Open Program.cs file in the FabrikamHost project. b. In the Main method, add a call to create a ServiceHost for the CustomerService type just below the creation of the service host named shStateMachineQueryService. ServiceHost shCustomerService = new ServiceHost( typeof(CustomerService), new Uri("http://localhost:8081/Fabrikam/"));

c. Move down in the code where the service hosts are being opened and add a line of code to open the host for the customer service right below the line which opens the shStateMachineQueryService host. shCustomerService.Open();

d. Finally, at the end of the Main method, add a call to close the host for the customer service as the host application is shutting down. shCustomerService.Close();

e. Build and run the host fixing any compiler errors that you receive. f. With the host still running, open Internet Explorer and browse to http://localhost:8081/Fabrikam. g. Verify that you are presented with the help page for the service that looks similar Page 11 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps to the following:

h. Leave the Fabrikam host running as you will use it in the next task. 6. Implement the client

Note: Now that you have a service implementation and a host for the service, you need to build a proxy that the client application can use to interact with the service. In this task you will create a proxy to be used by the client and the update the user interface to consume the data from the service. a. Open the CMD Shell from Start | All Programs | Microsoft Windows SDK. b. Change directories to the lab directory using the command below: cd \Fabrikam\Labs\before\Fabrikam.Presentation c.

Generate the proxy and merge the configuration by using the svcutil utility as shown below: svcutil http://localhost:8081/Fabrikam /out:CustomerServiceProxy.cs /config:app.config /mergeconfig

d. Stop the running instance of the host application and then back in Visual Studio 2005, open the Fabrikam – UI.sln solution file from the C:\Fabrikam\Labs\before directory and highlight the Fabrikam.Presentation project by clicking on it once. e. Choose Project | Show all files from the Visual Studio menu and expand the project node in the Solution Explorer if necessary. f. From the Solution Explorer, find the CustomerServiceProxy.cs file and rightclick to choose Include in Project. g. Open the App.config file in the Fabrikam.Presentation project and confirm that a new endpoint element was added under the element. The name attribute of the new element will be similar to BasicHttpBinding_ICustomerService. h. Add code to the presentation layer to consume the service. Open the MainWindow.xaml.cs file from the Fabrikam.Presentation project. i. Add a new private method to the form to consume the service and return the collection of customers. Create an instance of the proxy class and then call the GetCustomers method to get the customers from the service. [Snippet: Lab 02 Exercise 01 Task 06 GetCustomers]

Page 12 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps private IEnumerable GetCustomers() { List customers; CustomerServiceClient proxy = new CustomerServiceClient(); Customer[] aryCustomers = proxy.GetCustomerList(); customers = new List(aryCustomers); return customers; }

j. Finally, in the OnInitialized method add a few lines of code to hook up the result of the query to the user interface by setting the ItemSource property of the customer list view. [Snippet: Lab 02 Exercise 01 Task 06 CustomerView] object customerView = FindName("customerListView"); if (customerView != null) ((ListView)customerView).ItemsSource = GetCustomers();

k. Build the Fabrikam – UI solution and fix any compiler errors. l. Run the Fabrikam – Workflow and Services solution by either opening a second instance of Visual Studio 2005 or using the Windows Explorer, you can navigate to C:\Fabrikam\Labs\before\bin and run the FabrikamHost.exe. After the host starts and the services are ready (as evidenced by the output on the console), start the Fabrikam-UI solution from Visual Studio 2005. When the UI appears, click the Accounts button in the left carousel. The data in the user interface is populated by calling the CustomerService. m. When done, exit the UI and then shutdown the services host.

Page 13 of 26

A Server Scenario Lab with Windows Communication Foundation

Exercise 3 Windows Communication Foundation Manageability Scenario Manageability of services and applications is a key component to minimizing down time and maintaining a healthy system. Many applications and frameworks do not provide good information for developers and IT Pros to use when troubleshooting an application. Windows Communication Foundation comes with a rich set of manageability tools to help you configure, manage and monitor your services and applications. In this exercise, you will use some of these tools to gain an understanding of the features available to you. Tasks

Detailed Steps

Complete the following 4 tasks on:

a. Open the Service Configuration Editor from Start | All Programs | Microsoft Windows SDK | Tools.

CON312354 1. Enabling service tracing

b. Choose File | Open and browse to the App.Config file for the FabrikamHost folder in the C:\Fabrikam\Labs\before\FabrikamHost\ folder. c. In the Configuration pane on the left hand side find the Diagnostics node and highlight it. d. In the right-hand pane, click the following links: Enable Log Auto Flush, Enable Message Logging, and Enable Tracing. e. Under the Tracing heading, click the Trace Level link (defaulted to warning) and in the dialog box change the value to Information. The boxes labeled Propagate Activity and Activity Tracing should already be checked to allow data from multiple processes to be coalesced into a single picture of your service interactions. f. Highlight the MessageLogging node under Diagnostics in the Configuration pane and then set LogEntireMessage to True. g. Find the Diagnostics | Listeners node in the configuration explorer and highlight the ServiceModelTraceListener. h. Set the InitData property to ..\Logs\Fabrikam_Services_TraceLog.svclog i. Highlight the ServiceModelMessageLoggingListener and set the InitData property to ..\Logs\Fabrikam_Services_Messages.svclog j. Choose File | Save. k. Repeat steps b – i above for the App.config file in the Fabrikam.Presentation directory using “Client” instead of “Services” in the trace file names (i.e. Fabrikam_Client_TraceLog.svclog and Fabrikam_Client_Messages.svclog). l. Using Windows Explorer, verify that the following path is valid: C:\Fabrikam\Labs\before\Logs. If necessary, create the Logs folder.

2. Reviewing service

tracing

Note: Now that service tracing is configured, you will use the Service Trace Viewer to examine the trace files for a service. The Service Trace Viewer is a powerful tool to help you visualize service execution and message exchanges, as well as retrieve valuable information about the various activities occurring in your application. a. Open the two solutions (Fabrikam – Workflow and Services & Fabrikam – UI) in separate instances of Visual Studio 2005 if they are not already open. b. Start the Fabrikam – Workflow and Services solution and when it is running, start the Fabrikam – UI solution. c. Run through the demo scenario once and then close the client application and

Page 14 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps FabrikamHost application to stop debugging. d. Open the Service Trace Viewer from Start | All Programs | Microsoft Windows SDK | Tools. e. Choose File | Open once the trace viewer starts and browse to the Logs directory under your lab directory. f. Choose all four trace files that are found in the directory as you will want to review the messages and activity information from both the client and service. g. In the trace viewer, notice that the left window pane contains a list of activities which occurred in the processing of the application. These activities include trace activities for services being hosted, endpoints beginning to listen, and message trace events. Scroll down and find the first Process action trace entry which will be for the GetCustomerList operation and highlight it.

h. The upper right window pane will update to provide you a list of the traced activity events and messages logged for this communication. Browse through the events in this list to see the various types of information you can view. As you click on each event, the details of the trace appear in the lower right hand window pane. Pay particular attention to the Message Log Trace items reviewing the Action property which indicates the service and operation being called. Look at the last message log trace and you should be able to see the actual message data as it was returned to the client application. i. In the left pane, click on the Graph tab to see a graph of the message exchange and the activity trace events. j. Notice that both the Fabrikam.Presentation and FabrikamHost processes are shown and the graph provides a visual representation of the activity which occurred and the interactions between the two hosts. k. Continue highlighting different activity traces in the upper right panel and notice that the highlighting line on the graph moves to keep in synch with your changes. You can also click on a specific activity step in the graph to see the events list update.

Page 15 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps

l. In the left window pane, click the Messages tab to see the list of messages exchanged during the trace. You can click on a specific message to see the activity trace details of that message exchange. This view provides you a quick way to get information related to a particular message exchange. m. In the bottom right pane, select the Message tab and notice that you are presented with a formatted view of the message headers and body, which can be viewed in plain text as they were transmitted over the wire. Note: The service is configured to use the basicHttpBinding which does not support the WS-Security protocols. In order to be secure when using the basic binding, you must rely on transport security such as SSL. In the next exercise, you will configure your service for secure communications taking full advantage of the WS-Security specifications. n. Close the Service Trace Viewer. 3. Windows

Communication Foundation performance monitoring

Note: In addition to being able to trace activity and messages, Windows Communication Foundation provides a rich set of tools for monitoring applications using performance monitor and WMI. In this task, you will use the performance monitor tools to review the performance data available for all WCF services without any coding on the part of the developer. In addition to the values you see here, you can add your own custom performance counters to provide more specific monitoring values as they pertain to your custom service. a.

Open the Service Configuration Editor from Start | All Programs | Microsoft Windows SDK | Tools.

b. Choose File | Open and select the App.config file from the FabrikamHost project directory (it should appear on the Recent Files list off the File menu). c. Highlight the Diagnostics node in the configuration tree view. Click the link labeled Enable WMI Provider to change the status to On and click the one labeled Toggle Performance Counters until it shows a status of All. d. Save the file and close the configuration editor. e. Start both the workflow and services solution and the UI solution. Note: For Windows XP / 2003 f. Open the Performance administrative tool from Start | Control Panel | Administrative Tools.

Page 16 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps g. Click the + symbol in the toolbar or press Ctrl + I to add new counters to the monitor. h. In the Add Counter dialog, set the Performance Object to ServiceModelEndpoint 3.0.0.0.

i. In the instances pane (right hand pane) choose the quoteworkflows81.iquoteworkflow… instance. j. In the counters pane (left hand pane) choose the Calls item and click the Add button. Then choose the CallsDuration and click the Add button again. k. Click the Close button to close the Add Counters dialog. Note: Skip to step m. Note: For Windows Vista / Longhorn Server l. Open the Reliability and Performance Monitor administrative tool from Start | Control Panel | Administrative Tools. (Optionally, type Performance in the Start button Search bar) m. Select the Performance Monitor node in the left navigation tree and then click the + symbol in the toolbar or press Ctrl + I to add new counters to the monitor. n. In the Add Counter dialog, expand the ServiceModelEndpoint 3.0.0.0 item in the list.

Page 17 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps

o. Highlight the Calls item under ServiceModelEndpoint 3.0.0.0. p. In the Instances pane (bottom left pane) choose the quoteworkflow##.iquoteworkflow… instance and click the Add >> button. q. Select the CallsDuration item under ServiceModelEndpoint 3.0.0.0 and click the Add >> button again. r. Click the OK button to close the Add Counters dialog. s. In the performance view, you should now have the two new counters listed at the bottom of the window. Highlight each one, and review the data about each counter which appears between the list of counters and the graph. Notice that no values are currently shown. t. Leaving the performance monitor open, run through the demo using the user interface instance that is already running. u. Return to the performance monitor and review the values for the two counters you added. v. When done, close the monitoring application. 4. Windows

Communication Foundation and WMI

Note: WMI is the current standard for exposing management information from applications on the Windows platform. Windows Communication Foundation provides extensive support for WMI in the service model exposing services, endpoints, contracts, and their related objects through a WMI provider. This allows organizations to extend their current investments in management tools to cover their development efforts with WCF. In this task, you will use some of the common WMI tools to review the available information about your services. Note: This task requires that you have installed the WMI Tools and Scriptomatic as described in the setup documentation. a. Make sure the Fabrikam – Worklow and Services solution is started. If it is not, choose Debug | Start Debugging from the Visual Studio menu. b. Open the WMI Object Browser from Start | All Programs | WMI Tools. Note: Windows Vista users with User Account Control turned on: Right-click Internet Explorer and choose Run as Administrator. Then browse to Program Files\WMI Tools\Browser.htm

Page 18 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps c. Be sure to enable active content using the Internet Explorer toolbar if you get a warning. d. In the Connect to namespace dialog, enter root\ServiceModel and click OK when prompted to use the default credentials. e. In the Browse For Instance dialog, choose Service from the left column and click the Add button to move it to the right. f. Click OK and you then select the CustomerService instance from the Results dialog, clicking OK to exit the dialog. g. Highlight the service on the left and review the properties available on the property pane. Notice that you can get access to information about the service including the service behaviors, extensions, base addresses, etc. h. Expand the nodes in the tree view on the left to see the associations related to this service. You should be able to see the service endpoints and the application domains. i. Review the properties for the endpoint associated with this service. This is the same information you used to configure the service endpoint earlier using the Service Configuration Editor. j. Highlight the service node in the tree view, and then open the Associations tab on the property pane. This provides you a visual representation of the related objects. k. Browse around the interface a bit and take note of all the metadata that is available about the service. Compare this to your configuration and code to understand where the information comes from. l. Close the WMI Object Explorer. m. Open the ScriptomaticV2 application from under WMI Tools. Note: Windows Vista users with User Account Control on: Right-click the command prompt shortcut and choose Run as Administrator. Then change to the directory where you unzipped the Scriptomatic application and enter ScriptomaticV2.hta. n. From the WMI Namespace dropdown, choose root\ServiceModel. o. From the WMI Class dropdown, choose Endpoint. p. Select JScript for the Language and HTML for the Output Format. q. Click the Run button. You should see HTML output in Internet Explorer similar to that shown below.

Page 19 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps

r. Review the Jscript code that was generated for you. Change the language option if you are more comfortable with another language and review the code. s. Close all of the open applications (Internet Explorer, Scriptomatic, etc).

Page 20 of 26

A Server Scenario Lab with Windows Communication Foundation

Exercise 4 Windows Activation Service and Security Scenario In the previous exercise you used service tracing to view the messages that were sent between two services. One of the important features of Windows Communication Foundation is to provide easier support for implementing turnkey security solutions. In this exercise you will configure the service to support signed encrypted messages without changing any code. The services you have seen and implemented are currently hosted in a console application. This works very well for demonstrations and lab scenarios, but in the real world you want a host for your service that provides features such as process recycling, configurable identity, and service activation. “Longhorn” Server includes a new service known as Windows Activation Service that provides a perfect host for services. Tasks

Detailed Steps

Complete the following 3 tasks on:

Note: In this task, you will use IIS to host the customer service you built in Exercise 1 as a first step.

CON312354 1. Host a service in WAS

a. If necessary, open an instance of Visual Studio 2005 and then choose File | New | File. b. In the new file selection dialog, choose XML File. c. Add the following configuration information to the file. This provides the service hosting data about the customer service and the connection string it uses to lookup data. [Snippet: Lab 02 Exercise 03 Task 01 WebConfig] <system.serviceModel> <services> <service name="Fabrikam.Services.CustomerService"> <endpoint binding="basicHttpBinding" contract="Fabrikam.Contracts.ICustomerService" />

d. Choose File | Save XMLFile1.xml as and save the file as web.config in C:\Fabrikam\Labs\before\. Be sure to change the Save as type setting to config in the Save As dialog box. Note: Because the solution is already building to the bin directory, the before folder can be treated as a virtual directory. The default build directories for a project would be in the bin\debug folder and would need to be modified to support this. The file you

Page 21 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps just created will act as the configuration file for the IIS application we will create. Note: the endpoint does not have an address attribute because when hosting in IIS or WAS, the address is determined by the configuration of the host and the creation of a file to act as the activatable endpoint. You will configure these settings next. e. Click Start | Run and enter InetMgr.exe (or type InetMgr in the Start button Search bar) to start the IIS manager. f. Expand the nodes in the tree view in order to find the default web site. g. Right-click the web site node and choose Create Application from the context menu (use Add Application on Windows Vista). h. Name the application FabrikamServices and enter c:\fabrikam\labs\before as the path. Accept the default application pool. i. Leave the IIS manager open as you will be using it again, but return to Visual Studio 2005 and create a new text file using File | New | File. j. Enter the following single declaration to the file. <%@ServiceHost Service="Fabrikam.Services.CustomerService,Fabrikam.Servic es" %>

Note: The svc file acts as the endpoint for client applications to make service calls and also determines the address of the service. k. Choose File | Save TextFile1.txt As and save the file as CustomerService.svc in the before directory. l. Open the Fabrikam – UI solution from the before folder. m. Expand the Fabrikam.Presentation project and open the App.config file. n. Change the address of the customer service to point to the new endpoint you have created in WAS: http://localhost/FabrikamServices/CustomerService.svc. o. Remove the bindingConfiguration attribute from the customer service endpoint element. p. Run the Fabrikam – UI solution without starting the Fabrikam – Workflow and Services solution. You should be able to click the Accounts button the left hand carousel and view the accounts retrieved from the service. q. Close the UI when done. 2. Secure the service

Note: Now that you have hosted a service in WAS, and are ready to publish it out to other consumers, it will be important to secure the service as it contains sensitive customer data. In this task you will change the binding being used by the service and client in order to secure the communications. a. Make sure all the solutions are not debugging and then delete the log files from the logs directory. b. In the App.Config file for the Fabrikam.Presentation project and the web.config file you created in Task 1, change the binding name on the endpoint for the customer service from basicHttpBinding to wsHttpBinding. Note: That’s it. You have secured your communication between the services simply by choosing a binding which supports WS-Security. Where possible, all bindings are secure by default. The rest of the steps in this task simply help you see that the communication is secured. c. Save both files and run the Fabrikam – UI solution. d. Once the application appears, close it. e. Open the Service Trace Viewer from Start | All Programs | Microsoft Windows

Page 22 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps SDK | Tools and then open the two trace files in the Logs folder. f. In the left pane of the trace viewer, click on the Messages tab. g. Notice that there are now a number of messages preceding the call to the customer service. These are all security related messages which were exchanged to setup the secure communication between the client and server. h. Click on the last message which should be the response from the GetCustomerList operation on the service. i. In the lower right pane, view the XML and Message tabs and notice that you can no longer see the message body in plain text as it has been signed and encrypted. j. Close the Service Trace Viewer.

3. Use Windows

Activation Services to host a service over TCP

Note: One of the biggest benefits of the Windows Activation Service is that it provides the same great services that have been available using IIS but supports those services for numerous protocols including TCP, Named Pipes and MSMQ. This means that the arrival of a service request over TCP can cause WAS to activate the service for you and setup the host process automatically. In this task you will expose another endpoint for your service so that it can be reached over TCP without having to write a custom host. Note: If you are using User Account Control in Windows Vista, you will want to open a command prompt as the administrator and run the commands in this task from that command prompt. a. Open the Services administrative tools by choosing Start | Run and entering Services.msc. b. If the Net.Tcp Port Sharing Service is not started, then start it. c. Check the Net.Tcp Listener Adapter service and start it as well if it is not already running. Close the Services application when complete. d. You need to enable the Net.Tcp Listener adapter in WAS by using the AppCmd utility. Enter the following command at a command prompt to enable TCP listening on port 8081. Note that this assumes your default web site is actually called “Default Web Site”. This command should be entered as a single line. %windir%\system32\inetsrv\appcmd.exe set site "Default Web Site" +bindings.[protocol='net.tcp',bindingInformation='8083:*']

e. You also need to enable the tcp protocol for your application. Do so by using the following command in the command prompt. %windir%\system32\inetsrv\appcmd.exe set app "Default Web Site/FabrikamServices" /enabledProtocols:http,net.tcp

f. At the command prompt, IISReset to reset IIS and ensure your changes are in place. g. Update the web.config file found in the before directory of your lab to add a TCP endpoint. Add this configuration just below the current endpoint. <endpoint binding="netTcpBinding" contract="Fabrikam.Contracts.ICustomerService" />

Note: In the host, multiple endpoints can be configured to support different clients or different requirements. The binding you choose determines to a great extent the level of interoperability your endpoint supports. Being able to specify many different endpoints makes your service more accessible. The ability to add and modify these

Page 23 of 26

A Server Scenario Lab with Windows Communication Foundation Tasks

Detailed Steps endpoints without changes to code is extremely powerful. h. Open the App.config file in the Fabrikam.Presentation project and change the address and binding to support TCP. Set the binding attribute to netTcpBinding and the address attribute to net.tcp://localhost:8083/FabrikamServices/CustomerService.svc for the Customer Service endpoint (it has a contract value of ICustomerService). i. Save the configuration files and run the Fabrikam – UI solution again to test your changes. After the user interface comes up, you should be able to view accounts and see that you now accessed the service using TCP instead of HTTP without having to change hosts. j. Optionally, open up the service trace viewer and check the message traces. Were the messages encrypted?

Page 24 of 26

A Server Scenario Lab with Windows Communication Foundation

Exercise 5 Extending Windows Communication Foundation Services Scenario One of the great benefits of using Windows Communication Foundation is that most of the components within the service model are extensible or replaceable. In this exercise, you will see one way of extending the WCF runtime by adding custom behaviors to a service which allows code to examine the messages as they are being processed. Tasks

Detailed Steps

Complete the following task on:

Note: In this task you will attach a custom behavior to the quote workflow service to log all messages received and sent. This behavior will actually attach a message inspector which will log the messages to a monitoring service via MSMQ.

CON312354 1. Add a custom behavior to a service

a. Open the Fabrikam – Workflow and Services solution. b. Expand the Fabrikam.Services project in Solution Explorer and open the QuoteWorkflowService.cs file. c. Add the MessageLoggingExtension attribute to the QuoteWorkflowService class declaration. This attaches a custom behavior to the service. d. Save your changes and open the MessageLoggingExtension.cs file from the Fabrikam.ServiceExtensions project. e. Notice that the class implements the IContractBehavior interface. This is the interface that allows the class to attach itself to the service when the host is constructed. In this particular instance, the implementation simply adds a message inspector into the dispatcher, the code responsible for calling the service code. For simplicity, the MessageLoggingExtension also implements the IDispatchMessageInspector interface to allow it to examine the messages being sent to or from the service. Note: IDispatchMessageInspector is one interface that you can implement to extend the WindowsCommunicationFoundation, but there are other interfaces which provide hooks to do things such as validate parameters or choose the operation to execute. f. Find the AfterReceiveRequest and BeforeSendReply methods which provide the implementation of the IDispatchMessageInspector interface. Notice that both methods call the LogMessage method. LogMessage creates a message with the contents of the original message and sends them to another WCF service which will “log” them to the console. g. Build the solution. h. In Windows Explorer, open the C:\Fabrikam\Labs\before\bin\ directory and start the MessageLoggingRecorder.exe application by double-clicking on it. The console should show that the service is up and running. i. Go back to Visual Studio and start the Fabrikam – Worklow and Services solution and the Fabrikam – UI solution. Run through the demo, intermittently checking the console output of the MessageLoggingRecorder application. You should see the message content for each request and response to the quote workflow service being logged.

Page 25 of 26

A Server Scenario Lab with Windows Communication Foundation

Lab Summary In this lab you learned about the unified programming model provided by Windows Communication Foundation for building distributed applications. In addition, you were introduced to the powerful tracing, monitoring and management features built into Windows Communication Foundation. Finally, the ability to easily apply turnkey security and utilize multiple transports and hosts was examined.

Page 26 of 26

Related Documents

Wcf Crm
June 2020 4
Wcf
November 2019 12
Wcf
May 2020 4
Wcf Presentation
October 2019 7
Wcf Overview
November 2019 6
Wcf Fundamentals
June 2020 3