Search This Blog

Monday, November 13, 2023

Excellent 101 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,

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#)

    String userName = "";
    String userPwd = "";
    String userDomain= "";
    String crmServer = "";
    String crmPort = ";";
    String crmOrg = "";
    String 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#)

    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#)

    if (context.InputParameters.Contains("Target") &&  Context.InputParameters["Target"] is Entity)
    {
     //Your code goes here
    }
    
  4. CHECK IF A SPECIFIC ATTRIBUTE PRESENT IN A ENTITY (C#)

    if (entityObject.Attributes.ContainsKey("")
    {
    //Your code goes here
    }
    
  5. GET VALUE OF ATTRIBUTE FROM ENTITY (C#)

    entityObject.GetAttributeValue("");
    entityObject. GetAttributeValue  ("").Id.ToString();
    bool myAttributeVal  = entityObject.GetAttributeValue("")
    string myAttributeVal  = entityObject.GetAttributeValue("")
    
  6. CONVERT ENTITYCOLLECTION TO DATATABLE (C#)

    public DataTable convertEntityCollectionToDataTable(EntityCollection EC)
    {
    DataTable dt = new DataTable();
    int totalCount = EC.Entities.Count;
    for (int i = 0; i
  7. CHECK IF DATASET IS VALID (C#)

    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#)

    AliasedValue aliasedval=
    entityObject.GetAttributeValue("").Value;
    int optionSetVal = ((OptionSetValue) aliasedval).Value;
    //NOTE: 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#)

    // add this code before your actual plugin logic starts
    if (context.Depth >1)
    return;
  10. CODE TO USE SHARED VARIABLE IN PLUGINS (C#)

    //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#)

    Entity preEntityImage= (Entity)context.PreEntityImages["ImageName"];
    Entity postEntityImage = (Entity)context.PostEntityImages["ImageName"];
    //NOTE : The Image Names are defined in Plugin registration tool against the SDK steps.
    
  12. TRACE MESSAGES USING TRACING SERVICE IN PLUGIN (C#)

    ITracingService tracingService =
    (ITracingService)serviceProvider.GetService(typeof(ITracingService));
    tracingService.Trace ("");
    
  13. GET OPTIONSET TEXT IN PLUGIN (C#)

    if(entity.Contains(""))
    {
    string optionsettext = entity.FormattedValues["attributename"];
    }
    
  14. RETRIEVE ENTITY RECORD DATA USING QUERY EXPRESSION(C#)

    //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, );
    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#)

    string fetchxml = @"
    
    
    
    
    
    
    
    
    
     ";
    EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(fetchxml));
    
  16. RETRIEVE ENTITY RECORD DATA USING GUID OF THE RECORD(C#)

    ColumnSet cs = new ColumnSet("attribute1","attribute2");
    Entity result = _serviceProxy.Retrieve ("", new Guid(""), cs);
    
  17. UPDATE ENTITY RECORD (C#)

    Entity entityObj = new Entity();
    entityObj.LogicalName = "";
    entityObj.Id = 
    entityObj. = 
    crmservice.Update(entityObj);
    
    //Note: While assigning the value use the correct datatype converison. Lets say you are updating an //optionset then you have to use new OptionSetValue().
    
  18. DELETE ENTITY RECORD (C#)

    crmservice.Delete("",new Guid(""));
    
  19. CREATE AN ENTITY RECORD USING CRM SERVICE (C#)

    Entity entityObj = new Entity();
    entityObj.LogicalName = "";
    entityObj. = ;
    entityObj. = ;
    crmservice.Create(entityObj);
    
  20. RETRIEVE RECORD USING PAGING IF MORE RECORD PRESENT (C#)

    // 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#)

    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#)

    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#)

    //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#)

    // 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#)

    DataTypeExample
    Single Line of Textaccount[“name”] = Convert.ToString(“Microsoft India”); //String
    Option Setaccount[“accountcategorycode”] = new OptionSetValue(1); //Int
    Two Optionsaccount[“donotbulkemail”] = false; //boolean value -true/false
    ImageentityObj[“entityimage”] = File.ReadAllBytes(“Images\\144×144.png”);
    Whole Numberaccount[“numberofemployees”] = 50; //int Value
    Floating Point Numberaccount[“address1_latitude”] = Convert.ToDouble(-0.330); //double
    Decimal Numberaccount[“attributename”] = Convert.ToDecimal(3.5); //deciaml
    Currencyaccount[“revenue”] = new Money(50.60); //deciml Value
    Multiple Lines of Textaccount[“description”] = Convert.ToString(“this is a great acc”);
    Date and Timeaccount[“lastusedincampaign”] = new DateTime(2017,11,23); //yyyy,mm,dd
    Lookupaccount[“address1_addressid”] = new EntityReference(“address”,new Guid(“11111111-1111-1111-1111-111111111111”)); //32 bit guid
  26. GENERATE ENTITY METADATA USING C#

    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#)

    Entity preEntityImage= (Entity)context.PreEntityImages["ImageName"];
    Entity postEntityImage = (Entity)context.PostEntityImages["ImageName"];
    var oldNameValue = preEntityImage.GetAttribute("name");
    var newNameValue = postEntityImage.GetAttribute("name");
    if(oldNameValue.ToLower() != newNameValue.ToLower())
    {
    //Your code goes here
    }
    
    
  28. EARLY BOUND SYNTAX CREATING CONTACT RECORD (C#)

    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#)

    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#)

    For Boolean Type(Input)
    [Input("Bool input")]
    [Default("True")]
    public InArgument BoolFlag { get; set; }
    
    For Boolean Type(Output)
    [Output("Bool input")]
    public OutArgument BoolFlag { get; set; }
    
    For Boolean Type (Both Input and Output)
    [Input("Bool input")]
    [Output("Bool output")]
    [Default("False")]
    public InOutArgument BoolFlag { get; set; }
    
    DateTime
    [Input("DateTime input")]
    [Output("DateTime output")]
    [Default("2013-07-09T02:54:00Z")]
    public InOutArgument DateTime { get; set; }
    
    Decimal
    [Input("Decimal input")]
    [Output("Decimal output")]
    [Default("20.75")]
    public InOutArgument Decimal { get; set; }
    
    Double
    [Input("Double input")]
    [Output("Double output")]
    [Default("200.2")]
    public InOutArgument Double { get; set; }
    
    Integer
    [Input("Int input")]
    [Output("Int output")]
    [Default("2322")]
    public InOutArgument Int { get; set; }
    
    Money (Currency)
    [Input("Money input")]
    [Output("Money output")]
    [Default("232.3")]
    public InOutArgument Money { get; set; }
    
    OptionSetValue
    [Input("OptionSetValue input")]
    [Output("OptionSetValue output")]
    [AttributeTarget("account", "industrycode")]
    [Default("3")]
    public InOutArgument OptionSetValue { get; set; }
    
    String
    [Input("String input")]
    [Output("String output")]
    [Default("string default")]
    public InOutArgument String { get; set; }
    
    Entity Reference
    [Input("EntityReference input")]
    [Output("EntityReference output")]
    [ReferenceTarget("account")]
    [Default("3B036E3E-94F9-DE11-B508-00155DBA2902", "account")]
    public InOutArgument AccountReference { get; set; }.
    
    Required Argument Attribute
    [RequiredArgument]
    [Input("Update next Anniversary date for")]
    [ReferenceTarget("contact")]
    public InArgument Contact { get; set; }
    
    Output Parameters
    //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#)

    If Input argument is declared as below then we can get the value as explained below.
    [Input("Date Of Birth")]
    public InArgument 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#)

    If Output argument is declared as below then we can get the value as explained below.
    [Output("FinalAge")]
    public OutArgument Age { get; set; }
    
    protected override void Execute(CodeActivityContext context)
    {
    int CalculatedAge=30;
    Age.Set(context, CalculatedAge);
    }
    
    
  33. A SAMPLE CUSTOM WORKFLOW CODE (C#)

    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 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 Age { get; set; }
    }
    }
    
  34. A SAMPLE PLUGIN CODE (C#)

    using System;
    using System.ServiceModel;
    using Microsoft.Xrm.Sdk;
    namespace Microsoft.Crm.Sdk.Samples
    {
    public class FollowupPlugin: IPlugin
    {
    /// 
    /// A plug-in that creates a follow-up task activity when a new account is created.
    /// 
    /// Register this plug-in on the Create message, account entity,
    /// and asynchronous mode.
    /// 
    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") &&
    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 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

    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#)

    Try
    {
    //Your code
    }
    catch (FaultException 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#)

    String contactName = String.Format("offlineFilteredContact {0}", DateTime.Now.ToLongTimeString());
    String fetchXml =
    String.Format(""+
    ""+
    "", 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#

    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#)

    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#

    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)

    var myAttribute = Xrm.Page.getAttribute("name");
    
    
  42. ACCESS FIELD BY INDEX ON FORM (FORMSCRIPT/JAVASCRIPT)

    var myAttribute = Xrm.Page.getAttribute(0);
    
    
  43. GET ALL ATTRIBUTES ON FORM (FORMSCRIPT/JAVASCRIPT)

    var allAttributes = Xrm.Page.getAttribute();
    
    
  44. GET ALL OPTIONSET ATTRIBUTES OF THE FORM

    var optionsetAttributes =
    Xrm.Page.getAttribute(
    function (attribute, index) {
    return attribute.getAttributeType() == "optionset";
    });
    
    
  45. ALERT ALL ATTRIBUTES WITH REQUIRED VALIDATION OF THE FORM (JAVASCRIPT)

    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)

    var fieldvalue= Xrm.Page.getAttribute("name").getValue();
    
    
  47. SET THE VALUE OF A FIELD/ATTRIBUTE ON FORM (JAVASCRIPT)

    Xrm.Page.getAttribute("name").setValue("new value");
    
    
  48. GET THE TEXT VALUE OF THE CURRENTLY SELECTED OPTION OF AN OPTIONSET ATTRIBUTE (JAVASCRIPT)

    var addressType = Xrm.Page.getAttribute("address1_addresstypecode").getText();
    
    
  49. GET THE CURRENTLY SELECTED OPTION OBJECT IN AN OPTIONSET ATTRIBUTE (JAVASCRIPT)

    var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getSelectedOption();
    
    
  50. GET THE TYPE OF ATTRIBUTE (JAVASCRIPT)

    var attributeType = Xrm.Page.getAttribute("address1_addresstypecode").getAttributeType();
    
    
  51. GET HOW THE ATTRIBUTE IS FORMATTED (JAVASCRIPT)

    var attributeFormat = Xrm.Page.getAttribute(0).getFormat();
    
    
  52. GET THE INITIAL VALUE OF A BOOLEANOR OPTIONSET ATTRIBUTE (JAVASCRIPT)

    var attributeInitialValue = Xrm.Page.getAttribute("address1_addresstypecode").getInitialValue();
    
    
  53. DETERMINE WHETHER AN ATTRIBUTE VALUE HAS CHANGED (JAVASCRIPT)

    var isNameChanged = Xrm.Page.getAttribute("name").getIsDirty();
    
    
  54. GET MAXIMUM VALUE OF A FIELD (JAVASCRIPT)

    Var limitMaxvalue =  Xrm.Page.getAttribute("creditlimit").getMax();
    
    
  55. GET THE MAXIMUM ALLOWED LENGTH FOR AN ATTRIBUTE THAT CONTAINS A STRING (JAVASCRIPT)

    var maxNameLen=  Xrm.Page.getAttribute("name").getMaxLength();
    
    
  56. GET MINIMUM VALUE OF A FIELD (JAVASCRIPT)

    Var limitMinvalue =  Xrm.Page.getAttribute("creditlimit").getMin();
    
    
  57. GET THE LOGICAL NAME OF AN ATTRIBUTE (JAVASCRIPT)

    var attributeName = Xrm.Page.getAttribute("creditlimit").getName();
    
    
  58. GET THE OPTION SET TEXT BY VALUE OF ATTRIBUTE (JAVASCRIPT)

    var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getOption(1);
    alert(addressTypeOption.text); //displays 'Bill To'
    
    
  59. GET THE REQUIREMENT LEVEL OF AN ATTRIBUTE (JAVASCRIPT)

    var creditLimitRequired = Xrm.Page.getAttribute("creditlimit").getRequiredLevel();
    
    
  60. SET THE REQUIREMENT LEVEL OF AN ATTRIBUTE AS REQUIRED (JAVASCRIPT)

    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)

    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

    Xrm.Page.getAttribute("name").setSubmitMode("always");
    
    
  63. PREVENT A RECORD FROM BEING SAVED.

    function My_PreventSaveFunction(eContext) {
    eContext.getEventArgs().preventDefault();
    }
    //NOTE: Use the eContext parameter to capture the execution context and use the preventDefault method included with the event arguments.
    
    
  64. DETERMINE WHAT ACTION INITIATED THE SAVE.EVENT (JAVASCRIPT)

    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)

    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.

    Xrm.Page.getAttribute("name").controls.forEach(
    function (control, i) {
    control.clearNotification();
    })
    
    
  67. DISPLAY FORM LEVEL NOTIFICATIONS MESSAGE (JAVASCRIPT)

    Xrm.Page.ui.setFormNotification(
    "Hello",
    "INFO",
    "myMsg"
    );
    // myMsg is a uniquid used while displaying the message.
    
  68. REMOVE FORM LEVEL NOTIFICATIONS MESSAGE (JAVASCRIPT)

    Xrm.Page.ui.clearFormNotification("myMsg");
    
    
    
    
  69. DISPLAY A NON-BLOCKING ALERT DIALOG WITH A CALLBACK FUNCTION

    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.

    var agree = false;
    Xrm.Utility.confirmDialog(
    "Do you agree?",
    function () { agree = true;},
    function () { agree = false; }
    );
    
    
  71. ACCESS ALL THE CONTROLS FOR A SPECIFIC ATTRIBUTE

    var nameControls = Xrm.Page.getAttribute("name").controls.get();
    
    
  72. ACCESS A CONTROL BY NAME

    var nameControl = Xrm.Page.getControl("name");
    
    
  73. ACCESS A CONTROL BY INDEX

    var firstControl = Xrm.Page.getControl(0);
    
    
  74. ACCESS ALL CONTROLS

    var allControls = Xrm.Page.getControl();
    
    
  75. GET ALL OPTIONSET CONTROLS

    var optionsetControls = Xrm.Page.getControl(function (control, index) {
    return control.getControlType() == "optionset";
    })
    
    
  76. GET ALL CONTROLS OF A SPECIFIC SECTION OF A TAB

    var generalTabAccountInfoSectionControls = Xrm.Page.ui.tabs.get("general").sections.get("address").controls.get();
    
    
  77. DISABLE ALL CONTROLS FOR AN ATTRIBUTE

    Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });
    
  78. ACCESS A FIELD FROM HEADER SECTION WITH ATTRIBUTE NAME IS CUSTOMERNAME

    var nameControlInHeader = Xrm.Page.getControl("header_customername");
    
    
  79. ACCESS A FIELD CONTROL FROM BUSINESS PROCESS FLOW

    var nameControlInBPF = Xrm.Page.getControl("header_process_name");
    
    
  80. CHECK IF A CONTROL IS VISIBLE

    var isNameVisible = Xrm.Page.getControl("name").getVisible();
    
    
  81. HIDE OR SHOW A CONTROL OF A FIELD

    Xrm.Page.getControl("name").setVisible(false);
    
    
  82. GET A REFERENCE TO THE ATTRIBUTE FOR THE CONTROL

    var nameAttribute = Xrm.Page.getControl("name").getAttribute();
    
    
  83. GET ALL OPTIONSET CONTROLS

    var optionSetControls = Xrm.Page.getControl(function (control, index) { return control.getControlType() == "optionset"; });
    
    
  84. RETURN ALL DISABLED CONTROLS

    var disabledControls = Xrm.Page.getControl(function(control, index) { return control.getDisabled(); });
    
    
  85. DISABLE OR ENABLE EACH CONTROL

    Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });
    
    
  86. GET THE LABEL FOR A CONTROL

    var nameControlLabel = Xrm.Page.getControl("name").getLabel();
    
    
  87. CHANGE THE LABEL FOR A CONTROL

    Xrm.Page.getControl("name").setLabel("Company Name");
    
    
  88. GET THE NAME OF A CONTROL

    var firstControlName = Xrm.Page.getControl(0).getName();
    
    
  89. GET THE PARENT OF A CONTROL

    var parentSection = Xrm.Page.getControl("name").getParent();
    
    
  90. SET FOCUS ON A CONTROL

    Xrm.Page.getControl("name").setFocus();
    
  91. ADD AN OPTION TO AN OPTIONSET CONTROL

    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

    Xrm.Page.getControl("address1_addresstypecode").clearOptions();
    
  93. REMOVE A SINGLE OPTION FROM AN OPTIONSET CONTROL.

    Xrm.Page.getControl("address1_addresstypecode").removeOption(1);
    
  94. GET THE URL FOR THE CONTENT CURRENTLY DISPLAYED IN AN IFRAME.

    var iframeSource = Xrm.Page.getControl("IFRAME_targetPage").getSrc();
    
  95. SET THE URL FOR THE CONTENT TO BE DISPLAYED IN AN IFRAME.

    Xrm.Page.getControl("IFRAME_targetPage").setSrc("http://www.bing.com");
    
  96. ADD A CUSTOM VIEW FOR A LOOKUP.

    var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
    var viewDisplayName = "SDK Sample View";
    var fetchXml = ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    "";
    var layoutXml = ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    ""+
    "";
    Xrm.Page.getControl("parentaccountid").addCustomView(viewId, "account", viewDisplayName, fetchXml, layoutXml, true);
    
  97. GET AND SET THE DEFAULT VIEW FOR A LOOKUP.

    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

    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);
    }
    
  99. REFRESH THE DATA DISPLAYED IN THE SUBGRID

    Xrm.Page.getControl("accountcontactsgrid").refresh();
    
  100. SPECIFY WHETHER A DATE CONTROL SHOULD SHOW THE TIME PORTION OF THE DATE.

    Xrm.Page.getControl("createdon").setShowTime(false);
    
  101. FORM NAVIGATION SCRIPTS, TABS AND SECTIONS SCRIPT AND OTHER IMPORTANT SCRIPTS

    TaskMethodExample
    Get the name of a navigation itemgetIdvar 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.getLabelvar 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 itemsetLabelXrm.Page.ui.navigation.items.get(“navAddresses”).setLabel(“Other Addresses”);
    Change the More Addresses navigation item label to Other Addresses.
    Show or hide a navigation itemsetVisibleXrm.Page.ui.navigation.items.get(“navAddresses”).setVisible(false);
    Hide the More Addresses navigation item.
    Determine if a navigation item is visiblegetVisiblevar 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.setFocusXrm.Page.ui.navigation.items.get(“navAddresses”).setFocus();
    Set focus on the More Addresses navigation item.
    Determine if a tab is expanded or collapsedgetDisplayStatevar 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 tabsetDisplayStateXrm.Page.ui.tabs.get(“general”).setDisplayState(“collapsed”);
    Collapse the General tab.
    Determine if a tab is visiblegetVisiblevar 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 tabsetVisibleXrm.Page.ui.tabs.get(“general”).setVisible(false);
    Hide the General tab.
    Get the label for a tabgetLabelvar generalTabLabel = Xrm.Page.ui.tabs.get(“general”).getLabel();
    Assign the General tab label to the generalTabLabel variable.
    Change the label for a tabsetLabelXrm.Page.ui.tabs.get(“general”).setLabel(“Major”);
    Change the General tab label to Major.
    Set focus on a tabsetFocusXrm.Page.ui.tabs.get(“general”).setFocus();
    Set focus on the General tab.
    Get the name of the tabgetNamevar 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 sectiongetParentXrm.Page.getControl(“industrycode”).getParent().getParent().setFocus();
    Set focus on the tab that contains the Industry field.
    Determine if a section is visiblegetVisiblevar 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 sectionsetVisibleXrm.Page.getControl(“industrycode”).getParent().setVisible(false);
    Hide the section that contains the Industry field.
    Get the label for a sectiongetLabelvar 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 sectionsetLabelXrm.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 OnSaveeventaddOnSaveXrm.Page.data.entity.addOnSave(myFunction);
    Add the myFunction function to the OnSave event.
    Remove a function from the OnSaveeventremoveOnSaveXrm.Page.data.entity.removeOnSave(myFunction);
    Remove the myFunction function to the OnSave event.
    Add a function to the OnChangeevent of an attribute.addOnChangeXrm.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 attributeremoveOnChangeXrm.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 controladdPreSearchThe 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.getClientUrlvar serverUrl = Xrm.Page.context.getClientUrl();
    Assign a string that represents the URL to the serverUrlvariable.
    Get the unique identifier for the current user.getUserIdvar 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.getUserNamevar 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.getUserLcidvar 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.getUserRolesvar 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.getClientvar 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.getClientStatevar 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 entitygetEntityNamevar 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.
    getPrimaryAttributeValuevar 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 recordgetIdvar 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.refreshXrm.Page.data.refresh();
    Refreshes the data in the form.
    This method is only available for Updated entities.
    Save the current recordXrm.Page.data.entity.saveXrm.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.saveXrm.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.getIsDirtyvar 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.getDataXmlvar dataXml = Xrm.Page.data.entity.getDataXml();
    Assign a string that represents the data to be saved to the dataXmlvariable.



No comments:

Post a Comment