Thursday, June 9, 2011

Microsoft Dynamics CRM Architecture

Microsoft Dynamics CRM Architecture

In order to effectively customize Microsoft Dynamics CRM, you must first have good understanding of the application's architecture. The system's architecture influences how and where you can customize the system components.

The key to understanding the Microsoft Dynamics CRM architecture as it relates to customization is the Microsoft Dynamics CRM platform. One way to understand the value of the Microsoft Dynamics CRM platform is to contrast it with the client/server (two-tier) architecture that has been around for more than two decades.

Client/Server Architecture

In client/server architecture, most of the application logic is found in the client. The client processes the information and the server is typically just the database that processes transactions and stores the data. The services that the database provides may be unappreciated now that users have become accustomed to them. However, consider the difficulty that developers may face if they had to devise their own methods to store, retrieve, and manage data without the database.

The database simplifies much of the complexity that a developer has to deal with and provides him or her with the means to interact with the data through available APIs using languages such as Transact-SQL. But the client/server architecture has many shortcomings and there is only so much that a database designed for general use can provide.

Microsoft Dynamics CRM's Multi-Tier Architecture

Microsoft Dynamics CRM is a web-based application that uses a multi-tier architecture. This structure provides many benefits that support scalability, flexibility, and extensibility that cannot be matched using client/server architecture.

MICROSOFT DYNAMICS CRM CUSTOMIZATION ARCHITECTURE

In this multi-tier design, the Microsoft Dynamics CRM platform serves as an intermediary between the software developer and the database. Just as the database provides important services in the client/server architecture, the Microsoft Dynamics CRM platform provides a set of CRM specific APIs that not only handles interaction with the database, but also provides all the building blocks for the Microsoft Dynamics CRM application.

The parts of the picture marked with a cogindicate places where the Microsoft Dynamics CRM customizer can interact with the platform through code, the UI, custom reports etc. This course concentrates on the part labeled Extendable Application. The other parts will be described briefly, but detailed treatment is beyond the scope of this course.

The Microsoft Dynamics CRM platform removes the complexity that developers may otherwise have to deal with and provides a rich environment for customizing the application. Because it is designed specifically for use as a Relationship Management platform, it can provide more specific features that programmers can use when they build applications that use it.

The Business Entity Components part of the platform is responsible for creating domain-specific objects. Examples of domain-specific objects in Microsoft Dynamics CRM include Contact, Lead, Opportunity, Account, and Business Unit. These objects are created in response to instructions from the Application platform, ultimately from the Microsoft Dynamics standard UI or from customization code.

The goal of the Microsoft Dynamics CRM platform is to implement the service rules by manipulating and combining the underlying domain-specific objects. The platform accomplishes this by:

· Controlling access to objects through security

· Controlling access to the database through the data access layer

· Raising events for workflow processes and custom business logic implementations

Except for reports, every application that interacts with Microsoft Dynamics CRM does so through Web services in the Microsoft Dynamics CRM platform. This includes the Workflow tools and solutions created by ISVs. In summary, think of the platform layer as providing the entire infrastructure that is required to implement a complete Microsoft Dynamics CRM (or Extended CRM) application.

Domain and Business Logic

The platform by itself does not impose business-specific logic. This layer imposes only generic domain constraints. It contains the components for an application, but by itself is nothing more than a collection of related objects. However, the interaction between these domain specific objects implements more extensible business logic for the organization. You can apply business logic at the platform through workflow processes and plug-ins; or through the UI using Dialogs or event scripts on Forms.

· Microsoft Dynamics CRM Workflow enables you to create automated business processes at the platform layer. Workflow processes perform actions based on rules set up by the business. Workflow processes are triggered by events within Microsoft Dynamics CRM when specific actions are performed and specified conditions are met. The Workflows apply the business logic using built in steps or by allowing developers to add their own custom code to carry out a step.

