WCF Application Report

WCF Application Report
 
Last Week ,I read the book about WCF(Windows Communicate Foundation), and understand how to develop a application 
using it.
 
First ,you must download .net3.
0 framework from microsoft download center and vs2005 extention for wcf and wfx. Centainly, you must install it after download.
 
Sencond ,you have two option to selection host, one 
is base on IIS,the other is you program to make a host. If you want to base on IIS ,In vs2005,you can open file->new-> website, and select WCFService, then you will get WCF Service program template. Base on the template, you can build WCF Service quickly if you now some WCF basic knowledge ( that I will tell next).However, I prefer WCF Service’s host not base on the IIS,because you can only use http . with IIS5 , you are further restricted to having all services use the same port number. So we can program WCF service base on our own host. In vs2005,you can open file->project WCF Service Library. You wil get a WCF Service program template.There are some comment show you how to build host program in the template. You can use it to build a host.
Third ,we must 
get some base knowledge about wcf conception. The WCF is an SDK for developing and deploying services on Windows. WCF provides a runtime environment for your services, enabling you to expose CLR types as services, and to consume other services as CLR types. Most all of the WCF functionality is included in a single assembly called System.ServiceModel.dll in the System.ServiceModel namespace. In WCF, all services expose contracts. The contract is a platform-neutral and standard way of describing what the service does. WCF defines four types of Contracts.
1.Service contracts:Describe which operations the client can perform on the service. 
2.Data contracts:Define which data types are passed to and from the service. WCF defines implicit contracts for built-in types such as int and string, but you can easily define explicit opt-in data contracts for custom types. 
3.Fault contracts:Define which errors are raised by the service, and how the service handles and propagates errors to its clients.
4.Message contracts:Allow the service to interact directly with messages. Message contracts can be typed or untyped, and are useful in interoperability cases and when there is an existing message format you have to comply with. As a WCF developer, you should use message contracts only rarely.
 The other knowledge 
is we can use config to deploy other param. Such as address,binding,endpoint,secury etc.
Last 
for client program. In vs2005,we can begin a project and import service reference,the vs2005 will automatic make the file you need,using the namespace in the <Service References> directory provider, you can easy to get the service the WCF Service’s server provider.
Implement:
The Example 
is implement WCF to pack Webconnector.
1、create WCFService 
1)           open file->project WCF Service Library,name=WCFService. Then there will generate a program.cs file ,save it as WebConnector.cs.
2)           Add reference Timegrip.Paydutch.Component( for entity reference), Timegrip.Paydutch.Components.Connectors.WebSite(for webconnector reference)
3)           Pack the webform and relate entity for webconnector as a datacontract,such as:
[DataContract]
    
public class WebForm //pack webform entity
    {
        [DataMember]
        
public WebFormParameter[] Parameters;
        [DataMember]
        
public WebFormScrapeRequest[] ScrapeRequest;
        [DataMember]
        
public string PageUrl;
        [DataMember]
        
public string ActionUrl;
        [DataMember]
        
public string Cookie;
        [DataMember]
        
public string Referer;        
    }

    [DataContract]
    
public class WebFormResponse //pack webformresponse entity
    {
        
        [DataMember]
        
public WebFormResponseScrapeResponse[] ScrapeResponse;
 
        [DataMember]
        
public WebFormParameter[] OutParameters;
 
        [DataMember]
        
public string Cookie;
 
        [DataMember]
        
public string Html;
    }

 
    
public enum WebFormParameterDirection //pack ebFormParameterDirection enum 
    {
        [EnumMember]
        In,
        [EnumMember]
        Out
    }

    [DataContract]
    
public class WebFormParameter 
    
{
        
        [DataMember]
        
public string Name;
 
        [DataMember]
        
public string Value;
 
        [DataMember]
        
public int MaxLength;
 
        [DataMember]
        
public bool MaxLengthSpecified;
 
        [DataMember]
       
public WebFormParameterDirection Direction;
       
    }

    [DataContract]
    
public class WebFormScrapeRequest
    
{
        [DataMember]
        
public string Name;
        [DataMember]
        
public string Regex;
        [DataMember]
        
public int GroupIndex;        
    }

    [DataContract]
    
public class WebFormResponseScrapeResponse
    
{
        [DataMember]
        
public string Name;
        [DataMember]
        
public string value;
    }

4)           Pack the post and load service
public WebFormResponse Post(WebForm webForm)
        
