Tuesday 30 June 2015

Dynamics CRM check if user has System Administrator Role using OData

Make sure you have added jquery-1.9.1.min.js and JSON2.js in Entity form libraries

//Check login User has 'System Administrator' role
function CheckUserRole() {
    var currentUserRoles = Xrm.Page.context.getUserRoles();
    for (var i = 0; i < currentUserRoles.length; i++) {
         var userRoleId = currentUserRoles[i];
 var userRoleName = GetRoleName(userRoleId);
        if (userRoleName == "System Administrator") {
            return true;
        }
    }
    return false;
}


//Get Rolename based on RoleId
function GetRoleName(roleId) {
    //var serverUrl = Xrm.Page.context.getServerUrl();
    var serverUrl = location.protocol + "//" + location.host + "/" + Xrm.Page.context.getOrgUniqueName();
    var odataSelect = serverUrl + "/XRMServices/2011/OrganizationData.svc" + "/" + "RoleSet?$filter=RoleId eq guid'" + roleId + "'";
    var roleName = null;
    $.ajax(
        {
            type: "GET",
            async: false,
            contentType: "application/json; charset=utf-8",
            datatype: "json",
            url: odataSelect,
            beforeSend: function (XMLHttpRequest) { XMLHttpRequest.setRequestHeader("Accept", "application/json"); },
            success: function (data, textStatus, XmlHttpRequest) {
                roleName = data.d.results[0].Name;
            },
            error: function (XmlHttpRequest, textStatus, errorThrown) { alert('OData Select Failed: ' + textStatus + errorThrown + odataSelect); }
        }
    );
    return roleName;
}

Thursday 25 June 2015

Dynamic CRM Useful JavaScript Tidbits


1. Get the GUID value of a lookup field:

function AlertGUID() {
    var primaryContactGUID = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].id;
    alert(primaryContactGUID);
}

2. Get the Text value of a lookup field:

function AlertText() {
    var primaryContactName = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].name;
    alert(primaryContactName);
}

3. Get the value of a text field:

function AlertTextField() {
    var MainPhone = Xrm.Page.data.entity.attributes.get("telephone1").getValue();
    alert(MainPhone);
}

4. Get the value of an Option Set field:

function AlertOptionSetDatabaseValue() {
    var AddressTypeDBValue = Xrm.Page.data.entity.attributes.get("address1_addresstypecode").getValue();
    if (AddressTypeDBValue != null) {
        alert(AddressTypeDBValue);
    }
}

5. Get the text value of an Option Set field:

function AlertOptionSetDisplayValue() {
   var AddressTypeDisplayValue = Xrm.Page.data.entity.attributes.get("address1_addresstypecode").getText();
    if (AddressTypeDisplayValue != null) {
        alert(AddressTypeDisplayValue);
    }
}

6. Get the value of a Bit field:

function GetBitValue(fieldname) {
    return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}

7. Get the value of a Date field:\

returns a value like: Wed Nov 30 17:04:06 UTC+0800 2011
and reflects the users time zone set under personal options
function GetDate(fieldname) {
    return Xrm.Page.data.entity.attributes.get(fieldname).getValue();
}

8. Get the day, month and year parts from a Date field:

// This function takes the fieldname of a date field as input and returns a DD-MM-YYYY value
// Note: the day, month and year variables are numbers
function FormatDate(fieldname) {
    var d = Xrm.Page.data.entity.attributes.get(fieldname).getValue();
    if (d != null) {
        var curr_date = d.getDate();
        var curr_month = d.getMonth();
        curr_month++;  // getMonth() considers Jan month 0, need to add 1
        var curr_year = d.getFullYear();
        return curr_date + "-" + curr_month + "-" + curr_year;
    }
    else return null;
}

// An example where the above function is called
alert(FormatDate("new_date2"));

9. Set the value of a string field:


function SetStringField() {
    var Name = Xrm.Page.data.entity.attributes.get("name");
    Name.setValue("ABC");
}

10. Set the value of an Option Set (pick list) field:

Note: this example sets the Address Type field on the Account Form to “Bill To”, which corresponds to a database value of “1”
function SetOptionSetField() {
    var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
    AddressType.setValue(1);
}

