Wednesday, December 1, 2010

Using Silverlight Init parameters to get the WCF Service url dynamically

http://www.c-sharpcorner.com/UploadFile/dpatra/InitParamsInSilverlight06302009024633AM/InitParamsInSilverlight.aspx

http://msdn.microsoft.com/en-us/library/cc189004(v=VS.95).aspx


Step 1 :
Configure the WCF Service URL at web.config file



   1:  <configuration>
   2:    <appSettings>
   3:      <add key="myWCFServiceUrl" value="http://SomeServer:55460/myWCFService.svc" />
   4:    </appSettings>
   5:  </configuration>

Step 2 :
Supply the configured URL as a initparameters Silverlight 



   1:  <form id="form1" runat="server" style="height:100%">
   2:      <div id="silverlightControlHost">
   3:          <object data="data:application/x-silverlight-2," type="application/x-silverlight-2" width="100%" height="100%">
   4:                <param name="InitParams" value='myWCFServiceUrlParameter= <% =ConfigurationManager.AppSettings["myWCFServiceUrl"].ToString()%> '/>
   5:            <param name="source" value="ClientBin/mySilverlight.xap"/>
   6:                <param name="onError" value="onSilverlightError" />
   7:                <param name="background" value="white" />
   8:                <param name="minRuntimeVersion" value="4.0.50826.0" />
   9:                <param name="autoUpgrade" value="true" />
  10:                <a href="http://go.microsoft.com/fwlink/?LinkID=149156&v=4.0.50826.0" style="text-decoration:none">
  11:                     <img src="http://go.microsoft.com/fwlink/?LinkId=161376" alt="Get Microsoft Silverlight" style="border-style:none"/>
  12:                </a>
  13:            </object><iframe id="_sl_historyFrame" style="visibility:hidden;height:0px;width:0px;border:0px"></iframe></div>
  14:      </form>

Step 3 :
Modify the app.xaml.cs file to read the init parameters



   1:  public static string myWCFServiceURL = "";
   2:          public App()
   3:          {
   4:              this.Startup += this.Application_Startup;
   5:              this.Exit += this.Application_Exit;
   6:              this.UnhandledException += this.Application_UnhandledException;
   7:   
   8:              InitializeComponent();
   9:          }
  10:   
  11:          private void Application_Startup(object sender, StartupEventArgs e)
  12:          {
  13:              if (e.InitParams.ContainsKey("myWCFServiceUrlParameter") && !string.IsNullOrEmpty(e.InitParams["myWCFServiceUrlParameter"]))
  14:                  myWCFServiceURL = e.InitParams["myWCFServiceUrlParameter"];
  15:              this.RootVisual = new MainPage();
  16:          }

Step 4 :
use the URL during the WCF Client creation in Silverlight



   1:  myWCFServiceClient = new myWCFServiceClient(new BasicHttpBinding(), new EndpointAddress(App.myWCFServiceURL));