Tải bản đầy đủ (.pdf) (7 trang)

Lập trình .net 4.0 và visual studio 2010 part 24 docx

Bạn đang xem bản rút gọn của tài liệu. Xem và tải ngay bản đầy đủ của tài liệu tại đây (269.88 KB, 7 trang )

CHAPTER 7  WINDOWS COMMUNICATION FOUNDATION

166
Bridging Protocols
The router service can also be used to bridge between the bindings that are used. For example, on an
internal trusted network, you could use an unsecured connection for better performance that is then
bridged to a secure connection for external communication.
Redundancy
You can also use the new routing functionality to define a list of backup endpoints that will be used if
WCF encounters a CommunicationException or TimeoutException on the main endpoints. To define a list
of backup endpoints create a new backupLists section inside the routing block like so:

<backupLists>
<backupList name="backupList">
<add endpointName="fallover1" />
<add endpointName="fallover2" />
</backupList>
</backupLists>
WS-Discovery
WCF4 contains support for the WS-Discovery protocol that allows the discovery of services on a network.
WS-Discovery was originally developed as joint venture between BEA Systems, Canon, Intel, Microsoft,
and WebMethods, and is famously used in Windows Vista to provide the “people near me” functionality.
For more information on WS-Discovery please refer to
discovery/ws-discovery.pdf.
WS-Discovery is a great way of easing deployment of your applications, and perhaps even making
them more robust by discovering alternative endpoints to use in the event of failure.
WCF4 implements WS-Discovery via a new behavior called ServiceDiscoveryBehaviour that tells
WCF to make a service discoverable. WCF then creates an UdpAnnouncementEndpoint to listen for
discovery requests. WS-Discovery can operate in two different modes: managed and adhoc.
Managed Mode
In managed mode, a list of services is held in a central location (called the discovery proxy). When


services start up, they inform the discovery proxy of their location. Managed mode is more complex to
implement than adhoc, but it creates much less network traffic and is more suitable for use in larger
networks. It does, however, have the drawback that if your discovery proxy goes down there will be no
more service discovery (single point of failure).
Adhoc Mode
Services operating in adhoc mode broadcast their location over the network, which generates much
more network traffic but has no central point of failure. Adhoc mode is also restricted to the current
subnet. Let’s look into how to use WS-Discovery Adhoc mode now (note the WCF samples contain an
example of managed mode).
We will create a simple service that capitalizes a string, make it discoverable, and then find and
invoke it.
CHAPTER 7  WINDOWS COMMUNICATION FOUNDATION

167
1. Open Visual Studio and create a new C# console project called Chapter7.WCFDiscovery. This will
be the new service that we will discover.
2. Now add references to System.ServiceModel and System.ServiceModel.Discovery assemblies
and replace Program.cs with the following code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Discovery;
using System.ServiceModel.Description;

namespace Chapter7.WCFDiscovery
{
public class Program
{

static void Main(string[] args)
{
ServiceHost host =
new ServiceHost(typeof(ToUpperService),
new Uri("http://localhost:8081/DiscoverMe"));
host.AddServiceEndpoint(typeof(IToUpper), new BasicHttpBinding(),
"ToUpper");
host.AddServiceEndpoint(typeof(IToUpper), new WS2007HttpBinding(),
"ToUpper2");
host.Description.Behaviors.Add(
new ServiceMetadataBehavior() { HttpGetEnabled = true }
);

ServiceDiscoveryBehavior discoveryBehavior = new
ServiceDiscoveryBehavior();
host.Description.Behaviors.Add(discoveryBehavior);

host.AddServiceEndpoint(new UdpDiscoveryEndpoint());
discoveryBehavior.AnnouncementEndpoints.Add(new
UdpAnnouncementEndpoint());

host.Open();

Console.WriteLine("Service running");
Console.ReadKey();

}

public class ToUpperService : IToUpper
{

public string ToUpper(string Input)
{
return Input.ToUpper();
}
}
}
CHAPTER 7  WINDOWS COMMUNICATION FOUNDATION

168

[ServiceContract]
public interface IToUpper
{
[OperationContract]
string ToUpper(string Input);
}
}
3. Now add another console project to the solution called Chapter7.WCFFindServices. Add
references to the System.ServiceModel and System.ServiceModel.Discovery assemblies.
4. We now need to generate a proxy to enable us to call the service in the Chapter7.WCFDiscovery
project. To create the proxy we need to have Chapter7.WCFDiscovery running so right click on
the Chapter7.WCFDiscovery project, select DebugStart new instance (click allow to the
security warning if you get one).
5. You can check the service is running correctly by opening a web browser and going to http://
localhost:8081/DiscoverMe, where you should be presented with the service metadata page.
6. Open a Visual Studio command prompt and enter the following command to generate a proxy
class for this service:
svcutil.exe http://localhost:8081/DiscoverMe?wsdl
7. Copy the generated proxy class (which will be at the Visual Studio command prompt location)
to the Chapter7.WCFFindServices project.

8. In Chapter7.WCFFindServices amend Program.cs to the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Discovery;
using System.ServiceModel;

