Wednesday, September 17, 2014

Setting value in ms crm

I have seen many question in MS CRM Development where Consultant asking for MS CRM 2011 data type related question, like how to set lookup field, how to set/retrieve optionset value. so I thought to write code to show how we can set different data type field in MS CRM 2011.

Below is the example to create account using late bound

Entity _Account = new Entity();
_Account.LogicalName = “account”;
//setting text field
_Account.Attributes.Add(“name”, “Myaccount123″);

//setting optionset field
_Account.Attributes.Add(“accountcategorycode”, new OptionSetValue(2));

//setting datetime field
_Account.Attributes.Add(“new_collectiondate”, new DateTime(2012, 3, 25));

//setting currency field
_Account.Attributes.Add(“creditlimit”, new Money(300));

//setting lookup
_Account.Attributes.Add(“parentaccountid”, new EntityReference(“account”, new Guid(“XXX-XXX……..”)));

//setting decimal
_Account.Attributes.Add(“new_executivecommission”, new Decimal(55.5));

//setting boolean
_Account.Attributes.Add(“new_isbilled”, true);

service.Create(_Account);

Retrieve MS CRM fields using late bound

In this post I am going to Show how can we fetch value from different data type fields.



Entity _Account = service.Retrieve(“account”, new Guid(“XXXXX”), new ColumnSet(new string[] { “name”, “accountcategorycode”, “new_collectiondate”, “creditlimit”, “parentaccountid”, “new_executivecommission”, “new_isbilled” }));

//To fetch string value
string Name = _Account["name"].ToString();

//To fetch optionset selected value
int OptionSetValue = ((OptionSetValue)_Account["accountcategorycode"]).Value;

//To fetch date time field value
DateTime CollectionDate = ((DateTime)_Account["new_collectiondate"]).Date;

//To fetch money field value
decimal Creditlimit = ((Money)_Account["creditlimit"]).Value;

//To fetch decimal field value
decimal Executivecommission = (decimal)_Account["new_executivecommission"];

//To fetch lockup field
Guid ParentAccountID = ((EntityReference)_Account["parentaccountid"]).Id;

//To fetch Boolean field

Boolean IsBilled=(Boolean)_Account["new_isbilled"];

Tuesday, September 9, 2014

MS CRM 2011 Entity Images

PreEntityImages :(Gets the properties of the primary entity before the core platform operation has begins)

PreEntityImages used to capture the data when the form loads. That is the data which is present by default when the form loads.  The syntax for using the PreEntityImages in CRM 2011 is changed as compared to CRM 4.0.

Note:The PreEntityImages cannot be registered for “create” operation.

Syntax Used in CRM 2011 :
=======================

Suppose you registered the Plugin and added a Image with name “PreImage ”

public EntityImageCollection PreEntityImages { get;}
PostEntityImages : (Gets the properties of the primary entity after the core platform operation has been completed. )

The PostEntityImages contains the attributes value which are finally changed. We can capture the changed data before the database operation takes place. And can do any kind of validation based on the changed data.

Note: PostEntityImages can only be registered  for Update message and cannot be registered on Create message.

Syntax Used in CRM 2011 :

Suppose you registered the Plugin and added a Image with name “PostImage ”

Syntax:
=========

public EntityImageCollection PostEntityImages { get; }


Monday, June 9, 2014

Workflow solution creation , registration and usage in CRM2011

In this blog I would like to explain some practical steps about the Workflow lifecycle in CRM 2011.
The steps includes 
1. Creation of the workflow solution ( C# solution ) and generation of the assembly 

2. Registering the workflow assembly for CRM usage3. Using the workflow assembly in CRM 


1. Creation of the workflow solution and generation of the assembly 

The workflow can be defined as group of activities that performs the required process.+


a) Creating the activities of the Workflow steps in the C# solution  Workflow activities are defined in the System.Activities.dll of .NETFramework, so we need to add this dll to the workflow solution.


Define the Class : The workflow activities that are used in CRM are derived from the "CodeActivity" base class. so define the workflow activity class derived from the "CodeActivity" class.    