{
            
//return "Hello: " + myValue;
            Timegrip.Paydutch.Entities.WebForm oldWebForm=new Timegrip.Paydutch.Entities.WebForm();
            oldWebForm.ActionUrl 
= webForm.ActionUrl;
            oldWebForm.Cookie 
= webForm.Cookie;
            oldWebForm.PageUrl 
= webForm.PageUrl;    
            AddWebParameter(oldWebForm, webForm); 
//self define function           
            oldWebForm.Referer = webForm.Referer;
            
            AddScrapeRequest(oldWebForm, webForm); 
// selfdefine function
 
            Timegrip.Paydutch.Components.Connectors.WebConnector webConnector 
= new Timegrip.Paydutch.Components.Connectors.WebConnector();
            Timegrip.Paydutch.Entities.WebFormResponse oldWebFormResponse
=webConnector.Post(oldWebForm);
            
            WebFormResponse webFormResponse
=new WebFormResponse();
            webFormResponse.Cookie 
= oldWebFormResponse.Cookie;
            webFormResponse.Html 
= oldWebFormResponse.Html;
            
return webFormResponse;
        }

        
public WebFormResponse Load(WebForm webForm, bool validateForm)
        
{
            Timegrip.Paydutch.Entities.WebForm oldWebForm 
= new Timegrip.Paydutch.Entities.WebForm();
            oldWebForm.ActionUrl 
= webForm.ActionUrl;
            oldWebForm.Cookie 
= webForm.Cookie;
            oldWebForm.PageUrl 
= webForm.PageUrl;
            AddWebParameter(oldWebForm, webForm); 
//self define function           
            oldWebForm.Referer = webForm.Referer;
 
            AddScrapeRequest(oldWebForm, webForm); 
// selfdefine function
 
            Timegrip.Paydutch.Components.Connectors.WebConnector webConnector 
= new Timegrip.Paydutch.Components.Connectors.WebConnector();
            Timegrip.Paydutch.Entities.WebFormResponse oldWebFormResponse 
= webConnector.Load(oldWebForm,validateForm);
 
            WebFormResponse webFormResponse 
= new WebFormResponse();
            webFormResponse.Cookie 
= oldWebFormResponse.Cookie;
            webFormResponse.Html 
= oldWebFormResponse.Html;
            
return webFormResponse;
        }

5)           The all code of webconnector.cs
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.Runtime.Serialization;
using Timegrip.Paydutch.Components;
using Timegrip.Paydutch.Components.Connectors.WebSite;
using System.IO;
 
 
namespace Timegrip.Paydutch.WCFService
{
    
// You have created a class library to define and implement your WCF service.
    
// You will need to add a reference to this library from another project and add 
    
// the code to that project to host the service as described below. Another way
    
// to create and host a WCF service is by using the Add New Item, WCF Service 
    
// template within an existing project such as a Console Application or a Windows 
    
// Application.
 
    [ServiceContract()]
    
public interface IWebConnectService
    
{
        [OperationContract]
        WebFormResponse Post(WebForm webForm);
        [OperationContract]
        WebFormResponse Load(WebForm webForm, 
bool validateForm);
        [OperationContract]
        
string Test(string arg);
        
    }

    [ServiceBehavior(IncludeExceptionDetailInFaults 
=true)]
    
public class WebConnectService:IWebConnectService
    
{
        
//just for test
        public string Test(string arg)
        
{
            
return "Hello:" + arg;
        }

 
        
public WebFormResponse Post(WebForm webForm)
        
{
            
//return "Hello: " + myValue;
            Timegrip.Paydutch.Entities.WebForm oldWebForm=new Timegrip.Paydutch.Entities.WebForm();
            oldWebForm.ActionUrl 
= webForm.ActionUrl;
            oldWebForm.Cookie 
= webForm.Cookie;
            oldWebForm.PageUrl 
= webForm.PageUrl;    
            AddWebParameter(oldWebForm, webForm); 
//self define function           
            oldWebForm.Referer = webForm.Referer;
            
            AddScrapeRequest(oldWebForm, webForm); 
// selfdefine function
 
            Timegrip.Paydutch.Components.Connectors.WebConnector webConnector 
= new Timegrip.Paydutch.Components.Connectors.WebConnector();
            Timegrip.Paydutch.Entities.WebFormResponse oldWebFormResponse
=webConnector.Post(oldWebForm);
            
            WebFormResponse webFormResponse
=new WebFormResponse();
            webFormResponse.Cookie 
= oldWebFormResponse.Cookie;
            webFormResponse.Html 
= oldWebFormResponse.Html;
            
return webFormResponse;
        }

        
public WebFormResponse Load(WebForm webForm, bool validateForm)
        
{
            Timegrip.Paydutch.Entities.WebForm oldWebForm 
= new Timegrip.Paydutch.Entities.WebForm();
            oldWebForm.ActionUrl 
= webForm.ActionUrl;
            oldWebForm.Cookie 
= webForm.Cookie;
            oldWebForm.PageUrl 
= webForm.PageUrl;
            AddWebParameter(oldWebForm, webForm); 
//self define function           
            oldWebForm.Referer = webForm.Referer;
 
            AddScrapeRequest(oldWebForm, webForm); 
// selfdefine function
 
            Timegrip.Paydutch.Components.Connectors.WebConnector webConnector 
= new Timegrip.Paydutch.Components.Connectors.WebConnector();
            Timegrip.Paydutch.Entities.WebFormResponse oldWebFormResponse 
= webConnector.Load(oldWebForm,validateForm);
 
            WebFormResponse webFormResponse 
= new WebFormResponse();
            webFormResponse.Cookie 
= oldWebFormResponse.Cookie;
            webFormResponse.Html 
= oldWebFormResponse.Html;
            
return webFormResponse;
        }

        
Private Member
    }