namespace Chapter7.WCFFindServices
{
class Program
{
static void Main(string[] args)
{
DiscoveryClient discoveryClient =
new DiscoveryClient(new UdpDiscoveryEndpoint());
Console.WriteLine("Finding end points please wait this may take some
time ");

FindResponse discoveryResponse =
discoveryClient.Find(new FindCriteria(typeof(ToUpperClient)));

for (int Index = 0; Index < discoveryResponse.Endpoints.Count; Index++)
{
Console.WriteLine("Found end point at: " +
discoveryResponse.Endpoints[Index].Address.ToString());
}
CHAPTER 7  WINDOWS COMMUNICATION FOUNDATION

169

Console.WriteLine("Using end point: " +
discoveryResponse.Endpoints[0].Address.ToString());

EndpointAddress address = discoveryResponse.Endpoints[0].Address;

ToUpperClient service = new ToUpperClient(new BasicHttpBinding(),
address);
Console.WriteLine(service.ToUpper("make me uppercase!"));
Console.ReadKey();
}
}
}
9. Okay we’re ready to go so start up Chapter7.WCFDiscovery project first (otherwise we are not
going to find anything) by right clicking on it select DebugStart new instance. Once
Chapter7.WCFDiscovery is running then start up the Chapter7.WCFFindServices project in the
same manner then after a few minutes you should find that the service is discovered and
invoked as shown in Figure 7-2.

Figure 7-2. WCF discovery example
Service Announcement Events
WS-Discovery is also used when services go on and offline. WCF4 allows you to hook into this capability
by subscribing to the AnnouncementService’s OnlineAnnouncementReceived and
OfflineAnnouncementReceived events.
CHAPTER 7  WINDOWS COMMUNICATION FOUNDATION

170
WCF Starter Kit Integration
Two great features previously seen in the WCF REST starter kit ( />kits/wcf-rest/) have been brought into WCF4:
• Help pages
• HTTP caching

Help Pages
Help pages are automatically generated HTML pages that describe how to call your service and the type
of response it will return, and can be very helpful for working out how to call the darn thing. Help pages
are created automatically when you use the WebServiceHost class (although at the time of writing this
doesn’t seem to be the case) and using the HelpEnabled property on WebHttpBehaviour.
Let’s take a look at this now with a contrived example:
1. Create a new WCF service library project called Chapter7.WCFWebService.
2. Add a console application to the solution called Chapter7.WCFWebServiceHost.
3. By default in .NET 4.0, some project types reference the .NET client profile framework, which is
a smaller subsection of the main framework aimed at reducing your applications size. To
demonstrate help pages, we need to use functionality not contained in the client profile
framework, so right-click on the Chapter7.WCFWebServiceHost project, select Properties on
the context menu, and change the target framework to .NET Framework 4.0.
4. Now add a project reference to the Chapter7.WCFWebService project and a reference to the
System.ServiceModel and System.ServiceModel.Web assemblies.
5. Enter the following code in Program.cs (main method):
using System.ServiceModel.Web;



WebServiceHost MyServiceHost =
new WebServiceHost(typeof(Chapter7.WCFWebService.Service1),
new Uri("http://localhost:8888/Test"));
MyServiceHost.Open();
Console.WriteLine("Service running ");
Console.ReadLine();
MyServiceHost.Close();
6. Now open a browser and go to http://localhost:8888/Test/help and you should see
something similar to Figure 7-3 and 7-4.
CHAPTER 7  WINDOWS COMMUNICATION FOUNDATION


171

Figure 7-3. Service help page

Figure 7-4. Service help page
CHAPTER 7  WINDOWS COMMUNICATION FOUNDATION

172
HTTP Caching
One of the biggest advantages to using RESTful services is that you can take advantage of HTTP caching
features to improve performance and reduce load on the service. Caching wasn’t too easy to implement
prior to WCF4 however it is very easy in WCF4 with the simple addition of the AspNetCache profile
attribute to your methods:

[AspNetCacheProfile("MyCachingProfile")]

You then need to create a caching profile using the following configuration:

<outputCacheSettings>
<outputCacheProfiles>
<add name=" MyCachingProfile " duration="30" varyByParam="format"
varyByHeader="Accept" />
</outputCacheProfiles>
</outputCacheSettings>
Misc Changes
What follows are a number of other enhancements that have been introduced in WCF4.
Improved Integration with WF
Microsoft has put a big focus on improving the integration between WF and WCF, and this release sees
the introduction of a new project type called WF Service (a combined WCF and WF service represented

entirely in XAML). Please refer to Chapter 6 for full details.
Default Performance-Related Settings Changed
A number of default settings for WCF services have been tweaked for better performance:
• MaxConcurrentSessions was 10, and is now 100 x processor count.
• MaxConcurrentCalls was 16, and is now 16 x processor count.
• MaxConcurrentInstances was 26, and is now the total of MaxConcurrentSettions and
MaxConcurrentCalls.
Low Memory
A new minFreeMemoryToActivateService option has been added that defines the percentage of memory
that needs to be free in order for a service to be activated (defaulted to 5%). If less than the specified
memory is available then WCF will throw an exception.

×