eg : public class Sampleworkflow : CodeActivity {} Override the abstract methods of the CodeActivity class :
Execute() Method: 
CodeActivity class declares the Execute()  method as the abstract method. All the derived classes should define the execute() method in the derived classes i.e in the workflow activity classes.    eg: protected override void Execute(CodeActivityContext executionContext)
Some common attributes and code useful in the execute() method are:
1. IWorkflowContext (defined in Microsoft.Xrm.Sdk.Workflow.dll)  which is derived from the IExecutionContext:  contains the details about the CRM attributes and parameters that can be used in the workflow execution. we can get the IWorkflowContext as follows    IWorkflowContext context = executionContext.GetExtension();
    Using the IWorkflowContext , we can obtains the CRM context values like  current records GUID, , Current User's Guid, OrganizationName, OrganizationId etc., as follows:     getting the current record Guid : WorkflowContext.PrimaryEntityId;    getting the current Usee Guid : WorkflowContext.UserId;   
2. Organization Service and Organization Service Factory:    To execute any CRM SDK API's, we need to have the organization service or OrganizationServiceProxy. These objects can be created after getting the IOrganizationServiceFactory  object from the CodeActivityContext  and then by creating the service/serviceproxy by sending the user Guid to the Service factor        IOrganizationServiceFactory serviceFactory = executionContext.GetExtension();                     IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);
How to define and extract the Input and Output parameters required in the Workflow execution:  Defining the parameters: The input and output parameters for the workflow activity can be defined in the workflow activity class as follows:           a) String data type as input                  [Input("Account ID")]                  [Default("0")]                  public InArgument AccountName { get; set; }

Accessing the parameters : Input and output parameters can be obtained from the CodeActivityContext class passed to the execute() method.            string accountName = AccountName.Get(executionContext);           Where executionContext is the argument of type CodeActivityContext for the function execute()         b) Entity Reference type as input                    [Input("EntityReference input")]                    [ReferenceTarget()]                    [Default(, )]                    public InArgument  { get; set; }
        This data type can be accessed and assigned to the local variable of type Guid, within the execute() function as :                 Guid localGuid = (.Get(executionContext)).Id;
 After defining the execute() method with the required functionality for the workflow activity, compile and generate the workflow dll. 
This dll needs to be registered with the CRM. The steps that are to be followed for workflow registration into CRM 2011 will be available in my next blog on  Registering the workflow assembly for CRM usage

Sunday, June 8, 2014

Associate two records



using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;


namespace AssociatedLeadEmail_WF
{
    public class AssociatedLeadEmail_WF : CodeActivity
    {
        #region Set the input mandatory parameters.
        //Input Value of Associated Lead Record
        [RequiredArgument]
        [Input("Email Send")]
        [ReferenceTarget("cdi_emailsend")]
        public InArgument<EntityReference> EmailSend { get; set; }

        [RequiredArgument]
        [Input("Lead")]
        [ReferenceTarget("lead")]
        public InArgument<EntityReference> Lead { get; set; }

        [Output("Success")]
        public OutArgument<bool> Success { get; set; }

        #endregion

        protected override void Execute(CodeActivityContext context)
        {
            //Create the tracing service
            ITracingService tracingService = context.GetExtension<ITracingService>();
            //Create the context
            IWorkflowContext workFlowContext = context.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(workFlowContext.UserId);


            string str_EmailSend = this.EmailSend.Get(context) == null ? Guid.Empty.ToString() : this.EmailSend.Get(context).Id.ToString();
            string str_lead = this.Lead.Get(context) == null ? Guid.Empty.ToString() : this.Lead.Get(context).Id.ToString();
            try
            {
                Microsoft.Xrm.Sdk.EntityReference Moniker2 = new Microsoft.Xrm.Sdk.EntityReference();
                Moniker2.Id = Lead.Get(context).Id;
                Moniker2.LogicalName = "lead";//Entity Name

                // Code Create Moniker for second Entity: New_CustomEntity
                Microsoft.Xrm.Sdk.EntityReference Moniker1 = new Microsoft.Xrm.Sdk.EntityReference();
                Moniker1.Id = EmailSend.Get(context).Id;
                Moniker1.LogicalName = "cdi_emailsend";
                tracingService.Trace("Started Assosiating");
                AssociateManyToManyEntityRecords(service, Moniker1, Moniker2, "cdi_emailsend_lead");


            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message.ToString());
                //tracingService.Trace("Exception" + ex.Message.ToString());
                this.Success.Set(context, false);
                //return;
            }
        }

