Easy guide to understand WCF in Visual Studio 2008 SP1 and Visual Studio 2010 Express

Build SOA applications on the Microsoft platform with this hands-on WCF 4.0 book and eBook guide updated for VS2010

(For more resources on Microsoft, see here.)

Creating your first WCF application in Visual Studio 2008

You start creating a WCF project by creating a new project from File | New | Project.... This opens the New Project window. You can see that there are four different templates available. We will be using the WCF Service Library template.

Easy guide to understand WCF in Visual Studio

Change the default name and provide a name for the project (herein JayWcf01) and click OK. The project JayWcf01 gets created with the folder structure shown in the next image:

Easy guide to understand WCF in Visual Studio

If you were to expand References node in the above you would notice that System.ServiceModel is already referenced. If it is not, for some reason, you can bring it in by using the Add Reference... window which is displayed when you right click the project in the Solution Explorer.

IService1.vb is a service interface file as shown in the next listing. This defines the service contract and the operations expected of the service.

If you change the interface name "IService1" here, you must also update the reference to "IService1" in App.config.

<ServiceContract()> _
Public Interface IService1

<OperationContract()> _
Function GetData(ByVal value As Integer) As String

<OperationContract()> _
Function GetDataUsingDataContract(ByVal composite As CompositeType) As CompositeType

' TODO: Add your service operations here

End Interface

' Use a data contract as illustrated in the sample below to add composite types to service operations
<DataContract()> _
Public Class CompositeType

Private boolValueField As Boolean
Private stringValueField As String

<DataMember()> _
Public Property BoolValue() As Boolean
Get
Return Me.boolValueField
End Get
Set(ByVal value As Boolean)
Me.boolValueField = value
End Set
End Property

<DataMember()> _
Public Property StringValue() As String
Get
Return Me.stringValueField
End Get
Set(ByVal value As String)
Me.stringValueField = value
End Set
End Property

End Class

The Service Contract is a contract that will be agreed to between the Client and the Server. Both the Client and the Server should be working with the same service contract. The one shown above is in the server. Inside the service, data is handled as simple (e.g. GetData) or complex types (e.g. GetDataUsingDataContract). However outside the Service these are handled as XML Schema Definitions. WCF Data contracts provides a mapping between the data defined in the code and the XML Schema defined by W3C organization, the standards organization.

The service performed when the terms of the contract are properly adhered to is in the listing of Service1.vb file shown here.

' NOTE: If you change the class name "Service1" here, you must also update the
reference to "Service1" in App.config.
Public Class Service1
Implements IService1

Public Function GetData(ByVal value As Integer) As _
String Implements IService1.GetData
Return String.Format("You entered: {0}", value)
End Function

Public Function GetDataUsingDataContract(ByVal composite As CompositeType) _
As CompositeType Implements IService1.GetDataUsingDataContract
If composite.BoolValue Then
composite.StringValue = (composite.StringValue & "Suffix")
End If
Return composite
End Function

End Class

Service1 is defining two methods of the service by way of Functions. The GetData accepts a number and returns a string. For example, if the Client enters a value 50, the Server response will be "You entered: 50". The function GetDataUsingDataContract returns a Boolean and a String with 'Suffix' appended for an input which consists of a Boolean and a string.

The JayWcf01 is a completed program with a default example contract IService1 and a defined service, Service1. This program is complete in itself. It is a good practice to provide your own names for the objects. Notwithstanding the default names are accepted in this demo.

In what follows we test this program as is and then slightly modify the contract and test it again. The testing in the next section will invoke an in-built client and then later on we will publish it to the localhost which is an IIS 7 web server.

How to test this program

The program has a valid pair of contract and service and we should be able to test this service. The Windows Communication Foundation allows Visual Studio 2008 (also Visual Studio 2010 Express) to launch a host to test the service with a client.

Build the program and after it succeeds hit F5. The WcfSvcHost is spawned which stays in the taskbar as shown.

