Wednesday 30 April 2014

Creating a record using Jscript

Create a record using JavaScript


The below snippet code can be used to create a record by java Script. we nedd to add Json2 and jquery1.4.1.min files to webresource which we can get from SDK.

function RecordCreate() {
if(Xrm.Page.getAttribute('new_name') != null)   //checking whether the attribute is null or not
{
var name = Xrm.Page.getAttribute('new_name').getValue();
}
if(Xrm.Page.getAttribute('new_mainphone') != null)
{
var mainphone = Xrm.Page.getAttribute('new_mainphone').getValue();
}
    var context = Xrm.Page.context;
    var serverUrl = context.getServerUrl();
    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";
    var CRMObject = new Object();
    /////////////////////////////////////////////////////////////
    // Specify the ODATA entity collection
    var ODATA_EntityCollection = "/AccountSet";           //Entity_NameSet--- type of record to be created
    /////////////////////////////////////////////////////////////
    // Define attribute values for the CRM object you want created
    CRMObject.Name = name;                        //"Name" is Schema Name of a field in my account entity
    CRMObject.Telephone1 = mainphone;      //"Telephone1" is Schema Name of a field in my account entity
      CRMObject.Address1_Name=name;
  
    //Parse the entity object into JSON
    var jsonEntity = window.JSON.stringify(CRMObject);
    //Asynchronous AJAX function to Create a CRM record using OData
    $.ajax({ type: "POST",
        contentType: "application/json; charset=utf-8",
        datatype: "json",
        url: serverUrl + ODATA_ENDPOINT + ODATA_EntityCollection,
        data: jsonEntity,
        beforeSend: function (XMLHttpRequest) {
            //Specifying this header ensures that the results will be returned as JSON.
            XMLHttpRequest.setRequestHeader("Accept", "application/json");
        },
        success: function (data, textStatus, XmlHttpRequest) {
            alert("success");
            var NewCRMRecordCreated = data["d"];
            alert("CRM GUID created: " + NewCRMRecordCreated.AccountId);    //AccountId is a Primary field in Account Entity.
        },
        error: function (XMLHttpRequest, textStatus, errorThrown) {
            alert("failure");
        }
    });
}

Phone number validation in crm 2011

The Below snippet is essential for Validating Phone no in CRM2011. Add the JavaScript as Web Resource in CRM. Add Web Resource as On-Change Event of a particular Phone no field. Also check the option of Pass Execution Context as first parameter in handler properties.

function validatePhone(context)
{

var phone =context.getEventSource().getValue();
var sTmp = phone.replace(/[^0-9]/g, "");
phoneRegex = /^\d{10}$/;

if( !sTmp.match( phoneRegex ) )
   {
   event.returnValue = false;
   alert("Phone must contain 10 numbers.") ;
   }
else
  {
   var sTmpClean =  "(" + sTmp.substr(0, 3) + ") " + sTmp.substr(3, 3) + "-" + sTmp.substr(6, 4);
   context.getEventSource().setValue(sTmpClean);
  }
}


 Here the Phone no is validated that it contains 10 Characters and all are numeric and later placed in a Pr-defined format which is "(xxx)xxx-xxxx".

Plugin code to retrieve the label from Optionset value

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Microsoft.Xrm.Sdk.Metadata;
using Microsoft.Xrm.Sdk.Messages;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk;


namespace online
{
    public class plugintest : IPlugin
    {
        public void Execution(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            Entity targetEntity = null;
            if(context.InputParameters.Contains("Target")&& context.InputParameters["Target"]is Entity)
            {
                targetEntity = (Entity)context.InputParameters["Target"];
                if(targetEntity.LogicalName!="new_applicant")
                {
                    return;
                }

            }
            else
            {
                return;
            }
            try
            {
                IOrganizationService service = factory.CreateOrganizationService(context.UserId);
                OptionSetValue a = (OptionSetValue)targetEntity["new_groupselected"];
                string b = Getoptionsetbyvalue(service, "new_groupselected", a);
                targetEntity.Attributes.Add("new_displaylabel", b);
                service.Update(targetEntity);

            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException(string.Concat("an error occured in plugin ", ex.Message, Environment.NewLine, ex.StackTrace));
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(string.Concat("An error occured in plugin ", ex.Message, Environment.NewLine, ex.StackTrace));

            }
        }
            public static string Getoptionsetbyvalue(IOrganizationService serviceProvider,string attribute,OptionSetValue option)
            {
                string label=string.Empty;
                RetrieveAttributeRequest retriveattributrequest=new RetrieveAttributeRequest();
                retriveattributrequest.EntityLogicalName="new_selecetedapplicant";
                retriveattributrequest.LogicalName="new_groupselected";
                retriveattributrequest.RetrieveAsIfPublished=true;

                RetrieveAttributeResponse retriveattributeresponse=(RetrieveAttributeResponse)serviceProvider.Execute(retriveattributrequest);
                AttributeMetadata attributemetadat=(AttributeMetadata)retriveattributeresponse.AttributeMetadata;
                PicklistAttributeMetadata picklist=(PicklistAttributeMetadata)attributemetadat;
                foreach(OptionMetadata metadata in picklist.OptionSet.Options)
                {
                    if(metadata.Value==option.Value)
                    {
                        label=metadata.Label.UserLocalizedLabel.Label;

                    }
                }
                return label;
            }
        }
    }

Basic Plug-in in CRM

Plug-in

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
using Microsoft.Xrm.Sdk;
using System.Runtime.Serialization;

