Wednesday, June 10, 2015

Retrieve Global Optionset list of values with C#

This is a method that you can use to retrieve a Global Optionset list of values with C#, it works for CRM 2011, 2013 and 2015.

/// <summary>
/// Method to retrieve global optionset metadata values
/// </summary>
/// <param name="_serviceProxy">CRM Service instance</param>
/// <param name="_globalOptionSetName">Global Optionset name</param>
/// <returns>Returns the global optionset metadata values</returns>
private OptionMetadata[] GetGlobalOptionsetValues(OrganizationServiceProxy _serviceProxy, string _globalOptionSetName)
{
 OptionMetadata[] result = null;

 // Use the RetrieveOptionSetRequest message to retrieve  
 // a global option set by it's name.
 RetrieveOptionSetRequest retrieveOptionSetRequest = new RetrieveOptionSetRequest(){ Name = _globalOptionSetName };

 // Execute the request.
 RetrieveOptionSetResponse retrieveOptionSetResponse = (RetrieveOptionSetResponse)_serviceProxy.Execute(retrieveOptionSetRequest);            

 // Access the retrieved OptionSetMetadata.
 OptionSetMetadata retrievedOptionSetMetadata = (OptionSetMetadata)retrieveOptionSetResponse.OptionSetMetadata;

 // Get the current options list for the retrieved attribute.
 result = retrievedOptionSetMetadata.Options.ToArray();

 return result;
}      

Tuesday, June 9, 2015

UserHasTeam for CRM 2013 - Check if a user belongs to X team with Javascript

Method to check if the user belongs to X team, looking by name:

You can call it this way:

if(UserhasTeam("Sales Managers")){
           // Do something
}else{}


function UserHasTeam(teamName) {
    ///<summary>
    /// Checks to see if the current user is a member of a team with the passed in name.
    ///</summary>
    ///<param name="teamName" type="String">
    /// A String representing the name of the team to check if the user is a member of.
    ///</param>
    // build endpoint URL
    var serverUrl = Xrm.Page.context.getClientUrl();
    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
                var result = false;
    // query to get the teams that match the name
    oDataEndpointUrl += "TeamSet?$select=Name,TeamId&$filter=Name eq '" + teamName + "'";
    //var service = GetRequestObject();
    var service = new XMLHttpRequest();
    service.open("GET", oDataEndpointUrl, false);
    service.setRequestHeader("Accept", "application/json");
    service.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    service.onreadystatechange = function() {
        if (service.readyState == 4) {
            if (service.status == 200) {
                debugger;
                var requestResults = JSON.parse(service.responseText).d;
                if (requestResults != null && requestResults.results.length > 0) {
                    var teamCounter;
                    // iterate through all of the matching teams, checking to see if the current user has a membership
                    for (teamCounter = 0; teamCounter < requestResults.results.length; teamCounter++) {
                        var team = requestResults.results[teamCounter];
                        var teamId = team.TeamId;
                        // get current user teams
                        var currentUserTeams = getUserTeams(teamId);
                        // Check whether current user teams matches the target team
                        if (currentUserTeams != null) {
                            for (var i = 0; i < currentUserTeams.length; i++) {
                                var userTeam = currentUserTeams[i];
                                // check to see if the team guid matches the user team membership id
                                if (GuidsAreEqual(userTeam.TeamId, teamId)) {
                                    result = true;
                                }
                            }
                        } else {
                            result =  false;
                        }
                    }
                } else {
                    alert("Team with name '" + teamName + "' not found");
                    result =  false;
                }
            }
        }
    };
    service.send();
             
                return result;
}

function getUserTeams(teamToCheckId) {
    // gets the current users team membership
    var userId = Xrm.Page.context.getUserId().substr(1, 36);
    var serverUrl = Xrm.Page.context.getClientUrl();
                var result;
             
    var oDataEndpointUrl = serverUrl + "/XRMServices/2011/OrganizationData.svc/";
    oDataEndpointUrl += "TeamMembershipSet?$filter=SystemUserId eq guid' " + userId + " ' and TeamId eq guid' " + teamToCheckId + " '";
             
                var service = new XMLHttpRequest();
    service.open("GET", oDataEndpointUrl, false);
    service.setRequestHeader("Accept", "application/json");
    service.setRequestHeader("Content-Type", "application/json;charset=utf-8");
    service.onreadystatechange = function() {
        if (service.readyState == 4) {
            if (service.status == 200) {
                                                                // get user teams
                debugger;
                                                                var requestResults = JSON.parse(service.responseText).d;
                                                                if (requestResults != null && requestResults.results.length > 0) {
                                                                                result = requestResults.results;
                                                                }
                                                }
                                }
                }
                service.send();
                return result;
}

function GuidsAreEqual(guid1, guid2) {
    // compares two guids
    var isEqual = false;
    if (guid1 == null || guid2 == null) {
        isEqual = false;
    } else {
        isEqual = (guid1.replace(/[{}]/g, "").toLowerCase() == guid2.replace(/[{}]/g, "").toLowerCase());
    }
    return isEqual;
}

RetrieveMultiple - Retrieve more than 5000 records with C#

This method uses the RetrieveMultiple SDK Method and loops between all the Pages in order to avoid the 5000 records limitation.

/// <summary>
/// Method used to return more than 5000 records at the same time
/// </summary>
/// <param name="service">Organization service instance</param>
/// <param name="query">Query</param>
/// <returns>All entities that matches the query</returns>
private List < Entity > RetrieveMultiple(OrganizationServiceProxy service, QueryExpression query) {
 List < Entity > result = new List < Entity > ();
 int fetchCount = 5000;
 int pageNumber = 1;

 query.PageInfo = new PagingInfo();
 query.PageInfo.Count = fetchCount;
 query.PageInfo.PageNumber = pageNumber;
 query.PageInfo.PagingCookie = null;

 while (true) {
  EntityCollection collections = service.RetrieveMultiple(query);

  if (collections.Entities.Count > 0) {

   result.AddRange(collections.Entities);
  }

  if (collections.MoreRecords) {
   query.PageInfo.PageNumber++;
   query.PageInfo.PagingCookie = collections.PagingCookie;
  } else {
   break;
  }
 }

 return result;
}

CRM 2013 - Unable to run any report

Next time you are creating/editing security roles in CRM 2013 make sure you add the privilege to READ Currency entity.

 I was fighting with this issue, the users were unable to run any report under a new security role, after testing privileges one by one, I noticed that the security role needs to have the prvReadTransactionCurrency set to Organization level, this will allow the users to run any report (retrieving the data will depend on other privileges).


I will add pictures later...