11. Set a Date field / Default a Date field to Today:

//set date field to now (works on date and date time fields)
Xrm.Page.data.entity.attributes.get("new_date1").setValue(new Date());

12. Set a Date field to 7 days from now:

function SetDateField() {
    var today = new Date();
    var futureDate = new Date(today.setDate(today.getDate() + 7));
    Xrm.Page.data.entity.attributes.get("new_date2").setValue(futureDate);
    Xrm.Page.data.entity.attributes.get("new_date2").setSubmitMode("always"); // Save the Disabled Field
}

13. Set the Time portion of a Date Field:

// This is a function you can call to set the time portion of a date field
function SetTime(attributeName, hour, minute) {
        var attribute = Xrm.Page.getAttribute(attributeName);
        if (attribute.getValue() == null) {
            attribute.setValue(new Date());
        }
        attribute.setValue(attribute.getValue().setHours(hour, minute, 0));
}

// Here's an example where I use the function to default the time to 8:30am
SetTime('new_date2', 8, 30);

14. Set the value of a Lookup field:


// Set the value of a lookup field
function SetLookupValue(fieldName, id, name, entityType) {
    if (fieldName != null) {
        var lookupValue = new Array();
        lookupValue[0] = new Object();
        lookupValue[0].id = id;
        lookupValue[0].name = name;
        lookupValue[0].entityType = entityType;
        Xrm.Page.getAttribute(fieldName).setValue(lookupValue);
    }
}
Here’s an example of how to call the function (I retrieve the details of one lookup field and then call the above function to populate another lookup field):
var ExistingCase = Xrm.Page.data.entity.attributes.get("new_existingcase");
if (ExistingCase.getValue() != null) {
    var ExistingCaseGUID = ExistingCase.getValue()[0].id;
    var ExistingCaseName = ExistingCase.getValue()[0].name;
    SetLookupValue("regardingobjectid", ExistingCaseGUID, ExistingCaseName, "incident");
}


16. Set the Requirement Level of a Field:

Note: setRequiredLevel(“none”) would make the field optional again.
function SetRequirementLevel() {
    var AddressType = Xrm.Page.data.entity.attributes.get("address1_addresstypecode");
    AddressType.setRequiredLevel("required");
}

17. Disable a field:

function SetEnabledState() {
    var AddressType = Xrm.Page.ui.controls.get("address1_addresstypecode");
    AddressType.setDisabled(true);
}

18. Force Submit the Save of a Disabled Field:

// Save the Disabled Field
Xrm.Page.data.entity.attributes.get("new_date1").setSubmitMode("always");

19. Show/Hide a field:

function hideName() {
    var name = Xrm.Page.ui.controls.get("name");
    name.setVisible(false);
}

20. Show/Hide a field based on a Bit field

function DisableExistingCustomerLookup() {
   var ExistingCustomerBit = Xrm.Page.data.entity.attributes.get("new_existingcustomer").getValue();
    if (ExistingCustomerBit == false) {
       Xrm.Page.ui.controls.get("customerid").setVisible(false);
    }
    else {
       Xrm.Page.ui.controls.get("customerid").setVisible(true);
    }
}

21. Show/Hide a nav item:

Note: you need to refer to the nav id of the link, use F12 developer tools in IE to determine this
function hideContacts() {
    var objNavItem = Xrm.Page.ui.navigation.items.get("navContacts");
    objNavItem.setVisible(false);
}

22. Show/Hide a Section:

Note: Here I provide a function you can use. Below the function is a sample.
function HideShowSection(tabName, sectionName, visible) {
    try {
        Xrm.Page.ui.tabs.get(tabName).sections.get(sectionName).setVisible(visible);
    }
    catch (err) { }
}

HideShowSection("general", "address", false);   // "false" = invisible

23. Show/Hide a Tab:

Note: Here I provide a function you can use. Below the function is a sample.
function HideShowTab(tabName, visible) {
    try {
        Xrm.Page.ui.tabs.get(tabName).setVisible(visible);
    }
    catch (err) { }
}