namespace student
{
    public class students: IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            ITracingService tracer = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            Entity targetEntity=null;
            if(context.InputParameters.Contains("Target")&&context.InputParameters["Target"]is Entity)
            {
                targetEntity = (Entity)context.InputParameters["Target"];
                if(targetEntity.LogicalName!="new_selectedapplicant")
                {
                    return;
                }
            }
            else
            {
                return;
            }
            try
            {
                IOrganizationService service = factory.CreateOrganizationService(context.UserId);
                string a = targetEntity.FormattedValues["new_groupselected"];
           
   
             


                string b = ((string)targetEntity["new_name"]);
                string c = ((string)targetEntity["new_lastname"]);
                string d = ((string)targetEntity["new_fathersname"]);
                string e = ((string)targetEntity["new_emailid"]);
                string f = ((string)targetEntity["new_schoolname"]);
                decimal g = ((decimal)targetEntity["new_english"]);
                decimal h = ((decimal)targetEntity["new_hindi"]);
                decimal i = ((decimal)targetEntity["new_science"]);
                decimal j = ((decimal)targetEntity["new_maths"]);
                Entity contact = new Entity();
                if (a=="science")
                {
                    contact.LogicalName = "new_sciencestudent";
                    contact.Attributes.Add("new_name", b);
                    contact.Attributes.Add("new_lastname", c);
                    contact.Attributes.Add("new_fathersname", d);
                    contact.Attributes.Add("new_emailid", e);
                    contact.Attributes.Add("new_schoolname", f);
                    contact.Attributes.Add("new_english", g);
                    contact.Attributes.Add("new_hindi", h);
                    contact.Attributes.Add("new_science", i);
                    contact.Attributes.Add("new_maths", j);
                    service.Create(contact);
                }
                else if (a =="commerce")
                {
                    contact.LogicalName = "new_commercestudent";
                    contact.Attributes.Add("new_name", b);
                    contact.Attributes.Add("new_lastname", c);
                    contact.Attributes.Add("new_fathersname", d);
                    contact.Attributes.Add("new_emailid", e);
                    contact.Attributes.Add("new_schoolname", f);
                    contact.Attributes.Add("new_english", g);
                    contact.Attributes.Add("new_hindi", h);
                    contact.Attributes.Add("new_science", i);
                    contact.Attributes.Add("new_maths", j);
                    service.Create(contact);


                }
                else
                {
                    contact.LogicalName = "new_artsstudent";
                    contact.Attributes.Add("new_name", b);
                    contact.Attributes.Add("new_lastname", c);
                    contact.Attributes.Add("new_fathersname", d);
                    contact.Attributes.Add("new_emailid", e);
                    contact.Attributes.Add("new_schoolname", f);
                    contact.Attributes.Add("new_english", g);
                    contact.Attributes.Add("new_hindi", h);
                    contact.Attributes.Add("new_science", i);
                    contact.Attributes.Add("new_maths", j);
                    service.Create(contact);
                }
            }
            catch (FaultException<OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException(string.Concat("an error occured in plugin ", ex.Message, Environment.NewLine, ex.StackTrace));
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(string.Concat("An error occured in plugin " , ex.Message, Environment.NewLine, ex.StackTrace));

            }
       
        }
}
}

Mapping of Option Sets in Workflow

Mapping of Option Sets in Workflow


Mapping of Option Sets in Workflow

Option Sets assigned in each Entity are local within Entity hence cannot be used to map to another Entity in Workflows/Dialogues. So Option sets need to be declared globally.



1)    To Declare an Option set go to Settings.



2)    Now Go to Customizations in the Left Navigation Plane



3)    Now Open the Customize the System.



4)    Then the following Window will open,




5)    Now go to Option Sets in the Left Navigation Plane.



6)    Now Create a new Option set.


7)    Now give a name to the Options Sets, Add options and give label to each option and save it.



8)    Now go to the entity form where this option set is required. Click on new field, the following window will open give the name of the field and in Type choose option sets.




9)    Now select “Yes” for Use Existing Option Set



10)    Now select your Defined Option Set from the given Options.


11)    Now Click on Save & Close button.
12)    Repeat the steps 8 to 11 for another Entity Form.
13)    Now in Defining Workflow/Dialogue both the entity form fields can be mapped as shown below screen shot.

Creating Reports in CRM 2011

Reports are the graphical representation of concerned data. It consists is the replica of the data in graphical manner.

1)   Go to Workplace in Navigation plane in CRM. The above screen shot provides the description.


2)   Now go to Reports in My Work in Navigation plane


3)   Now Click on NEW in the Ribbon bar



4)   The following window will open



5)   Now Click on Report Wizard




6)   The following window will open and select whether creating aNew Report or Use an Existing Report from a lookup table and Click on Next.




7)   Now give a unique name to the Report, and give required description. Select any record from the option set forPrimary Record Type and Click on Next.
Eg:- to create a report for leads select Lead from the option sets.




8)   Now give a condition so that you can get the required fields. It better to put a condition as Status active, then it will consider all the active records from a particular entity. The following screen shot can explain you.




9)   Now Click on Next the following window opens. Now select the required fields as columns. You can also use Navigation arrows to move the column left/right.




10)            Now select the required fields and click on Next. The following window will open. Here we need to mention about type of record whether in Table form or Table with Chartform.
Note: - For table with chart should contain one numerical Column.
Click on Next.
I have choose Table with Chart option
Now the following window will open



Here you need to select a field for X-axis, as Y-axis is for mandatory be a numerical column.
Now Click on Next.



11)            Now the Report is created, the following window will Display it Click on Finish



12)            Now Go to Reports in My Work in Navigation plane
Double click on the Report name which you have mentioned
The following window will open. Now Click on Run Report.

  

13)            Then the following window will be displayed as report generating


14)            Finally the Report is generated. You can export it as XML/CSV formats.