Dynamics 365





Saturday, December 14, 2013

CRM 2011 - Auto populate values on lookup value selected - json ODATA

On Lookup up change get Account Entity values get auto populated using ODATA JSON script

function retrieveRecord() {

    var odataSetName = "AccountSet";
    debugger;
    var accountLookup = Xrm.Page.getAttribute("pmax_companyname1").getValue();
    if (accountLookup != null) {
        var AccountID = accountLookup[0].id;
    }
    // Get Server URL

    var serverUrl = Xrm.Page.context.getServerUrl();

    var serverUrl = "http://117.218.28.36/pmax-crm";

    //The OData end-point

    var ODATA_ENDPOINT = "/XRMServices/2011/OrganizationData.svc";

    //Asynchronous AJAX function to Retrieve a CRM record using OData
    debugger;
    $.ajax({

        type: "GET",

        contentType: "application/json; charset=utf-8", datatype: "json",

        url: serverUrl + ODATA_ENDPOINT + "/" + odataSetName + "(guid'" + AccountID + "')",

        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) {

            readRecord(data, textStatus, XmlHttpRequest)

        },

        error: function (XmlHttpRequest, textStatus, errorThrown) {

            alert("Error – " + errorThrown)

        }

    });

}

    function readRecord(data, textStatus, XmlHttpRequest) {

    alert("Record read successfully!!");

    var account = data;

    alert("Name – " + account.d.Telephone1);
    alert("Name – " + account.d.WebSiteURL);

    Xrm.Page.getAttribute("pmax_website").setValue(account.d.WebSiteURL);
    Xrm.Page.getAttribute("pmax_website").setSubmitMode("always");

    Xrm.Page.getAttribute("pmax_businessphone").setValue(account.d.Telephone1);
    Xrm.Page.getAttribute("pmax_businessphone").setSubmitMode("always");
  

    }

Thursday, December 12, 2013

Default the Activities 'Filter on' to 'All' for Account and Contact - CRM 2011


Default the Activities 'Filter on' to 'All' for Account and Contact

 

//default the Activities 'Filter on' to 'All' for Account and Contact 