You can click WcfSvcHost to display the WCF Service Host window popping-up as shown. The host gets started as shown here. The service is hosted on the developmental server.

Easy guide to understand WCF in Visual Studio

This is immediately followed by the WCF Test Client user interface popping-up as shown. In this harness you can test the service.

Easy guide to understand WCF in Visual Studio

(For more resources on Microsoft, see here.)

Testing the service with WCF Test Client

The service endpoint points to the Visual Studio's internal development web server as shown above. The service interface in this UI has two methods GetData() and GetDataUsingDataContract(). Additionally it also has a Config file.

Double click GetData() in the left. The GetData tabbed page is displayed.

Easy guide to understand WCF in Visual Studio

In the GetData tabbed page you see a top "Request" pane and a bottom "Response" pane displayed. You enter a value in the top pane, say, removing the 0 and typing in the number 100. After entering the value you hit the Invoke button, the service will return a response in the bottom pane as shown. This is exactly what you can expect from the GetData() in Service1.vb.

Easy guide to understand WCF in Visual Studio

Similarly you can test the other function. Double click GetDataUsingDataContract. A new tabbed page is opened as shown. It is a composite type whose value is JayWcf01.Composite Type. Here you have two inputs and two outputs.

Easy guide to understand WCF in Visual Studio

You provide two values, a Boolean and a string and the service echoes the values. Enter false or true in the Bool type box and a string, say, Hello in the second and hit Invoke. You get a response as shown here.

Easy guide to understand WCF in Visual Studio

The Formatted data is being shown but you can also see what it looks like when it is outside the service. Hit XML tab for example in the above. The XML schema definition gets displayed as shown in the next listing for the chosen request. Notice the highlighted Request & Response in the XML.

