Home » ASP.NET | Code | RIA | Headline

Mac Address in Silverlight 4

4. May 2010 by thebeebs 0 Comments

A few weeks ago I was discussing way to Get A Mac Address in Silverlight 4 with James Forage. I was looking to see  if there was a managed way of doing this, sadly there isn’t. However James discovered a rather interesting Unmanaged way using Silverlight 4’s new AutomationFactory. I’ve posted the code below

public partial class MyClient : UserControl
{
        public MyClient()
        {
            MACAddressManager macAddressManager = new MACAddressManager();
            macAddressManager.OnGetMACAddressCompleted += new EventHandler(macAddressManager_OnGetMACAddressCompleted);
            macAddressManager.BeginGetMACAddress();
        }

        void macAddressManager_OnGetMACAddressCompleted(object sender, EventArgs e)
        {
            MACAddressManager manager = (MACAddressManager) sender;
            // MAC Address  value is in manager.MACAddress
        }
}

public class MACAddressManager
{
        private dynamic sWbemServices;
        private dynamic sWbemSink;

        public string MACAddress { get; private set; }
        public event EventHandler OnGetMACAddressCompleted;

        private void EndGetMACAddress(object sender, EventArgs e)
        {
            dynamic objWbemObject = sender;
            MACAddress = objWbemObject.MACAddress;
            if (OnGetMACAddressCompleted != null)
                OnGetMACAddressCompleted(this, EventArgs.Empty);
        }

        public void BeginGetMACAddress()
        {
            if ((Application.Current.IsRunningOutOfBrowser) && (Application.Current.HasElevatedPermissions) && (AutomationFactory.IsAvailable))
            {
                dynamic sWbemLocator = AutomationFactory.CreateObject("WbemScripting.SWBemLocator");
                sWbemServices = sWbemLocator.ConnectServer(".");
                sWbemServices.Security_.ImpersonationLevel = 3; //impersonate

                sWbemSink = AutomationFactory.CreateObject("WbemScripting.SWbemSink");
                sWbemSink.OnObjectReady += new EventHandler(EndGetMACAddress);

                string query = "SELECT * FROM Win32_NetworkAdapterConfiguration where IPEnabled=true";
                sWbemServices.ExecQueryAsync(sWbemSink, query);
            }
        }
    }

Comments

Add comment


(Will show your Gravatar icon)  

  Country flag

biuquote
  • Comment
  • Preview
Loading