HideShowTab("general", false);   // "false" = invisible
24. Save the form:

function SaveAndClose() {
    Xrm.Page.data.entity.save();
}
25. Save and close the form:
function SaveAndClose() {
    Xrm.Page.data.entity.save("saveandclose");
}

26. Close the form:

Note: the user will be prompted for confirmation if unsaved changes exist
function Close() {
    Xrm.Page.ui.close();
}

27. Determine which fields on the form are dirty:

var attributes = Xrm.Page.data.entity.attributes.get()
 for (var i in attributes)
 {
    var attribute = attributes[i];
    if (attribute.getIsDirty())
    {
      alert("attribute dirty: " + attribute.getName());
    }
 }

28. Determine the Form Type:

Note: Form type codes: Create (1), Update (2), Read Only (3), Disabled (4), Bulk Edit (6)
function AlertFormType() {
    var FormType = Xrm.Page.ui.getFormType();
     if (FormType != null) {
        alert(FormType);
    }
}

29. Get the GUID of the current record:

function AlertGUID() {
    var GUIDvalue = Xrm.Page.data.entity.getId();
    if (GUIDvalue != null) {
        alert(GUIDvalue);
    }
}

30. Get the GUID of the current user:

function AlertGUIDofCurrentUser() {
    var UserGUID = Xrm.Page.context.getUserId();
     if (UserGUID != null) {
        alert(UserGUID);
    }
}

31. Get the Security Roles of the current user:

(returns an array of GUIDs, note: my example reveals the first value in the array only)
function AlertRoles() {
    alert(Xrm.Page.context.getUserRoles());
}

32. Determine the CRM server URL:

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

33. Refresh a Sub-Grid:

var targetgird = Xrm.Page.ui.controls.get("target_grid");
targetgird.refresh();


35. Pop an existing CRM record (new approach):
function PopContact() {
    //get PrimaryContact GUID
    var primaryContactGUID = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].id;
    if (primaryContactGUID != null) {
        //open Contact form
        Xrm.Utility.openEntityForm("contact", primaryContactGUID)
    }
} 

36. Pop an existing CRM record (old approach):

Note: this example pops an existing Case record. The GUID of the record has already been established and is stored in the variable IncidentId.
//Set features for how the window will appear
var features = "location=no,menubar=no,status=no,toolbar=no";

// Get the CRM URL
var serverUrl = Xrm.Page.context.getServerUrl();

// Cater for URL differences between on premise and online
if (serverUrl.match(/\/$/)) {
    serverUrl = serverUrl.substring(0, serverUrl.length - 1);
}

window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&id=" + encodeURIComponent(IncidentId), "_blank", features, false);

37. Pop a blank CRM form (new approach):

function PopNewCase() {
    Xrm.Utility.openEntityForm("incident")
}

38. Pop a new CRM record with default values (new approach):

function CreateIncident() {
    //get Account GUID and Name
    var AccountGUID = Xrm.Page.data.entity.getId();
    var AccountName = Xrm.Page.data.entity.attributes.get("name").getValue();
    //define default values for new Incident record
    var parameters = {};
    parameters["title"] = "New customer support request";
    parameters["casetypecode"] = "3";
    parameters["customerid"] = AccountGUID;
    parameters["customeridname"] = AccountName;
    parameters["customeridtype"] = "account";
    //pop incident form with default values
    Xrm.Utility.openEntityForm("incident", null, parameters);
}


40. Pop a Dialog from a ribbon button

Note: this example has the Dialog GUID and CRM Server URL hardcoded, which you should avoid. A simple function is included which centres the Dialog when launched.
function LaunchDialog(sLeadID) {
    var DialogGUID = "128CEEDC-2763-4FA9-AB89-35BBB7D5517D";
    var serverUrl = "https://avanademarchdemo.crm5.dynamics.com/";
    serverUrl = serverUrl + "cs/dialog/rundialog.aspx?DialogId=" + "{" + DialogGUID + "}" + "&EntityName=lead&ObjectId=" + sLeadID;
    PopupCenter(serverUrl, "mywindow", 400, 400);
    window.location.reload(true);
}