<s:Envelope xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:s="http://www.w3.org/2003/05/soap-envelope">
<s:Header>
<a:Action s:mustUnderstand="1">http://tempuri.org/IService1/GetDataUsingDataContract</a:Action>
<a:MessageID>urn:uuid:649b2ad6-96a6-474a-926b-655e96761d65</a:MessageID>
<a:ReplyTo>
<a:Address>http://www.w3.org/2005/08/addressing/anonymous</a:Address>
</a:ReplyTo>
</s:Header>
<s:Body>
<GetDataUsingDataContract xmlns="http://tempuri.org/">
<composite xmlns:d4p1="http://schemas.datacontract.org/2004/07/JayWcf01" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<d4p1:BoolValue>true</d4p1:BoolValue>
<d4p1:StringValue>Hello</d4p1:StringValue>
</composite>
</GetDataUsingDataContract>
</s:Body>
</s:Envelope>
The response that is returned by the service is this:
<s:Envelope xmlns:s="http://www.w3.org/2003/05/soap-envelope" xmlns:a="http://www.w3.org/2005/08/addressing" xmlns:u="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">
<s:Header>
<a:Action s:mustUnderstand="1" u:Id="_2">http://tempuri.org/IService1/GetDataUsingDataContractResponse</a:Action>
<a:RelatesTo u:Id="_3">urn:uuid:e51944dd-3182-4125-9940-89184fb9c9c2</a:RelatesTo>
<o:Security s:mustUnderstand="1" xmlns:o="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<u:Timestamp u:Id="uuid-7c2f4fd8-7dfd-4d89-933a-8d14d3ac2085-14">
<u:Created>2010-06-26T19:45:27.500Z</u:Created>
<u:Expires>2010-06-26T19:50:27.500Z</u:Expires>
</u:Timestamp>
<c:DerivedKeyToken u:Id="uuid-7c2f4fd8-7dfd-4d89-933a-8d14d3ac2085-7" xmlns:c="http://schemas.xmlsoap.org/ws/2005/02/sc">
<o:SecurityTokenReference>
<o:Reference URI="urn:uuid:4ba9cd03-0a55-492e-80b1-961d528b1d02" ValueType="http://schemas.xmlsoap.org/ws/2005/02/sc/sct" />
</o:SecurityTokenReference>
<c:Offset>0</c:Offset>
<c:Length>24</c:Length>
<c:Nonce>B43r5GunQqD+6FJovNl4vg==</c:Nonce>
</c:DerivedKeyToken>
<c:DerivedKeyToken u:Id="uuid-7c2f4fd8-7dfd-4d89-933a-8d14d3ac2085-8" xmlns:c="http://schemas.xmlsoap.org/ws/2005/02/sc">
<o:SecurityTokenReference>
<o:Reference URI="urn:uuid:4ba9cd03-0a55-492e-80b1-961d528b1d02" ValueType="http://schemas.xmlsoap.org/ws/2005/02/sc/sct" />
</o:SecurityTokenReference>
<c:Nonce>ogcKzda7gr76EnQp89SG3Q==</c:Nonce>
</c:DerivedKeyToken>
<e:ReferenceList xmlns:e="http://www.w3.org/2001/04/xmlenc#">
<e:DataReference URI="#_1" />
<e:DataReference URI="#_4" />
</e:ReferenceList>
<e:EncryptedData Id="_4" Type="http://www.w3.org/2001/04/xmlenc#Element" xmlns:e="http://www.w3.org/2001/04/xmlenc#">
<e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc" />
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<o:SecurityTokenReference>
<o:Reference ValueType="http://schemas.xmlsoap.org/ws/2005/02/sc/dk" URI="#uuid-7c2f4fd8-7dfd-4d89-933a-8d14d3ac2085-8" />
</o:SecurityTokenReference>
</KeyInfo>
<e:CipherData>
<e:CipherValue>Zw+iMyHKM8iuYG6GN1BW+4vk1ykTx1lPyzsspgqkly/v/ajQlPLcBef1HbAuqympTlgE8shlb83j2Bt+ycWjDW/TOf+2h5QoKkYTvqc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5vSK5jkIdRJYeHwPzLULxSWIRi/XovkXDBTrlf9M/IRnznt0DAm4YcWaGf2mz48XOOk9z4IHWv8jHIdx9Re8LrNXwSEG7GcJHMvj8la2IJEUPDfO+gMgpCoU7axiO5CN8voP9hgd+KSJyR9WtwfOSvpKBMVm5p0SDbOrto7fd11Pl9nG1mQGFFoR8lw7T+3EtkIO64lS0XYfYx1drlPHgQG3qVZWQV1NgkHKRewkmyyzy5SHvJOx1IcGkWdmZiZQyeO640ZqPzkWKuYzT/JDM0Mbk2p5iXW3JtffSciJpejZ4RW/+yDilr87M1tVeEK4pGLBYRY4Nl83w44/OYKhhudw8iWxEDr2Ev80+uHr3+bNAeYe/3XJdWmDk2I3Q0LO0xLL8AAfl8rAnwrGEpTHHS5XgqxDxFJgqwwmxTHeAUc6iMSPW0xuZ2o2E1tv4kUwUPb+9EpRPWLOBFiRPZ4D/x+2+T0+RDpTKmreKUSpSWXHMFXFjcqgvxqG0THlRUV0CRWe9QrvqqjClL/8udKTtq4oHpono6vDshY+h/xAy8LXsHd4wTjLw1VceoPbWRyDkFYR236WwXoRdLuxvNocSJlO6KpuzmuUy4JVkao2LLNyPS3Tx6+oCa8EeuBYVA5UzJ7CtYV7aobcwjMLuiURxIavcRRO5/UYJghBGaZGrBj6KiNYW8Yl0nFhZzaBX1CMPNZQ5aylgcWjkSrEhNdpsfAeBHZlvMHp/7f38Ob+BptFifvRft9TXA+QPGLVdTBDg6P8XCDk3SavqIg2fGBuHrW59gDNI6FqXzJVziV42poPZy6nTTPFFdXiQWlFHWWOMzlM78DuPF/KPaYsZSjk/SI8686O87rPYnYeSMEuUZBjDNfRyJQt3Ck4ft+V60RX/O2A9GZkn4wDXf3l6Mx8r2g39Ei03WZB3IbFKHaZa5jERqkMYRhYpMfJQA+8RgMHnh+9PjmE9aV8wQG159a+i93e7a</e:CipherValue>
</e:CipherData>
</e:EncryptedData>
</o:Security>
</s:Header>
<s:Body u:Id="_0">
<GetDataUsingDataContractResponse xmlns="http://tempuri.org/">
<GetDataUsingDataContractResult xmlns:a="http://schemas.datacontract.org/2004/07/JayWcf01" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
<a:BoolValue>true</a:BoolValue>
<a:StringValue>HelloSuffix</a:StringValue>
</GetDataUsingDataContractResult>
</GetDataUsingDataContractResponse>
</s:Body>
</s:Envelope>

