New in WCF 4.0 Note & Filters for Message Logging Note

http://msdn.microsoft.com/en-us/library/ee354381.aspx

Using Filters for Message Logging

            -WindowsCommunication Foundation (WCF) message logging can be customized using anXPathfilter

            -Code:

            <messageLogginglogMessagesAtTransportLevel="true"logMessagesAtServiceLevel="true" >

               <filters>

                          <addxmlns:soap="http://www.w3.org/2003/05/soap-envelope"xmlns:a="http://www.w3.org/2005/08/addressing">/soap:Envelope/soap:Header/a:Action[starts-with(text(),'MyContractNamespace/MyContractName')]</add>

               </filters>

            </messageLogging>

What’s New in WCF 4?

Simplified Configuration

            -default endpoints, binding and behavior configurations

            -default endpoints

                        -Ifyou don’t provide any WCF configuration for a particular service, the WCF 4runtime automatically configures your service with some standard endpoints and default binding/behavior configurations.

                        -code:(assuming the blow code does not have any configuration file)

                                    ServiceHosthost = new ServiceHost(typeof(GreetingService),

                                                newUri("http://localhost:8080/greeting"))

                                    host.Open();

                        -note: default endpoint behavioronly kicks in when the service has not beenconfigured with any endpoints.

            -default binding

                        -define default binding configurations by simply omitting the binding configuration name when defining the new configuration. ThenWCF will use that default configuration for any endpointsusing that binding that don’t have an explicitbinding configuration set on them

                        -code:

                                    <bindings>

                                                <basicHttpBinding>

                                                            <bindingmessageEncoding="Mtom"/> <!-- notice there’s no name attribute-->

                                                </basicHttpBinding>

                                    </bindings>

            -default behavior

                        -definedefault behavior configurations by omitting the name in the configurationdefinition.

                        -code:

                                    <behaviors>

                                                <serviceBehaviors>

                                                            <behavior><!-- notice no name attribute -->

                                                                        <serviceMetadatahttpGetEnabled="true"/>

                                                            </behavior>

                                                </serviceBehaviors>

                                    </behaviors>

            -Standard Endpoints

                        -e.g.:

                                    -mexEndpoint

                                    -dynamicEndpoint

                                    -discoveryEndpoint

                                    -udpDiscoveryEndpoint

                                    -announcementEndpoint

                                    -announcementEndpoint

                                    -etc

                        -use“kind” attributeto specify the name of a standard endpoint

                        -code:

                                    <servicename="GreetingService">

                                                <endpointkind="basicHttpBinding" contract="IHello"/>

                                                <endpointkind="mexEndpoint" address="mex" />

                                    </service>

            -Simplifying IIS/ASP.NET Hosting

                        -code:(withouteven interface definition)

                                    <%@ServiceHost Language="C#" Debug="true"Service="HelloWorldServiceCodeBehind="~/App_Code/HelloWorldService.cs" %>

                                    [ServiceContract]

                                    publicclass HelloWorldService

                                    {

                                                [OperationContract]

                                                publicstring HelloWorld()

                                                {

                                                            return"hello, world";

                                                }

                                    }

            -File-lessActivation

                        -code:

                        <configuration>

                                    <system.serviceModel>

                                                <serviceHostingEnvironment>

                                                            <serviceActivations>

                                                                        <addrelativeAddress="Greeting.svc"service="GreetingService"/>

                                                            </serviceActivations>

                                                </serviceHostingEnvironment>

                                    </system.serviceModel>

                        </configuration>   

Discovery

            -support adhoc andmanaged service discovery behaviors

            -In ad hocmode,Ad hoc discovery is limited by the protocol used for multicastingmessages, in the case for UDP only the services listening in on the localsubnet will be able to receive the messages.

            -Code:

                        DiscoveryClientdiscovery Client =new DiscoveryClient(new UdpDiscoveryEndpoint());

                        FindCriteriafindCriteria = new FindCriteria(typeof(ICalculatorService));

                        FindResponsefindResponse = discoveryClient.Find(findCriteria);

                        EndpointAddressaddress = findResponse.Endpoints[0].Address;

            -Using Scopes when Discovering Endpoints

                        -to narrowthe discovery results by providing additional scoping information

                        -code(clientside)

                        DiscoveryClientdiscoveryClient = new DiscoveryClient("udpDiscoveryEndpoint");

                        Uriscope = new Uri("ldap:///ou=engineering,o=exampleorg,c=us");

                        FindCriteriafindCriteria = new FindCriteria(typeof(ICalculatorService));

                        findCriteria.Scopes.Add(scope);

                        FindResponsefindResponse = discoveryClient.Find(findCriteria);