        private bool AssociateManyToManyEntityRecords(IOrganizationService service, Microsoft.Xrm.Sdk.EntityReference moniker1, Microsoft.Xrm.Sdk.EntityReference moniker2, string strEntityRelationshipName)
        {
            try
            {
                AssociateRequest request = new AssociateRequest();
                request.Target = moniker1;
                request.RelatedEntities = new EntityReferenceCollection { moniker2 };
                request.Relationship = new Relationship(strEntityRelationshipName);

                // Execute the request.
                service.Execute(request);


                return true;
            }
            catch (Exception exp)
            {
                return false;
            }
        }

    }
}

Send Template Email

The Send Template Email custom workflow activity will search for Template Records where the Lead Source and Lead Sub-Source are match the Source and Sub-Source from the designated lead, or are null. Using the email template specified on the Template Record, the custom workflow activity will create an email from the template and send it to the lead

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Activities;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Workflow;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Metadata;


namespace LeadTemplate_WF
{
    public class LeadTemplate_WF : CodeActivity
    {
        #region Set the input mandatory parameters.
        //Input Value of Template Record
        [RequiredArgument]
        [Input("new_leadorigin")]
        [ReferenceTarget("sbi_leadorigin")]
        public InArgument<EntityReference> LeadOrgin { get; set; }

        [RequiredArgument]
        [Input("new_leadsuborigin")]
        [ReferenceTarget("sbi_leadsuborigin")]
        public InArgument<EntityReference> LeadSubOrgin { get; set; }

        [Output("Notes")]
        public OutArgument<String> Notes { get; set; }

        [Output("Success")]
        public OutArgument<bool> Success { get; set; }

        [Output("From Address")]
        public OutArgument<String> FromAddress { get; set; }

        [Output("ClickDimensions Email Template")]
        [ReferenceTarget("cdi_emailtemplate")]
        public OutArgument<EntityReference> ClickDimensionsEmailTemplate { get; set; }

        #endregion

