Wednesday, June 15, 2011

Get Current User ID and Organization ID from Microsoft Dynamics CRM 2011 In SIlverlight Using WhoAmIRequest

This tutorial will show you how to get the currently logged in User ID and Organization ID from Microsoft Dynamics CRM 2011 using C# in Silverlight with WhoAmIRequest

IMPORTANT: First things first.  You have to set up your Silverlight app to make a web services connection to CRM.   The best tutorial I have found for this is located here in the MSDN:
http://msdn.microsoft.com/en-us/library/gg594452.aspx
After you finish that setup you are ready to implement the rest of this post.

Now once that is done you can set up your call to the CRM Organization service reference.

Here is the call in C#:

private void GetOrganizationandUserID()
{
    try
    {

        OrganizationRequest request = new OrganizationRequest() { RequestName = "WhoAmI" };
        //request["Query"] = query;

        IOrganizationService service = SilverlightUtility.GetSoapService();

        service.BeginExecute(request, new AsyncCallback(CrmGetUserOrgInfo_Callback), service);
    }
    catch (Exception ex)
    {
        this.ReportError(ex);
    }
}

Now here is the call-back code:

private void CrmGetUserOrgInfo_Callback(IAsyncResult result)
{
    try
    {
        OrganizationResponse response = ((IOrganizationService)result.AsyncState).EndExecute(result);
        Guid OrgID = (Guid)response["OrganizationId"];
        Guid UserID = (Guid)response["UserId"];
        guidOrganizationID = OrgID;
        guidUserID = UserID;
        this.Dispatcher.BeginInvoke(DisplayOrgAndUserInfo);


    }
    catch (Exception ex)
    {
        this.ReportError(ex);
    }
}

You will need to use the this.Dispatcher.BeginInvoke to call a method to act on the UI or perform actions in the main thread.  I did not include the dispatcher invoked method called "DisplayOrgAndUserInfo" in this case because it could do anything in the UI.  In my case I will tell you though it is setting a TextBox.Text property to the value of the global variables guidOrganizationID and guidUserID .

You will notice that the biggest change in thinking and syntax from standard CRM SDK work will be that you have to specify your request and response properties as strings explicitly in code.

I hope this helps!

-

2 comments:

  1. and without soap request, you can call javascript xrm context to get user id, like:

    dynamic xrmObj = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");

    return new Guid(xrmObjeto.Page.context.getUserId());

    Good job with your excellent blog posts!

    Christophe Trevisani Chavey.
    www.virtualgroup.com.br

    ReplyDelete
    Replies
    1. Very true!!! You keep up the good work also! Just bear in mind that your solution will only work if the Silverlight XAP is part of a web resource that you upload into the application.

      Delete