Tuesday, June 27, 2017

JavaScript For Querying An Entity And Updating Attribute Values In Form

Introduction

This article demonstrates how to query an entity using FetchXML, JavaScript (XRMServiceToolKit), and how to update the form fields on form load or on change event.

Steps to implement JavaScript function in Dynamics CRM Form

JavaScript filename - TotalValueUpdate.js 
  1. function TotalValues(FieldName, TotalFieldName) {  
  2.     var countval = Xrm.Page.getAttribute("new_count").getValue(); // To get the field value of count – used in FetchXML query  
  3.     var quarter = Xrm.Page.getAttribute("new_quarter").getValue(); // To get the field value of quarter – used in FetchXML query  
  4.     quarter = quarter - 1;  
  5.     var FieldValue = Xrm.Page.getAttribute(FieldName).getValue();  
  6.     var fetchXML = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" + " <entity name='new_report'>" + " <attribute name='new_reportid' />" + " <attribute name='new_name' />" + " <attribute name='" + TotalFieldName + "' />" + " <attribute name='createdon' />" + " <order attribute='new_name' descending='false' />" + " <filter type='and'>" + " <condition attribute='new_count' operator='eq' value='" + countval + "' />" + " <condition attribute='new_quarter' operator='eq' value='" + quarter + "' />" + " </filter>" + " </entity>" + "</fetch>"  
  7.     var Records = XrmServiceToolkit.Soap.Fetch(fetchXML);  
  8.     if (Records.length > 0) {  
  9.         var prevTotalValue = Records[0].attributes[TotalFieldName].value;  
  10.         var curTotalValue = prevTotalValue + FieldValue  
  11.         Xrm.Page.getAttribute(TotalFieldName).setValue(curTotalValue);  
  12.         return true;  
  13.     } else {  
  14.         Xrm.Page.getAttribute(TotalFieldName).setValue(FieldValue);  
  15.         return false;  
  16.     }  
  17. }   
To add the above JavaScript file to Web Resource in Microsoft Dynamics CRM, please follow the below steps.
Go to the top ribbon, select the Settings icon and from there, click on the "Solutions" to create a new custom solution.




To create new solution, provide the values to the yellow highlighted fields shown below.

Then, select Web Resources from the left navigation and upload the JavaScript file using New icon (yellow highlighted).




Click on the Form Editor of the Report form to configure how and when the JavaScript function should be called on change event of a field.

Now, select the field and Change Properties from the top ribbon.



Select the Events tab and include all the highlighted JavaScript files by clicking "Add" icon. The most important thing in Event Handlers section is to select the Event OnChange and map the TotalValues() from the TotalValueUpdate.js.



















































Now, go to the Events Handler section, click on the Add button to mention the JavaScript library name from the dropdown and to specify the function name. Then, click OK once you are done.












































Final output
Now, go to the entity form and check the value of Total values after entering this quarter value. It will be automatically adding the quarter value to the previous total and updating it to the current total value field.


I hope this article will be helpful for you to understand how to query Dynamics CRM Entities and update attributes in Form using JavaScript.

Wednesday, May 24, 2017

To read the XML using JavaScript (works in all browsers)

In this blog, I have explained the steps to read the XML using JavaScript. 

The below XML has Root "Tasks" and nodes "TaskName".

Input XML:
<?xml version="1.0" ?>
<Tasks>   
    <TaskName id="PromoteBestPractice">Promoted best practices</TaskName>
    <TaskName id="PromoteBeneEngage">Promoted beneficiary engagement and self-management</TaskName>
    <TaskName id="SustainPlan">Worked on a sustainability plan</TaskName>
</Tasks>


This JavaScript function accepts the xmlPath and xmlnodename as parameters. 

JavaScript:

function ChangeLabelTaskNameFrmXML(xmlPath,xmlnodename) {  
  
    var request = new XMLHttpRequest();
    request.open("GET", xmlPath, false);
    request.send();
    var xmldoc = request.responseXML; 
   //Extract the different values using a loop.     
    var xmlnode = xmldoc.getElementsByTagName(xmlnodename);

   // To read the xml nodes in XML file
    for (var i = 0; i < xmlnode.length; i++) {
        var lbltaskname = xmlnode[i].getAttribute('id');
        var newlbltaskname = xmlnode[i].textContent;
        alert ("Key:" + lbltaskname + "; Value: " + newlbltaskname );
   } 


Final Output will be displayed in message box with Key and Value as shown below.

Output:

Key: PromoteBestPractice; Value: Promoted best practices

Monday, May 22, 2017

Dynamics 365: To replace the labels in Entity Form using JavaScript


In this blog, have explained the steps for replacing the labels in Entity Form using JavaScript, XML and CSS files in Dynamics 365.

The total procedure contains 3 steps they are:

1.     XML file containing the label names to be replaced.

2.     Two JavaScript files are used here, one is for replacing the label and the other one to load the CSS dynamically.

3.     CSS file to change the styles of labels to wrap the text in the label.

XML Filename:

The most important things to be done in XML are naming root and nodes, id is the key to replace the label name. Field display name should be mentioned in id.

Tasks.XML

<?xml version="1.0" ?>

<Tasks>  

    <TaskName id="PnP">Promoted best practices, such as design, error handling and documentation. </TaskName>

    <TaskName id="Architecture">To build the process flow and infrastructure required for system. </TaskName>

    <TaskName id="SustainPlan">Worked on a sustainability plan</TaskName> 

</Tasks>

 Below JavaScript files will take care of the label text change.

JavaScript:

ReplaceLabels.js

function ChangeLabelTaskNameFrmXML() {  

   var xmlPath="../WebResources/new_Tasks.xml";

   //Put the <TaskName> element into an object. 

   var xmlnodePath = "//Tasks/TaskName";

   var xmldoc = new ActiveXObject("Microsoft.XMLDOM");

   xmldoc.preserveWhiteSpace = true;

   xmldoc.async = false;

   xmldoc.load(xmlPath);

   //Extract the different values using a loop.  

   var xmlnodelist;

   xmlnodelist= xmldoc.selectNodes(xmlnodePath);  

   for (var i = 0; i < xmlnodelist.length; i++) {

      var lbltaskname = xmlnodelist(i).getAttribute('id');

         var newlbltaskname =  xmlnodelist(i).text;

      ChangeLabelTaskName(lbltaskname, newlbltaskname);

   }

}



function ChangeLabelTaskName(lblTaskName, newlblTaskName)

{

  var lbl = "new_" + lblTaskName.toLowerCase();

  Xrm.Page.ui.controls.get(lbl).setLabel(newlblTaskName);  

}

Below JavaScript will load the CSS that contains the style for wrapping the text in label.

LoadCSS.js (for On-Premises and Online)

function LoadCSS(path) {

    var head = window.parent.document.getElementsByTagName('head')[0];

    var link = window.parent.document.createElement('link');

    link.rel = 'stylesheet';

    link.type = 'text/css';

    link.href = path;

    link.media = 'all';

    window.parent.document.head.appendChild(link);

}


 
Web Resources:
To Upload files (JavaScript, XML and CSS) to Web Resource.

While uploading files to Web Resource, you should provide few values like name, display name, file type and then upload file using browse button.


Form Properties:
After uploading files to Web Resources, you must select the Entity Form where the labels have to be replaced.

Now, go to Form Properties as shown above and add required JavaScript files as shown below. Once you have included the JavaScript files, you must map the functions from JavaScript and provide parameter values in Event Handlers section as shown in the below screenshots.

Please remember, we need to call these JavaScript functions on Form load (Control = Form, Event= OnLoad). That too CSS should be loaded first and then followed by replacing label text.

Here the function name is ChangeLabelTaskNameFrmXML and the parameters are provided as comma separated values.

Hope this article will help you to solve the issue in replacing form control labels with desired text.

Monday, May 15, 2017

To validate multiple HTML input form using single jQuery file

As we all know validation is very important for any input forms, Here is a sample for jQuery validation for HTML that can be used for any number form. Only thing we need to do is calling the jQuery function in each HTML input form. 

In the below example, we can see two files Input.html and validation.js. First 3 lines of Input.html shows how to link validation.js and other related jQuery files to make the validation work.

When the submit button is clicked, it will call the validation $('#newfrm').validate and follows the rules set in  $('#txtInput').rules('add', { rule1: true, rule2: true });

Rule:1 

This is responsible for validating the text only input in the text box with id txtInput.

Rule: 2

This is responsible for validating null value in the text box with id txtInput.

File: Input.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://code.jquery.com/ui/1.9.2/jquery-ui.js"></script>
<script type="text/javascript" src="Validation.js"></script>
<form id="newfrm">
    <input type="text" id="txtInput" name="txt" />
    <input type="submit" value="submit" />
    
</form>

File: Validation.js

var validator = $('#newfrm').validate({
        ignoreTitle: true,
        errorPlacement: function (error, element) {
            element.attr('title', error.text());
        }
    });

    $.validator.addMethod('rule1', function (value, element) {       
        var isValid = false;
        var regex = /^[a-zA-Z ]*$/;
        isValid = regex.test($(element).val());    
        $(element).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
        return isValid;        
    }, 'Rule 1, failed!');
    
    $.validator.addMethod('rule2', function (value, element) {
        var isValid = false;
        if($.trim($(element).val()) == '')
        {isValid = true;}        
        return isValid;       
    }, 'Rule 2, failed!');

    //Assign both rules to the text box.
    $('#txtInput').rules('add', { rule1: true, rule2: true });
});

Friday, May 12, 2017