Service Announcements

            -Code(client side)

                        AnnouncementServiceannouncementService = new AnnouncementService();

                        announcementService.OnlineAnnouncementReceived+= OnOnlineEvent;

       announcementService.OfflineAnnouncementReceived += OnOfflineEvent;

                        using(ServiceHost announcementServiceHost =

            new ServiceHost(announcementService))

        {

                         // Listen for the announcements sent over UDPmulticast

           announcementServiceHost.AddServiceEndpoint(

                newUdpAnnouncementEndpoint());

           announcementServiceHost.Open();

                        }

                       

Routing Service

            -content-basedrouting, protocol bridging, and error handling

            -bindingand Contract

                        -Contract type

                                    -ISimplexDatagramRouter

                                    -IRequestReplyRouter

                                    -ISimplexSessionRouter

                                    -IDuplexSessionRouter

Note: ISimplexDatagramRouter/ISimplexSessionRouter is for operation with IsOneWay=true, the different between ISimplexDatagramRouter and ISimplexSessionRouter is ISimplexSessionRouter required "SessionMode.Required"

      IRequestReplyRouter use in request-reply service contract

       IDuplexSessionRouter required  "SessionMode.Required" + IDuplexRouterCallback

http://www.novokshanov.com/2012/02/routing-service-extensions/

Note: I. Routing Service does not support one-way and request-reply operations on a single endpoint over HTTP transport.

Yes! If you happened to route to a service endpoint which has a mix of one-way and request-reply operations, and you have to use the most commonly available transport – HTTP, you are in troubles. As a matter of fact, Routing Service comes with a single contract (out of 4) that supports one-way and request-reply operationsIDuplexSessionRouter. However you can only use it over duplex transports like net.tcp or net.pipe.

                        -Code:

                        <endpointaddress="oneway-basic"

                  binding="basicHttpBinding"

                  name="onewayEndpointBasic"

                        contract="System.ServiceModel.Routing.ISimplexDatagramRouter"/>          

            -Configuringthe RoutingService with Message Filters

                        -Code:

                                    <!--enablethe RoutingBehavior on the RouterService-->

                                    <behaviorname="routingData">

                                                <serviceMetadatahttpGetEnabled="True"/>

                                                            <!--Define the Routing Behavior and specify the filter table name -->

                                                <routingfilterTableName="filterTable1" />

                                    </behavior>

                                   

                                    <!--Define the client endpoints that we want the Router to communicate with.

                                    Theseare the destinations that the Router will send messages to. -->

                                    <client>

                                      <endpointname="CalculatorService1"

                                      address="http://localhost:8000/servicemodelsamples/calcservice1"

                                       binding="wsHttpBinding"contract="*" />

                                      <endpointname="CalculatorService2"

                                      address="http://localhost:8001/servicemodelsamples/calcservice2"

                                       binding="wsHttpBinding"contract="*" />

                                    </client>

                                   

                                     <!--ROUTING SECTION -->

                                    <routing>

                                      <!-- Define the filters that we want therouter to use. -->

                                      <filters>

                                                <filtername="MatchAllFilter1" filterType="MatchAll" />

                                      </filters>

                                      <!-- Define the filter table that containsthe matchAll filter -->

                                      <filterTables>

                                                <filterTablename="filterTable1">

                                                            <!--Map the filter to a client endpoint that was previously defined.

                                                                         Messages matching this filter will be sent tothis destination. -->

                                                  <addfilterName="MatchAllFilter1"endpointName="CalculatorService1" />

                                                </filterTable>

                                                </filterTables>

                                    </routing>

            -MessageFilters and Content-based Routing

                        -built-in MessageFilter

                                    -ActionMessageFilter

                                    -EndpointAddressMessageFilter

                                    -EndpointNameMessageFilter

                                    -PrefixEndpointAddressMessageFilter

                                    -XPathMessageFilter

                        -Code

                                    -Sample1:        <filters>

                                                            <filtername="addFilter"filterType="Action"

                                                            filterData="http://Microsoft.Samples.ServiceModel/ICalculator/Add"/>

                                                </filters>

                                                <filterTables>

                                                            <filterTablename="filterTable1">

                                                                        <addfilterName="addFilter"endpointName="CalculatorService1"/>

                                    -Sample2:<filters>

                                                                        <filtername="addFilter" filterType="XPath"

                                                                                    filterData="/s:Envelope/s:Header/wsa:Action=

                                                                                    'http://Microsoft.Samples.ServiceModel/ICalculator/Add'"/>

                                                            ...

                                                            <namespaceTable>

                                                                        <addprefix="s"namespace="http://www.w3.org/2003/05/soap-envelope" />

                                                                        <addprefix="wsa" namespace="http://www.w3.org/2005/08/addressing"/>

                                                            </namespaceTable>

                                                            <filterTables>

                                                                        <filterTablename="filterTable1">

                                                                        <addfilterName="addFilter"endpointName="CalculatorService1"/>

                                                                       