· Plug-ins refer to the ability to create business logic extensions using pre- and post-plug-ins available in the platform. Plug-ins are extension points made available by the Microsoft Dynamics CRM platform. There is a published set of events that a Plug-In can subscribe to. As part of the subscription, a developer must specify an event handler, which is a segment of customized code that runs in response to the system event. There are certain parts of the Microsoft Dynamics CRM application that include business logic that is not found in the platform and cannot be customized.

An example of this is the logic that converts a Lead into a Contact, Account, and Opportunity. This behavior occurs because the application interacts with the platform to create these new objects based on programmatic information stored in the Lead object. The platform creates the Lead, but the built-in business logic performed by the application converts the Lead to a Contact, Account, and Opportunity.

Database Access

The Microsoft Dynamics CRM platform has a Data Access layer to handle all interactions between the application and Microsoft SQL Server, which contains the Microsoft Dynamics CRM database.

Developers must not directly access or update the CRM database for the following reasons:

· It introduces the opportunity for invalid or corrupt data to be added to the database, which in turn can cause the Microsoft Dynamics CRM platform to function incorrectly.

The Microsoft Dynamics CRM database structure might change without notice in a future release.

Saturday, May 21, 2011

Understanding Plug-ins in MS CRM 2011

What is a Plug-in??

A plug-in is custom business logic (code) that you can integrate with Microsoft Dynamics CRM 2011 and Microsoft Dynamics CRM Online to modify or augment the standard behavior of the platform. Another way to think about plug-ins is that they are handlers for events fired by the Microsoft Dynamics CRM platform. You can subscribe, also known as registering, a plug-in to a known set of events to have your code run when the event occurs.

CRM Event Pipeline

  • Calls to the CRM web services execute some message.
  • Each message creates a pipeline made up of various stages.
  • Plug-ins can be registered on different stages in the pipeline
  • A CRM “2011” plug-in is a .NET class that implementsMicrosoft.Xrm.Sdk.IPlugin
  • Assemblies registered with CRM and stored in database, GAC or on disk

CRM Event Pipeline Visualization

PreEvent

Stage 10: Pre-validation

PreEvent

Stage 20: Pre-operation

Core Operation

Stage 30: MainOperation

PostEvent

Stage 40: Post-operation

PostEvent

Stage 50: Post-operation (deprecated*)

Note: 20,30,40 are Transaction Scope


Parent/Child Pipelines

  • Parent and Child Pipelines no longer exist
  • Pre-event Plugin in Parent Pipeline in CRM 4.0

Pre-validation in CRM 2011 (outside transaction)

  • Pre-event Plugin in Child Pipeline in CRM 4.0

Pre-operation in CRM 2011 (inside transaction)

Sync/Async Execution

  • Plugins can execute

- Synchronously during pipeline execution

- Asynchronously – queued for later execution

Plug-ins in CRM4

  • Plug-ins ran in the same process context and not isolated
  • Plug-ins could not participate in SQL transactions
  • Plug-in registration had to be done by a Deployment Administrator

Plug-ins in CRM 2011

  • Able to participate in SQL transactions
  • Able to create traces returned with exceptions
  • Plug-in assemblies can have 2 isolation modes:

- None or Sandbox

  • The addition of the Sandbox isolation mode enables the use of plug-ins in CRM Online.

- Custom workflow activities will not be enabled in CRM Online for CRM 2011

Writing a Plugin

  • Implement IPlugin

Just the Execute method

  • Constructor can take two strings

Unsecure config

Secure config

  • Work with data from IPluginExecutionContext

Target, pre-images and post-images etc…

Handed a late bound Entity
Can transform to early bound type using generic method
targetEntity.ToEntity()

  • Ensure plugin code is stateless

Do not assume state is maintained between executions

Pre/Post Event Images

  • Snapshot of Entity state at that point in time
  • Removes need to call RetrieveRequest to get entity state during execution
  • Attributes to be imaged must be specified in registration

- SdkMessageProcessingStepRegistration.Images

  • Available via properties at runtime

- Pre: IPluginExecutionContext.PreEntityImages

- Post: IPluginExecutionContext.PostEntityImages

Offline Support

  • Offline plugins execute in context of CRM Outlook Add-in
  • Plugins can be: Online/Offline/Both
  • Check if offline via
    %ExecutionContext%.IsExecutingOffline
  • Offline plugins should be idempotent

