Advertisements

Archive

Archive for January, 2012

Reading Querystring using Jscript

January 24, 2012 1 comment

Hi,

Below is the Jscript function to parse query string (i.e., In to Parameter & Value pair)

// Read querystring and returns Parameter & Value pair Array

function fetchQueryStringParams() {

var qrStr = window.location.search;

var spQrStr = qrStr.substring(1);

var arrQrStr = new Array();

// splits each of pair

var arr = spQrStr.split(‘&’);

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

// splits each of field-value pair

var index = arr[i].indexOf(‘=’);

var key = arr[i].substring(0, index);

var val = arr[i].substring(index + 1);

// saves each of field-value pair in an array variable

arrQrStr[key] = val;

}

return arrQrStr;

}

How do I call this method?

function onload() {

var arrQrStr = fetchQueryStringParams();

alert(“First Name” + arrQrStr[‘fname’]);

alert(“Last Name” + arrQrStr[‘lname’]);

}

Hope it helps 🙂

You must use the Role Management Tool to install .Net Framework Exception

January 19, 2012 1 comment

Hi,

Today I got below error screen when I try to install .Net 3.5 Framework SP1 on my WIN 2008 R2 server .

Dotnet framework installation failed

Dotnet framework installation failed

 

Reason :-

  • Windows 2008 R2 natively ships with the .NET 3.5 SP1 framework.
  • So, it wont allow us to run the .Net 3.5 framework setup file.

Workaround :-

  • As Windows 2008 R2 ships with the .NET 3.5 SP1, We just need to enable the feature from “Server Manager“.

Steps to enable feature on Server Manager :-

  • Click on “Start” button and type keyword “Server”
  • Double click on “Server Manager” link
Opening Server Manager

Opening Server Manager

  • On the “Server Manager” window, Choose “Features -> Add Features”
Choose features on Server Manager

Choose features on Server Manager

  • Check the “Dotnet Frameowrk 3.5.1 Features” check box
Check the Dotnet Frameowrk 3.5.1 Features

Check the Dotnet Frameowrk 3.5.1 Features

  • Restart the server

Hope it helps 🙂

 

 

Fetching user security roles using Linq in CRM 2011 Plug-in’s

January 17, 2012 5 comments

Hi,

Below is the sample code to fetch the User’s security roles based on the “User Id” in the Plug-in’s using Linq

        /// <summary>

/// Returns the list of User security role names

/// </summary>

private List<string> GetUserRoles(IOrganizationService service, Guid userId) {

// Create Query Expression to fetch Role Entity

var query = new QueryExpression

{

// Setting the link entity condition and filter condition criteria/

LinkEntities =

{

new LinkEntity

{

LinkFromEntityName = “role”,

LinkFromAttributeName = “roleid”,

LinkToEntityName = “systemuserroles”,

LinkToAttributeName = “roleid”,

LinkCriteria = new FilterExpression

{

FilterOperator =

LogicalOperator.And,

Conditions =

{

new ConditionExpression

{

AttributeName =  “systemuserid”,

Operator =    ConditionOperator.Equal,

Values =

{

userId

}

}

}

}

}

},

ColumnSet = new ColumnSet(true),

EntityName = “role”

};

// Obtain results from the query expression.

var userRoles = service.RetrieveMultiple(query);

// Get the usre role names collection

var roleNames = new List<string>();

if (userRoles != null)   {

roleNames.AddRange(

from entrole in userRoles.Entities

select entrole as Role

into role

where role != null && role.RoleId != null

select role.Name);

}

return roleNames;

}

How do I call this method :-

  • In your plug-in, pass the service and User Id as parameters to this method

public void Execute(IServiceProvider serviceProvider) {

context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

var service = serviceFactory.CreateOrganizationService(context.UserId);

// Get the current users Security Roles Name’s

Var roleNames = GetUserRoles(service, this.context.UserId);

}

Hope it helps 🙂

Setting default view using Plug-in’s in CRM 2011

January 17, 2012 7 comments

Hi,

We often get the requirement to set a default view based on some criteria (Ex – Could be based on logged in user role, etc…). We can achieve this using a Plug-in.

Little insight :-

  • When you click on an entity (i.e., ‘Contacts’ in my sample) in CRM application, In the background a “RetreieveMultiple” method call  happens on “savedquery” entity.

'Contacts' link

  • “savedquery” is a system entity in CRM which stores the meta data of all the views in the system

Plug-in Logic :-

  • We register a Plug-in for the RetreieveMultiple message on the savedquery entity to be executed in the post stage
  • From “Outputparameters” fetch the “BusinessEntityCollection” (i.e., Views of particular entity)
  • Loop through the views and set “isdefault” property to “true” for the desired view

–          Below is the sample code

public void Execute(IServiceProvider serviceProvider)

{

this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

var service = serviceFactory.CreateOrganizationService(this.context.UserId);

if (this.context.InputParameters.Contains(“Query”) && this.context.InputParameters[“Query”] is QueryExpression && this.context.Stage == 40){

var qe = (QueryExpression)this.context.InputParameters[“Query”];

if (qe.Criteria != null) {

var condition = (ConditionExpression)qe.Criteria.Conditions[1];

// “Type code” of entity you want default views ( Object type code of ‘contact’ is 2)

//  Refer Useful article on how to get “Object Type Code”

if (condition.Values[0].Equals(2)) {

// Name of the view you want to set as Default

string ourDefaultView = “My custom view – Contacts”;

if (!string.IsNullOrEmpty(ourDefaultView)){

var collection = (EntityCollection)this.context.OutputParameters[“BusinessEntityCollection”];

collection = ChangeViewCollection(ourDefaultView, collection);

this.context.OutputParameters[“BusinessEntityCollection”] = collection;

}

}

}}}

