[Silverlight]整合Silverlight與WCF ----- Day7

[Silverlight]整合Silverlight與WCF ----- Day7

WCF是微軟在.NET Framework 3.0用來處理通訊的一個基本架構。透過這個架構,可以讓你建立強大的服務導向、連結服務的系統。

 

今天,我們直接透過範例來了解,Silverlight與WCF如何整合?

1.

首先,建立一個叫作SLWithWcf_D7的專案(如果你不知道要怎麼新增,請參考[Silverlight]Hello Siverlight ----- Day 1)

 

2.

在「SLWithWcf_D7.Web」專案中,新增一個WCF Service,命名為MyWcf。

image

 

新增後,我們可以看到它的程式碼如下:

namespace SLWithWcf_D7.Web

{

    // NOTE: If you change the interface name "IMyWcf" here, you must also update the reference to "IMyWcf" in Web.config.

    [ServiceContract]

    public interface IMyWcf

    {

        [OperationContract]

        void DoWork();

    }

}

 

 

然後我們將它變更成下列程式碼(等等要呼叫的SayHello方法):

namespace SLWithWcf_D7.Web

{

    // NOTE: If you change the interface name "IMyWcf" here, you must also update the reference to "IMyWcf" in Web.config.

    [ServiceContract]

    public interface IMyWcf

    {

        [OperationContract]

        string SayHello(string userName);

    }

}

 

 

3.

接下來,在MyWcf.svc.cs檔案中,我們實做SayHello的程式碼:

public string SayHello(string userName)

{

   if (DateTime.Now.Hour >= 8 && DateTime.Now.Hour < 12)

   {

      return "Hi, " + userName + ",現在是早上,才剛上班,不要偷懶喔!!";

   }

   else if (DateTime.Now.Hour >= 12 && DateTime.Now.Hour <= 17)

   {

      return "Hi, " + userName + ",現在是下午,在撐一下,就要下班了!!";

   }

   else

   {

      return "Hi, " + userName + ",下班就是要休息喔!!";

   }

}

 

4.

在SLWithWcf_D7專案中,我們在Page.xaml中,輸入下列Xaml Code:

<UserControl x:Class="SLWithWcf_D7.Page"

   xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"

   xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"

   Width="400" Height="300">

    <Grid x:Name="LayoutRoot" Background="White">

        <StackPanel x:Name="MyPanel" Orientation="Vertical" >

            <TextBox x:Name="InputName" Width="80" ></TextBox>

            <TextBox x:Name="MessageHere"></TextBox>

            <Button x:Name="LinkWCF" Content="呼叫WCF" Width="60" Click="LinkWCF_Click"></Button>

        </StackPanel>

    </Grid>

</UserControl>

 

5.

在SLWithWcf_D7專案中,選擇新增Service Reference,

image

 

尋找在此方案中的Service。

image

 

命名為MyWCFService,然後按下OK按鈕

image

 

新增的兩個檔案,參考Service以及config設定。

image

 

6.

在Page.xaml.cs中撰寫下列程式碼,這是去呼叫WCF Service,然後WCF Service回傳處理後的資料:

private void LinkWCF_Click(object sender, RoutedEventArgs e)

{

   MyWCFService.MyWcfClient wcfService = new SLWithWcf_D7.MyWCFService.MyWcfClient();

   wcfService.SayHelloCompleted += new EventHandler<SLWithWcf_D7.MyWCFService.SayHelloCompletedEventArgs>(wcfService_SayHelloCompleted);

   wcfService.SayHelloAsync(InputName.Text);

}

 

void wcfService_SayHelloCompleted(object sender, SLWithWcf_D7.MyWCFService.SayHelloCompletedEventArgs e)

{

   MessageHere.Text = e.Result;

}

 

 

 

7.

按下F5執行,輸入名字後,按下呼叫WCF Service,可是卻發現了這個錯誤:

image

 

8.

這個錯誤實在看不懂,檢查一下SLWithWcf_D7專案的config檔,發現這個檔案裡面竟然沒有設定值。

然後突然看到在新增項目裡面有一個Silverlight-enabled WCF Service,新增一個來跟WCF Service比較,

發現在下列設定有不一樣的地方:

WCF Service:

<services>

      <service behaviorConfiguration="SLWithWcf_D7.Web.MyWcfBehavior" name="SLWithWcf_D7.Web.MyWcf">

        <endpoint address="" binding="wsHttpBinding" contract="SLWithWcf_D7.Web.IMyWcf">

          <identity>

            <dns value="localhost"/>

          </identity>

        </endpoint>

        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange"/>

      </service>