- May be executed twice

- Use IsOfflinePlayback property to check

Transaction Support

  • CRM 2011 Stages support plugin execution inside the database transaction

- Stages 20 & 40

  • Uncaught exceptions force a rollback
  • IExecutionContext.IsInTransaction
  • Transaction spans CRM DB operations only

- No distributed transaction support

  • Plugins registered outside transaction stage will participate in transaction if executed as nested pipeline of transactional parent

Wednesday, May 18, 2011

Tips 'n' Tricks - MSCRM 2011

Dynamics CRM 2011: DL Configuration

Following are the Configuration Steps:

1. Add a Mailbox to the DL

2. Customize the QUEUE entity and add a custom Email Field on the form

3. Add the Mailbox EMAIL ID in the Email Field and DL in the Custom field.

4. Inbound should be Email Router.

5. Configure the Step1 mailbox in EmailRouter.

Mechanism: Any Email to DL will be sent to Mailbox(which is added in the DL),Email Router will process into CRM and if TO address matches the DL name then it will be sent to respective QUEUE.

Dynamics CRM 2011: Accessing Sub-Grid controls from form Javascript:

If CRM form has multiple Sub-grids and there is a requirement for some scripting to show/hide Sub-grid control, Place your sub-grids in different sections and show/Hide sections instead of controls. Since RTM version has a limitation to access all the sub-grid controls on the form through Scripting and this behavior is in-consistent.

Dynamics CRM 2011: Restrict Access to a field

1. Create a field security profile.

2. Associate users or teams with the profile.

3. Add specific field permissions, such as Create, Update or Read to the profile.

Dynamics CRM 2011: Size Limitations for Web Resource

The maximum size of files that can be uploaded is determined by the Organization.MaxUploadFileSize property. This property is set in the E-mail tab of the System Settings in the application. This setting affects more than just e-mail attachments. This setting will also limit the size of files that can be attached to notes and Web resources. The default setting is 5MB.

Dynamics CRM 2011: Edit Attribute Properties in Bulk

CRM 2011 facilitates to modify Attribute properties in Bulk from 'Field' list view of Entity.

We can update Requirement Level,Searchable and Audit Options in Bulk.Particularly this option will help alot when Audit is enabled at Entity level, since audit will get enabled for all fields by default. We can choose this option to Set/Reset Audit at attribute level.

Dynamics CRM 2011: Considerations for Code Upgrade

Followng are considerations for Code Upgrade from CRM 4.0 to Dynamics CRM 2011:

New Authentication Scheme: Supports claims-based authentication and Active Directory authentication

New Types: Supports use of native .NET types whenever possible. For example, the type CrmBoolean used in MSCRM 4.0 is now of type bool or System.Boolean.

New Entity Class:Use the Entity class to work with entities instead of the DynamicEntity class.This lets you use late binding so that you can work with types

Use WCF Data Services Instead of ASMX Files

Use the Consolidated and Expanded Query Methods:There are now three different types of queries you can use, depending on the best choice for your scenario.QueryExpression, FetchExpression and LINQ

Use New Error Handling: In WCF terms, exceptions returned from the channel are called faults.

for e.g. FaultException(Microsoft.Xrm.Sdk.OrganizationServiceFault)

Dynamics CRM2011: Number of records in a list (5000+) indication

We can configure the count of records value shown in the grid at the bottom.

In order todo this, we need to modify the TotalRecordCountLimit setting in the DeploymentProperties table of MSCRM_CONFIG database as below.

UPDATE DeploymentProperties

SET IntColumn = 'Reqd.Value'

WHERE ColumnName = 'TotalRecordCountLimit'

- Then do IISREST in the web server

- Note: This is applicable to all organizations in the server

Dynamics CRM 2011: Ribbon Area

The form editor does not let you customize the ribbon area. The ribbon controls displayed for a specific form are defined in three layers:

All Entities: An entity template defines a default set of form ribbon controls for all entities. This is the ribbon you will see in a new custom entity where the ribbon hasn’t been modified.

