101 Code Snippet Dynamics CRM

101 Most Used Dynamics 365 CRM code snippets

Here is a list of most used code snippet used in Dynamics 365 CRM.Remember to add required namespace whenever required while inserting code. Keep the CRM SDK folder ready to take the reference of the assemblies for below namespace.

Most frequently used namespaces are given below,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
using System;
using System.Configuration;
using System.ServiceModel;
// These namespaces are found in the Microsoft.Crm.Sdk.Proxy.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Crm.Sdk.Messages;
// These namespaces are found in the Microsoft.Xrm.Sdk.dll assembly
// located in the SDK\bin folder of the SDK download.
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Tooling.Connector;
// These namespaces are found in the Microsoft.Xrm.Client.dll assembly
// located in the SDK\bin folder of the SDK download.
using System.Collections.Generic;

Most frequently used code snippets are given below,

  1. Code to connect Organization (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    String userName = "<UserName>";
    String userPwd = "<Password>";
    String userDomain= "<Domain>";
    String crmServer = "<Server>";
    String crmPort = "<Port>;";
    String crmOrg = "<OrgName>";
    String homeRealm = "<HomeRealm>";
    NetworkCredential netCred =
    new  System.Net.NetworkCredential(userName, userPwd, userDomain, homeRealm);
    CrmServiceClient  crmSvc =
    new CrmServiceClient(netCred, crmServer, crmPort, crmOrg);
  2. Derive Context, CRM service object in Plugin (C#)

    1
    2
    3
    4
    5
    6
    IPluginExecutionContext context =
    (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext));
    IOrganizationServiceFactory serviceFactory =
    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService Service =
    ServiceFactory.CreateOrganizationService(context.UserId);
  3. Validate if a specific attribute present in the plugin context input parameter (C#)

    1
    2
    3
    4
    if (context.InputParameters.Contains("Target") &&  Context.InputParameters["Target"] is Entity)
    {
     //Your code goes here
    }

    [/cc]

  4. Check if a specific attribute present in a entity (C#)

    1
    2
    3
    4
    if (entityObject.Attributes.ContainsKey("<attributename>")
    {
    //Your code goes here
    }
  5. Get Value of attribute from entity (C#)

    1
    2
    3
    4
    entityObject.GetAttributeValue<OptionSetValue>("<attributeName>");
    entityObject. GetAttributeValue <EntityReference> ("<attributename>").Id.ToString();
    bool myAttributeVal  = entityObject.GetAttributeValue<bool>("<attributename>")
    string myAttributeVal  = entityObject.GetAttributeValue<string>("<attributename>")
  6. Convert EntityCollection to DataTable (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    public DataTable convertEntityCollectionToDataTable(EntityCollection EC)
    {
    DataTable dt = new DataTable();
    int totalCount = EC.Entities.Count;
    for (int i = 0; i < totalCount; i++)
    {
    DataRow row = dt.NewRow();
    Entity myEntity = (Entity)EC.Entities[i];
    var keys= myEntity.Attributes.Keys;
    foreach (var item in keys)
    {
    string columnName = item;
    string value = getValuefromAttribute(myEntity.Attributes[item]);
    if (dt.Columns.IndexOf(columnName) == -1)
    {
    dt.Columns.Add(item, Type.GetType("System.String"));
    }
    row[columnName] = value;
    }
    dt.Rows.Add(row);
    }
    return dt;
    }
    private string getValuefromAttribute(object p)
    {
    if (p.ToString() == "Microsoft.Xrm.Sdk.EntityReference")
    {
    return ((EntityReference)p).Name;
    }
    if (p.ToString() == "Microsoft.Xrm.Sdk.OptionSetValue")
    {
    return ((OptionSetValue)p).Value.ToString();
    }
    if (p.ToString() == "Microsoft.Xrm.Sdk.Money")
    {
    return ((Money)p).Value.ToString();
    }
    if (p.ToString() == "Microsoft.Xrm.Sdk.AliasedValue")
    {
    return ((Microsoft.Xrm.Sdk.AliasedValue)p).Value.ToString();
    }
    else{
    return p.ToString();
    }
    }
  7. Check if dataset is valid (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    bool flag=false;
    if(Objdataset.Tables.Count>0)
    {
    if(Objdataset.Tables[0].Rows.Count>0)
    {
    Flag=true;
    }
    }
  8. Retrieve Optionset Value from an AliasedValue (C#)

    1
    2
    3
    4
    AliasedValue aliasedval=
    entityObject.GetAttributeValue< AliasedValue >("<aliasedAttributeName>").Value;
    int optionSetVal = ((OptionSetValue) aliasedval).Value;
    //<strong>NOTE</strong>: for other datatypes just use the datatype in above line of code to get the value.
  9. Code to stop Plugin from infinite loop (C#)

    1
    2
    3
    // add this code before your actual plugin logic starts
    if (context.Depth >1)
    return;
  10. Code to use Shared Variable in Plugins (C#)

    1
    2
    3
    4
    //Set the shared variable Value
    context.SharedVariables.Add("PrimaryContact", (Object)contact.ToString());
    //Get the Shared Variable Value
    Guid contact =new Guid((string)context.SharedVariables["PrimaryContact"]);
  11. Get the Pre & Post Entity Images in Plugin (C#)

    1
    2
    3
    Entity preEntityImage= (Entity)context.PreEntityImages["ImageName"];
    Entity postEntityImage = (Entity)context.PostEntityImages["ImageName"];
    //<strong>NOTE :</strong> The Image Names are defined in Plugin registration tool against the SDK steps.
  12. Trace Messages using Tracing service in Plugin (C#)

    1
    2
    3
    ITracingService tracingService =
    (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    tracingService.Trace ("<Your Message>");
  13. Get Optionset Text in Plugin (C#)

    1
    2
    3
    4
    if(entity.Contains("<attributename>"))
    {
    string optionsettext = entity.FormattedValues["attributename"];
    }
  14. Retrieve entity record data using Query Expression(C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    //Query for the GUID of the Account using Account Name
    QueryExpression query = new QueryExpression("account");
    string[] cols = { "accountid", "name"};
    query.Criteria = new FilterExpression();
    query.Criteria.AddCondition("name", ConditionOperator.Equal, <targetaccountName>);
    query.ColumnSet = new ColumnSet(cols);
    EntityCollection account = crmServices.RetrieveMultiple(query);
    //Casting the reference to GUID
    Guid accountId = (Guid)account[0].Attributes["accountid"];
  15. Retrieve entity record data using Fetch XML(C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    string fetchxml = @"<fetch mapping='logical'>
    <entity name='account'>
    <attribute name='accountid'/>
    <attribute name='name'/>
    <link-entity name='systemuser' to='owninguser'>
    <filter type='and'>
    <condition attribute='lastname' operator='eq' value='Tracy' />
    </filter>
    </link-entity>
    </entity>
    </fetch> "
    ;
    EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(fetchxml));
  16. Retrieve entity record data using Guid of the record(C#)

    1
    2
    ColumnSet cs = new ColumnSet("attribute1","attribute2");
    Entity result = _serviceProxy.Retrieve ("<EntityName>", new Guid("<Record Guid>"), cs);
  17. Update Entity Record (C#)

    1
    2
    3
    4
    5
    6
    7
    Entity entityObj = new Entity();
    entityObj.LogicalName = "<entityname>";
    entityObj.Id = <GUid>
    entityObj.<AttributeName> = <Value>
    crmservice.Update(entityObj);

    <strong>//Note</strong>: While assigning the value use the correct datatype converison. Lets say you are updating an //optionset then you have to use <strong>new OptionSetValue(<Value>).</strong>
  18. Delete Entity Record (C#)

    1
    crmservice.Delete("<entityname>",new Guid("<GUid>"));
  19. Create an Entity Record using CRM service (C#)

    1
    2
    3
    4
    5
    Entity entityObj = new Entity();
    entityObj.LogicalName = "<entityname>";
    entityObj.<AttributeName1> = <Value1>;
    entityObj.<AttributeName2> = <Value2>;
    crmservice.Create(entityObj);
  20. Retrieve record using paging if more record present (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    // The number of records per page to retrieve.
    int queryCount = 200;
    // Initialize the page number.
    int pageNumber = 1;
    // Initialize the number of records.
    int recordCount = 0;

    // Define the condition expression for retrieving records.
    ConditionExpression pagecondition = new ConditionExpression();
    pagecondition.AttributeName = "parentaccountid";
    pagecondition.Operator = ConditionOperator.Equal;
    pagecondition.Values.Add(_parentAccountId);

    // Create the query expression and add condition.
    QueryExpression pagequery = new QueryExpression();
    pagequery.EntityName = "account";
    pagequery.Criteria.AddCondition(pagecondition);
    pagequery.ColumnSet.AddColumns("name", "emailaddress1");

    // Assign the pageinfo properties to the query expression.
    pagequery.PageInfo = new PagingInfo();
    pagequery.PageInfo.Count = queryCount;
    pagequery.PageInfo.PageNumber = pageNumber;

    // The current paging cookie. When retrieving the first page
    // pagingCookie should be null.
    pagequery.PageInfo.PagingCookie = null;
    Console.WriteLine("Retrieving account records in pages...\n");
    Console.WriteLine("#\tAccount Name\t\tEmail Address");
    while (true)
    {
    // Retrieve the page.
    EntityCollection results =_service.RetrieveMultiple(pagequery);
    if (results.Entities != null)
    {
    // Retrieve all records from the result set.
    foreach (Account acct in results.Entities)
    {
    Console.WriteLine("{0}.\t{1}\t{2}", ++recordCount,
    acct.Name, acct.EMailAddress1);
    }
    }
    // Check for more records, if it returns true.
    if (results.MoreRecords)
    {
    Console.WriteLine("\n****************\nPage number {0}\n****************",
    pagequery.PageInfo.PageNumber);
    Console.WriteLine("#\tAccount Name\t\tEmail Address");

    // Increment the page number to retrieve the next page.
    pagequery.PageInfo.PageNumber++;

    // Set the paging cookie to the paging cookie returned from current results.
    pagequery.PageInfo.PagingCookie = results.PagingCookie;
    }
    else
    {
    // If no more records are in the result nodes, exit the loop.
    break;
    }
    }
  21. Get Optionset Values and Text Metadata in CRM (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    var attributeRequest = new RetrieveAttributeRequest
    {
    EntityLogicalName = "entityName",
    LogicalName = "attributeName",
    RetrieveAsIfPublished = true
    };
    var attributeResponse = (RetrieveAttributeResponse)service.Execute(attributeRequest);
    var attributeMetadata = (EnumAttributeMetadata)attributeResponse.AttributeMetadata;

    var optionList = (from o in attributeMetadata.OptionSet.Options
    select new { Value = o.Value, Text = o.Label.UserLocalizedLabel.Label }).ToList();
  22. Update the Status of Records (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    Guid leadId = new Guid("D020F344-A470-E111-B9DA-00155D04DC01");
    SetStateRequest request = new SetStateRequest
    {
    EntityMoniker = new EntityReference("lead", leadId),
    State = new OptionSetValue(2),
    Status = new OptionSetValue(6)
    };
    crmService.Execute(request);
    //NOTE: State : Active/Inactive
  23. Read Excel Sheet Record to Data Set (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    //Use the below namespace first:
    using Excel = Microsoft.Office.Interop.Excel;
    using System.Data;
    //Code to read excel data
    OleDbConnection  conn =
    new OleDbConnection("provider=Microsoft.Jet.OLEDB.4.0;Data Source='c:\\test.xls';Extended Properties=Excel 8.0;");
    OleDbDataAdapter  cmd = new OleDbDataAdapter("select * from [Sheet1$]", conn);
    cmd.TableMappings.Add("Table", "TestTable");
    DataSet DtSet = DataSet();
    cmd.Fill(DtSet);
  24. Supress Duplicate Detection Rule while creating record (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    // Create operation by suppressing duplicate detection
    CreateRequest reqCreate = new CreateRequest();
    reqCreate.Target = account;
    reqCreate.Parameters.Add("SuppressDuplicateDetection", true);
    // NOTE : Change to false to activate the duplicate detection.
    CreateResponse createResponse = (CreateResponse)_service.Execute(reqCreate);
    Guid _dupAccountId = createResponse.id;
    // Retrieve the account containing with its few attributes.
    ColumnSet cols = new ColumnSet(
    new String[] { "name", "accountnumber"});
    Entity retrievedAccount = _service.Retrieve("account", _dupAccountId, cols);
    // Update the existing account with new account number.
    retrievedAccount.AccountNumber = "ACC006";
    // Update operation – update record, if a duplicate is not found.
    UpdateRequest reqUpdate = new UpdateRequest();
    reqUpdate.Target = retrievedAccount;
    reqUpdate["SuppressDuplicateDetection"] = false; // Duplicate detection is activated.
    // Update the account record.
    UpdateResponse updateResponse = (UpdateResponse)_service.Execute(reqUpdate);
  25. Assigning Values to Different DataType Field while creating Record (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    <table width="500">
    <tbody>
    <tr>
    <td width="150"><strong>DataType</strong></td>
    <td width="384"><strong>Example</strong></td>
    </tr>
    <tr>
    <td width="150">Single Line of Text</td>
    <td width="384">account["name"] = Convert.ToString("Microsoft India"); //String</td>
    </tr>
    <tr>
    <td width="150">Option Set</td>
    <td width="384">account["accountcategorycode"] = new OptionSetValue(1); //Int</td>
    </tr>
    <tr>
    <td width="150">Two Options</td>
    <td width="384">account["donotbulkemail"] = false;  //boolean value -true/false</td>
    </tr>
    <tr>
    <td width="150">Image</td>
    <td width="384">entityObj["entityimage"] = File.ReadAllBytes("Images\\144x144.png");</td>
    </tr>
    <tr>
    <td width="150">Whole Number</td>
    <td width="384">account["numberofemployees"] = 50; //int Value</td>
    </tr>
    <tr>
    <td width="150">Floating Point Number</td>
    <td width="384">account["address1_latitude"] = Convert.ToDouble(-0.330); //double</td>
    </tr>
    <tr>
    <td width="150">Decimal Number</td>
    <td width="384">account["attributename"] = Convert.ToDecimal(3.5); //deciaml</td>
    </tr>
    <tr>
    <td width="150">Currency</td>
    <td width="384">account["revenue"] = new Money(50.60); //deciml Value</td>
    </tr>
    <tr>
    <td width="150">Multiple Lines of Text</td>
    <td width="384">account["description"] = Convert.ToString("this is a great acc");</td>
    </tr>
    <tr>
    <td width="150">Date and Time</td>
    <td width="384">account["lastusedincampaign"] = new DateTime(2017,11,23); //yyyy,mm,dd</td>
    </tr>
    <tr>
    <td width="150">Lookup</td>
    <td width="384">account["address1_addressid"] = new EntityReference("address",new Guid("11111111-1111-1111-1111-111111111111")); //32 bit guid</td>
    </tr>
    </tbody>
    </table>
  26. Generate Entity Metadata using C#

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest()
    {
    EntityFilters = EntityFilters.Entity,
    RetrieveAsIfPublished = true
    };

    // Retrieve the MetaData.
    RetrieveAllEntitiesResponse response = (RetrieveAllEntitiesResponse)_serviceProxy.Execute(request);

    // Create an instance of StreamWriter to write text to a file.
    // The using statement also closes the StreamWriter.
    // To view this file, right click the file and choose open with Excel.
    // Excel will figure out the schema and display the information in columns.

    String filename = String.Concat("EntityInfo.xml");
    using (StreamWriter sw = new StreamWriter(filename))
    {
    // Create Xml Writer.
    XmlTextWriter metadataWriter = new XmlTextWriter(sw);

    // Start Xml File.
    metadataWriter.WriteStartDocument();

    // Metadata Xml Node.
    metadataWriter.WriteStartElement("Metadata");


    foreach (EntityMetadata currentEntity in response.EntityMetadata)
    {
    //if (currentEntity.IsIntersect.Value == false)
    if (true)
    {
    // Start Entity Node
    metadataWriter.WriteStartElement("Entity");

    // Write the Entity's Information.
    metadataWriter.WriteElementString("EntitySchemaName", currentEntity.SchemaName);
    metadataWriter.WriteElementString("OTC", currentEntity.ObjectTypeCode.ToString());
    metadataWriter.WriteElementString("OwnershipType", currentEntity.OwnershipType.Value.ToString());
    if (currentEntity.DisplayName.UserLocalizedLabel != null)
    metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocalizedLabel.Label);
    if (currentEntity.DisplayCollectionName.UserLocalizedLabel != null)
    metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocalizedLabel.Label);
    metadataWriter.WriteElementString("IntroducedVersion", currentEntity.IntroducedVersion.ToString());
    metadataWriter.WriteElementString("AutoRouteToOwnerQueue", currentEntity.AutoRouteToOwnerQueue.ToString());
    metadataWriter.WriteElementString("CanBeInManyToMany", currentEntity.CanBeInManyToMany.Value.ToString());
    metadataWriter.WriteElementString("CanBePrimaryEntityInRelationship", currentEntity.CanBePrimaryEntityInRelationship.Value.ToString());
    metadataWriter.WriteElementString("CanBeRelatedEntityInRelationship", currentEntity.CanBeRelatedEntityInRelationship.Value.ToString());
    metadataWriter.WriteElementString("CanCreateAttributes", currentEntity.CanCreateAttributes.Value.ToString());
    metadataWriter.WriteElementString("CanCreateCharts", currentEntity.CanCreateCharts.Value.ToString());
    metadataWriter.WriteElementString("CanCreateForms", currentEntity.CanCreateForms.Value.ToString());
    metadataWriter.WriteElementString("CanCreateViews", currentEntity.CanCreateViews.Value.ToString());
    metadataWriter.WriteElementString("CanModifyAdditionalSettings", currentEntity.CanModifyAdditionalSettings.Value.ToString());
    metadataWriter.WriteElementString("CanTriggerWorkflow", currentEntity.CanTriggerWorkflow.Value.ToString());

    metadataWriter.WriteElementString("IsActivity", currentEntity.IsActivity.Value.ToString());
    //metadataWriter.WriteElementString("ActivityTypeMask", currentEntity.ActivityTypeMask.ToString());

    metadataWriter.WriteElementString("IsActivityParty", currentEntity.IsActivityParty.Value.ToString());

    metadataWriter.WriteElementString("IsAuditEnabled", currentEntity.IsAuditEnabled.Value.ToString());
    metadataWriter.WriteElementString("IsAvailableOffline", currentEntity.IsAvailableOffline.ToString());
    metadataWriter.WriteElementString("IsChildEntity", currentEntity.IsChildEntity.ToString());
    metadataWriter.WriteElementString("IsConnectionsEnabled", currentEntity.IsConnectionsEnabled.ManagedPropertyLogicalName.ToString());
    metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.Value.ToString());
    metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.Value.ToString());

    metadataWriter.WriteElementString("IsDocumentManagementEnabled", currentEntity.IsDocumentManagementEnabled.Value.ToString());
    metadataWriter.WriteElementString("IsDuplicateDetectionEnabled", currentEntity.IsDuplicateDetectionEnabled.Value.ToString());
    if (currentEntity.IsEnabledForCharts != null)
    metadataWriter.WriteElementString("IsEnabledForCharts", currentEntity.IsEnabledForCharts.Value.ToString());
    metadataWriter.WriteElementString("IsImportable", currentEntity.IsImportable.Value.ToString());
    metadataWriter.WriteElementString("IsIntersect", currentEntity.IsIntersect.Value.ToString());

    metadataWriter.WriteElementString("IsMailMergeEnabled", currentEntity.IsMailMergeEnabled.Value.ToString());
    metadataWriter.WriteElementString("IsManaged", currentEntity.IsManaged.Value.ToString());
    metadataWriter.WriteElementString("IsMappable", currentEntity.IsMappable.Value.ToString());

    metadataWriter.WriteElementString("IsReadingPaneEnabled", currentEntity.IsReadingPaneEnabled.Value.ToString());
    metadataWriter.WriteElementString("IsRenameable", currentEntity.IsRenameable.Value.ToString());
    metadataWriter.WriteElementString("IsValidForAdvancedFind", currentEntity.IsValidForAdvancedFind.Value.ToString());
    metadataWriter.WriteElementString("IsValidForQueue", currentEntity.IsValidForQueue.Value.ToString());
    metadataWriter.WriteElementString("IsVisibleInMobile", currentEntity.IsVisibleInMobile.Value.ToString());

    metadataWriter.WriteElementString("PrimaryIdAttribute", currentEntity.PrimaryIdAttribute);
    metadataWriter.WriteElementString("PrimaryNameAttribute", currentEntity.PrimaryNameAttribute);
    metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
    metadataWriter.WriteElementString("RecurrenceBaseEntityLogicalName", currentEntity.RecurrenceBaseEntityLogicalName);
    if (currentEntity.Description.UserLocalizedLabel != null)
    metadataWriter.WriteElementString("Description", currentEntity.Description.UserLocalizedLabel.Label);

    // End Entity Node
    metadataWriter.WriteEndElement();
    }
    }

    // End Metadata Xml Node
    metadataWriter.WriteEndElement();
    metadataWriter.WriteEndDocument();

    // Close xml writer.
    metadataWriter.Close();
    }
  27. Check if Old Value and New Value of Field are different in Plugin Images (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    Entity preEntityImage= (Entity)context.PreEntityImages["ImageName"];
    Entity postEntityImage = (Entity)context.PostEntityImages["ImageName"];
    var oldNameValue = preEntityImage.GetAttribute<String>("name");
    var newNameValue = postEntityImage.GetAttribute<String>("name");
    if(oldNameValue.ToLower() != newNameValue.ToLower())
    {
    //Your code goes here
    }
  28. Early Bound Syntax creating Contact Record (C#)

    1
    2
    3
    4
    5
    6
    7
    Contact contact = new Contact()
    {
    FirstName = "Charles",
    LastName = "Brown",
    Address1_Line1 = "123 Main St."
    };
    _contactId = _serviceProxy.Create(contact);
  29. Late Bound Syntax creating Contact Record (C#)

    1
    2
    3
    4
    5
    Entity contactent = new Entity("contact");
    contactent["firstname"] = "Charles";
    contactent["lastname"] = "Brown ";
    contactent["address1_line1"] = "123 Main St.";
    Guid _contactId = _serviceProxy.Create(contactent);
  30. Declaring Input & Output Arguments,Default Value & Set Requirement Level of the Parameter in Custom Workflow Activities(C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    <strong>For Boolean Type(Input)</strong>
    [Input("Bool input")]
    [Default("True")]
    public InArgument BoolFlag { get; set; }

    <strong>For Boolean Type(Output)</strong>
    [Output("Bool input")]
    public OutArgument BoolFlag { get; set; }

    <strong>For Boolean Type (Both Input and Output)</strong>
    [Input("Bool input")]
    [Output("Bool output")]
    [Default("False")]
    public InOutArgument BoolFlag { get; set; }

    <strong>DateTime</strong>
    [Input("DateTime input")]
    [Output("DateTime output")]
    [Default("2013-07-09T02:54:00Z")]
    public InOutArgument DateTime { get; set; }

    <strong>Decimal</strong>
    [Input("Decimal input")]
    [Output("Decimal output")]
    [Default("20.75")]
    public InOutArgument Decimal { get; set; }

    <strong>Double</strong>
    [Input("Double input")]
    [Output("Double output")]
    [Default("200.2")]
    public InOutArgument Double { get; set; }

    <strong>Integer</strong>
    [Input("Int input")]
    [Output("Int output")]
    [Default("2322")]
    public InOutArgument Int { get; set; }

    <strong>Money (Currency)</strong>
    [Input("Money input")]
    [Output("Money output")]
    [Default("232.3")]
    public InOutArgument Money { get; set; }

    <strong>OptionSetValue</strong>
    [Input("OptionSetValue input")]
    [Output("OptionSetValue output")]
    [AttributeTarget("account", "industrycode")]
    [Default("3")]
    public InOutArgument OptionSetValue { get; set; }

    <strong>String</strong>
    [Input("String input")]
    [Output("String output")]
    [Default("string default")]
    public InOutArgument String { get; set; }

    <strong>Entity Reference</strong>
    [Input("EntityReference input")]
    [Output("EntityReference output")]
    [ReferenceTarget("account")]
    [Default("3B036E3E-94F9-DE11-B508-00155DBA2902", "account")]
    public InOutArgument AccountReference { get; set; }.

    <strong>Required Argument Attribute</strong>
    [RequiredArgument]
    [Input("Update next Anniversary date for")]
    [ReferenceTarget("contact")]
    public InArgument Contact { get; set; }

    <strong>Output Parameters</strong>
    //this is the name of the parameter that will be returned back to the workflow
    [Output("Credit Score")]
    //this line identifies the specific attribute which will be passed back to the workflow
    [AttributeTarget(CustomEntity, "new_creditscore")]
    // declares the output parameter and declares the proper data type of the parameter being passed back.
    public OutArgument CreditScore {get;set;}
  31. Get Value from Input Argument in Custom Workflow Activities (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    <strong>If Input argument is declared as below then we can get the value as explained below.</strong>
    [Input("Date Of Birth")]
    public InArgument<DateTime> DOB { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
    DateTime dtDOB = DOB.Get(context);
    }
  32. Set Value from Out Argument in Custom Workflow Activities (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    <strong>If Output argument is declared as below then we can get the value as explained below.</strong>
    [Output("FinalAge")]
    public OutArgument<Int32> Age { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
    int CalculatedAge=30;
    Age.Set(context, CalculatedAge);
    }
  33. A Sample Custom Workflow Code (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    using System.Collections.Generic;
    using System.Linq;
    using System.Activities;
    using Microsoft.Xrm.Sdk.Workflow;
    namespace GetAge
    {
    public sealed class CalculateAge:CodeActivity
    {
    [Input("Date Of Birth")]
    public InArgument<DateTime> DOB { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
    DateTime dtDOB = DOB.Get(context);
    int CalculatedAge =
    Convert.ToInt32((DateTime.Now.Subtract(dtDOB).TotalDays)/365);
    Age.Set(context, CalculatedAge);
    }

    [Output("FinalAge")]
    public OutArgument<Int32> Age { get; set; }
    }
    }
  34. A Sample Plugin Code (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    namespace Microsoft.Crm.Sdk.Samples
    {
    public class FollowupPlugin: IPlugin
    {
    /// <summary>
    /// A plug-in that creates a follow-up task activity when a new account is created.
    /// </summary>
    /// <remarks>Register this plug-in on the Create message, account entity,
    /// and asynchronous mode.
    /// </remarks>
    public void Execute(IServiceProvider serviceProvider)
    {
    //Extract the tracing service for use in debugging sandboxed plug-ins.
    ITracingService tracingService =
    (ITracingService)serviceProvider.GetService(typeof(ITracingService));

    // Obtain the execution context from the service provider.
    IPluginExecutionContext context = (IPluginExecutionContext)
    serviceProvider.GetService(typeof(IPluginExecutionContext));

    // The InputParameters collection contains all the data passed in the message request.
    if (context.InputParameters.Contains("Target") &amp;amp;&amp;amp;
    context.InputParameters["Target"] is Entity)
    {
    // Obtain the target entity from the input parameters.
    Entity entity = (Entity)context.InputParameters["Target"];

    // Verify that the target entity represents an account.
    // If not, this plug-in was not registered correctly.
    if (entity.LogicalName != "account")
    return;

    try
    {
    // Create a task activity to follow up with the account customer in 7 days.
    Entity followup = new Entity("task");

    followup["subject"] = "Send e-mail to the new customer.";
    followup["description"] =
    "Follow up with the customer. Check if there are any new issues that need resolution.";
    followup["scheduledstart"] = DateTime.Now.AddDays(7);
    followup["scheduledend"] = DateTime.Now.AddDays(7);
    followup["category"] = context.PrimaryEntityName;

    // Refer to the account in the task activity.
    if (context.OutputParameters.Contains("id"))
    {
    Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
    string regardingobjectidType = "account";

    followup["regardingobjectid"] =
    new EntityReference(regardingobjectidType, regardingobjectid);
    }

    // Obtain the organization service reference.
    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

    // Create the task in Microsoft Dynamics CRM.
    tracingService.Trace("FollowupPlugin: Creating the task activity.");
    service.Create(followup);
    }
    catch (FaultException<OrganizationServiceFault> ex)
    {
    throw new InvalidPluginExecutionException("An error occurred in the FollowupPlugin plug-in.", ex);
    }

    catch (Exception ex)
    {
    tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
    throw;
    }
    }
    }
    }
    }
  35. Write Log Messages into a Text File

    1
    2
    3
    4
    5
    6
    7
    8
    9
    Public void WriteLog(string msg)
    {
    String datestamp = DateTime.Now.Date.ToString("d");
    string path = string.Format(@"E:\AppServ\{0}_log.txt", datestamp);  // define the path to save the file
    if (!File.Exists(path)){ File.Create(path); }

    TextWriter tw = new StreamWriter(path);
    tw.WriteLine(msg); tw.Close();
    }
  36. Code for Exception handling (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    Try
    {
    //Your code
    }
    catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
    {
    Console.WriteLine("The application terminated with an error.");
    Console.WriteLine("Timestamp: {0}", ex.Detail.Timestamp);
    Console.WriteLine("Code: {0}", ex.Detail.ErrorCode);
    Console.WriteLine("Message: {0}", ex.Detail.Message);
    Console.WriteLine("Inner Fault: {0}",
    null == ex.Detail.InnerFault ? "No Inner Fault": "Has Inner Fault");
    }
    catch (System.TimeoutException ex)
    {
    Console.WriteLine("The application terminated with an error.");
    Console.WriteLine("Message: {0}", ex.Message);
    Console.WriteLine("Stack Trace: {0}", ex.StackTrace);
    Console.WriteLine("Inner Fault: {0}",
    null == ex.InnerException.Message ? "No Inner Fault": ex.InnerException.Message);
    }
    catch (System.Exception ex)
    {
    Console.WriteLine("The application terminated with an error.");
    Console.WriteLine(ex.Message);

    // Display the details of the inner exception.
    if (ex.InnerException != null)
    {
    Console.WriteLine(ex.InnerException.Message);
    FaultException fe = ex.InnerException
    as FaultException;
    if (fe != null)
    {
    Console.WriteLine("Timestamp: {0}", fe.Detail.Timestamp);
    Console.WriteLine("Code: {0}", fe.Detail.ErrorCode);
    Console.WriteLine("Message: {0}", fe.Detail.Message);
    Console.WriteLine("Trace: {0}", fe.Detail.TraceText);
    Console.WriteLine("Inner Fault: {0}",
    null == fe.Detail.InnerFault ? "No Inner Fault": "Has Inner Fault");
    }
    }
    }
  37. Create Outlook offline Filters (C#)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    String contactName = String.Format("offlineFilteredContact {0}", DateTime.Now.ToLongTimeString());
    String fetchXml =
    String.Format("<fetch version="1.0"output-format="xml-platform"mapping="logical"><entity name="contact"><attribute name="contactid"/><filter type="and">"+
    "<condition attribute="ownerid"operator="eq-userid"/><condition attribute="description"operator="eq"value="{0}"/>"+
    "<condition attribute="statecode"operator="eq"value="0"/></filter></entity></fetch>", contactName);
    SavedQuery filter = new SavedQuery();
    filter.FetchXml = fetchXml;
    filter.IsQuickFindQuery = false;
    filter.QueryType = SavedQueryQueryType.OfflineFilters;
    filter.ReturnedTypeCode = Contact.EntityLogicalName;
    filter.Name = "ReadOnlyFilter_"+ contactName;
    filter.Description = "Sample offline filter for Contact entity";
    _offlineFilter = _serviceProxy.Create(filter);
  38. Encryption and Decryption using C#

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    using System;
    using System.Security.Cryptography;
    using System.Text;

    namespace SecurityModule
    {
    public class EncryptionManager
    {
    public static string Encrypt(string input, string key)
    {
    byte[] inputArray = UTF8Encoding.UTF8.GetBytes(input);
    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
    tripleDES.Mode = CipherMode.ECB;
    tripleDES.Padding = PaddingMode.PKCS7;
    ICryptoTransform cTransform = tripleDES.CreateEncryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
    tripleDES.Clear();
    return Convert.ToBase64String(resultArray, 0, resultArray.Length);
    }
    public static string Decrypt(string input, string key)
    {
    byte[] inputArray = Convert.FromBase64String(input);
    TripleDESCryptoServiceProvider tripleDES = new TripleDESCryptoServiceProvider();
    tripleDES.Key = UTF8Encoding.UTF8.GetBytes(key);
    tripleDES.Mode = CipherMode.ECB;
    tripleDES.Padding = PaddingMode.PKCS7;
    ICryptoTransform cTransform = tripleDES.CreateDecryptor();
    byte[] resultArray = cTransform.TransformFinalBlock(inputArray, 0, inputArray.Length);
    tripleDES.Clear();
    return UTF8Encoding.UTF8.GetString(resultArray);
    }
    }
    }
  39. Read All Text to string and Read all Line to array form a Text File (C#)

    1
    2
    3
    4
    string path = @"c:\temp\MyTest.txt";
    // Open the file to read from.
    string readText = File.ReadAllText(path);
    string[] readText = File.ReadAllLines(path);
  40. Split Text using separator in C#

    1
    2
    3
    string source = "ONE|TWO|THREE";
    string[] stringSeparators = new string[] {"|"};
    string[] result= source.Split(stringSeparators, StringSplitOptions.None);
  41. Access Field by Name on Form (Formscript/Javascript)

    1
    var myAttribute = Xrm.Page.getAttribute("name");
  42. Access Field by Index on Form (Formscript/Javascript)

    1
    var myAttribute = Xrm.Page.getAttribute(0);
  43. Get all Attributes on Form (Formscript/Javascript)

    1
    var allAttributes = Xrm.Page.getAttribute();
  44. Get All optionset Attributes of the Form

    1
    2
    3
    4
    5
    var optionsetAttributes =
    Xrm.Page.getAttribute(
    function (attribute, index) {
    return attribute.getAttributeType() == "optionset";
    });
  45. Alert All attributes with Required Validation of the Form (Javascript)

    1
    2
    3
    4
    5
    6
    7
    function AlertRequiredAttributes () {
    Xrm.Page.data.entity.attributes.forEach(
    function (attribute, index) {
    if (attribute.getRequiredLevel() == "required")
    { alert(attribute.getName()); }
    });
    }
  46. Get the Value of a field/attribute on form (Javascript)

    1
    var fieldvalue= Xrm.Page.getAttribute("name").getValue();
  47. Set the Value of a field/attribute on form (Javascript)

    1
    Xrm.Page.getAttribute("name").setValue("new value");
  48. Get the text value of the currently selected option of an optionset attribute (Javascript)

    1
    var addressType = Xrm.Page.getAttribute("address1_addresstypecode").getText();
  49. Get the currently selected option object in an optionset attribute (Javascript)

    1
    var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getSelectedOption();
  50. Get the type of attribute (Javascript)

    1
    var attributeType = Xrm.Page.getAttribute("address1_addresstypecode").getAttributeType();
  51. Get how the attribute is formatted (Javascript)

    1
    var attributeFormat = Xrm.Page.getAttribute(0).getFormat();
  52. Get the initial value of a Booleanor Optionset attribute (Javascript)

    1
    var attributeInitialValue = Xrm.Page.getAttribute("address1_addresstypecode").getInitialValue();
  53. Determine whether an attribute value has changed (Javascript)

    1
    var isNameChanged = Xrm.Page.getAttribute("name").getIsDirty();
  54. Get Maximum Value of a Field (Javascript)

    1
    Var limitMaxvalue =  Xrm.Page.getAttribute("creditlimit").getMax();
  55. Get the maximum allowed length for an attribute that contains a string (Javascript)

    1
    var maxNameLen=  Xrm.Page.getAttribute("name").getMaxLength();
  56. Get MInimum Value of a Field (Javascript)

    1
    Var limitMinvalue =  Xrm.Page.getAttribute("creditlimit").getMin();
  57. Get the logical name of an attribute (Javascript)

    1
    var attributeName = Xrm.Page.getAttribute("creditlimit").getName();
  58. Get the Option set text by value of attribute (Javascript)

    1
    2
    var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getOption(1);
    alert(addressTypeOption.text); //displays 'Bill To'
  59. Get the requirement level of an attribute (Javascript)

    1
    var creditLimitRequired = Xrm.Page.getAttribute("creditlimit").getRequiredLevel();
  60. Set the requirement level of an attribute as Required (Javascript)

    1
    Xrm.Page.getAttribute("creditlimit").setRequiredLevel("required"); //required/none/ recommended
  61. Check if the data in an attribute will be submitted when the data is saved (Javascript)

    1
    var nameSubmitMode = Xrm.Page.getAttribute("name").getSubmitMode(); // always/never/ dirty
  62. Control whether data in an attribute will be saved when the record is saved

    1
    Xrm.Page.getAttribute("name").setSubmitMode("always");
  63. Prevent a record from being saved.

    1
    2
    3
    4
    function My_PreventSaveFunction(eContext) {
    eContext.getEventArgs().preventDefault();
    }
    <strong>//NOTE</strong>: Use the <strong>eContext</strong> parameter to capture the execution context and use the <strong>preventDefault</strong> method included with the event arguments.
  64. Determine what action initiated the save.event (Javascript)

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    function GetSaveModeTextFunction(eContext) {
    var saveModeCode = eContext.getEventArgs().getSaveMode();
    var saveModeText = "Unknown";
    switch (saveModeCode) {
    case 1:
    saveModeText = "Save";
    break;
    case 2:
    saveModeText = "SaveAndClose";
    break;
    case 5:
    saveModeText = "Deactivate";
    break;
    case 6:
    saveModeText = "Reactivate";
    break;
    case 7:
    saveModeText = "Send";
    break;
    case 15:
    saveModeText = "Disqualify";
    break;
    case 16:
    saveModeText = "Qualify";
    break;
    case 47:
    saveModeText = "Assign";
    break;
    case 58:
    saveModeText = "SaveAsCompleted";
    break;
    case 59:
    saveModeText = "SaveAndNew";
    break;
    case 70:
    saveModeText = "AutoSave";
    break;
    }
    return saveModeText;
    }
    //NOTE :Pass the execution context from event handler screen
  65. Display a notification message near the field control to indicate that data is not valid. (Javascript)

    1
    2
    3
    4
    Xrm.Page.getAttribute("name").controls.forEach(
    function (control, i) {
    control.setNotification("'Input Value' is not valid.");
    })
  66. Remove a notification message already displayed for a control.

    1
    2
    3
    4
    Xrm.Page.getAttribute("name").controls.forEach(
    function (control, i) {
    control.clearNotification();
    })
  67. Display form level notifications message (javascript)

    1
    2
    3
    4
    5
    6
    Xrm.Page.ui.setFormNotification(
    "Hello",
    "INFO",
    "myMsg"
    );
    // <strong>myMsg</strong> is a uniquid used while displaying the message.
  68. Remove form level notifications message (Javascript)

    1
    Xrm.Page.ui.clearFormNotification("<strong>myMsg</strong>");
  69. Display a non-blocking alert dialog with a callback function

    1
    2
    3
    4
    5
    6
    var alertDisplayedFlag = false;
    Xrm.Utility.alertDialog(
    "Showing Alert Window",
    function () { alertDisplayedFlag = true; }
    )
    //NOTE: Display an alert and set the value of the alertDisplayedFlag variable when it is closed.
  70. Display a non-blocking confirm dialog with different callbacks depending on the button clicked by the user.

    1
    2
    3
    4
    5
    6
    var agree = false;
    Xrm.Utility.confirmDialog(
    "Do you agree?",
    function () { agree = true;},
    function () { agree = false; }
    );
  71. Access all the controls for a specific attribute

    1
    var nameControls = Xrm.Page.getAttribute("name").controls.get();
  72. Access a control by name

    1
    var nameControl = Xrm.Page.getControl("name");
  73. Access a control by index

    1
    var firstControl = Xrm.Page.getControl(0);
  74. Access all controls

    1
    var allControls = Xrm.Page.getControl();
  75. Get all optionset controls

    1
    2
    3
    var optionsetControls = Xrm.Page.getControl(function (control, index) {
    return control.getControlType() == "optionset";
    })
  76. Get all controls of a specific section of a Tab

    1
    var generalTabAccountInfoSectionControls = Xrm.Page.ui.tabs.get("general").sections.get("address").controls.get();
  77. Disable all controls for an attribute

    1
    Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });
  78. Access a field from header section with attribute name is customername

    1
    var nameControlInHeader = Xrm.Page.getControl("header_customername");
  79. Access a field control from business process flow

    1
    var nameControlInBPF = Xrm.Page.getControl("header_process_name");
  80. Check if a control is Visible

    1
    var isNameVisible = Xrm.Page.getControl("name").getVisible();
  81. Hide or show a control of a field

    1
    Xrm.Page.getControl("name").setVisible(false);
  82. Get a reference to the attribute for the control

    1
    var nameAttribute = Xrm.Page.getControl("name").getAttribute();
  83. Get all optionset controls

    1
    var optionSetControls = Xrm.Page.getControl(function (control, index) { return control.getControlType() == "optionset"; });
  84. Return all disabled controls

    1
    var disabledControls = Xrm.Page.getControl(function(control, index) { return control.getDisabled(); });
  85. Disable or enable each control

    1
    Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });
  86. Get the label for a control

    1
    var nameControlLabel = Xrm.Page.getControl("name").getLabel();
  87. Change the label for a control

    1
    Xrm.Page.getControl("name").setLabel("Company Name");
  88. Get the name of a control

    1
    var firstControlName = Xrm.Page.getControl(0).getName();
  89. Get the parent of a control

    1
    var parentSection = Xrm.Page.getControl("name").getParent();
  90. Set focus on a control

    1
    Xrm.Page.getControl("name").setFocus();
  91. Add an option to an optionset control

    1
    2
    3
    4
    var addressTypeCodeControl = Xrm.Page.getControl("address1_addresstypecode");
    var billToAddressOption = addressTypeCodeControl.getAttribute().getOption(1);
    addressTypeCodeControl.clearOptions();
    addressTypeCodeControl.addOption(billToAddressOption);
  92. Remove all the options from an optionset control

    1
    Xrm.Page.getControl("address1_addresstypecode").clearOptions();
  93. Remove a single option from an optionset control.

    1
    Xrm.Page.getControl("address1_addresstypecode").removeOption(1);
  94. Get the URL for the content currently displayed in an IFRAME.

    1
    var iframeSource = Xrm.Page.getControl("IFRAME_targetPage").getSrc();
  95. Set the URL for the content to be displayed in an IFRAME.

    1
    Xrm.Page.getControl("IFRAME_targetPage").setSrc("http://www.bing.com");
  96. Add a custom view for a lookup.

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
    var viewDisplayName = "SDK Sample View";
    var fetchXml = "<fetch version='1.0' "+
    "output-format='xml-platform' "+
    "mapping='logical'>"+
    "<entity name='account'>"+
    "<attribute name='name' />"+
    "<attribute name='address1_city' />"+
    "<order attribute='name' "+
    "descending='false' />"+
    "<filter type='and'>"+
    "<condition attribute='ownerid' "+
    "operator='eq-userid' />"+
    "<condition attribute='statecode' "+
    "operator='eq' "+
    "value='0' />"+
    "</filter>"+
    "<attribute name='primarycontactid' />"+
    "<attribute name='telephone1' />"+
    "<attribute name='accountid' />"+
    "<link-entity "+
    "alias='accountprimarycontactidcontactcontactid' "+
    "name='contact' "+
    "from='contactid' "+
    "to='primarycontactid' "+
    "link-type='outer' "+
    "visible='false'>"+
    "<attribute name='emailaddress1' />"+
    "</link-entity>"+
    "</entity>"+
    "</fetch>";
    var layoutXml = "<grid name='resultset' "+
    "object='1' "+
    "jump='name' "+
    "select='1' "+
    "icon='1' "+
    "preview='1'>"+
    "<row name='result' "+
    "id='accountid'>"+
    "<cell name='name' "+
    "width='300' />"+
    "<cell name='telephone1' "+
    "width='100' />"+
    "<cell name='address1_city' "+
    "width='100' />"+
    "<cell name='primarycontactid' "+
    "width='150' />"+
    "<cell name='accountprimarycontactidcontactcontactid.emailaddress1' "+
    "width='150' "+
    "disableSorting='1' />"+
    "</row>"+
    "</grid>";
    Xrm.Page.getControl("parentaccountid").addCustomView(viewId, "account", viewDisplayName, fetchXml, layoutXml, true);
  97. Get and Set the default view for a lookup.

    1
    2
    3
    var defaultViewId = Xrm.Page.getControl("parentaccountid").getDefaultView();
    var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
    Xrm.Page.getControl("parentaccountid").setDefaultView(viewId);
  98. Filter the records returned for a lookup control

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    var Sdk = window.Sdk || {};
    Sdk.filterCustomerAccounts = function () {
    //Only show accounts with the type 'Preferred Customer'
    var customerAccountFilter = "<filter type='and'><condition attribute='accountcategorycode' operator='eq' value='1'/></filter>";
    Xrm.Page.getControl("parentaccountid").addCustomFilter(customerAccountFilter, "account");
    }
    //set 'Sdk.setParentAccountIdFilter' in the Opportunity form Onload event handler
    Sdk.setParentAccountIdFilter = function () {
    Xrm.Page.getControl("parentaccountid").addPreSearch(Sdk.filterCustomerAccounts);
    }
  99. Refresh the data displayed in the subgrid

    1
    Xrm.Page.getControl("accountcontactsgrid").refresh();
  100. [/cc]

  101. Specify whether a date control should show the time portion of the date.

    1
    Xrm.Page.getControl("createdon").setShowTime(false);
  102. [/cc]

  103. Form Navigation Scripts, Tabs and Sections Script and other important scripts

    Task Method Example
    Get the name of a navigation item getId var navItemIds = [];
    Xrm.Page.ui.navigation.items.forEach(
    function (item, index)
    { navItemIds.push(item.getId()) }
    );Create a navItemIds array that contains the id values of each navigation item in the Xrm.Page.ui.navigation.items collection.
    Get the label of a navigation item. getLabel var navAddressesLabel = Xrm.Page.ui.navigation.items.get(“navAddresses”).getLabel();
    Assign the label for the More Addresses navigation item to the navAddressesLabel variable.
    Set the label of a navigation item setLabel Xrm.Page.ui.navigation.items.get(“navAddresses”).setLabel(“Other Addresses”);
    Change the More Addresses navigation item label to Other Addresses.
    Show or hide a navigation item setVisible Xrm.Page.ui.navigation.items.get(“navAddresses”).setVisible(false);
    Hide the More Addresses navigation item.
    Determine if a navigation item is visible getVisible var moreAddressesVisible = Xrm.Page.ui.navigation.items.get(“navAddresses”).getVisible()
    Assign a Boolean value to the moreAddressesVisible variable to represent whether the More Addresses navigation item is visible.
    Set focus on a navigation item. setFocus Xrm.Page.ui.navigation.items.get(“navAddresses”).setFocus();
    Set focus on the More Addresses navigation item.
    Determine if a tab is expanded or collapsed getDisplayState var isGeneralTabExpanded = (Xrm.Page.ui.tabs.get(“general”).getDisplayState() == “expanded”)
    Assign a Boolean value to the isGeneralTabExpanded variable that indicates whether the General tab is expanded.
    Expand or collapse a tab setDisplayState Xrm.Page.ui.tabs.get(“general”).setDisplayState(“collapsed”);
    Collapse the General tab.
    Determine if a tab is visible getVisible var isGeneralTabVisible = Xrm.Page.ui.tabs.get(“general”).getVisible();
    Assign a Boolean value to the isGeneralTabVisible variable indicating whether the Generaltab is visible.
    Show or hide a tab setVisible Xrm.Page.ui.tabs.get(“general”).setVisible(false);
    Hide the General tab.
    Get the label for a tab getLabel var generalTabLabel = Xrm.Page.ui.tabs.get(“general”).getLabel();
    Assign the General tab label to the generalTabLabel variable.
    Change the label for a tab setLabel Xrm.Page.ui.tabs.get(“general”).setLabel(“Major”);
    Change the General tab label to Major.
    Set focus on a tab setFocus Xrm.Page.ui.tabs.get(“general”).setFocus();
    Set focus on the General tab.
    Get the name of the tab getName var firstTabName = Xrm.Page.ui.tabs.get(0).getName();
    Assign the name of the first tab to the firstTabName variable.
    Get the parent tab of a section getParent Xrm.Page.getControl(“industrycode”).getParent().getParent().setFocus();
    Set focus on the tab that contains the Industry field.
    Determine if a section is visible getVisible var industrySectionVisible = Xrm.Page.getControl(“industrycode”).getParent().getVisible();
    Assign a Boolean value to the industrySectionVisible variable indicating whether the section containing the Industry field is visible.
    Show or hide a section setVisible Xrm.Page.getControl(“industrycode”).getParent().setVisible(false);
    Hide the section that contains the Industry field.
    Get the label for a section getLabel var industryFieldSectionLabel = Xrm.Page.getControl(“industrycode”).getParent().getLabel();
    Assign the label of the section containing the Industry field to the industryFieldSectionLabel variable.
    Change the label for a section setLabel Xrm.Page.getControl(“industrycode”).getParent().setLabel(“Detailed Information”);
    Change the label of the section that contains the Industry field to Detailed Information.
    Add a function to the OnSaveevent addOnSave Xrm.Page.data.entity.addOnSave(myFunction);
    Add the myFunction function to the OnSave event.
    Remove a function from the OnSaveevent removeOnSave Xrm.Page.data.entity.removeOnSave(myFunction);
    Remove the myFunction function to the OnSave event.
    Add a function to the OnChangeevent of an attribute. addOnChange Xrm.Page.getAttribute(“name”).addOnChange(myFunction);
    Add the myFunction function to the OnChange event of the Account Name field.
    Remove a function from the OnChangeevent of an attribute removeOnChange Xrm.Page.getAttribute(“name”).removeOnChange(myFunction);
    Remove the myFunction function to the OnChange event of the Account Name field.
    Add a function to the PreSearchevent of a lookup control addPreSearch The following code sample is for the Opportunity form Account (parentaccountid) lookup. When the Sdk.setParentAccountIdFilter function is set in the form Onloadevent handler, the Sdk.filterCustomAccounts function is added to the PreSearch event for that lookup. The result is that only accounts with the Category(accountcategorycode) value of Preferred Customer (1) will be returned.
    JavaScript
    var Sdk = window.Sdk || {};
    Sdk.filterCustomerAccounts = function () {
    //Only show accounts with the type ‘Preferred Customer’
    var customerAccountFilter = ““;
    Xrm.Page.getControl(“parentaccountid”).addCustomFilter(customerAccountFilter, “account”);
    }
    //set ‘Sdk.setParentAccountIdFilter’ in the Opportunity form Onload event handler
    Sdk.setParentAccountIdFilter = function () {
    Xrm.Page.getControl(“parentaccountid”).addPreSearch(Sdk.filterCustomerAccounts);
    }
    Get the URL to connect to the organization. getClientUrl var serverUrl = Xrm.Page.context.getClientUrl();
    Assign a string that represents the URL to the serverUrlvariable.
    Get the unique identifier for the current user. getUserId var userId = Xrm.Page.context.getUserId();
    Assign a string that represents the user’s Id to the userId variable.
    Get the name of the current user. getUserName var userName = Xrm.Page.context.getUserName();
    Assign a string that represents the user’s name to the userName variable.
    This method is only available for Updated entities.
    Get the language code that represents the user’s preferred user interface language. getUserLcid var userLCID = Xrm.Page.context.getUserLcid();
    Assign a number that indicates the user’s preferred language to the userLCID variable.
    Get an array of strings that represents the GUID values for each security role assigned to the current user and any teams that the user is associated with. getUserRoles var userRoles = Xrm.Page.context.getUserRoles();
    Assign an array of strings that represents the user’s security roles to the userRoles variable.
    Determine whether the script is running in the Microsoft Dynamics 365 for Outlook client. client.getClient var isOutlookClient = (Xrm.Page.context.client.getClient() == “Outlook”);
    Assign a Boolean value that represents whether your code is running in the Dynamics 365 for Outlook client to the isOutlookClient variable.
    Determine whether the user is working offine with the Microsoft Dynamics 365 for Microsoft Office Outlook with Offline Access client. client.getClientState var IsOffline = (Xrm.Page.context.client.getClientState() == “Offline”);
    Assign a Boolean value that represents whether the user is currently working offline to the IsOfflinevariable.
    Get the logical name of the current entity getEntityName var entityName = Xrm.Page.data.entity.getEntityName();
    Assign the logical entity name to the entityName variable.
    Get the value of the primary attribute for the current entity.
    The primary attribute is the value used to identify the record. For example contact.fullname.
    getPrimaryAttributeValue var primaryAttributeValue = Xrm.Page.data.entity.getPrimaryAttributeValue();
    Assign the value of the primary attribute to the primaryAttributeValue variable.
    This method is only available for Updated entities.
    Get the Id of the current record getId var recordId = Xrm.Page.data.entity.getId();
    Assign the id of the record to the recordId variable.
    Asynchronously refresh the data of the form without reloading the page. refresh Xrm.Page.data.refresh();
    Refreshes the data in the form.
    This method is only available for Updated entities.
    Save the current record Xrm.Page.data.entity.save Xrm.Page.data.entity.save();
    Saves the record. There are optional arguments. Use saveandcloseor saveandnew to perform the equivalent actions.
    Save the current record asynchronously with the option to set
    callback functions to be executed after the save operation is completed.
    Xrm.Page.data.save Xrm.Page.data.save().then(
    function(){
    Xrm.Utility.alertDialog(“Record saved”);
    },
    function(error){
    Xrm.Utility.alertDialog(error.message);
    });Saves the record and displays a message showing the status of the save.
    This method is only available for Updated entities.
    Determine whether any data in the current record is changed. getIsDirty var isDirty = Xrm.Page.data.entity.getIsDirty();
    Assign a Boolean value that represents whether data in the record has changed to the isDirty variable.
    Get a string that represents the data that will be sent to the server when the record is saved. getDataXml var dataXml = Xrm.Page.data.entity.getDataXml();
    Assign a string that represents the data to be saved to the dataXmlvariable.

    [/cc]

  104. Thanks for reading the post.