Protocol Bridging

            -Code:<!-- Define the client endpoints that we want the Router to communicatewith.

         These are thedestinations that the Router will send messages to. -->

                        <client>

                                    <endpointname="CalculatorService1"

                                    address="net.tcp://localhost:8001/servicemodelsamples/calcservice1"

                                    binding="netTcpBinding"contract="*" />

                                   

Error Handing and Fault Tolerance

            -Code:

                                     <filterTables>

                                                <filterTablename="filterTable1">

                                                            <addfilterName="addFilter" endpointName="CalculatorService1"

                                                            alternateEndpoints="backupEndpoints"/>                 

                                    <backupLists>

                                                <backupListname="backupEndpoints">

                                                            <addendpointName="CalculatorService2"/>

                                                </backupList>

                                    </backupLists>

Multicast Routing Behavior

            -When theincoming message matches multiple filters found in the configured filter table,the RoutingService will automatically route the message to each of the targetendpoints associated with the “matched” filters.

            -Code:<filters>

        <filtername="wildcardFilter" filterType="MatchAll" />

      </filters>

     <filterTables>

        <filterTablename="filterTable1">

          <addfilterName="wildcardFilter"endpointName="CalculatorService1"/>

          <addfilterName="wildcardFilter"endpointName="CalculatorService2"/>

          <addfilterName="wildcardFilter" endpointName="CalculatorService3"/>

       </filterTable>

Improved REST Support

            -AutomaticHelp Page

                        -Whenusing the "WebServiceHost" class ,your RESTful services willautomatically enjoy the benefits of the automatic help page functionality.

            -HTTPCaching Support

                        -Oneof the primary potential benefits of REST is HTTP caching.

                        -[AspNetCacheProfile]implementation builds on the standard ASP.NET output caching mechanism.

                                    -Code:[AspNetCacheProfile("CacheFor60Seconds")]

                                                [WebGet(UriTemplate=XmlItemTemplate)]

                                                [OperationContract]

                                                publicCounter GetItemInXml()

                                                {

                                                            returnHandleGet();

                                                }

                                               

                                                <system.web>

                                                            <caching>

                                                              <outputCacheSettings>

                                                                        <outputCacheProfiles>

                                                                          <add name="CacheFor60Seconds"duration="60" varyByParam="format" />

                                                                        </outputCacheProfiles>

                                                              </outputCacheSettings>

                                                            </caching>

                                                           

            -Message Format Selection

                        -Code:[WebGet(UriTemplate= "?format=json",    ResponseFormat=WebMessageFormat.Json)]

                                                [OperationContract]

                                                publicCounter GetItemInJson()

                                                {

                                                            returnHandleGet();

                                                }

                                               

                        -Automatic format selection based on HTTP “Accept” headers, client need t odetermine whichformat to use via "HTTP Content-Type and Accept headers"

                                    -Code:<system.serviceModel>

                                                <standardEndpoints>

                                                  <webHttpEndpoint>

                                                            <!--the "" standard endpoint is used for auto creating a web endpoint.-->

                                                            <standardEndpointname="" helpEnabled="true"

                                                                        automaticFormatSelectionEnabled="true"/>

                                                  </webHttpEndpoint>

                                                </standardEndpoints>

                                                </system.serviceModel>            

                                                Accept:application/json  

                        -Explicitly specify the message format atruntime.

                                    -WebOperationContext

                                                -The following code shows how we can extend the GetItem operation by writing codethat first looks for a “format” query string parameter and explicitly sets the response format accordingly. If it doesn’t find a “format” parameter, it willsimply rely on the Accept header like before.

                                                -Code:

                                                  string formatQueryStringValue =

                                                            WebOperationContext.Current.IncomingRequest.UriTemplateMatch.QueryParameters[

                                                   "format"];

                                                            if(!string.IsNullOrEmpty(formatQueryStringValue))

                                                            {

                                                            if(formatQueryStringValue.Equals("xml",

                                                               System.StringComparison.OrdinalIgnoreCase))

                                                            {

                                                                        WebOperationContext.Current.OutgoingResponse.Format= WebMessageFormat.Xml;

                                                            }

                                                            elseif (formatQueryStringValue.Equals("json",

                                                               System.StringComparison.OrdinalIgnoreCase))

                                                            {

 

                                                            WebOperationContext.Current.OutgoingResponse.Format= WebMessageFormat.Json;

                                                            }

                                               

RESTful Error Handling

            -Since RESTful services don’t use SOAP, you no longer have the standard SOAP faultmechanism at your disposal,

            -WebFaultException<T>

            -Code:

                        throw new WebFaultException<string>(string.Format("Unsupported format'{0}'",format), HttpStatusCode.BadRequest);



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值