How to write macro using Excel VBA with sample code - Dynamic Array


In the below code snippet, it shows how to create dynamic array in VBA with a simple example of storing list of people from the excel range and displaying it in message box.

Step:1 
Open excel sheet and provide list of people names in range starting from A1. 













Step:2

Now go to Developer tab and select visual basic to write macro.




Step:3

After seeing the below window, create a module (to create macro) by following the below steps.






















Step:4

Now copy and paste the below code snippet in the module.

Sub ListOfPeople()
'declare array of unknown length
Dim PersonNames() As String
'initially there are no people
Dim NumberOfPeople As Integer
NumberOfPeople = 0
'loop over all of the people cells
Dim PersonNameInCell As Range
Dim TopCell As Range
Dim ListofPeopleNamesRange As Range
Set TopCell = Range("A1")
Set ListofPeopleNamesRange = Range(TopCell, _
TopCell.End(xlDown))
For Each PersonNameInCell In ListofPeopleNamesRange
'for each person found, extend array
NumberOfPeople = NumberOfPeople + 1
ReDim Preserve PersonNames(NumberOfPeople - 1)
PersonNames(NumberOfPeople - 1) = PersonNameInCell.Value
Next PersonNameInCell
'list out contents to show worked
Dim msg As String
Dim i As Integer
msg = "People in array: " & vbCrLf
For i = 1 To NumberOfPeople
msg = msg & vbCrLf & PersonNames(i - 1)
Next i
MsgBox msg
End Sub



Step: 5

Close the coding window and go to Developer tab, click macros to run the macro you have created just now.






















Step: 6

Here is the final output, you have read the list of people from the excel range, stored it in dynamic array and finally displayed those list of people from the array.






















Hope it would have been helpful for you, will come up with another blog soon.










Thursday, May 11, 2017

To assign actions to links that are in DataGridView cells using C#


Here is the code to show another form based on the value in the DataGridView selected cell. You need to create another form (form2) and will be displayed on clicking the cell that contains values in the If condition. Please change the new form name in the code accordingly.

private void dataGridView1_CellContentClick(object sender,
DataGridViewCellEventArgs e)
{
  if (dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value != null)
  { 
   string cellval = dataGridView1.Rows[e.RowIndex].Cells[e.ColumnIndex].Value.ToString();
    if (cellval.Contains("google"))
     {
        Form2 frm = new Form2(this);
        frm.Show();
     }
   }


To set value for owner field in Dynamics CRM using Plugin


In this blog, I will demonstrate how to set value for the owner field on record creation in Child entity (Contact) from Parent entity (Account) plugin using C# in Dynamics CRM.

Creating a Plugin

The below code snippet shows how the owner field of the newly created record is being set. But one thing we need to know is this process can be done only during pre-creation stage, if we are trying to update the owner field of a record which is already created then we may need to use AssignRequest as shown in section 2.



Section:1

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

using Microsoft.Xrm.Sdk;

using Microsoft.Xrm.Sdk.Messages;

using System.ServiceModel.Description;

using Microsoft.Xrm.Sdk.Query;

using System.Runtime.Serialization;



namespace projectname.fieldmappings

{

    public class FieldMappings : IPlugin

    {

       //Main function of the plugin

        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.

            Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext)

                serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext));



            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));



            IOrganizationService orgService = serviceFactory.CreateOrganizationService(context.UserId);

           

            // The Input Parameters 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"];



                 //Create record in Contact Entity

                  Entity ContactDetails = new Entity("Contact");

                  // To assign the owner id of Contact Details

                  EntityReference owner = new EntityReference();

                  owner.Id = ((EntityReference)(entity.Attributes["primarycontactid"])).Id;// Taking id from current entity and assigning it to contact’s owner

                  owner.LogicalName = ((EntityReference)(entity.Attributes["primarycontactid"])).LogicalName; // Taking id from current entity and assigning it to contact’s owner

                  ContactDetails["ownerid"] = owner;



orgSvc.Create(ContactDetails);

            }

         }

      }

}



Please refer this link for registering and debugging the plugin.

Section: 2

To update the owner field of existing record, use the below code.

// Create the Request Object and Set the Request Object's Properties

AssignRequest assignowner = new AssignRequest

    {

        Assignee = new EntityReference(SystemUser.EntityLogicalName,

            _otherUserId),

        Target = new EntityReference(Account.EntityLogicalName,

            _accountId)

    };





// Execute the Request

orgService.execute(assignowner);

Output:

Account

Primary Contact: Dave Adam

Contact:

Owner: Dave Adam

No matter who creates the contact from Account but the plugin will set the primary contact as owner.

 Hope this blog may be helpful for you, will come up with another blog soon.

Augmented Reality and Virtual Reality

Here is the quick overview of Augmented Reality and Virtual Reality, also have explained how it is being used today and how it can chan...