Posts Tagged 'code configuration'

Beyond Configuring Web Services in WCF 4.5

In my previous post, I looked at how easy it was to add a basic HTTP Web Service to a Web site in the beta of the .NET Framework 4.5 through code: Just add a shared/static method called Configure to your service and put some code in it to configure the ServiceConfiguration object passed to the method. In fact, because of the defaults that WCF 4.5 takes for a WCF service in a Web Site you don’t really need to add any code at all. In my example I did add some code to explicitly enable my service as a basic HTTP Web Service. I also chose to configure the service to return a contract and verbose error messages (both of which are turned off by default) to support testing.

But the power of WCF is in providing multiple ways of accessing the same code–as a basic Web Service or as a high performance TCP-based service. Adding TCP access requires a change in the project type:  Testing a TCP-based service from Visual Studio is awkward (at best). Instead, you’ll want to create a WCF Service library where you service is hosted by WAS rather than IIS. While that makes testing your TCP access is simplified, the defaults don’t give you a service automatically and you’ll need to use a few more lines of code.

After creating your WCF Service library project add a new WCF Service to it, giving the service some meaningful name (I used “CustomerService”). Then, to demonstrate the power of configuring by code, go to your app.config file and delete the entire system.model element. You’re now ready to control your service from code.

These two lines of code make your service available as a Web Service and as a TCP-based service (which will have orders-of-magnitude better performance than the HTTP-based Web service):

PublicSharedSub Configure(sc AsServiceConfiguration) 
sc.EnableProtocol(New BasicHttpBinding)  
sc.EnableProtocol(New NetTcpBinding) 

While that (in theory) makes your service accessible, it doesn’t make the information about the service (the metadata) available. As a result, you won’t be able to either use Visual Studio’s WCF Test Client or be able add a service reference for your service to another project by using the Add Service Reference dialog’s Discover button. To enable the metadata you use the same code that I had in my previous post but with one extra line of code that specifies the address where the metadata is available. In that line you create a System.URI object specifying the address (the address must reference your computer name but the port and service name are up to you) and use it to set the HttpGetUrl property:

Dim behavior As New Description.ServiceMetadataBehavior 
behavior.HttpGetEnabled = True 
behavior.HttpGetUrl = New System.Uri("http://localhost:1868/Customers") 
sc.Description.Behaviors.Add(behavior) 

You also need to add endpoints for HTTP and TCP access to your service. For that, you use the AddServiceEndpoint method on the ServiceConfiguration object passed to your Configure method. The first parameter to the AddServiceEndpoint is the type of the interface that your service implements (“ICustomers” in this example), the second parameter is the binding class for the endpoint, and the final parameter is the address itself (make sure that you use different addresses for each endpoint):

sc.AddServiceEndpoint(GetType(ICustomerService), 
         New BasicHttpBinding(), 
         "http://localhost:1868/Customers") 
sc.AddServiceEndpoint(GetType(ICustomer), 
         New NetTcpBinding(),  
         "net.tcp://localhost:1867/Customers")

