Tuesday, 10 March 2015

23:38 - 2 comments

JavaScript Code for Age Calculation from Date of Birth | MS CRM


Age Calculation:

Add Java Scripts code as on change of Date Of Birth field value Then you will get age value when ever Date Of Birth value change.


function CalcAge()
{
    var now = new Date(); //Todays Date  
    var birthday = Xrm.Page.getAttribute("new_dob").getValue(); //Get the Date of Birth value 
    
    var diff = now.getMonth() - birthday.getMonth();  //Check to see if Birthday has already passed
if (diff > -1) //If Birthday has already occurred  
    {
        var bd1 = now.getFullYear() - birthday.getFullYear();
        //set the age attribute
        Xrm.Page.getAttribute("new_a").setValue(bd1.toString()); 
    }
    else //If Birthday has not already occurred 
    {
        var bd2 = now.getFullYear() - birthday.getFullYear() - 1;
        Xrm.Page.getAttribute("new_a").setValue(bd2.toString());
    }

}

Monday, 9 March 2015

22:18 - No comments

Filtering the sub grid records in dynamics CRM | MS CRM



Create a sub grid in the required entity.

For example I am adding Account sub grid in Lead entity Form:




Go to Settings à Customizations à Customize the system à Select the entity (Account) à Views



In views open Account Lookup view, Edit Filter criteria in that add condition


Now save and publish, then you will get the particular sub grid filter 

00:42 - No comments

Implementing Auto Numbering function using plugin in CRM: | MS CRM


Here I am going to create auto numbering plugin for lead entity

Step 1:
First create one custom entity for Auto Numbering. Which is used for configuring auto numbering operation.


Step 2:

Create following fields
1.       Entity Name
2.       Prefix or Postfix
3.       Starting Number


Step 3:
Create a field to display auto number in the required entity


Step 4:
Using the code below create a plugin for auto number generation.




Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Sdk.Discovery;
using Microsoft.Crm.Sdk.Messages;
using System.ServiceModel;
using System.Runtime.Serialization;


namespace AutoNumberPlugin
{
    public class Class1:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
  IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.
GetService(typeof(IPluginExecutionContext));
 IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.
GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName == "lead")
                {

                    try
                    {
                        var fetchXml ="<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                            fetchXml +="<entity name='new_auto'>";
                            fetchXml +="<attribute name='new_autoid' />";
                            fetchXml +="<attribute name='new_name' />";
                               fetchXml +="<attribute name='new_prefix' />";
                               fetchXml +="<attribute name='new_startingnumber' />";
                            fetchXml +="<attribute name='createdon' />";
                            fetchXml +="<order attribute='new_name' descending='false' />";
                            fetchXml +="<filter type='and'>";
                            fetchXml +="<condition attribute='new_name' operator='eq' value='"+entity.LogicalName+"' />";
                            fetchXml +="</filter>";
                            fetchXml +="</entity>";
                            fetchXml +="</fetch>";
                            var result = service.RetrieveMultiple(new FetchExpression(fetchXml));
                            if (result.Entities.Count > 0)
                            {
                                Guid AutoNumberId = ((Guid)result.Entities[0].Attributes["new_autoid"]);
                                String Prefix = ((String)result.Entities[0].Attributes["new_prefix"]);

                                String Number = ((String)result.Entities[0].Attributes["new_startingnumber"]);

                                Int32 No = Convert.ToInt32(Number);
                                No = No + 1;

                                String ACCcode = Prefix + (Convert.ToString(No)).PadLeft(4, '0');

                                ColumnSet attributes1 = new ColumnSet(new string[] { "leadid", "new_lead_id" });
                                Entity acc = service.Retrieve("lead", entity.Id, attributes1);
                                if (!(acc.Contains("new_lead_id")))   
                                {
                                    acc.Attributes["new_lead_id"] = ACCcode;
                                    service.Update(acc);


                                    ColumnSet attributes2 = new ColumnSet(new string[] { "new_startingnumber" });
                                    Entity ano = service.Retrieve("new_auto", AutoNumberId, attributes2);
                                    ano.Attributes["new_startingnumber"] = Convert.ToString(No);
                                    service.Update(ano);
                                }
                            }


                    }
                    catch (Exception ex)
                    {
                        throw new InvalidPluginExecutionException("An error occured in plugin. " + ex, ex);
                    }
                }
            }
        }


    }



}

Sunday, 8 March 2015

22:12 - 2 comments

Delete a Record in CRM using OData Query | MS CRM