Per Entity: Changes to the default form ribbon definition can be defined for an entity that will appear in all forms for that entity.

Per Form: An individual form can contain changes to the default entity form ribbon definition in the RibbonDiffXml (FormXML) element.

Note:While the ribbon provides capabilities to retrieve data from a form or grid, the only capability to interact with the ribbon using form scripting is the Xrm.Page.ui.refreshRibbon method.

Dynamics CRM 2011: Debug a Sandboxed Plug-in

The sandbox host process monitors the sandbox worker process which is executing the plug-in. The host process checks if the plug-in stops responding, if it is exceeding memory thresholds, and more. If the worker process doesn't respond for than 30 seconds, it will be shutdown. In order to debug a sandbox plug-in, you must disable this shutdown feature. To disable the shutdown feature, set the following registry key to 1 (DWORD)

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSCRM\SandboxDebugPlugins

Dynamics CRM 2011: Remove unused "using" statement in VS2010

Most of the times in our code there will be using statements which are unused.

To remove these unused using statements, do the below.

Go to Visual Studio 2010 ->Open .cs file -> Right click -> select Organize Usings -> Remove Unused Usings

Dynamics CRM 2011: Update existing data using Data Import Tool

With CRM 2011, In order to update existing data, we can Export data to Excel and check the tiny box at the bottom to enable for re-import. It stores the GUID in a hidden column and upon re-import, updates the original data.

Dynamics CRM 2011: Javascript Global Context

When creating htm pages as webresources in 2011 there are many times you would want to get information about CRM such as the orgname and server url. This is where the ClientGlobalContext comes in to play.

""

Remember that if the web resource name has a folder name(s) before it you must include preceding "../" in front of the script name.By adding this reference into your htm file you will now have access to several javascript functions like getAuthenticationHeader,getOrgUniqueName,getUserId and getUserRoles etc.,

Dynamics CRM 2011: Dialog-Related Activities

In Microsoft Dynamics CRM 2011 , some new activities are introduced for the dialogs. These activities are available as steps in the Microsoft Dynamics CRM Process Designer.

Query CRM Data: Enables you to define query variables that can be used to query Microsoft Dynamics CRM data.

Assign Value: Enables you to perform simple arithmetic (increment, decrement, and multiply) and string (append) operations on the variables and input arguments in dialogs.

Link Child Dialog: You can specify a dialog as a child dialog, and invoke it from within another dialog (parent) by using the Link Child Dialog step in the parent dialog.

Stop Dialog: Enables you to end a dialog at a particular stage in the dialog flow.

JavaScript - MS CRM 2011

Dynamics CRM 2011: Passing Selected Record Guids to JS function

Use the below Xml Script to pass Selected Grid record Guids to JScript function called from Ribbon button

The Above CRM parameter "SelectedControlSelectedItemIds" is accessible in function "Clone"

function Clone(SelectedControlSelectedItemIds)

{

alert(SelectedControlSelectedItemIds);

//..

}


//Get Entity Name
function GetEntityName() {
return Xrm.Page.data.entity.getEntityName();
}

//Get User Id
function GetUserId() {
return Xrm.Page.context.getUserId()
}

//Get User Roles
function GetUserRole() {
return Xrm.Page.context.getUserRoles();
}
//Hide Tab
function HideTab(tabName){
var Tab = Xrm.Page.ui.tabs.get(tabName);
if (Tab != null){
Tab.setVisible(false);
}
}

//Display Tab
function DisplayTab(tabName) {
var Tab = Xrm.Page.ui.tabs.get(tabName);
if (Tab != null) {
Tab.setVisible(true);
}
}

//Hide Section
function HideSection(tabName, sectionName){
var Tab = Xrm.Page.ui.tabs.get(tabName);
if (Tab != null){
var Section = Tab.sections.get(sectionName);
if (Section != null) {
Section.setVisible(false);
}
}
}