        protected override void Execute(CodeActivityContext context)
        {
            //Create the tracing service
            ITracingService tracingService = context.GetExtension<ITracingService>();
            //Create the context
            IWorkflowContext workFlowContext = context.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(workFlowContext.UserId);


            string strLeadOrgin = this.LeadOrgin.Get(context) == null ? Guid.Empty.ToString() : this.LeadOrgin.Get(context).Id.ToString();
            string strLeadSubOrgin = this.LeadSubOrgin.Get(context) == null ? Guid.Empty.ToString() : this.LeadSubOrgin.Get(context).Id.ToString();

            const String FetchTemplateRecord = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
  <entity name='new_templaterecord'>
    <attribute name='new_templaterecordid' />
    <attribute name='new_name' />
    <attribute name='new_leadsuborigin' />
    <attribute name='new_leadorigin' />
    <attribute name='new_template' />
    <attribute name='new_templatesource' />
    <order attribute='new_leadorigin' descending='true' />
    <order attribute='new_leadsuborigin' descending='true' />
    <filter type='and'>
      <condition attribute='new_templatetype' operator='eq' value='100000000' />
      <condition attribute='new_template' operator='not-null' />
      <filter type='or'>
        <filter type='and'>
          <condition attribute='new_leadorigin' operator='eq' uitype='sbi_leadorigin' value='{0}' />
          <filter type='or'>
            <condition attribute='new_leadsuborigin' operator='eq' uitype='sbi_leadsuborigin' value='{1}' />
            <condition attribute='new_leadsuborigin' operator='null' />
          </filter>
        </filter>
        <condition attribute='new_leadorigin' operator='null' />
      </filter>
    </filter>
  </entity>
</fetch>";
            // Team Query 
            const String FetchTeam = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
                                                              <entity name='team'>
                                                                <attribute name='name' />
                                                                <attribute name='businessunitid' />
                                                                <attribute name='teamid' />
                                                                <attribute name='teamtype' />
                                                                <attribute name='queueid' />
                                                                 <attribute name='emailaddress' />
                                                                <order attribute='name' descending='false' />
                                                                <filter type='and'>
                                                                  <condition attribute='teamtype' operator='eq' value='0' />
                                                                </filter>
                                                                <link-entity name='businessunit' from='businessunitid' to='businessunitid' alias='ae'>
                                                                  <link-entity name='lead' from='owningbusinessunit' to='businessunitid' alias='af'>
                                                                    <filter type='and'>
                                                                      <condition attribute='leadid' operator='eq' uitype='lead' value='{0}' />
                                                                    </filter>
                                                                  </link-entity>
                                                                </link-entity>
                                                              </entity>
                                                            </fetch>";


            try
            {
                tracingService.Trace("Retrieving the Template Record");

                FetchExpression fetchQuerytoRetrieveTemplateRecord = new FetchExpression(String.Format(FetchTemplateRecord, strLeadOrgin, strLeadSubOrgin));
                //tracingService.Trace("Retrieving " + fetchQuerytoRetrieveTemplateRecord);

                // Retrive Business Unit’s Team 
                FetchExpression fetchQuerytoRetrieveTeam = new FetchExpression(String.Format(FetchTeam, strLeadOrgin));

                var aa = service.RetrieveMultiple(fetchQuerytoRetrieveTemplateRecord);

                var bb = service.RetrieveMultiple(fetchQuerytoRetrieveTeam);

                if (aa.Entities.Count > 0)
                {
                    // tracingService.Trace("Entity count " + aa.Entities.Count);
                    Entity TemplateRecordObj = aa.Entities[0];

                    string strtitle = TemplateRecordObj.Attributes.Contains("new_name") ? TemplateRecordObj.Attributes["new_name"].ToString() : "No Name found";
                    //tracingService.Trace("strtitle " + strtitle.ToString());
                    Guid TempalteID = Guid.Empty;

                    string TempID = TemplateRecordObj.Attributes.Contains("new_template") ? TemplateRecordObj.Attributes["new_template"].ToString() : "Test Guid";
                    //tracingService.Trace("strTempID " + TempID.ToString());


                    if (Guid.TryParse(TemplateRecordObj.Attributes["new_template"].ToString(), out TempalteID) && TemplateRecordObj.Contains("new_templatesource"))
                    {
                        switch (((OptionSetValue)TemplateRecordObj["new_templatesource"]).Value)
                        {
                            case 100000001://CRM Email Template
                                tracingService.Trace("Sending emails");
                                InstantiateTemplateRequest req = new InstantiateTemplateRequest();
                                req.ObjectId = workFlowContext.PrimaryEntityId;
                                req.ObjectType = workFlowContext.PrimaryEntityName;
                                req.TemplateId = TempalteID;

                                InstantiateTemplateResponse resp = (InstantiateTemplateResponse)service.Execute(req);

                                Entity tmpEmail = new Entity("email");

                                if (resp.EntityCollection != null && resp.EntityCollection.Entities.Count > 0)
                                {
                                    tmpEmail = resp.EntityCollection.Entities[0];
                                }
                                List<Entity> toParty = new List<Entity>();
                                Entity tempParty = new Entity("activityparty");
                                tempParty["partyid"] = new EntityReference(workFlowContext.PrimaryEntityName, workFlowContext.PrimaryEntityId);
                                toParty.Add(tempParty);
                                tmpEmail.Attributes["to"] = toParty.ToArray();

                                tmpEmail.Attributes["regardingobjectid"] = new EntityReference(workFlowContext.PrimaryEntityName, workFlowContext.PrimaryEntityId);

                                service.Create(tmpEmail);

                                SendEmailRequest sendReq = new SendEmailRequest();
                                sendReq.EmailId = tmpEmail.Id;
                                sendReq.TrackingToken = "";
                                sendReq.IssueSend = true;
                                SendEmailResponse res = (SendEmailResponse)service.Execute(sendReq);

                                // Set the Output Parameters
                                this.Success.Set(context, true);
                                this.Notes.Set(context, strtitle);
                                this.ClickDimensionsEmailTemplate.Set(context, null);
                                this.FromAddress.Set(context, null);
                                break;

                            case 100000000://ClickD Email Template
                                this.ClickDimensionsEmailTemplate.Set(context, new EntityReference("cdi_emailtemplate", TempalteID));
                                if (bb.Entities.Count > 0)
                                {
                                    Entity TeamObj = bb.Entities[0];
                                   // string str_queuename = TeamObj.Attributes.Contains("name") ? TeamObj.Attributes["name"].ToString() : "No Queue Name Found";
                                    string str_emailaddress = TeamObj.Attributes.Contains("emailaddress") ? TeamObj.Attributes["emailaddress"].ToString() : "No Email Address Found";
                                    this.FromAddress.Set(context, str_emailaddress);
                                }
                                break;
                        }

                    }

                }
            }
            catch (Exception ex)
            {
                //throw new Exception(ex.Message.ToString());
                //tracingService.Trace("Exception" + ex.Message.ToString());
                this.Notes.Set(context, ex.Message.ToString());
                //return;
            }
        }
    }

}