function PopupCenter(pageURL, title, w, h) {
    var left = (screen.width / 2) - (w / 2);
    var top = (screen.height / 2) - (h / 2);
    var targetWin = window.showModalDialog(pageURL, title, 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width=' + w + ', height=' + h + ', top=' + top + ', left=' + left);
}

41. Pop a URL from a ribbon button

Great info on the window parameters you can set here: http://javascript-array.com/scripts/window_open/
function LaunchSite() {
    // read URL from CRM field
    var SiteURL = Xrm.Page.data.entity.attributes.get("new_sharepointurl").getValue();
    // execute function to launch the URL
    LaunchFullScreen(SiteURL);
}

function LaunchFullScreen(url) {
 // set the window parameters
 params  = 'width='+screen.width;
 params += ', height='+screen.height;
 params += ', top=0, left=0';
 params += ', fullscreen=yes';
 params += ', resizable=yes';
 params += ', scrollbars=yes';
 params += ', location=yes';

 newwin=window.open(url,'windowname4', params);
 if (window.focus) {
     newwin.focus()
 }
 return false;
}

42. Pop the lookup window associated to a Lookup field:

window.document.getElementById('new_existingcase').click();

43. Pop a Web Resource (new approach):

function PopWebResource() {
    Xrm.Utility.openWebResource("new_Hello");
}

44. Using a SWITCH statement

function GetFormType() {
    var FormType = Xrm.Page.ui.getFormType();
    if (FormType != null) {
        switch (FormType) {
            case 1:
                return "create";
                break;
            case 2:
                return "update";
                break;
            case 3:
                return "readonly";
                break;
            case 4:
                return "disabled";
                break;
            case 6:
                return "bulkedit";
                break;
            default:
                return null;
        }
    }
}

45. Pop an Ok/Cancel Dialog

function SetApproval() {
    if (confirm("Are you sure?")) {
        // Actions to perform when 'Ok' is selected:
        var Approval = Xrm.Page.data.entity.attributes.get("new_phaseapproval");
        Approval.setValue(1);
        alert("Approval has been granted - click Ok to update CRM");
        Xrm.Page.data.entity.save();
    }
    else {
        // Actions to perform when 'Cancel' is selected:
        alert("Action cancelled");
    }
}

Wednesday 24 June 2015

Microsoft Dynamic crm 2013 Javascript documentation

Check out following reference documentation for client-side events and object models that can be used with JavaScript libraries. * marked is new in CRM 2013

  • Xrm.Utility: Xrm.Utility object provides a container for useful functions not directly related to the current page. 
Xrm.Utility
alertDialog Displays a dialog box with a message.
confirmDialog Displays a confirmation dialog box that contains a message as well as OK and Cancel buttons.
isActivityType Determine if an entity is an activity entity.
openEntityForm Opens an entity form.
openWebResource Opens an HTML web resource.


  • Xrm.Page.data: Xrm.Page.data provides an entity object that provides collections and methods to manage data within the entity form
Xrm.Page.data
getIsValid* Do a validation check for the data in the form.
refresh* Asynchronously refresh all the data of the form without reloading the page.
save* Saves the record asynchronously with the option to set callback functions.
Xrm.Page.data.entity
addOnSave Adds a function to be called when the record is saved.
getDataXml Returns a string representing the xml that will be sent to the server when the record is saved.
getEntityName Returns a string representing the logical name of the entity for the record.
getId Returns a string representing the GUID id value for the record.
getIsDirty Returns a Boolean value that indicates if any fields in the form have been modified.
getPrimaryAttributeValue* Gets a string for the value of the primary attribute of the entity.
removeOnSave Removes a function to be called when the record is saved.
save Saves the record with the options to close or new.

  • Xrm.Page.context: Xrm.Page.context provides methods to retrieve information specific to an organization, a user, or parameters that were passed to the form in a query string.
Xrm.Page.context
client.getClient* Returns a value to indicate which client the script is executing in.
client.getClientState* Returns a value to indicate the state of the client.
getClientUrl Returns the base URL that was used to access the application.
getCurrentTheme Returns a string representing the current Microsoft Office Outlook theme chosen by the user.
getOrgLcid Returns the LCID value that represents the base language for the organization.
getOrgUniqueName Returns the unique text value of the organization’s name.
getQueryStringParameters Returns a dictionary object of key value pairs that represent the query string arguments that were passed to the page.
getUserId Returns the GUID of the SystemUser.Id value for the current user.
getUserLcid Returns the LCID value that represents the provisioned language that the user selected as their preferred language.
getUserName* Returns the name of the current user.
getUserRoles Returns an array of strings that represent the GUID values of each of the security roles that the user is associated with.
isOutlookClient (Deprecated) Returns a Boolean value indicating if the user is using Microsoft Dynamics CRM for Outlook.
isOutlookOnline (Deprecated) Returns a Boolean value that indicates whether the user is connected to the CRM server.
prependOrgName Prepends the organization name to the specified path.

  •   Xrm.Page.ui: provides collections and methods to manage the user interface of the form. 
Xrm.Page.ui
clearFormNotification* Remove form level notifications.
close Method to close the form.
formSelector.getCurrentItem Method to return a reference to the form currently being shown.
formSelector.items A collection of all the form items accessible to the current user.
getViewPortHeight Method to get the height of the viewport in pixels.
getViewPortWidth Method to get the width of the viewport in pixels.
getCurrentControl Get the control object that currently has focus.
getFormType Get the form context for the record.
navigation.items A collection of all the navigation items on the page.
setFormNotification* Display form level notifications.
refreshRibbon Re-evaluate the ribbon data that controls what is displayed in it.
Collections
Xrm.Page.data.entity.attributes All attributes on the page.
Xrm.Page.ui.controls All controls on the page.
Xrm.Page.ui.formSelector.items All the forms available to the user.
Xrm.Page.ui.navigation.items All the items in the form navigation area.
Xrm.Page.ui.tabs All the tabs on the page.
Xrm.Page Attribute.controls All the controls for the attribute.
Xrm.Page.ui Section.controls All the controls in the section.
Xrm.Page.ui Tab.sections All the sections in the tab.
Collections Methods
forEach Apply an action in a delegate function to each object in the collection.
get Get one or more object from the collection depending on the arguments passed.
getLength Get the number of items in the collection.

  • Attributes: Attributes store the data available in the record. Attributes are available from the Xrm.Page.data.entity.attributes collection. To access an attribute you can use the Xrm.Page.data.entity.attributes.get method or the shortcut version Xrm.Page.getAttribute. Following table shows how you can query attribute properties to understand what kind of attribute it is or change the behavior of the attribute.
Xrm.Page.getAttribute(“…”)
getAttributeType Get the type of attribute.
getFormat Get the attribute format.
getIsDirty Determine whether the value of an attribute has changed since it was last saved.
getIsPartyList Determine whether a lookup attribute represents a partylist lookup.
getMaxLength Get the maximum length of string which an attribute that stores string data can have.
getName Get the name of the attribute.
getParent Get a reference to the Xrm.Page.data.entity object that is the parent to all attributes.
getRequiredLevel Returns a string value indicating whether a value for the attribute is required or recommended.
getSubmitMode Sets whether data from the attribute will be submitted when the record is saved. always / never / dirty
getUserPrivilege Determine what privileges a user has for fields using Field Level Security.
getValue / setValue Gets or Sets the data value for an attribute.
setRequiredLevel Sets whether data is required or recommended for the attribute before the record can be saved. none / required / recommended
setSubmitMode Returns a string indicating when data from the attribute will be submitted when the record is saved.
Number Attribute Methods
getMax / getMin Returns a number indicating the maximum or minimum allowed value for an attribute.
getPrecision Returns the number of digits allowed to the right of the decimal point.
setPrecision* Override the precision set for a number attribute.
DateTime Attribute Methods
setIsAllDay* Specify whether a date control should set a value including the entire day.
setShowTime* Specify whether a date control should show the time portion of the date.

  • Controls: Controls represent the user interface elements in the form. Each attribute in the form will have at least one control associated with it. Not every control is associated with an attribute. IFRAME, web resource, and subgrids are controls that do not have attributes. Controls are available from the Xrm.Page.ui.controls collection. To access a control you can use the Xrm.Page.ui.controls.get method or the shortcut version Xrm.Page.getControl. 


Xrm.Page.getControl(“…”)
clearNotification* Remove a message already displayed for a control.
getAttribute Get the attribute that the control is bound to.
getControlType Get information about the type of control.
getDisabled / setDisabled Get or Set whether the control is disabled.
getLabel / setLabel Get or Set the label for the control.
getName Get the name of the control.
getParent Get the section object that the control is in.
getVisible / setVisible Get or Set a value that indicates whether the control is currently visible.
setFocus Sets the focus on the control.
setNotification* Display a message near the control to indicate that data is not valid.

  • Lookup Controls: The following table lists the functions of Lookup Control.


addCustomFilter* Use fetchXml to add additional filters to the results displayed in the lookup. Each filter will be combined with an ‘AND’ condition.
addCustomView Adds a new view for the lookup dialog box.
addPreSearch* Use this method to apply changes to lookups based on values current just as the user is about to view results for the lookup.
getDefaultView / setDefaultView Get or Set Id value of the default lookup dialog view.
removePreSearch* Use this method to remove event handler

  • OptionSet: The following table lists the functions of OptionSet Control.


getInitialValue Returns a value that represents the value set for an optionset or boolean when the form opened.
getOption[s] Returns an option object with the value matching the argument passed to the method.
getSelectedOption Returns the option object that is selected.
getText Returns a string value of the text for the currently selected option for an optionset attribute.
adoption / removeOption Adds or remove an option to an option set control.
clearOptions Clears all options from an Option Set control.


  • IFRAME and Web Resource Controls: An IFRAME control allows you to include a page within a form by providing a URL. An HTML web resource added to a form is presented using an IFRAME element. Silverlight and image web resources are embedded directly within the page. The following table lists the functions of IFrame or Web Resource controls.


getData / setData Get or Set the value of the data query string parameter passed to a Silverlight web resource.
getInitialUrl Returns the default URL that an I-frame control is configured to display. This method is not available for web resources.
getObject Returns the object in the form that represents an I-frame or web resource.
getSrc / setSrc Get or Set the current URL being displayed in an IFrame or web resource.


  • Sub-Grid Control: Sub-Grid control has refresh method. We can use this method to refresh data displayed in a Sub-Grid.


refresh Refreshes the data displayed in a Sub-Grid.


  • OnChange Event: There are three methods you can use to work with the OnChange event for an attribute.


addOnChange / removeOnChange Sets or remove a function to be called when the attribute value is changed.
fireOnChange Causes the OnChange event

Tuesday 23 June 2015

Debug CRM plugin using profiler Dynamic CRM

 Plugin Registration Tool


  1. From the plugin registration tool, click the Install Profiler.
    
   2. Once it finished, make sure Plugin Profiler exists.


   3.  Select the plugin step needed to debug, click Profiler to enable profiling.



 4. In the CRM system, perform the account creation which will trigger the plugin to be execute.        Download the error log file and save it.


 5. Run the visual studio solution, attach debug process named "PluginRegistration". Set a break point in the code.


 6. Open the plugin registration tool, click the Debug button


 7. Browse the profile location with the erro log we downloaded . Choose the assembly location and click start plugin execution.


 8. System will auto step into visual studio breakpoint line







Plugin to get Order-details using QueryExpression - Microsoft Dynamics CRM

  //Setup query to get all sales order details

  QueryExpression q = new QueryExpression();
   q.EntityName = "salesorderdetail";
    ColumnSet cSet = new ColumnSet(new string[] { "salesorderdetailid", "quantity", "productid" });
     q.ColumnSet = cSet;
    ConditionExpression con1 = new ConditionExpression("salesorderid", ConditionOperator.Equal, SalesOrderID.ToString());
    FilterExpression filter = new FilterExpression();
    filter.Conditions.Add(con1);
    q.Criteria = filter;
     RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();
     retrieve.Query = q;

     //Get the response
    RetrieveMultipleResponse response = (RetrieveMultipleResponse)service.Execute(retrieve);