    [DataContract]
    
public class WebForm //pack webform entity
    {
        [DataMember]
        
public WebFormParameter[] Parameters;
        [DataMember]
        
public WebFormScrapeRequest[] ScrapeRequest;
        [DataMember]
        
public string PageUrl;
        [DataMember]
        
public string ActionUrl;
        [DataMember]
        
public string Cookie;
        [DataMember]
        
public string Referer;        
    }

    [DataContract]
    
public class WebFormResponse //pack webformresponse entity
    {
        
        [DataMember]
        
public WebFormResponseScrapeResponse[] ScrapeResponse;
 
        [DataMember]
        
public WebFormParameter[] OutParameters;
 
        [DataMember]
        
public string Cookie;
 
        [DataMember]
        
public string Html;
    }

 
    
public enum WebFormParameterDirection //pack ebFormParameterDirection enum 
    {
        [EnumMember]
        In,
        [EnumMember]
        Out
    }

    [DataContract]
    
public class WebFormParameter 
    
{
        
        [DataMember]
        
public string Name;
 
        [DataMember]
        
public string Value;
 
        [DataMember]
        
public int MaxLength;
 
        [DataMember]
        
public bool MaxLengthSpecified;
 
        [DataMember]
       
public WebFormParameterDirection Direction;
       
    }

    [DataContract]
    
public class WebFormScrapeRequest
    
{
        [DataMember]
        
public string Name;
        [DataMember]
        
public string Regex;
        [DataMember]
        
public int GroupIndex;        
    }

    [DataContract]
    
public class WebFormResponseScrapeResponse
    
{
        [DataMember]
        
public string Name;
        [DataMember]
        
public string value;
    }
    
    
}

2、 create WCFHost ,for simple ,we just create a console application host. Certainly,You can create any type application .
1)file-> new ->project then select console application ,name=WCFHost.you will get class1.cs template. Save it as main.cs 
2)add reference ,on the project tabpage,select wcfwevice ,on the .net tabpage select system.ServiceModel.
3)create host program; such as:
static void HostingServiceViaCode()
        
{
            
try
            
{
                
using (ServiceHost ServiceHost = new ServiceHost(typeof(WebConnectService)))
                
{
 
 
                    
//Add the opened event handler to make a friendly message displayed after opening the Service host indicating the Service begin to listen to request from Clients.
                    
//     Console.WriteLine(ServiceHost.BaseAddresses.Count.ToString());
 
                    ServiceHost.Opened 
+= delegate { Console.WriteLine(" WebConnectService begin to listen via the Address:{0},{1}\n any key to close the listener", ServiceHost.BaseAddresses[0].ToString(), ServiceHost.BaseAddresses[1].ToString()); };
 
                    
//Open the Service host make it begin to listen to the Clients.
 
                    ServiceHost.Open();
 
 
                    
//wait a enterkey to close the listener
                    Console.Read();
                    ServiceHost.Close();
 
                }

            }

            
catch (Exception e)
            
{
                Console.WriteLine(
"{0}", e.Message);
            }
           
       }

 
4)add a app.config file to deploy the service,you can reference below,it provider two endpoint,one address is : http://localhost:8080/WebConnectService, the other is : net.tcp://localhost:8001/WebConnectService/:
<?xmlversion="1.0"encoding="utf-8" ?>
<configuration>
 
<system.serviceModel>
    
<services>
      
<servicename="Timegrip.Paydutch.WCFService.WebConnectService"behaviorConfiguration="WebConnectServiceBehavior" >
        
<host>
          
<baseAddresses>
            
<addbaseAddress="http://localhost:8080/WebConnectService"/>
            
<addbaseAddress="net.tcp://localhost:8001/WebConnectService/"/>
          
</baseAddresses>
        
</host>
        
<endpointcontract="Timegrip.Paydutch.WCFService.IWebConnectService"binding="wsHttpBinding" />
        
<endpoint     address = "net.tcp://localhost:8001/WebConnectService/"     binding = "netTcpBinding"   bindingConfiguration = "TransactionalTCP" contract = "Timegrip.Paydutch.WCFService.IWebConnectService"    />
        