Ribbon and UI Customizations


Email Template Selector

On the form ribbon of the Template Record add a flyout to display a list of Email Templates for leads. On click of a button in the flyout, set the Template field to the id of the specified Email Template. The flyout should be enabled only for existing, editable records.


Code:
/************************************************
populateArticles - function to populate a button
on the ribbon with the available disclaimers
Policy is 1
************************************************/
function PopulateArticles1(CommandProperties) {

    var serverUrl = Xrm.Page.context.getClientUrl();
    var requestUrl = serverUrl + "/xrmservices/2011/OrganizationData.svc/cdi_emailtemplateSet?$select=cdi_emailtemplateId,cdi_name&$filter=statecode/Value eq 0";
    
    $.ajax({
        type: "GET",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        async: false,
        url: requestUrl,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.             
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            var engines = data.d["results"];

            var theXml = '<Menu Id=\"Columbus.new_templaterecord.ClickDimensionButton\"><MenuSection Id=\"Columbus.new_templaterecord.ClickDimensionButton.Section\" Sequence=\"10\"><Controls Id=\"Columbus.new_templaterecord.ClickDimensionButton.Controls\">';
            var i = 0;
            for (engineKey in engines) {
                theXml += '<Button Id=\"' + engines[engineKey].cdi_emailtemplateId + "||" + engines[engineKey].cdi_name + '\" Command=\"new.new_templaterecord.ClickDimensionEmailTemplate.Command\" Sequence=\"' + ((i + 1) * 10).toString() + '\" LabelText=\"' + engines[engineKey].cdi_name + '\" />';
                i++;
            }
            theXml += '</Controls></MenuSection></Menu>';
            //prompt("the xml", theXml);
            CommandProperties.PopulationXML = theXml;

        },
        error: function (XmlHttpRequest, textStatus, errorThrown) {
            alert(XmlHttpRequest.status + "\n" + textStatus + "\n" + errorThrown);
        }
    });
}
/***  end populateArticles    ***/


/************************************************
openKbArticle - function to append a specific
disclaimer to the field
************************************************/
function openKbArticle1(CommandProperties) {
    var controlId = CommandProperties.SourceControlId;
   // alert(controlId);
    Xrm.Utility.openEntityForm("kbarticle", controlId);
}


function MainAlert1(CommandProperties) {
    var controlId = CommandProperties.SourceControlId;
var Tem_Type='100000000';
if(controlId != null)
{
var str_array = controlId.split('||');
for (var i = 0; i < str_array.length; i++) {
            // Trim the excess whitespace.
            str_array[i] = str_array[i].replace(/^\s*/, "").replace(/\s*$/, "");
        }
controlId=str_array[0];
var name=str_array[1];
    Xrm.Page.getAttribute("new_template").setValue(controlId);
Xrm.Page.getAttribute("new_name").setValue(name);
Xrm.Page.getAttribute("new_templatesource").setValue(Tem_Type);
}
else
{
 alert("Please Select the Template!");
 return;
}
}
/***   end openKbArticle   ***/

Thursday, May 15, 2014

Useful Javascript which is used Frequently in MS CRM.


