-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
1/15
Understanding WindowsCommunication Foundation
Microsoft Virtual Labs
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
2/15
Understanding Windows Communication Foundation
Table of Contents
Understanding Windows Communication Foundation............................................................. 1
Exercise 1 Creating a Windows Communication Foundation Service and Client.........................................................2
Exercise 2 Windows Communication Foundation Manageability...............................................................................10Lab Summary ..............................................................................................................................................................13
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
3/15
Understanding Windows Communication Foundation
Page 1 of 13
Understanding Windows Communication
Foundation
Objectives After completing this lab, you will be better able to: Demonstrate the capabilities and tools of Windows Communication
Foundation.
ScenarioAs a developer for Fabrikam, it is your job to help in building the distributed
applications such as the CRM system used in the demonstration. You are first
tasked with creating a service which provides a list of customers that are
available in the system.
Estimated Time toComplete This Lab 90 Minutes
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
4/15
Understanding Windows Communication Foundation
Page 2 of 13
Exercise 1Creating a Windows Communication Foundation Serviceand Client
ScenarioIn this first 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.
Tasks Detailed Steps
1. Create the structuralcontract
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 theinformation 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.
a. Navigate to c:\Fabrikam\Labs\before\and double-click the FabrikamWorkflow and Services.sln file to open the solution.
b. If a Security warning dialog appears, select the Load project normally radiobutton and clickOK.
c. In the Solution Explorer, expand the Fabrikam.Contracts project. This is whereall of the structural contracts for the WCF services reside.
d. Right-click the Fabrikam.Contracts project and choose Add | Class.e. Name the new class Customer.cs and clickAdd in the dialog.f. Make the class public by adding the public keyword to the beginning of the class
declaration.
g. To start programming structural contracts in the customer class, you need to addusing 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;
h. In order to be a WCF contract, the class must be marked with the DataContractattribute. Add this attribute to your class now. The class definition should look
like the one shown below.
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
5/15
Understanding Windows Communication Foundation
Page 3 of 13
Tasks Detailed Steps
[DataContract()]
public class Customer
{
}
i. Now that the class is defined as a contract, the members of the class must bedefined and those that should be included in the exposed WCF contract should bemarked 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;
j. For simplicity, add a constructor that provides a way to instantiate an instance of acustomer 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;
}
k. Finally, we want the customer class to be able to handle the scenario where theLastContact 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;
}
Note: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
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
6/15
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
7/15
Understanding Windows Communication Foundation
Page 5 of 13
Tasks Detailed Steps
using System.Configuration;
e. 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
have Visual Studio generate the interface stub for you.
f. Add a privatestring field named connectionString to hold the databaseconnection string and a parameterless constructor to initialize the value by reading
from the configuration file [Snippet: Lab 02 Exercise 01 Task 03 Constructor].
g. 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()
{}
}
h. Now implement the service by accessing the data in the database and using it tocreate a list of customer objects to return. The code below provides the
implementation of the GetCustomers operation. [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),
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
8/15
Understanding Windows Communication Foundation
Page 6 of 13
Tasks Detailed Steps
reader.GetString(1),
reader.GetString(2),
reader.GetString(3)));
}
reader.Close();
return custList;
}
i. Finally, add a behavior to your service to control the instancing model used byWCF 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.
j. Build the Fabrikam.Service project by right-clicking on it and choosing Build. Fixany compiler errors that you find.
4. Configure the servicebindings
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 and browse to select theFabrikamHost\App.Config file.
c. Expand the Advanced node and then select the Service Behaviors node.d. In the tasks pane, clickNew Service Behavior Configuration.e. In the Behavior configuration pane, name the configuration MetadataBehavior
and then click the Add button.
f. Choose the serviceMetadata item and clickAdd.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 bin directory directly beneath your lab
directory.
k. Choose the Fabrikam.Services.CustomerService type that you created in the lasttask and choose Next.
l. The correct interface should be chosen for you, but if it is not, use the same
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
9/15
Understanding Windows Communication Foundation
Page 7 of 13
Tasks Detailed Steps
method as the previous step choosing the Fabrikam.Contracts.dll assembly and
the Fabrikam.Contracts.ICustomerService interface. ClickNext to move to the
next step of the wizard.
m.For the communication type, choose Http and clickNext.n. Leave the default setting ofBasic HTTP Interoperability and clickNext.o. When prompted for the address, enter:
http://localhost:8081/Fabrikam/CustomerService and press Next.
p. Complete the wizard and then examine the configuration. You should now have anew 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 service node and then set the BehaviorConfiguration toMetadataBehavior.
r. Choose File | Save and then exit the configuration tool.s. In Visual Studio, open the App.config file in the FabrikamHost project and
notice that addition of the new configuration item for the service.
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 ofcode 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 customerservice 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
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
10/15
Understanding Windows Communication Foundation
Page 8 of 13
Tasks Detailed Steps
http://localhost:8081/Fabrikam.
g. Verify that you are presented with the help page for the service that looks similarto 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 asshown below:
svcutil http://localhost:8081/Fabrikam /out:CustomerServiceProxy.cs
/config:app.config /mergeconfig
d. Open the Fabrikam UI.sln solution file from the lab directory and highlight theFabrikam.Presentation project by clicking on it once.
e. Choose Project | Show all files from the Visual Studio menu.f. From the solution explorer, find the CustomerServiceProxy.cs file and right-
click to choose Include in Project.
g. Open the app.config file in the Fabrikam.Presentation project and confirm that anew 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 theMainWindow.xaml.cs file from the Fabrikam.Presentation project.
i. Add a new private method to the form to consume the service and return thecollection 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]
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
11/15
Understanding Windows Communication Foundation
Page 9 of 13
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 resultof 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. After the solution starts and
the services are ready (as evidenced by the output on the console) start the
Fabrikam-UI solution. When the UI appears, click the Accounts button in the left
carousel. The data in the user interface is populated by calling the
CustomerService.
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
12/15
Understanding Windows Communication Foundation
Page 10 of 13
Exercise 2Windows Communication Foundation Manageability
ScenarioManageability of services and applications is a key component to minimizing down time and maintaining a healthysystem. 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
1. Enabling servicetracing
a. Open the Service Configuration Editor from Start | All Programs | MicrosoftWindows SDK | Tools.
b. Choose File | Open and browse to the App.Config file for the FabrikamHostfolder in the lab folder.
c. In the Configuration pane on the left hand side find the Diagnostics node andhighlight it.
d. In the right-hand pane, click the following links: Enable Log Autoflush, EnableMessage Logging, and Enable Tracing.
e. Under the tracing heading, click the Trace Level link (defaulted to warning) andin the dialog box change the value to Information. Also, check the boxes labeled
Propagate Activity and Activity Tracing to allow data from multiple processes to
be coalesced into a single picture of your service interactions.
f. Highlight the MessageLogging node under Diagnostics and then setLogEntireMessage to True.
g. Find the Diagnostics |Listeners node in the configuration explorer and highlightthe ServiceModelTraceListener.
h. Set the InitData property to ..\Logs\Fabrikam_Services_TraceLog.svclogi. 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).
2. Reviewing servicetracing
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 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 andFabrikamHost application to stop debugging.
d. Open the Service Trace Viewer from Start | All Programs | Microsoft Windows
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
13/15
Understanding Windows Communication Foundation
Page 11 of 13
Tasks Detailed Steps
SDK | Tools.
e. Choose File | Open once the trace viewer starts and browse to the Logs directoryunder your lab directory.
f. Choose all four trace files that are found in the directory as you will want to reviewthe 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 activitieswhich 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 activityevents and messages logged for this communication. Browse through the events inthis 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 exchangeand the activity trace events.
Note: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.
j. Continue highlighting different activity traces in the upper right panel and noticethat 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.
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
14/15
Understanding Windows Communication Foundation
Page 12 of 13
Tasks Detailed Steps
k. In the left window pane, click the Messages tab to see the list of messagesexchanged 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.
l. In the bottom right pane, select the Message tab and notice that you are presentedwith 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.
m.Finally, in the toolbar for the upper right pane, click the Group By button andselect Activity Boundary. Notice that the data is now collected in the list grouped
by the particular activity it was logged with. You can also apply filters so you can
reduce the amount of data that you have to review to find the specific detail you
are looking for.
-
8/8/2019 ASP.net - Understanding Windows Communication Foundation
15/15
Understanding Windows Communication Foundation
Page 13 of 13
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.