How to Get the Current Windows User Name in Silverlight 4 Using the AutomationFactory

[tweetmeme source=”jojitsoriano” only_single=false]
My Silverlight 4 application requires that during data entry, the user name of the current Windows user defaults to the field named User Name. I found some workarounds in the web like making use of JavaScript, ASP.Net applications, etc. but following Justin Angel’s blog titled Cutting Edge Silverlight4 COM+ Features, I came up with this procedure with fewer lines of code.  

private string GetLocalUserName()
    string strLocalUserName = string.Empty; 

    if (App.Current.HasElevatedPermissions)
        using (dynamic WshNetwork = AutomationFactory.CreateObject("WScript.Network"))
            strLocalUserName = WshNetwork.UserName;
    return strLocalUserName;

Some notes to make this work:  

  1. The dynamic keyword requires references to System.Core.dll and Microsoft.CSharp.dll.
  2. The AutomationFactory class is under System.Runtime.InteropServices.Automation namespace for the final release of Silverlight 4. The examples in Justin Angel’s blog which shows ComAutomationFactory under the System.Windows.Interop namespace were written in Silverlight 4 Beta 1.
  3. The COM+ automation feature is only available in out-of-browser Silverlight 4 applications with elevated privileges that’s why there’s a need to check on the value of App.Current.HasElevatedPermissions.
  4. As Justin emphasized, this feature works only on Windows machines.

Justin Angel provided a lot of information and examples in his blog post regarding COM+ automation, thus illustrating how powerful this feature really is at least for applications running in Windows operating system for now.  

This work is licensed under a Creative Commons Attribution By license.
This entry was posted in .Net Tips, Silverlight and tagged , , . Bookmark the permalink.

One Response to How to Get the Current Windows User Name in Silverlight 4 Using the AutomationFactory

  1. Pravangsu Biswas says:

    Geart article. worked.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s