Saturday, 4 February 2012

WhoAmIRequest from a Silverlight Web Resource in MS Dynamics CRM 2011

Probably the simplest request that can be made in MS Dynamics CRM, is a WhoAmI request. This request returns details (UserId, BusinessUnitId & OrganizationId) of the current user or the user under whose context the code is running.

Note that this code, assumes that you have followed the "Use the SOAP Endpoint for Web Resources with Silverlight" walkthrough from the SDK, which can also can be found here.
private void WhoAmIButton_Click(object sender, RoutedEventArgs e)
{
    OrganizationRequest req = new OrganizationRequest() { RequestName = "WhoAmI" };
    IOrganizationService service = SilverlightUtility.GetSoapService();

    service.BeginExecute(req, new AsyncCallback(WhoAmIResult), service);
}
As per usual with Silverlight, it is necessary to make a callback to get the response, which is below:
private void WhoAmIResult(IAsyncResult result)
{
  try
  {
      OrganizationResponse response =  
              ((IOrganizationService)result.AsyncState).EndExecute(result);
 
      Guid userId = new Guid(response["UserId"].ToString());
  }
  catch (Exception ex)
  {                
      throw ex;
  }
}
Do note that if you need the UserId value to perform another query, you'll need to ensure that the second query is not made until this one (WhoAmIResult) has finished.

No comments:

Post a Comment