function filterAllActivities() {
    document.getElementById("navActivities").onclick = function () {
        loadArea("areaActivities"); 
        document.getElementById("areaActivitiesFrame").onload = function () {
            var entityName = Xrm.Page.data.entity.getEntityName();
            var entity = entityName.charAt(0).toUpperCase() + entityName.substr(1);
            var doc = this.contentWindow.document;
            var filterOn = doc.getElementById("crmGrid_" + entity + "_ActivityPointers_datefilter"); 
            filterOn.value = "All";
            filterOn.FireOnChange();
        };
    };

 

Monday, November 4, 2013

Close quote Plugin code in c#.net

Close quote Plugin code in c#.net

Below code to achieve logic 
  using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
namespace CloseQuote
{
    public class PluginCloseQuote:IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            try
            {
                // Plugin to close the quote
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity && context.Depth<2)
                {
                    Entity entity = context.InputParameters["Target"] as Entity;

                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(new Guid?(context.UserId));


                    OrganizationServiceContext orgContext = new OrganizationServiceContext(service);
                    Entity postImageEntity = (context.PostEntityImages != null && context.PostEntityImages.Contains("PostImage")) ? context.PostEntityImages["PostImage"] : null;
                  
                    if (postImageEntity.GetAttributeValue<bool>("pmax_isclosequote"))
                    {
                     
                        if (((OptionSetValue)postImageEntity.Attributes["statecode"]).Value == 0)
                        {
                            //method to Activate quote
                            SetEntityStatus(service, entity.Id, "quote");

                        }
                       
                        //method to close quote
                        CloseQuoteRequest req = new CloseQuoteRequest();
                        Entity quoteClose = new Entity("quoteclose");
                        quoteClose.Attributes.Add("quoteid", new EntityReference("quote", entity.Id));
                        quoteClose.Attributes.Add("subject", "Customer was mean so we just closed it.");
                        req.QuoteClose = quoteClose;
                        req.RequestName = "CloseQuote";
                        OptionSetValue o = new OptionSetValue();
                        o.Value = 5;
                        req.Status = o;
                       
                        CloseQuoteResponse resp = (CloseQuoteResponse)service.Execute(req);
                    }
                    else if (postImageEntity.GetAttributeValue<bool>("pmax_isactivatequote"))
                    {
                        if (((OptionSetValue)postImageEntity.Attributes["statecode"]).Value == 0)
                        {
                            //method to Activate quote
                            SetEntityStatus(service, entity.Id, "quote");

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(
                   "An error occurred in the CloseQuote.PluginCloseQuote Plug-in" + ex.Message, ex);
            }
        }
        //activate the quote
        private void SetEntityStatus(IOrganizationService service, Guid recordGUID, string entityName)
        {

            SetStateRequest setState = new SetStateRequest();

            setState.EntityMoniker = new EntityReference();

            //Pass GUID of the record to be activated or Deactivated

            setState.EntityMoniker.Id = recordGUID;

            setState.EntityMoniker.Name = entityName;

            setState.EntityMoniker.LogicalName = entityName;

            //Setting ‘State’ i.e., (0 – Active ; 1 – InActive)

            setState.State = new OptionSetValue();

            setState.State.Value = 1;

            //Setting ‘Status’ i.e., (1 – Active ; 2 – InActive)

            setState.Status = new OptionSetValue();

            setState.Status.Value = 3;

            SetStateResponse setStateResponse = (SetStateResponse)service.Execute(setState);

        }
        private void SetEntityStatusActive(IOrganizationService service, Guid recordGUID, string entityName)
        {

            SetStateRequest setState = new SetStateRequest();

            setState.EntityMoniker = new EntityReference();

            //Pass GUID of the record to be activated or Deactivated

            setState.EntityMoniker.Id = recordGUID;

            setState.EntityMoniker.Name = entityName;

            setState.EntityMoniker.LogicalName = entityName;

            //Setting ‘State’ i.e., (0 – Active ; 1 – InActive)

            setState.State = new OptionSetValue();

            setState.State.Value = 3;

            //Setting ‘Status’ i.e., (1 – Active ; 2 – InActive)

            setState.Status = new OptionSetValue();

            setState.Status.Value = 5;

            SetStateResponse setStateResponse = (SetStateResponse)service.Execute(setState);

        }
        private SetStateRequest inactiveSuspect(Entity entSuspect)
        {
            //to set prospect record inactive
            //WinOpportunityRequest

           
            SetStateRequest setState = new SetStateRequest();

            setState.EntityMoniker = new EntityReference();

            //Pass GUID of the record to be activated or Deactivated

            setState.EntityMoniker.Id = entSuspect.Id;

            setState.EntityMoniker.Name = "quote";

            setState.EntityMoniker.LogicalName = entSuspect.LogicalName;

            //Setting ‘State’ i.e., (0 – Active ; 1 – InActive)

            setState.State = new OptionSetValue();

            setState.State.Value = 0;

            //Setting ‘Status’ i.e., (1 – Active ; 2 – InActive)

            setState.Status = new OptionSetValue();

            setState.Status.Value = 1;


            return setState;
            //
        }
    }
}
 

Wednesday, September 11, 2013

SubGrid Refresh or SubGrid Attach even usig Java Script

 below peice of code to refresh the subgrid.
 
function SubGridLoadWait() {
    setTimeout(OnAccountFormLoad, 3000);
}

function OnAccountFormLoad() {
    //Set Action on subgrid Refresh
    //debugger;
    var subGrid = document.getElementById("SuspectGrid");
    //if(subGrid) {
    subGrid.attachEvent("onrefresh", getPrimaryRows);

    //SubGrid.attachEvent("onrefresh", CallbackFunction);
    //SubGrid.control.add_onRefresh(CallbackFunction);

    //}

}

//This function fires on subgrid refresh

function getPrimaryRows() {
    var isPrimaryYes = false;
    var isPrimaryNo = false;
    var gridControl = document.getElementById('SuspectGrid').control;
    var ids = gridControl.get_allRecordIds();
    for (i = 0; i < ids.length; i++) {

        var primary = gridControl.getCellValue('new_isprimarysuspect', ids[i]);
        if (primary=="Yes") {
            isPrimaryYes = true;
            break;
        }
        else if(primary=="No"){
            isPrimaryNo = true;
        }
    }
    if (isPrimaryYes) {

        Xrm.Page.getAttribute("new_canhaveprimarysuspect").setValue(true);
//        alert("Primary Suspect checked");
    }
    else if (isPrimaryNo) {
        Xrm.Page.getAttribute("new_canhaveprimarysuspect").setValue(false);
      //  alert("Primary Suspect unchecked");
    }
}

Tuesday, September 3, 2013

Capitalize First String Character of a word in Text Field of Dynamics CRM 2011

 Capitalize First String Character of a word in Text Field of Dynamics CRM 2011
So, One of the Post in LinkedIn asking if anyone can help with a Script that can Capitalize First String Character of a word in Text Field of Dynamics CRM 2011.

For eg. If i have a custom Full Name Field or Address filed. If User enters like 1107 medowville lane,
The script should automatically converts it to Pascal Casing like, 1107 Medowville Lane.

I thought to give it a try and here is the full functional code.

function ConvertFirstCharToCaps()
{
var attribute = Xrm.Page.getAttribute("new_address"); // Change the Schema Name here

if(attribute != null)

var str = attribute.getValue();
    var pieces = str.split(" ");
    for ( var i = 0; i < pieces.length; i++ )
    {
        var j = pieces[i].charAt(0).toUpperCase();
        pieces[i] = j + pieces[i].substr(1);
    }

Xrm.Page.getAttribute("new_address").setValue(pieces.join(' '));

}

It can be converted to Parametrized Function, but here i am just giving an idea how this code can work on each field.

Hope this will help, Please change the Attribute name as per your Attribute Schema Name.

Thanks.

Wednesday, August 28, 2013

Prevent Users to Mark Complete or Close the Task if "Owner" of the Task is not the "Created by" of the Task using Plug-in in Dynamics CRM 2011

Requirement :  Prevent Users to Mark Complete or Close the Task if "Owner" of the Task is not the "Created by" of the Task using Plug-in in Dynamics CRM 2011.
On Click of Mark Complete on Ribbon button from anywhere in CRM Webpage (Form, Subgrid, HomeGrid), if the Task "Owner" is not Same as Task "Created By" then Owner should be prevented from Mark the Task Complete or Close with a User Friendly Message and and also a custom field on Task form called "Able to Mark complete" if the value of the Check box is true (Yes) then to override this requirement, i mean user can Mark Complete or Close.
Implementation:
First Create a Javascript to control the enabling and disabling of "Able to Mark complete" field on the Update form of Task. This field will be enabled for Creator of the Task on Create or Update form, but if the Owner of the Task is not the Creator of the Task then this field should be prevented to update on Update form of Task entity. Here is the JavaScript code to do so (I am avoiding the step to Add the JavaScript as web-resource and Attaching the code to Task form).
function DisableAbleToCompleteField()
{

var  formType = Xrm.Page.ui.getFormType();

   if (formType == 2)
   {
      var userid = Xrm.Page.context.getUserId();
      var creatorlookup = Xrm.Page.getAttribute("createdby");
      if (creatorlookup!= null)
      {
         var creatorlookupvalue = creatorlookup .getValue();
         if (creatorlookupvalue != null)
         {
              var creatorid = creatorlookupvalue[0].id;
          }
       }
                if (userid == creatorid) 
                  Xrm.Page.getControl("new_abletomarkcomplete").setDisabled(false);
           else       
                  Xrm.Page.getControl("new_abletomarkcomplete").setDisabled(true);
          
    }   else        
 Xrm.Page.getControl("new_abletomarkcomplete").setDisabled(false);
}

The Complete Code for the Plug-in to prevent an Owner to Mark Complete or Close the Task:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.Diagnostics;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.CSharp;
using System.Data;
using System.Runtime.Serialization;
using Microsoft.Crm.Sdk.Messages;

namespace TaskClosurePermissionPlugin

{
    public class TaskClosure : IPlugin
    {
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            if (context.PrimaryEntityName == "task")
            {

                if (context.InputParameters.Contains("EntityMoniker") && context.InputParameters["EntityMoniker"] is EntityReference && context.Depth < 2)

                {
                    if (context.PreEntityImages.Contains("PreImage"))
                    {

                        Entity taskentity = (Entity)context.PreEntityImages["PreImage"];

                        EntityReference owneridLookup = (EntityReference)taskentity.Attributes["ownerid"];
                        EntityReference createdbyLookup = (EntityReference)taskentity.Attributes["createdby"];
                       
                        if (owneridLookup.Id != createdbyLookup.Id)
                        {
                            if (taskentity.Contains("new_abletomarkcomplete") && !taskentity.GetAttributeValue<bool>("new_abletomarkcomplete"))
                            {
                                throw new InvalidPluginExecutionException("This Task is Created by : "+createdbyLookup.Name+" ,  User : "+owneridLookup.Name +" is not allowed to Mark Complete or Close the Task.");
                            }
                        }
                    }
                }
                else
                {
                    throw new InvalidPluginExecutionException("Activity should be Task.");
                }

            }


       }

    }
}

