Monday, March 7, 2016

CRM 2016 WEB API - Retrieve Specific Record

This is a helper function to retrieve and specific record in CRM 2016 using the WEB API

function RetrieveEntity2016(clientURL, entityId, entityType, query) {
    var req = new XMLHttpRequest();
    req.open('GET', clientURL + "/api/data/v8.0/"; + entityType + "(" + entityId + ")" + query, true);
    req.setRequestHeader("Accept", "application/json");
    req.setRequestHeader("Content-type", "application/json; charset=utf-8");
    req.setRequestHeader("OData-MaxVersion", "4.0");
    req.setRequestHeader("OData-Version","4.0");
 
    req.onreadystatechange = function () {
        if (this.readyState == 4 /* complete */) {
            req.onreadystatechange = null;
            if (this.status == 200) {
                var data = window.JSON.parse(this.response);
                console.log("Retrieved " + entityType + " with entity id "+ data.accountid);
            }
            else {
                var error = window.JSON.parse(this.response).error;
                console.log(error.message);
            }
        }
    };
    req.send();
}

CRM 2016 WEB API - Create record with Javascript

This is a helper function to create records in CRM 2016 using the WEB API



function CreateRecord2016(entity, entityName){
 try{   
  /* Example of entity : note, all fields in lowercase
   var CRMObject = new Object(); 
   CRMObject.new_name = "test name";   
   CRMObject.new_customfieldname = "test";   
  */
  var req = new XMLHttpRequest()
  req.open("POST",encodeURI(clientURL + "/api/data/v8.0/" + entityName + "s"), true);
  req.setRequestHeader("Accept", "application/json");
  req.setRequestHeader("Content-Type", "application/json; charset=utf-8");
  req.setRequestHeader("OData-MaxVersion", "4.0");
  req.setRequestHeader("OData-Version", "4.0");
  req.onreadystatechange = function () {
   if (this.readyState == 4 /* complete */) {
    req.onreadystatechange = null;
    if (this.status == 204) {
     var createdRecordId = this.getResponseHeader("OData-EntityId");
     
     result = createdRecordId;
    }
    else {
     var error = JSON.parse(this.response).error;
     //console.log(error.message);
     result = error;
    }
   }
  };
  req.send(window.JSON.stringify(entity)); 

  
  //Asynchronous AJAX function to Create a CRM record using OData 
  return result;
 }catch(err){
  showError(arguments.callee.toString().match(/function\s+([^\s\(]+)/)[1], err.message);
 }
}

function showError(functionName, errorMessage) 
{   
   alert(functionName + ": " + errorMessage);
}

Tuesday, September 8, 2015

Function to make the form read only and skip the fields you want

function formdisable() {
    var skipFields = ",new_fieldtoskip1name,new_fieldtoskip2name,";
 
    var allAttributes = Xrm.Page.data.entity.attributes.get();
    for (var i in allAttributes) {
        var myattribute = Xrm.Page.data.entity.attributes.get(allAttributes[i].getName());
        var myname = myattribute.getName();
        if (skipFields.indexOf("," + myname + ",") != -1) {
            continue;
        }

        try {
            Xrm.Page.getControl(myname).setDisabled(true);
        } catch (err) {}
    }
}

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...