There is an annoyance when you go to test your service: In a Service Library, in the absence of any entries in the config file, the test client can’t retrieve the information about the service. You’ll first get a dialog that the “WCF Service Host cannot find any service metadata”–just click the No button to continue. When the Test Client appears, it won’t display any services. You’ll need to go to the Test Client’s File menu and select Add Service to display the Add Service dialog box. In the box, enter the URL you used to set the HttpGetUrl property followed by “?wsdl” (e.g. “http://localhost:1868/Customers?wsdl”—and make sure you type the URL exactly the way it appears in your code). When you click the OK button, the Test Client will finally grab the service information and you’ll be able to test your service. The good news here is that, once you enter the URL with ?wsdl successfully, you won’t have to enter it again (you will still need to go through all the dialogs, though).

And there you go: With less than a dozen lines of code you’ve configured a service as both a basic HTTP service and TCP-based service. Adding additional access methods (e.g. named pipes, advanced web services, https) should just consist of enabling the protocol with the EnableProtocol method and adding a compatible endpoint.

As before, your best Learning Tree source for WCF information is Programming WCF Web Services for .NET: A Comprehensive Hands-On Introduction.

Peter Vogel

One Line of Code to Configure WCF 4.5

The WCF 4.5 beta simplifies configuring WCF, provides better support for code-based configuration, and makes it easier to do code-based configuration in Web sites. Don’t get me wrong: I like the WCF configuration files but, I gather, I may be in a minority. Many developers prefer to configure their WCF services from code where possible. Unfortunately, one of the places where that isn’t possible is the most common place to host WCF services: in a Web application (well, I’m told it was possible but only in the sense that it’s possible to remove your own appendix).

WCF 4.5 (at least, in the beta) provides a simple solution: Add a static/shared method called Configure to your service class and fill it with the code required to configure your service. WCF will call that Configure method at the appropriate moment and pass the method an instance of the ServiceHost class. In your Configure method, you can work with that ServiceHost to configure your service.

What’s especially impressive is how simple it is. The default settings alone mean that if you add an svc file to your Web site then you have a Web Service. You can make that explicit, however, with a single line of code. This example makes the service containing this method available as a Web Service with no WCF-related tags required in the config file at all:

Public Shared Sub Configure(sc AsServiceConfiguration) 
 sc.EnableProtocol(NewBasicHttpBinding()) 
End Sub 

You can configure these services by instantiating behavior classes, configuring them, and adding them to the ServiceConfiguration’s Description property’s Behaviors collection. That’s a good thing because, while my previous example was all the code you need (in fact one more line than you needed), it’s probably not all the code you want, for two reasons.

Configuring the Service

First, with just that code you won’t be able to retrieve the WSDL contract for this service (what WCF refers to as service’s “metadata”) so you won’t be able to use Visual Studio’s WCF test client (you also won’t be able to use the Discover button in Visual Studio’s Add Service Reference dialog). For testing purposes, and until you can save to a separate file the WSDL contract that you can give to the developers building the clients/consumers for this service, you’ll want to configure your service to return a WSDL contract. To tell your service to make its metadata available you add code like the following to your Configure method. This code creates a ServiceMetadataBehavior object, sets its HttpGetEnabled property to True (that actually turns on the feature), and add the configured behavior to the Behaviors collection:

Dim behavior As New Description.ServiceMetadataBehavior 
behavior.HttpGetEnabled = True 
sc.Description.Behaviors.Add(behavior) 

Second, by default, WCF services don’t return a lot of information in their exception messages. That’s a good thing: While that information is very useful in debugging, it probably isn’t something you want to share with the general public. However, in testing, you probably do want that those chattier error messages and you can enable the with this code in the Configure method:

Dim debugBehavior As New Description.ServiceDebugBehavior 
debugBehavior.IncludeExceptionDetailInFaults = True 
sc.Description.Behaviors.Add(debugBehavior) 

But both of these changes highlight an issue with code-based configuration. In production, you probably don’t want your service freely giving up its contract to whoever asks for it. Instead you probably want to control access to your service’s contracts so that you have some idea who’s using your service and can contact those users when you’re making changes to your service. And you certainly don’t want to send out those verbose error messages from your production system. So, before moving your service to production you’re going to want to change the values used in this code.

The problem is that, with the code I’ve used here, there’s no simple way to inspect the assembly you’re deploying to production to determine if the settings are correct: the code is compiled and is unreadable. One of the nice features of the config files is that you could inspect them (and even change them) with Notepad. The right answer is probably to move settings that will change from one installation to another (e.g. test and production) into your AppSettings where you’ll still have visibility to them.

Many of Learning Tree’s courses touch on WCF but your best source for information is Programming WCF Web Services for .NET. It’s four intensive days of everything you’d want to know about WCF.

Peter Vogel


Learning Tree International

.NET & Visual Studio Courses

Learning Tree offers over 210 IT training and Management courses, including a full curriculum of .NET training courses.

Free White Papers

Questions on current IT or Management topics? Access our Complete Online Resource Library of over 65 White Papers, Articles and Podcasts

Enter your email address to subscribe to this blog and receive notifications of new posts by e-mail.

Join 29 other subscribers
Follow Learning Tree on Twitter

Archives

Do you need a customized .NET training solution delivered at your facility?

Last year Learning Tree held nearly 2,500 on-site training events worldwide. To find out more about hosting one at your location, click here for a free consultation.
Live, online training