To Delete a record in CRM, we require JQuery min 1.4 &  JSON2 script file which we can get from SDK from this specific path
SampleCode\JS\RESTEndpoint\JavaScriptRESTDataOperations\JavaScriptRESTDataOperations\Scripts

Now add the following code to your web resource,
Also add JSon.js and Jquery1.4min.js to the Library 

---------->


function delete()
{
var lookupObject = Xrm.Page.getAttribute("new_lookup").getValue();   //getting the id through lookup
var id = lookupObject[0].id;
var set="your entity schema nameSet"
deletelog(id,set);
}

function deletelog(id,odata)
{
 var serverUrl = Xrm.Page.context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    $.ajax({
    type: "POST",
    contentType: "application/json; charset=utf-8",
    datatype: "json",
    url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'"+id+"')",
    beforeSend: function (XMLHttpRequest) {
    XMLHttpRequest.setRequestHeader("Accept", "application/json");
    XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");
    },
    success: function (data, textStatus, XmlHttpRequest) {
    alert("Deleted successfully");
    },
    error: function (XmlHttpRequest, textStatus, errorThrown) {
    alert("Error while deletion " + errorThrown);
   
    }
    });
}

21:55 - No comments

Update a Record in CRM using OData Query | MS CRM




To Update a record in CRM, we require JQuery min 1.4 &  JSON2 script file which we can get from SDK from this specific path

Now add the following code to your web resource.
Also add JSon.js and Jquery1.4min.js to the Library
------------------>

function update()
{
var lookupObject = Xrm.Page.getAttribute("new_lookup").getValue();   //getting the id through lookup
var id = lookupObject[0].id;
var obj = new Object();
obj.new_name = "Hello";
var set="your entity schema nameSet"
updatelog(id,obj,set);

}
function updatelog(id,obj1,odata)
{
var jsonEntity = window.JSON.stringify(obj1);
var serverUrl = window.parent.Xrm.Page.context.getClientUrl();
var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
$.ajax({
                                type: "POST",
                                contentType: "application/json; charset=utf-8",
                                datatype: "json",
                                data: jsonEntity,
                                url: serverUrl + ODATA_ENDPOINT + "/" + odata + "(guid'" + id + "')",
                                beforeSend: function(XMLHttpRequest)
                                {
                                                XMLHttpRequest.setRequestHeader("Accept", "application/json");
                                                XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
        }
                                success: function (data, textStatus, XmlHttpRequest) {
                                alert("Updated successfully");
                                },
                                error: function (XmlHttpRequest, textStatus, errorThrown) {
                                if (XmlHttpRequest && XmlHttpRequest.responseText) {
                                alert("Error while updating " + odataSetName+ " ; Error – " + XmlHttpRequest.responseText);
                                }
                                }
                });

}

Friday, 6 March 2015

21:15 - No comments

Creating users in CRM 2015: | MS CRM

Creating users in CRM 2015:

In Microsoft online CRM we can create up to 25 users, where in on-premise CRM we can create n number of users. When we create new CRM there will be one default users that is admin, for creating more users with various privileges. Follow the steps below:
For Online CRM 2015:
Step 1:
 Settings -> Security -> Users and then click new ribbon then it will open a new window for add user.


 

After that click Add and License Users
A new tab will  be opened now. In that window click on the “+” button then it will open a dialog box.



Give the necessary details and then click “Create” button.

Now new user has been created.


Thursday, 5 March 2015

22:24 - No comments

CRM 2013 – Client API: Save | MS CRM

Event Arguments

There are a few useful additions that have been added to the client API around the Save event. They are 3 methods that have been formally introduced:
The key method is the getSaveMode function. Think about the new auto-save feature on updated forms. The getSaveMode function allow the JavaScript method executing on the Save event to know why/how the record is being saved. That gives you the flexibility as a developer to add some additional logic to handle your scenario… Below is the list of values returned by the getSaveMode function based on the entity type.


Entity
Event Mode
Value
All
Save
1
All
Save and Close
2
All
Save and New
59
All
AutoSave
70
Activities
Save as Completed
58
All
Deactivate
5
All
Reactivate
6
User or Team owned entities
Assign
47
Email (E-mail)
Send
7
Lead
Qualify
16
Lead
Disqualify
15
This is fantastic as you can now write script to handle very specific scenario like an activity being resolved, a record being saved and closed, assigned and other cases. Below is a usage example in which we prevent the auto-save from happening as presented in the SDK documentation:
Example code:
function preventAutoSave(econtext) {
   var eventArgs = econtext.getEventArgs();
   if (eventArgs.getSaveMode() == 70) {
      eventArgs.preventDefault();
   }

}