/// <summary>

/// Setting IsDefault property of views

/// </summary>

private EntityCollection ChangeViewCollection(string ourDefaultViewName, EntityCollection records){

foreach (Entity record in records.Entities){

string viewName = (string)record[“name”];

if (viewName.Equals(ourDefaultViewName)){

record[“isdefault”] = new bool();

record[“isdefault”] = true;

}

else {

record[“isdefault”] = new bool();

record[“isdefault”] = false;

}

}

return records;

}

Plug-in Registration Steps :-

Message Name – RetrieveMultiple

Entity – SavedQuery

Stage – post

  • Register the assembly & Refresh the CRM application

@@ 🙂 Here goes my 50th article. Thanks for all your visits and valuable comments 🙂 @@

How to Debug Plug-Ins in CRM

January 13, 2012 7 comments

Hi,

Sometimes you might get wonder (even frustrated) why the debugger is not hitting the break point in your Plug-In code file.

Below are the Checklist to perform prior to start the debugging of your Plug-in assembly.

  • Ensure that your plug-in assembly is signed (See)
  • Rebuild the plug-in assembly
  • Reset the IIS (i.e. Open command prompt and run ‘iisreset’ command)
  • Restart CRM Asynchronous Service on CRM server (Only in case of asynchronous plug-in or Custom workflow )
  • Copy the .pdb file and your .dll file to server’s assembly (i.e., ..\Program Files\Microsoft Dynamics CRM\Server\bin\assembly)
  • Open the Plug-in Registration Tool (Download)
  • Browse the dll from your Plug-Ins projects “bin\debug” folder
  • In Plug-in Registration Tool , Choose “Specify the location where assembly should be stored” option as “Disk”
  • Register the step
  • Register the image(s) if any
  • Attach the process by opening the Plug-in project in the Visual Studio and then
    • From menu choose “Debug -> Attach to Process…” ( or Click ‘Alt + Ctrl + P’)
    • Select  w3wp.exe (i.e.,Worker Process), if plug-in is Synchronous
    • Select CRMAsyncService.exe, if Plug-in is asynchronous or Custom workflow.
Attaching Worker Process (w3wp.exe)

Attaching Worker Process (w3wp.exe)

  • You are all set by now and put a break point (Click F9) on relevant code line.

In case of Remote Debugger :-

  • If your CRM server machine is different from your development machine
  • Install “Visual Studio Remote Debugger” (Download) on CRM server machine
  • Run it as “Administrator”
  • Follow the same steps above except while attaching Process, in the “Attach to Process” window, set “Qualifier” as “CRM server machine”

Debug plug-in in outlook offline mode

  • Clean and rebuild the plug-in solution on your machine using visual studio
  • Register the plugin on the server
  • Synchronize the organization with the outlook
  • Go Offline
  • Attach the debugger to the process “Microsoft.Crm.Application.Hoster.exe
  • Place a breakpoint in the code.
  • Run the scenario

Hope it helps 🙂

Auto numbering logic in CRM 2011

January 11, 2012 Leave a comment

Hi,

Auto numbering feature is one of the most frequently asked requirement in CRM projects and below is the sample.

In my sample, I am going to generate an auto number to the each ‘Contact’ that create under a particular ‘Account’. The auto number format will be “Contact – 001, Contact – 002,….”.

To achieve the above requirement,  I am going to

  • Create a Plug-In on “Pre – Create” event of the contact
  • Use the CRM early bound

Steps :-

  • Generate  “Organization Service Context Class” using the Code Generation Tool (CrmSvcUtil.exe). (See)
  • You will get a “ServiceContext.cs” file with all entity wrapper classes.
  • Create a new Plug-In project and add the generated “ServiceContext.cs” file
  • Add a new class “ContactAutoNumber.cs” to the project and paste below code

public class ContactAutoNumber: IPlugin {

private Entity dynEntity;

private contact objContact;

public void Execute(IServiceProvider serviceProvider)        {

this.context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

var service = serviceFactory.CreateOrganizationService(this.context.UserId);

if (this.context.InputParameters.Contains(“Target”) && this.context.InputParameters[“Target”] isEntity)  {

// Obtain the target entity from the input parmameters.

this.dynEntity = (Entity)this.context.InputParameters[“Target”];

// Cast “Dynamic Entity” to “Contact”

this.objContact = this.dynEntity.ToEntity<contact>();

}

// Instantiate “Service Context” (i.e., The name of ‘Organization Service Context Class’)

var svcContext = new ServiceContext(service);

// Get the “Contact” list under parent ‘Account’ by “AccountId”

var contacts = svcContext.ContactSet.Where(

ns => (ns.AccountId.Id ==this.objContact.AccountId.Id));

// Get the count of the contacts

var cntContacts= Enumerable.Count(contacts);

// Increment the suffix count

var strFormat = (cntContacts + 1).ToString();

// Logic to prepare format “001,002,…..”

if (strFormat.Length < 3){

strFormat = (strFormat.Length == 1) ?

“00” + strFormat : “0” + strFormat;

}

// Set the auto number to your attribute

this.objContact.{Attribute_Name}= “contact – “ + strFormat;

}

}

}

Plug – In Registration step :-

Message : Create

Entity : contact

Statge : Pre

  • Register the Plug -in as above mentioned

Hope it helps 🙂