</services>

 

 

Silverlight-enabled WCF Service:

<services>

          <service behaviorConfiguration="TestSL.Web.Service1Behavior"

              name="TestSL.Web.Service1">

              <endpoint address="" binding="basicHttpBinding" contract="TestSL.Web.Service1" />

              <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />

          </service>

</services>

 

 

一個使用wsHttpBinding,一個使用basicHttpBinding。

 

變更一下原來的WCF Service的Binding設定,改成basicHttpBinding。然後更新Service Reference。

你就可以看到ServiceReferences.ClientConfig裡面包含了設定。

image

 

9.

按下F5再度執行。Work Fine~

image

 

 

我們再來作進階的處理:

1.

在WCF Service Interface(IMyWcf.cs)中,新增下列程式碼:

實作一個List的物件,這個物件包含有Name、Address以及sex屬性。

namespace SLWithWcf_D7.Web

{

    // NOTE: If you change the interface name "IMyWcf" here, you must also update the reference to "IMyWcf" in Web.config.

    [ServiceContract]

    public interface IMyWcf

    {

        [OperationContract]

        string SayHello(string userName);

 

        [OperationContract]

        List<Customer> GetCustomerData();

    }

 

    [DataContract]

    public class Customer

    {

        [DataMember]

        public string Name;

 

        [DataMember]

        public string Address;

 

        [DataMember]

        public string sex;

    }

}

 

 

2.

在MyWcf.svc.cs,新增下列方法:

 

public List<Customer> GetCustomerData()

{

    List<Customer> cus = new List<Customer>();

    cus.Add(new Customer{ Name="lolota", Address="台北市", sex="M"});

    cus.Add(new Customer{ Name="eva", Address = "台北市", sex = "F" });

    cus.Add(new Customer{ Name="twee", Address="台北市", sex="M" });

    cus.Add(new Customer{ Name="bunny", Address="台中市",sex="M"});

 

    return cus;

}

 

 

3.

接下來,我們來處理Layout的部份,加入這段Xaml Code:

<StackPanel x:Name="MyPanel2" Orientation="Vertical" Margin="0,84,0,36" >

        <Button x:Name="LinkWCFCustomrData" Content="回傳Customer資料" Width="110" Click="LinkWCFCustomrData_Click"></Button>

        <TextBlock></TextBlock>

        <ItemsControl x:Name="ItemControl1" Height="142" Width="376">

            <ItemsControl.ItemTemplate>

                <DataTemplate x:Name="CusName">

                    <Grid ShowGridLines="True" >

                        <Grid.RowDefinitions>

                            <RowDefinition/>

                            <RowDefinition/>

                            <RowDefinition/>

                            <RowDefinition/>

                        </Grid.RowDefinitions>

                        <Grid.ColumnDefinitions>

                            <ColumnDefinition />

                            <ColumnDefinition />

                            <ColumnDefinition />

                        </Grid.ColumnDefinitions>

 

                        <TextBox Grid.Column="0" Text="{Binding Path=Name}" />

                        <TextBox Grid.Column="1" Text="{Binding Path=Address}"/>

                        <TextBox Grid.Column="2" Text="{Binding Path=sex}"/>

                    </Grid>

                </DataTemplate>

            </ItemsControl.ItemTemplate>

        </ItemsControl>

</StackPanel>

 

 

4.

加入下列程式碼:

private void LinkWCFCustomrData_Click(object sender, RoutedEventArgs e)

{

   MyWCFService.MyWcfClient wcfService = new SLWithWcf_D7.MyWCFService.MyWcfClient();

   wcfService.GetCustomerDataCompleted += new EventHandler<SLWithWcf_D7.MyWCFService.GetCustomerDataCompletedEventArgs>(wcfService_GetCustomerDataCompleted);

   wcfService.GetCustomerDataAsync();

}

 

void wcfService_GetCustomerDataCompleted(object sender, SLWithWcf_D7.MyWCFService.GetCustomerDataCompletedEventArgs e)

{

   ItemControl1.ItemsSource = e.Result;

}

 

 

5.

按下F5執行:

image

線上Demo

 

程式碼下載

 

如果你對WCF有興趣,想研究,可以參考這本書籍 - Microsoft Windows Communication Foundation 新一代應用程式通訊架構

 

試煉大會,我們下次見!!

 

 

如果您有微軟技術開發的問題,可以到MSDN Forum發問。

如果您有微軟IT管理的問題,可以到TechNet Forum發問喔。