The Plugin has to use Pre-Image to compare the values of the fields before transaction happens in the Database.
Now the Registration Process of Plug-in:
Open the Plugin registration Tool, Select your Organization, Log as Admin user (Or if any user has granted permission). 
1. Register New Assembly by browsing your dll.
2. You have to Register steps for the plugin on SetState and SetStateDynamicEntity both steps.
3. Register Pre-Image for both Steps.
 
Once done, you are now Ok to test your business scenario,

Following are the screen shots, on Single Task and Multiple Tasks Closure Process from the CRM Landing Page (In My case Dashboard):

Single Task Selected:
Once done, you are now Ok to test your business scenario,

Following are the screen shots, on Single Task and Multiple Tasks Closure Process from the CRM Landing Page (In My case Dashboard):

Single Task Selected:
Once done, you are now Ok to test your business scenario,

Following are the screen shots, on Single Task and Multiple Tasks Closure Process from the CRM Landing Page (In My case Dashboard):

Single Task Selected:

Tuesday, August 6, 2013

Display label of option set based on value

 Dynamics 365 Optionset label display using Javascript

string GlobaloptionsetText = GetCRMOptionSetLabel(service, entity.LogicalName, "new_rating", irating);
   private string GetCRMOptionSetLabel(IOrganizationService service, string entityname, string optionsetname, int value)
        {
            Microsoft.Xrm.Sdk.Messages.RetrieveAttributeRequest reqOptionSet = new Microsoft.Xrm.Sdk.Messages.RetrieveAttributeRequest();
            reqOptionSet.EntityLogicalName = entityname;
            reqOptionSet.LogicalName = optionsetname;
            Microsoft.Xrm.Sdk.Messages.RetrieveAttributeResponse resp = (Microsoft.Xrm.Sdk.Messages.RetrieveAttributeResponse)service.Execute(reqOptionSet);
            Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata opdata = (Microsoft.Xrm.Sdk.Metadata.PicklistAttributeMetadata)resp.AttributeMetadata;
            var option = opdata.OptionSet.Options.FirstOrDefault(o => o.Value == value);
            return option.Label.LocalizedLabels.FirstOrDefault().Label;
        }

Monday, July 15, 2013

Random Number Generation through plug-in in MS Dynamics 2011

The Requirement is to generate a Unique Random Auto-generated Number while creating a record in Custom Prospect entity.

public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service =  (IOrganizationService)factory.CreateOrganizationService(context.UserId);

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
            {
                Entity entity = (Entity)context.InputParameters["Target"];
                int count = 0;
                if (entity.LogicalName == "new_prospect")
                {
                    // A Prospect number attribute should not already exist because
                    // it is system generated.
                

                    if (entity.Attributes.Contains("new_prospectnumber") == false)
                    {
                        // Create a new Prospect number attribute, set its value, and add
                        // the attribute to the entity's attribute collection.
                        Random rndgen = new Random();
                        entity.Attributes.Add("new_prospectnumber", rndgen.Next().ToString());
                        entity.Attributes.Add("new_updatecounter", count.ToString());
                      
                    }
                    else
                    {
                        // Throw an error, because Prospect numbers must be system generated.
                        // Throwing an InvalidPluginExecutionException will cause the error message
                        // to be displayed in a dialog of the Web application.
                        throw new InvalidPluginExecutionException("The Prospect number can only be set by the system.");
                    }
                }
            }
        }