//Display Section
function DisplaySection(tabName, sectionName) {
var Tab = Xrm.Page.ui.tabs.get(tabName);
if (Tab != null) {
var Section = Tab.sections.get(sectionName);
if (Section != null) {
Section.setVisible(true);
}
}
}

//Disable the attributes in a Section
function DisableAttributesSection(tabName, sectionName) {
var Tab = Xrm.Page.ui.tabs.get(tabName);
if (Tab != null) {
var Section = Tab.sections.get(sectionName);
if (Section != null) {
var iCount = Section.controls.getLength();
if (iCount > 0) {
for (var iLoop = 0; iLoop < iCount; iLoop++) {
Section.controls.get(iLoop).setDisabled(true);
}
}
}
}
}

//Enable the attributes in a Section
function EnableAttributesSection(tabName, sectionName) {
var Tab = Xrm.Page.ui.tabs.get(tabName);
if (Tab != null) {
var Section = Tab.sections.get(sectionName);
if (Section != null) {
var iCount = Section.controls.getLength();
if (iCount > 0) {
for (var iLoop = 0; iLoop < iCount; iLoop++) {
Section.controls.get(iLoop).setDisabled(false);
}
}
}
}
}

//Disable Attribute
function DisableAttribute(attributeName) {
var Attribute = Xrm.Page.data.entity.attributes.get(attributeName);
if (Attribute != null) {
Attribute.controls.get(0).setDisabled(true);
}
}

//Enable Attribute
function EnableAttribute(attributeName) {
var Attribute = Xrm.Page.data.entity.attributes.get(attributeName);
if (Attribute != null) {
Attribute.controls.get(0).setDisabled(false);
}
}

//Hide Attribute
function HideAttribute(attributeName) {
var Attribute = Xrm.Page.data.entity.attributes.get(attributeName);
if (Attribute != null) {
Attribute.controls.get(0).setVisible(false);
}
}

//Display Attribute
function DisplayAttribute(attributeName) {
var Attribute = Xrm.Page.data.entity.attributes.get(attributeName);
if (Attribute != null) {
Attribute.controls.get(0).setVisible(true);
}
}


//Set Values
function SetValues(attributeName, value, name, entityName) {
var Attribute = Xrm.Page.data.entity.attributes.get(attributeName);
if (Attribute != null) {
var type = Attribute.getAttributeType();
switch (type) {
case "boolean":
Attribute.setValue(value);
Attribute.setSubmitMode("always");
break;
case "decimal":
Attribute.setValue(parseFloat(value));
Attribute.setSubmitMode("always");
break;
case "double":
Attribute.setValue(parseFloat(value));
Attribute.setSubmitMode("always");
break;
case "integer":
Attribute.setValue(parseInt(value));
Attribute.setSubmitMode("always");
break;
case "money":
Attribute.setValue(parseFloat(value));
Attribute.setSubmitMode("always");
break;
case "optionset":
Attribute.setValue(parseInt(value));
Attribute.setSubmitMode("always");
break;
case "memo":
Attribute.setValue(value);
Attribute.setSubmitMode("always");
break;
case "string":
Attribute.setValue(value);
Attribute.setSubmitMode("always");
break;
case "datetime":
Attribute.setValue(value);
Attribute.setSubmitMode("always");
break;
case "lookup":
var values = new Array();
values[0] = new Object();
values[0].id = value;
values[0].name = name;
values[0].entityType = entityName;
Attribute.setValue(values);
Attribute.setSubmitMode("always");
break;
}
}
}

//Get Values
function GetValues(attributeName) {
var Attribute = Xrm.Page.data.entity.attributes.get(attributeName);
if (Attribute != null) {
var type = Attribute.getAttributeType();
var value = Attribute.getValue();
if (value != null) {
switch (type) {
case "boolean":
return value;
break;
case "decimal":
return value;
break;
case "double":
return value;
break;
case "integer":
return value;
break;
case "money":
return value;
break;
case "optionset":
return value;
break;
case "memo":
return value;
break;
case "string":
return value;
break;
case "datetime":
return value.toString();
break;
case "lookup":
return value[0].id.toString();
break;
}
}
}
}

MSCRM 2011 New Features