This WCF Test Client interface can be used to add (right click the My Service Projects...) another service for testing after locating its URL or, remove an existing service from the interface.

Although this is extremely easy to use interface (similar to the one available in earlier versions for web services) this is not recommended for production use. A better option is to host the service on IIS as shown later.

Modifying the Contract

Let's slightly modify the contract. This will require the service to be modifed as well. The service should reflect the contract terms.

Modify the contract as shown in the next snippet for the interface, IService1.

<OperationContract()> _
Function GetData(ByVal value1 As Integer, ByVal value2 As Integer) As String

This defines what is expected by one of the methods of the service GetData. The service should take in two integers and generate a string.

The GetData() function of Service1 must be modified as shown in the next listing. We are not making any changes to the other funcction in Service1.

Public Function GetData(ByVal value1 As Integer, ByVal value2 As Integer) As _
String Implements IService1.GetData
Return String.Format("Your total is : {0}", value1 + value2)
End Function

After making these changes Build and hit F5. The Service host is displayed followed by the WCF Test Client as shown previously. Testing with two input values in GetData should display the result as shown in the next figure.

Publishing to IIS 7

It is presently hosted in the development server and it can be published to the Internet Information Services server, in the present case, IIS7 on Windows 7 Ultimate.

In order to publish to IIS 7 you must first create an application on IIS 7. This post shows how to create an application on IIS 7. Highlight the project and right click. Choose Publish. The Publish WCF Service window where you can choose a location to publish the service is displayed.

Easy guide to understand WCF in Visual Studio

Click the ellipsis (...) button and it opens up the publish options you have with the default being the local IIS. Here we will publish to the WcfTests an application we created earlier (presently empty) on IIS 7 in the earlier step.

Easy guide to understand WCF in Visual Studio

Highlight WcfTests application and click Open. The URL gets into the Target Location of the earlier image (the image file previous to the one above). Click Publish. You should see the following message when the publishing is successful.

------ Build started: Project: JayWcf01, Configuration: Release Any CPU ------
JayWcf01 -> C:\Users\jay\Documents\Visual Studio 2008\Projects\JayWcf01\JayWcf01\bin\Release\JayWcf01.dll
------ Publish started: Project: JayWcf01, Configuration: Release Any CPU ------
Connecting to http://localhost/WcfTests...
Publishing folder /...
Publishing folder bin...
========== Build: 1 succeeded or up-to-date, 0 failed, 0 skipped ==========
========== Publish: 1 succeeded, 0 failed, 0 skipped ==========

Now verify that this is present in your IIS application and review the files created by accessing the default web site as shown.

Easy guide to understand WCF in Visual Studio

Summary

This article described the default template available in VS 2008 (also works the same in VS2010 Express) to create a WCF application and to understand the out of the box WCF development tools namely the WCF Service Host and WCF Test Client. Modifying the service and service contract was also described. Publishing the service to the Internet Information Services was described where in the local host was an IIS7 web server.


Further resources on this subject:


Books to Consider

comments powered by Disqus
X

An Introduction to 3D Printing

Explore the future of manufacturing and design  - read our guide to 3d printing for free