#眉標=VS2008、WCF、SOA
#副標=體驗新一代整合開發環境(7)
#大標=WCF如何協助企業發展SOA資訊系統? 
#作者=文/圖	王寧疆



===<反灰>============= 
[ServiceContract]
public interface IService 
{
    [OperationContract]
    double GetStockPrice(int StockNo);
}
==<end>==============





===<反灰>============= 
public class Service : IService	//實作IService介面的類別
{
	public double GetStockPrice(int StockNo)	//實作查詢股價的服務
     {
        Random r = new Random();	//建立Random類別的物件
        return r.NextDouble() * r.Next(1,101);	//利用亂數模擬股價的變化
	}
}
==<end>==============




===<反灰>============= 
 [DataContract()]
public class SalesData 
{
    private decimal m_CategorySales;	//儲存屬性內容值的變數
    [DataMember()]	//宣告屬性為交換資料的一部分
    public decimal CategorySales	//定義屬性
    {
        get { return m_CategorySales;}	//傳回屬性的內容值
        set { m_CategorySales = value;}	//設定屬性的內容值
     }
}
==<end>==============




===<反灰>============= 
 [MessageContract]
public class PatientRecord 
{
   [MessageHeader(ProtectionLevel=None)] public int recordID;		//宣告不保護
   [MessageHeader(ProtectionLevel=Sign)] public string patientName;	//宣告加上簽章保護
   [MessageHeader(ProtectionLevel=EncryptAndSign)] public string SSN;//宣告加上簽章和加密
   [MessageBodyMember(ProtectionLevel=None)] public string comments;//宣告不保護
   [MessageBodyMember(ProtectionLevel=Sign)] public string diagnosis;	//宣告要加上簽章
   [MessageBodyMember(ProtectionLevel=EncryptAndSign)] 
     public string medicalHistory;	//宣告加上簽章和加密
}
==<end>==============




===<反灰>============= 
 [OperationContract]
BankingTransactionResponse Process(BankingTransaction bt);

[OperationContract]
void Store(BankingTransaction bt);

[OperationContract]
BankingTransactionResponse GetResponse();
==<end>==============




===<反灰>============= 
 [OperationContract]
bool Validate(BankingTransaction bt);	//傳回值型態非MessageContract定義的型態

[OperationContract]
void Reconcile(BankingTransaction bt1, BankingTransaction bt2);	//參數超過一個 
==<end>==============




===<反灰>============= 
 [ServiceContract]
public interface IService 
{
    [OperationContract]
    [FaultContract(typeof(MyFaultException))]
    double GetStockPrice(int StockNo);
}
==<end>==============




===<反灰>============= 
public class Service : IService 
{
	public double GetStockPrice(int StockNo)	//查詢股價的服務
     {
        Random r = new Random();
	   try
        {
		//執行服務
        }
        catch (Exception exp)
        {
            MyFaultException theFault = new MyFaultException("例外原因");	//建立例外類別的物件
            throw new FaultException<MyFaultException>(theFault);	//引發例外
        }
        return r.NextDouble() * r.Next(1,101);	//利用亂數模擬股價的變化
	}
}
==<end>==============




===<反灰>============= 
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <system.serviceModel>
    <services>
      …
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="MyServiceTypeBehaviors">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>
</configuration>
==<end>==============




===<反灰>============= 
try
{
    ServiceClient ww = new ServiceClient();
    double result = ww.GetStockPrice();	//呼叫功能
}
catch (FaultException<MyFaultException> ee)	//處理引發的例外
{
    result = "Exception: " + ee.Message;
}
==<end>==============




===<反灰>============= 
 [ServiceBehavior(TransactionAutoCompleteOnSessionClose=true,
      TransactionIsolationLevel=IsolationLevel.ReadCommitted,
      TransactionTimeout="00:00:30")]
public class ServiceClass : IServiceClass
{
   [OperationBehavior]
   string IServiceClass.GetText()
   {
      StreamReader sw = new StreamReader(@"c:\temp\WCFServiceTest.txt");
      return sw.ReadLine();
   }
}
==<end>==============




===<反灰>============= 
 [OperationBehavior(TransactionAutoComplete=true, TransactionScopeRequired=true)]
string IServiceClass.GetText()
{
    StreamReader sw = new StreamReader(@"c:\wrox\WCFServiceTest.txt");
    return sw.ReadLine();
}
==<end>==============



===<反灰>============= 
 [TransactionFlow(TransactionFlowOption.Mandatory)]
int IServiceClass.MultiplyNumbers(int firstvalue, int secondvalue)
{
    return firstvalue * secondvalue;
}
==<end>==============




===<反灰>============= 
<customBinding>
   <binding configurationName="customReliableHttpBinding">
      <reliableSession ordered="true" />
      <textMessageEncoding messageVersion="Default" encoding="utf-8" />
      <httpTransport />
   </binding>
</customBinding>
==<end>==============



===<反灰>============= 
HttpTransportBindingElement httpTransport = 
     new HttpTransportBindingElement();	//使用HTTP繫結物件
TextMessageEncodingBindingElement textMessageEncoding = 
      	new TextMessageEncodingBindingElement();	//建立物件
textMessageEncoding.Encoding = System.Text.Encoding.UTF8;	//指定文字編碼
textMessageEncoding.MessageVersion = MessageVersion.Default;	//預設訊息版本
ReliableSessionBindingElement reliableSession = 
      	new ReliableSessionBindingElement();	//建立物件
reliableSession.Ordered = true;	/訊息傳遞順序檢察
CustomBinding reliableHttpBinding = new CustomBinding(
            reliableSession, textMessageEncoding, httpTransport);	//自訂繫結物件
==<end>==============




===<反灰>============= 
 [DeliveryRequirements(RequireOrderedDelivery=true)]
public class FinancingPackageBuilder : IFinancingPackageBuilder
==<end>==============




===<反灰>============= 
<system.serviceModel>
  <services>
    <service name="HelloIndigo.HelloIndigoService" >
      <endpoint contract="HelloIndigo.IHelloIndigoService" binding="netTcpBinding" />
    </service>
  </services>
</system.serviceModel>
==<end>==============




===<反灰>============= 
<netTcpBinding>
  <binding name="netTcp">
    <security mode="Transport">
      <transport clientCredentialType="Windows" />
    </security>
  </binding>
</netTcpBinding>
==<end>==============




===<反灰>============= 
<wsHttpBinding>
  <binding name="wsHttp">
    <security mode="Message">
      <message clientCredentialType="UserName" establishSecurityContext="false" />
    </security>
  </binding>
</wsHttpBinding>
==<end>==============