<endpoint    address = "MEX"      binding = "mexTcpBinding"      contract = "IMetadataExchange"   />
      
</service>      
    
</services>
    
<bindings>
      
<netTcpBinding>
        
<bindingname = "TransactionalTCP"
           transactionFlow 
= "true"
         
/>
      
</netTcpBinding>
    
</bindings>
 
    
<behaviors>
      
<serviceBehaviors>
        
<behaviorname="WebConnectServiceBehavior" >
          
<serviceMetadatahttpGetEnabled="true" />          
         
 
        
</behavior>
      
</serviceBehaviors>
    
</behaviors>
 
 
</system.serviceModel> 
</configuration>
 
5in main function execute the HostingServiceViaCode(),the all code of main.cs is such as:
using System;
using System.Collections.Generic;
using System.Text;
using Timegrip.Paydutch.WCFService;
using System.ServiceModel;
namespace WCFHost
{
    
class MainThread
    
{
        
static void Main(string[] args)
        
{
            HostingServiceViaCode();
        }

        
static void HostingServiceViaCode()
        
{
            
try
            
{
                
using (ServiceHost ServiceHost = new ServiceHost(typeof(WebConnectService)))
                
{
 
 
                    
//Add the opened event handler to make a friendly message displayed after opening the Service host indicating the Service begin to listen to request from Clients.
                    
//     Console.WriteLine(ServiceHost.BaseAddresses.Count.ToString());
 
                    ServiceHost.Opened 
+= delegate { Console.WriteLine(" WebConnectService begin to listen via the Address:{0},{1}\n any key to close the listener", ServiceHost.BaseAddresses[0].ToString(), ServiceHost.BaseAddresses[1].ToString()); };
 
                    
//Open the Service host make it begin to listen to the Clients.
 
                    ServiceHost.Open();
 
 
                    
//wait a enterkey to close the listener
                    Console.Read();
                    ServiceHost.Close();
 
                }

            }

            
catch (Exception e)
            
{
               Console.WriteLine(
"{0}", e.Message);
            }
           
 
        }

    }

}

 
3、Create WCFClient for Test. For simple ,we just create a console application too. ;
1)open file->new->project,select console application. Name=WCFClient.the you will get program.cs file.
2)Run the WCFHost,the right click the project and select the menu item: add service reference, input the service=” http://localhost:8080/WebConnectService” or service=”net.tcp://localhost:8001/WebConnectService/”,which provide by WCFHost. And service reference name=” WebConnectService” just for program using.
Add the system.ServiceModel reference 
3)In the program.cs,you can reference the service such as it is a local namespace. The code in prgram.cs is:
using System;
using System.Collections.Generic;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Channels;
using WCFClient.WebConnectService;
namespace WCFClient
{
    
class Program
    
{
        
static void Main(string[] args)
        
{
            WebConnectServiceClient client 
= new WebConnectServiceClient("WSHttpBinding_IWebConnectService");// WSHttpBinding_IwebConnectService is a bind name in the app.config
           
// Console.WriteLine(client.Test("Mr Right"));
            
            WebForm webForm 
= new WebForm();
            WebFormParameter param1
=new WebFormParameter();
            param1.Name
="";
            param1.Direction
=WebFormParameterDirection.Out;
            param1.MaxLength
=0;
            param1.MaxLengthSpecified
=false;
            param1.Value
="";
            webForm.Parameters 
= new WebFormParameter[] { param1};
            WebFormScrapeRequest param2
=new WebFormScrapeRequest();
            param2.Name
="TestScrapeName";
            param2.Regex
= @"3ssS\sc";
            param2.GroupIndex
=0;
            webForm.ScrapeRequest 
= new WebFormScrapeRequest[]{param2};
            webForm.PageUrl 
= "http://xm.infopls.net/police/";
            webForm.ActionUrl 
= "http://xm.infopls.net/police/";
            webForm.Cookie 
= "";            
            WebFormResponse webFromResponse
= client.Post(webForm);
 
            Console.WriteLine(webFromResponse.Html);
            Console.ReadKey();
            
        }

    }

}

 
4)You can find the WebForm,WebFormParameter etc in the program context.there are in the \service reference\webconnectservice.map\webconnectservice.cs
5)And the config file is generate automatic.
 
Experience:
The WCF program 
is easy to promgram and reliable to deploy. It is productivity for build a distribute App. However, because the wcf is base on attribute, all the precomponent data entity must redefine as a data contract and make a translate .
 
 
 



Trackback: http:
//tb.blog.csdn.net/TrackBack.aspx?PostId=1559194



posted @ 2007-08-01 12:14  wenanry  阅读(521)  评论(0编辑  收藏  举报