1.  Get the GUID value of a lookup field:
Note: this example reads and pops the GUID of the primary contact on the Account form
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:
Note: this example reads and pops the name of the primary contact on the Account form
function AlertText() {
    var primaryContactName = Xrm.Page.data.entity.attributes.get("primarycontactid").getValue()[0].name;
    alert(primaryContactName);
}
3.  Get the value of a text field:
Note: this example reads and pops the value of the Main Phone (telephone1) field on the Account form
function AlertTextField() {
    var MainPhone = Xrm.Page.data.entity.attributes.get("telephone1").getValue();
    alert(MainPhone);
}
4.  Get the database value of an Option Set field:
Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form
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:
Note: this example reads and pops the value of the Address Type (address1_addresstypecode) field on the Account form
function AlertOptionSetDisplayValue() {
   var AddressTypeDisplayValue = Xrm.Page.data.entity.attributes.get("address1_addresstypecode").getText();
    if (AddressTypeDisplayValue != null) {
        alert(AddressTypeDisplayValue);
    }
}
6.  Get the database value of a Bit field:
// example GetBitValue("telephone1");
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
// example GetDate("createdon");
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:
Note: this example sets the Account Name field on the Account Form to “ABC”
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:
Note: here I am providing a reusable function…
// 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");
}
15.  Split a Full Name into First Name and Last Name fields:
function PopulateNameFields() {
    var ContactName = Xrm.Page.data.entity.attributes.get("customerid").getValue()[0].name;
    var mySplitResult = ContactName.split(" ");
    var fName = mySplitResult[0];
    var lName = mySplitResult[1];
    Xrm.Page.data.entity.attributes.get("firstname").setValue(fName);
    Xrm.Page.data.entity.attributes.get("lastname").setValue(lName);
}
16.  Set the Requirement Level of a Field:
Note: this example sets the requirement level of the Address Type field on the Account form to Required. 
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();
34.  Change the default entity in the lookup window of a Customer or Regarding field:
Note: I am setting the customerid field’s lookup window to offer Contacts (entityid 2) by default (rather than Accounts). I have also hardcoded the GUID of the default view I wish displayed in the lookup window.
function ChangeLookup() {
    document.getElementById("customerid").setAttribute("defaulttype", "2");
    var ViewGUID= "A2D479C5-53E3-4C69-ADDD-802327E67A0D";
    Xrm.Page.getControl("customerid").setDefaultView(ViewGUID);
}
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);
}
39.  Pop a new CRM record with default values (old approach):
Note: this example pops the Case form from the Phone Call form, defaulting the Case’s CustomerID based on the Phone Call’s SenderID and defaulting the Case Title to “New Case”
//Collect values from the existing CRM form that you want to default onto the new record
var CallerGUID = Xrm.Page.data.entity.attributes.get("from").getValue()[0].id;
var CallerName = Xrm.Page.data.entity.attributes.get("from").getValue()[0].name;

//Set the parameter values
var extraqs = "&title=New Case";
extraqs += "&customerid=" + CallerGUID;
extraqs += "&customeridname=" + CallerName;
extraqs += "&customeridtype=contact";

//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);
}

//Pop the window
window.open(serverUrl + "/main.aspx?etn=incident&pagetype=entityrecord&extraqs=" + encodeURIComponent(extraqs), "_blank", features, false);
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");
    }
}


46.  Alert Dialog
This function takes in two parameters:
message: The message you wish to display in the alert.
onCloseCallBack: A function to execute when the user clicks on OK or closes the alert window using the X button.

The following code will display an alert and then will set the First Name field of a Contact to “Frosty” when the user clicks on OK.
CRM2013.showAlert = function () {
    Xrm.Utility.alertDialog("This will set the First Name to 'Frosty'", function () {
        Xrm.Page.getAttribute("firstname").setValue("Frosty");
    });
}

47.  Confirm Dialog
This function takes in three parameters:
message: The message you wish to display in the alert.
yesCloseCallback: A function to execute when the user clicks on Yes.
noCloseCallback: A function to execute when the user clicks on Cancel.




The following code will prompt the user to confirm if they want to save the form. If they select Yes, the form will save. If they select Cancel, the Email Address field will have focus set.
CRM2013.showConfirmation = function () {
    Xrm.Utility.confirmDialog("Are you sure you want to save this record?",
        function () {
      Xrm.Page.data.entity.save();
        },
        function () {
            Xrm.Page.getControl("emailaddress1").setFocus();
    });
}







Get files of last hour in Azure Data Factory

  Case I have a Data Factory pipeline that should run each hour and collect all new files added to the data lake since the last run. What is...