SilverLight調用WebService的方法

作者: Roger W  來源: 博客園  發布時間: 2010-08-31 16:49  閱讀: 6275 次  推薦: 0   原文鏈接   [收藏]  

  在我們添加Service Reference的時候,可能不知道該服務最終會被部署到什么位置,或者該服務可能被遷移,此時我們可以使用以下手段進行Service的調用,提高代碼編寫的靈活性。

  步驟1:修改宿主Web頁面的代碼,將服務地址以初始化參數方式傳入。

<form id="form1" runat="server" style="height:100%">
    <div id="silverlightControlHost">
        <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
          ...
          
<param name="InitParams" value="serviceAddress=http://localhost/services/myservices.asmx" />
          <href="http://go.microsoft.com/fwlink/?LinkID=149156&v=3.0.40624.0" style="text-decoration:none">
               <img src="http://go.microsoft.com/fwlink/?LinkId=108181" alt="Get Microsoft Silverlight" style="border-style:none"/>
          </a>
        </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
    </form>

  步驟2:添加Service引用并注冊調用遠程方法的事件處理。

  添加Service的引用不必贅述.但此處添加Service Reference的目的僅在于獲得遠程方法的命名空間等程序結構信息。

  如果我們的Silverlight程序主頁面名叫MainPage,則在MainPage.xaml.cs中添加如下代碼:

       public void InitializeServices(string serviceAddress)
        {
            BasicHttpBinding basicBinding = new BasicHttpBinding();
            CustomBinding binding = new CustomBinding(basicBinding);
            BindingElement binaryElement = new BinaryMessageEncodingBindingElement();

            EndpointAddress endPoint = new EndpointAddress(serviceAddress);

            MyService.MyServicesSoapClient serviceClient = (MyServicesSoapClient)Activator.CreateInstance(typeof(MyServicesSoapClient), binding, endPoint);
            serviceClient.MyRemoteMethodCompleted += new EventHandler<MyService.MyRemoteMethodCompletedEventArgs>(serviceClient_MyRemoteMethodCompleted);
            serviceClient.MyRemoteMethodAsync();//調用遠程方法
        }

  步驟3:修改App.xaml.cs,添加Application.Startup事件處理方法Application_Startup。

        private void Application_Startup(object sender, StartupEventArgs e)
        {
            
this.RootVisual = new MainPage();
            
string serviceAddress = e.InitParams["serviceAddress"].ToString();
            (this.RootVisual as MainPage).InitializeServices(serviceAddress);
        }

  OK,至此,我們已經實現了在程序啟動時調用一個MyRemoteMethod方法。以上代碼稍加改動,我們就可以在程序的任意位置以這種方式調用遠程方法了。

  此方法對WCF Service的調用也有效,手段類似,實現略有不同。

0
0
 
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()