Tuesday, January 1, 2013

Get Host Name and IP Address in Silverlight

1. Open aspx page in which xap file is hosted.

2. Write following code in Page_Load Event.


<script runat="server">  
   public string HostName {get; set;}
   public string UserIp {get; set;} 
  protected void Page_Load(object sender, EventArgs e)
  {
 //Code for get system IP
  
 HostName=System.Net.Dns.GetHostName();
 System.Net.IPHostEntryipEntry=System.Net.Dns.GetHostEntry(strHostName);
 System.Net.IPAddress[]addr=ipEntry.AddressList;
 foreach(System.Net.IPAddress ip in addr)
 {
  if(ip.AddressFamily==System.Net.Sockets.AddressFamily.InterNetwork)
  {
   UserIp=ip.ToString();     
   break;
  }
 }  
  }

</script>
 
3. Now you can pass IP and Host Name to Silverlight application
using parameter in initParams tag with key-value pair.

 <param name="initParams"  
    value="<%= string.Format("HostName={0},HostIP={1}", HostName, UserIp) %>" /> 


4. Get passed Parameter values in Application_Startup event  in App.xaml.cs file in Silverlight Application. 

private void Application_Startup(object sender, StartupEventArgs e) 

      if (e.InitParams.ContainsKey("HostName")) 
      { 
            TerminalModel.Instance.HostName = e.InitParams["HostName"]; 
      } 
      if (e.InitParams.ContainsKey("HostIP")) 
      { 
            TerminalModel.Instance.HostIP = e.InitParams["HostIP"]; 
      }
}

 

2 comments:

  1. This worked great! Thank you so much.
    I extended "public sealed partial class WebContext : WebContextBase" and added two public Properties "public string HostName { get; set; }" and "public string HostIP { get; set; }" then I replaced "TerminalModel.Instance.HostName" with "WebContext.Current.HostName"

    Now those two values are available throughout my application as lifetime objects.

    ReplyDelete
  2. Get passed Parameter values in Application_Startup event in App.xaml.cs file in Silverlight Application.
    what is my server name

    ReplyDelete