Tuesday, July 28, 2015

CRM 2011/2013/2015 Javascript: Get Logged in User Full Name

CRM 2011

 function getUserFullName() {  
   var serverUrl = getCrmServerUrl();  
   var userRequest = GetRequestObject();  
   userRequest.open("GET", serverUrl + "/SystemUserSet(guid'" + Xrm.Page.context.getUserId() + "')?$select=FullName", false);  
   userRequest.setRequestHeader("Accept", "application/json");  
   userRequest.setRequestHeader("Content-Type", "application/json; charset=utf-8");  
   userRequest.send();  
   if (userRequest.status === 200) {  
     var retrievedUser = JSON.parse(userRequest.responseText).d;  
     var userFullName = retrievedUser.FullName;  
     return userFullName;  
   }  
   else {  
     return "";  
   }  
 }  
 function getCrmServerUrl() {  
   if (Xrm.Page.context.getClientUrl) // CRM 2011 UR 12+ and CRM 2013  
   {  
     serverUrl = Xrm.Page.context.getClientUrl() + "/";  
   }  
   else // CRM 2011 UR 11 or below  
   {  
     serverUrl = Xrm.Page.context.getServerUrl();  
   }  
   // Adjust URL for differences between on premise and online  
   if (serverUrl.match(/\/$/)) {  
     serverUrl = serverUrl.substring(0, serverUrl.length - 1);  
   }  
   return serverUrl + "/XRMServices/2011/OrganizationData.svc";  
 }  
 function GetRequestObject() {  
   if (window.XMLHttpRequest) {  
     return new window.XMLHttpRequest;  
   }  
   else {  
     try {  
       return new ActiveXObject("MSXML2.XMLHTTP.3.0");  
     }  
     catch (ex) {  
       return null;  
     }  
   }  
 }  


CRM 2013/2015

Xrm.Page.context.getUserName()