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.

Performance issues and solutions for list and libraries in SharePoint

In this blog we are going to see the root cause for performance issues faced in SharePoint List and Libraries. Main reason for the performance issue is, lack of planning and not following the best practices.

Here I have listed down few things that may be the reason for causing performance issues.

· Lack of proper planning in creation of SharePoint List and Library.
· Views with proper grouping and filter not implemented.
· Absence of archival process for old documents or list items, makes the list or library to grow day by day and that will result in performance issue if not maintained properly.
· No cleanup activities on List or Library to remove unwanted items.

How to improve the performance of List or Library?

· Enabling indexing and implementing proper filters and grouping in views.
· Using proper folder structure to organize the contents.
· Based on the usage and type of content you can plan for Document center site if the contents are more related to documents repository.
· Implement proper retention policies by setting expiry date for documents created.
· Cleanup lists and libraries periodically.
· Storing high volume of media and other documents to OneDrive or secondary storage and have those links stored in a list.
· Now in SharePoint 2016 there are lot of new features for Document libraries have been introduced. Have mentioned few of them below:   
      a. Durable links (no more bad links, even if you move the files from one directory to another, Still the users will be able to make use of the old links to the document). Note: it works only for Microsoft office documents and PDFs.
      b. Now we can use OneDrive for business to store files and can be shared with other users.
      c. Large file support: Now supports uploading and downloading files larger than 2,047 MB.
      d. Special characters are allowed in filenames.
      e. Threshold limit has been increased above 5000 and auto indexing is in place.

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...