Bhubaneswar, Odisha, India
+91-8328865778
support@softchief.com

101 Most Used Dynamics 365 CRM codes

101 Most Used Dynamics 365 CRM codes

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,
[code lang=”php”]
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;
[/code]

Most frequently used code snippets are given below,

    1. Code to connect Organization (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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);
      [/code]

    2. Derive Context, CRM service object in Plugin (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      IPluginExecutionContext context =
      (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext));
      IOrganizationServiceFactory serviceFactory =
      (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
      IOrganizationService Service =
      ServiceFactory.CreateOrganizationService(context.UserId);
      [/code]

    3. Validate if a specific attribute present in the plugin context input parameter (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      if (context.InputParameters.Contains("Target") && Context.InputParameters["Target"] is Entity)
      {
      //Your code goes here
      }
      [/code]
      [/code]

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

      [code lang=”php” tab_size=”4″ lines=”40″]
      if (entityObject.Attributes.ContainsKey("")
      {
      //Your code goes here
      }
      [/code]

    5. Get Value of attribute from entity (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      entityObject.GetAttributeValue("");
      entityObject. GetAttributeValue ("").Id.ToString();
      bool myAttributeVal = entityObject.GetAttributeValue("")
      string myAttributeVal = entityObject.GetAttributeValue("")
      [/code]

    6. Convert EntityCollection to DataTable (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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();
      }
      }
      [/code]

    7. Check if dataset is valid (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      bool flag=false;
      if(Objdataset.Tables.Count>0)
      {
      if(Objdataset.Tables[0].Rows.Count>0)
      {
      Flag=true;
      }
      }
      [/code]

    8. Retrieve Optionset Value from an AliasedValue (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      AliasedValue aliasedval=
      entityObject.GetAttributeValue< AliasedValue >("").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.
      [/code]

    9. Code to stop Plugin from infinite loop (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      // add this code before your actual plugin logic starts
      if (context.Depth &gt;1)
      return;[/code]

    10. Code to use Shared Variable in Plugins (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      //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"]);
      [/code]

    11. Get the Pre & Post Entity Images in Plugin (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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.
      [/code]

    12. Trace Messages using Tracing service in Plugin (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      ITracingService tracingService =
      (ITracingService)serviceProvider.GetService(typeof(ITracingService));
      tracingService.Trace ("");
      [/code]

    13. Get Optionset Text in Plugin (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      if(entity.Contains(""))
      {
      string optionsettext = entity.FormattedValues["attributename"];
      }
      [/code]

    14. Retrieve entity record data using Query Expression(C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      //Query for the GUID of the Acodeount using Acodeount Name
      QueryExpression query = new QueryExpression("acodeount");
      string[] cols = { "acodeountid", "name"};
      query.Criteria = new FilterExpression();
      query.Criteria.AddCondition("name", ConditionOperator.Equal, );
      query.ColumnSet = new ColumnSet(cols);
      EntityCollection acodeount = crmServices.RetrieveMultiple(query);
      //Casting the reference to GUID
      Guid acodeountId = (Guid)acodeount[0].Attributes["acodeountid"];
      [/code]

    15. Retrieve entity record data using Fetch XML(C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      string fetchxml = @"

      ";
      EntityCollection result = _serviceProxy.RetrieveMultiple(new FetchExpression(fetchxml));
      [/code]

    16. Retrieve entity record data using Guid of the record(C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      ColumnSet cs = new ColumnSet("attribute1","attribute2");
      Entity result = _serviceProxy.Retrieve ("", new Guid(""), cs);
      [/code]

    17. Update Entity Record (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Entity entityObj = new Entity();
      entityObj.LogicalName = "";
      entityObj.Id =
      entityObj. =
      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().</strong>
      [/code]

    18. Delete Entity Record (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      crmservice.Delete("",new Guid(""));
      [/code]

    19. Create an Entity Record using CRM service (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Entity entityObj = new Entity();
      entityObj.LogicalName = "";
      entityObj. = ;
      entityObj. = ;
      crmservice.Create(entityObj);
      [/code]

    20. Retrieve record using paging if more record present (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      // 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 = "parentacodeountid";
      pagecondition.Operator = ConditionOperator.Equal;
      pagecondition.Values.Add(_parentAcodeountId);

      // Create the query expression and add condition.
      QueryExpression pagequery = new QueryExpression();
      pagequery.EntityName = "acodeount";
      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 acodeount records in pages…\n");
      Console.WriteLine("#\tAcodeount 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 (Acodeount acodet in results.Entities)
      {
      Console.WriteLine("{0}.\t{1}\t{2}", ++recordCount,
      acodet.Name, acodet.EMailAddress1);
      }
      }
      // Check for more records, if it returns true.
      if (results.MoreRecords)
      {
      Console.WriteLine("\n****************\nPage number {0}\n****************",
      pagequery.PageInfo.PageNumber);
      Console.WriteLine("#\tAcodeount 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;
      }
      }
      [/code]

    21. Get Optionset Values and Text Metadata in CRM (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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();
      [/code]

    22. Update the Status of Records (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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

      [/code]

    23. Read Excel Sheet Record to Data Set (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      //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);

      [/code]

    24. Supress Duplicate Detection Rule while creating record (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      // Create operation by suppressing duplicate detection
      CreateRequest reqCreate = new CreateRequest();
      reqCreate.Target = acodeount;
      reqCreate.Parameters.Add("SuppressDuplicateDetection", true);
      // NOTE : Change to false to activate the duplicate detection.
      CreateResponse createResponse = (CreateResponse)_service.Execute(reqCreate);
      Guid _dupAcodeountId = createResponse.id;
      // Retrieve the acodeount containing with its few attributes.
      ColumnSet cols = new ColumnSet(
      new String[] { "name", "acodeountnumber"});
      Entity retrievedAcodeount = _service.Retrieve("acodeount", _dupAcodeountId, cols);
      // Update the existing acodeount with new acodeount number.
      retrievedAcodeount.AcodeountNumber = "Acode006";
      // Update operation – update record, if a duplicate is not found.
      UpdateRequest reqUpdate = new UpdateRequest();
      reqUpdate.Target = retrievedAcodeount;
      reqUpdate["SuppressDuplicateDetection"] = false; // Duplicate detection is activated.
      // Update the acodeount record.
      UpdateResponse updateResponse = (UpdateResponse)_service.Execute(reqUpdate);

      [/code]

    25. Assigning Values to Different DataType Field while creating Record (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      <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">acodeount["name"] = Convert.ToString("Microsoft India"); //String</td>
      </tr>
      <tr>
      <td width="150">Option Set</td>
      <td width="384">acodeount["acodeountcategorycode"] = new OptionSetValue(1); //Int</td>
      </tr>
      <tr>
      <td width="150">Two Options</td>
      <td width="384">acodeount["donotbulkemail"] = false; //boolean value -true/false</td>
      </tr>
      <tr>
      <td width="150">Image</td>
      <td width="384">entityObj["entityimage"] = File.ReadAllBytes("Images\\144×144.png");</td>
      </tr>
      <tr>
      <td width="150">Whole Number</td>
      <td width="384">acodeount["numberofemployees"] = 50; //int Value</td>
      </tr>
      <tr>
      <td width="150">Floating Point Number</td>
      <td width="384">acodeount["address1_latitude"] = Convert.ToDouble(-0.330); //double</td>
      </tr>
      <tr>
      <td width="150">Decimal Number</td>
      <td width="384">acodeount["attributename"] = Convert.ToDecimal(3.5); //deciaml</td>
      </tr>
      <tr>
      <td width="150">Currency</td>
      <td width="384">acodeount["revenue"] = new Money(50.60); //deciml Value</td>
      </tr>
      <tr>
      <td width="150">Multiple Lines of Text</td>
      <td width="384">acodeount["description"] = Convert.ToString("this is a great acode");</td>
      </tr>
      <tr>
      <td width="150">Date and Time</td>
      <td width="384">acodeount["lastusedincampaign"] = new DateTime(2017,11,23); //yyyy,mm,dd</td>
      </tr>
      <tr>
      <td width="150">Lookup</td>
      <td width="384">acodeount["address1_addressid"] = new EntityReference("address",new Guid("11111111-1111-1111-1111-111111111111")); //32 bit guid</td>
      </tr>
      </tbody>
      </table>
      [/code]

    26. Generate Entity Metadata using C#

      [code lang=”php” tab_size=”4″ lines=”40″]
      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();
      }
      [/code]

    27. Check if Old Value and New Value of Field are different in Plugin Images (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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
      }

      [/code]

    28. Early Bound Syntax creating Contact Record (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Contact contact = new Contact()
      {
      FirstName = "Charles",
      LastName = "Brown",
      Address1_Line1 = "123 Main St."
      };
      _contactId = _serviceProxy.Create(contact);
      [/code]

    29. Late Bound Syntax creating Contact Record (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Entity contactent = new Entity("contact");
      contactent["firstname"] = "Charles";
      contactent["lastname"] = "Brown ";
      contactent["address1_line1"] = "123 Main St.";
      Guid _contactId = _serviceProxy.Create(contactent);

      [/code]

    30. Declaring Input & Output Arguments,Default Value & Set Requirement Level of the Parameter in Custom Workflow Activities(C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      <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("acodeount", "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("acodeount")]
      [Default("3B036E3E-94F9-DE11-B508-00155DBA2902", "acodeount")]
      public InOutArgument AcodeountReference { 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;}

      [/code]

    31. Get Value from Input Argument in Custom Workflow Activities (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      <strong>If Input argument is declared as below then we can get the value as explained below.</strong>
      [Input("Date Of Birth")]
      public InArgument DOB { get; set; }

      protected override void Execute(CodeActivityContext context)
      {
      DateTime dtDOB = DOB.Get(context);
      }

      [/code]

    32. Set Value from Out Argument in Custom Workflow Activities (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      <strong>If Output argument is declared as below then we can get the value as explained below.</strong>
      [Output("FinalAge")]
      public OutArgument Age { get; set; }

      protected override void Execute(CodeActivityContext context)
      {
      int CalculatedAge=30;
      Age.Set(context, CalculatedAge);
      }

      [/code]

    33. A Sample Custom Workflow Code (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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; }
      }
      }
      [/code]

    34. A Sample Plugin Code (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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 acodeount is created.
      ////// Register this plug-in on the Create message, acodeount 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") &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 acodeount.
      // If not, this plug-in was not registered correctly.
      if (entity.LogicalName != "acodeount")
      return;

      try
      {
      // Create a task activity to follow up with the acodeount 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 acodeount in the task activity.
      if (context.OutputParameters.Contains("id"))
      {
      Guid regardingobjectid = new Guid(context.OutputParameters["id"].ToString());
      string regardingobjectidType = "acodeount";

      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 ocodeurred in the FollowupPlugin plug-in.", ex);
      }

      catch (Exception ex)
      {
      tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
      throw;
      }
      }
      }
      }
      }

      [/code]

    35. Write Log Messages into a Text File

      [code lang=”php” tab_size=”4″ lines=”40″]
      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();
      }
      [/code]

    36. Code for Exception handling (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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");
      }
      }
      }

      [/code]

    37. Create Outlook offline Filters (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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);

      [/code]

    38. Encryption and Decryption using C#

      [code lang=”php” tab_size=”4″ lines=”40″]
      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);
      }
      }
      }

      [/code]

    39. Read All Text to string and Read all Line to array form a Text File (C#)

      [code lang=”php” tab_size=”4″ lines=”40″]
      string path = @"c:\temp\MyTest.txt";
      // Open the file to read from.
      string readText = File.ReadAllText(path);
      string[] readText = File.ReadAllLines(path);

      [/code]

    40. Split Text using separator in C#

      [code lang=”php” tab_size=”4″ lines=”40″]
      string source = "ONE|TWO|THREE";
      string[] stringSeparators = new string[] {"|"};
      string[] result= source.Split(stringSeparators, StringSplitOptions.None);

      [/code]

    41. Acodeess Field by Name on Form (Formscript/Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var myAttribute = Xrm.Page.getAttribute("name");

      [/code]

    42. Acodeess Field by Index on Form (Formscript/Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var myAttribute = Xrm.Page.getAttribute(0);

      [/code]

    43. Get all Attributes on Form (Formscript/Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var allAttributes = Xrm.Page.getAttribute();

      [/code]

    44. Get All optionset Attributes of the Form

      [code lang=”php” tab_size=”4″ lines=”40″]
      var optionsetAttributes =
      Xrm.Page.getAttribute(
      function (attribute, index) {
      return attribute.getAttributeType() == "optionset";
      });

      [/code]

    45. Alert All attributes with Required Validation of the Form (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      function AlertRequiredAttributes () {
      Xrm.Page.data.entity.attributes.forEach(
      function (attribute, index) {
      if (attribute.getRequiredLevel() == "required")
      { alert(attribute.getName()); }
      });
      }
      [/code]

    46. Get the Value of a field/attribute on form (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var fieldvalue= Xrm.Page.getAttribute("name").getValue();

      [/code]

    47. Set the Value of a field/attribute on form (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getAttribute("name").setValue("new value");

      [/code]

    48. Get the text value of the currently selected option of an optionset attribute (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var addressType = Xrm.Page.getAttribute("address1_addresstypecode").getText();

      [/code]

    49. Get the currently selected option object in an optionset attribute (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getSelectedOption();

      [/code]

    50. Get the type of attribute (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var attributeType = Xrm.Page.getAttribute("address1_addresstypecode").getAttributeType();

      [/code]

    51. Get how the attribute is formatted (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var attributeFormat = Xrm.Page.getAttribute(0).getFormat();

      [/code]

    52. Get the initial value of a Booleanor Optionset attribute (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var attributeInitialValue = Xrm.Page.getAttribute("address1_addresstypecode").getInitialValue();

      [/code]

    53. Determine whether an attribute value has changed (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var isNameChanged = Xrm.Page.getAttribute("name").getIsDirty();

      [/code]

    54. Get Maximum Value of a Field (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Var limitMaxvalue = Xrm.Page.getAttribute("creditlimit").getMax();

      [/code]

    55. Get the maximum allowed length for an attribute that contains a string (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var maxNameLen= Xrm.Page.getAttribute("name").getMaxLength();

      [/code]

    56. Get MInimum Value of a Field (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Var limitMinvalue = Xrm.Page.getAttribute("creditlimit").getMin();

      [/code]

    57. Get the logical name of an attribute (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var attributeName = Xrm.Page.getAttribute("creditlimit").getName();

      [/code]

    58. Get the Option set text by value of attribute (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var addressTypeOption = Xrm.Page.getAttribute("address1_addresstypecode").getOption(1);
      alert(addressTypeOption.text); //displays ‘Bill To’

      [/code]

    59. Get the requirement level of an attribute (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var creditLimitRequired = Xrm.Page.getAttribute("creditlimit").getRequiredLevel();

      [/code]

    60. Set the requirement level of an attribute as Required (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getAttribute("creditlimit").setRequiredLevel("required"); //required/none/ recommended

      [/code]

    61. Check if the data in an attribute will be submitted when the data is saved (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      var nameSubmitMode = Xrm.Page.getAttribute("name").getSubmitMode(); // always/never/ dirty

      [/code]

    62. Control whether data in an attribute will be saved when the record is saved

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getAttribute("name").setSubmitMode("always");

      [/code]

    63. Prevent a record from being saved.

      [code lang=”php” tab_size=”4″ lines=”40″]
      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.

      [/code]

    64. Determine what action initiated the save.event (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      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
      [/code]

    65. Display a notification message near the field control to indicate that data is not valid. (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getAttribute("name").controls.forEach(
      function (control, i) {
      control.setNotification("’Input Value’ is not valid.");
      })

      [/code]

    66. Remove a notification message already displayed for a control.

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getAttribute("name").controls.forEach(
      function (control, i) {
      control.clearNotification();
      })

      [/code]

    67. Display form level notifications message (javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.ui.setFormNotification(
      "Hello",
      "INFO",
      "myMsg"
      );
      // <strong>myMsg</strong> is a uniquid used while displaying the message.
      [/code]

    68. Remove form level notifications message (Javascript)

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.ui.clearFormNotification("<strong>myMsg</strong>");

      [/code]

    69. Display a non-blocking alert dialog with a callback function

      [code lang=”php” tab_size=”4″ lines=”40″]
      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.

      [/code]

    70. Display a non-blocking confirm dialog with different callbacks depending on the button clicked by the user.

      [code lang=”php” tab_size=”4″ lines=”40″]
      var agree = false;
      Xrm.Utility.confirmDialog(
      "Do you agree?",
      function () { agree = true;},
      function () { agree = false; }
      );

      [/code]

    71. Acodeess all the controls for a specific attribute

      [code lang=”php” tab_size=”4″ lines=”40″]
      var nameControls = Xrm.Page.getAttribute("name").controls.get();

      [/code]

    72. Acodeess a control by name

      [code lang=”php” tab_size=”4″ lines=”40″]
      var nameControl = Xrm.Page.getControl("name");

      [/code]

    73. Acodeess a control by index

      [code lang=”php” tab_size=”4″ lines=”40″]
      var firstControl = Xrm.Page.getControl(0);

      [/code]

    74. Acodeess all controls

      [code lang=”php” tab_size=”4″ lines=”40″]
      var allControls = Xrm.Page.getControl();

      [/code]

    75. Get all optionset controls

      [code lang=”php” tab_size=”4″ lines=”40″]
      var optionsetControls = Xrm.Page.getControl(function (control, index) {
      return control.getControlType() == "optionset";
      })

      [/code]

    76. Get all controls of a specific section of a Tab

      [code lang=”php” tab_size=”4″ lines=”40″]
      var generalTabAcodeountInfoSectionControls = Xrm.Page.ui.tabs.get("general").sections.get("address").controls.get();

      [/code]

    77. Disable all controls for an attribute

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });
      [/code]

    78. Acodeess a field from header section with attribute name is customername

      [code lang=”php” tab_size=”4″ lines=”40″]
      var nameControlInHeader = Xrm.Page.getControl("header_customername");

      [/code]

    79. Acodeess a field control from business process flow

      [code lang=”php” tab_size=”4″ lines=”40″]
      var nameControlInBPF = Xrm.Page.getControl("header_process_name");

      [/code]

    80. Check if a control is Visible

      [code lang=”php” tab_size=”4″ lines=”40″]
      var isNameVisible = Xrm.Page.getControl("name").getVisible();

      [/code]

    81. Hide or show a control of a field

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getControl("name").setVisible(false);

      [/code]

    82. Get a reference to the attribute for the control

      [code lang=”php” tab_size=”4″ lines=”40″]
      var nameAttribute = Xrm.Page.getControl("name").getAttribute();

      [/code]

    83. Get all optionset controls

      [code lang=”php” tab_size=”4″ lines=”40″]
      var optionSetControls = Xrm.Page.getControl(function (control, index) { return control.getControlType() == "optionset"; });

      [/code]

    84. Return all disabled controls

      [code lang=”php” tab_size=”4″ lines=”40″]
      var disabledControls = Xrm.Page.getControl(function(control, index) { return control.getDisabled(); });

      [/code]

    85. Disable or enable each control

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getAttribute("name").controls.forEach(function (control, index) { control.setDisabled(true); });

      [/code]

    86. Get the label for a control

      [code lang=”php” tab_size=”4″ lines=”40″]
      var nameControlLabel = Xrm.Page.getControl("name").getLabel();

      [/code]

    87. Change the label for a control

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getControl("name").setLabel("Company Name");

      [/code]

    88. Get the name of a control

      [code lang=”php” tab_size=”4″ lines=”40″]
      var firstControlName = Xrm.Page.getControl(0).getName();

      [/code]

    89. Get the parent of a control

      [code lang=”php” tab_size=”4″ lines=”40″]
      var parentSection = Xrm.Page.getControl("name").getParent();

      [/code]

    90. Set focus on a control

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getControl("name").setFocus();
      [/code]

    91. Add an option to an optionset control

      [code lang=”php” tab_size=”4″ lines=”40″]
      var addressTypeCodeControl = Xrm.Page.getControl("address1_addresstypecode");
      var billToAddressOption = addressTypeCodeControl.getAttribute().getOption(1);
      addressTypeCodeControl.clearOptions();
      addressTypeCodeControl.addOption(billToAddressOption);
      [/code]

    92. Remove all the options from an optionset control

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getControl("address1_addresstypecode").clearOptions();
      [/code]

    93. Remove a single option from an optionset control.

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getControl("address1_addresstypecode").removeOption(1);
      [/code]

    94. Get the URL for the content currently displayed in an IFRAME.

      [code lang=”php” tab_size=”4″ lines=”40″]
      var iframeSource = Xrm.Page.getControl("IFRAME_targetPage").getSrc();
      [/code]

    95. Set the URL for the content to be displayed in an IFRAME.

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getControl("IFRAME_targetPage").setSrc("http://www.bing.com");
      [/code]

    96. Add a custom view for a lookup.

      [code lang=”php” tab_size=”4″ lines=”40″]
      var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
      var viewDisplayName = "SDK Sample View";
      var fetchXml = ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      "&lt;link-entity "+ "alias=’acodeountprimarycontactidcontactcontactid’ "+ "name=’contact’ "+ "from=’contactid’ "+ "to=’primarycontactid’ "+ "link-type=’outer’ "+ "visible=’false’&gt;"+
      ""+
      ""+
      ""+
      "";
      var layoutXml = ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      ""+
      "";
      Xrm.Page.getControl("parentacodeountid").addCustomView(viewId, "acodeount", viewDisplayName, fetchXml, layoutXml, true);
      [/code]

    97. Get and Set the default view for a lookup.

      [code lang=”php” tab_size=”4″ lines=”40″]
      var defaultViewId = Xrm.Page.getControl("parentacodeountid").getDefaultView();
      var viewId = "{C7034F4F-6F92-4DD7-BD9D-9B9C1E996380}";
      Xrm.Page.getControl("parentacodeountid").setDefaultView(viewId);
      [/code]

    98. Filter the records returned for a lookup control

      [code lang=”php” tab_size=”4″ lines=”40″]
      var Sdk = window.Sdk || {};
      Sdk.filterCustomerAcodeounts = function () {
      //Only show acodeounts with the type ‘Preferred Customer’
      var customerAcodeountFilter = "";
      Xrm.Page.getControl("parentacodeountid").addCustomFilter(customerAcodeountFilter, "acodeount");
      }
      //set ‘Sdk.setParentAcodeountIdFilter’ in the Opportunity form Onload event handler
      Sdk.setParentAcodeountIdFilter = function () {
      Xrm.Page.getControl("parentacodeountid").addPreSearch(Sdk.filterCustomerAcodeounts);
      }
      [/code]

    99. Refresh the data displayed in the subgrid

      [code lang=”php” tab_size=”4″ lines=”40″]
      Xrm.Page.getControl("acodeountcontactsgrid").refresh();
      [/code]

[/code]

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

    [code lang=”php” tab_size=”4″ lines=”40″]
    Xrm.Page.getControl("createdon").setShowTime(false);
    [/code]

 

[/code]

  • 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 Acodeount 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 Acodeount Name field.
    Add a function to the PreSearchevent of a lookup control addPreSearch The following code sample is for the Opportunity form Acodeount (parentacodeountid) lookup. When the Sdk.setParentAcodeountIdFilter function is set in the form Onloadevent handler, the Sdk.filterCustomAcodeounts function is added to the PreSearch event for that lookup. The result is that only acodeounts with the Category(acodeountcategorycode) value of Preferred Customer (1) will be returned.
    JavaScript
    var Sdk = window.Sdk || {};
    Sdk.filterCustomerAcodeounts = function () {
    //Only show acodeounts with the type ‘Preferred Customer’
    var customerAcodeountFilter = “”;
    Xrm.Page.getControl(“parentacodeountid”).addCustomFilter(customerAcodeountFilter, “acodeount”);
    }
    //set ‘Sdk.setParentAcodeountIdFilter’ in the Opportunity form Onload event handler
    Sdk.setParentAcodeountIdFilter = function () {
    Xrm.Page.getControl(“parentacodeountid”).addPreSearch(Sdk.filterCustomerAcodeounts);
    }
    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 Acodeess 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.

    [/code]

 

Thanks for reading the post.