Thursday, 28 July 2016

Plugin in CRM


crm plugin 2013 This link tells about crm plugin 2013

Writing a Plugin MSDN
Exception in plugin


Plugins

A plug-in is a .NET assembly that can be used to interceptevents generated from the CRM system.

. Performing a complicated update routine on CRMentities and/or attributes when it might be impracticalto use JavaScript.

. Grabbing data from another system and updating CRMwhen an entity instance is being created or updated

. Updating another system programmatically

Using plug-ins, you can fire a custom action or event on anyentity, for example, on the account entity either before orafter it has been created, updated or deleted.

Event execution pipeline order in which the event and the plug-incalls are executed.
TIP



This is a step by step guide to create a plug-in in CRM 2011.

1. Create a class library project in vs2012.
2. Sign the assembly by using the Signing tab of the project's properties sheet.

3. Add references to microsoft.crm.sdk.proxy ,Microsoft.xrm.sdk ,system.ServiceModel and System.Runtime.Serialization.

4. Here is code for this tutorial. This plugin will check if the account number
field is empty, create a task for the user to fill this up.

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Text;
// Microsoft Dynamics CRM namespace(s)
usingMicrosoft.Xrm.Sdk;
usingSystem.ServiceModel;

namespace CRMPlugin1
{
public class createNote:IPlugin
{
public void Execute(IServiceProvider serviceProvider)
{

// Obtain the execution context from the service provider.
IPluginExecutionContext context = (IPluginExecutionContext)
serviceProvider.GetService(typeof(IPluginExecutionContext));


// The InputParameters collection contains all the data passed in the message request.
if (context.InputParameters.Contains("Target") &&
context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parmameters.
Entity entity = (Entity)context.InputParameters["Target"];



try
{
//check if the account number exist

if (entity.Attributes.Contains("account number") == false)
{

//create a task
Entity task = new Entity("task");
task["subject"] = "Account number is missing";
task["regardingobjectid"] = new EntityReference("account",newGuid(context.OutputParameters["id"].ToString()));

//adding attribute using the add function
// task["description"] = "Account number is missng for the following account. Please enter the account number";
task.Attributes.Add("description", "Account number is missng for the following account. Please enter the account number");



// Obtain the organization service reference.
IOrganizationServiceFactoryserviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);


// Create the task in Microsoft Dynamics CRM.
service.Create(task);


}
}

catch (FaultException ex)
{
throw new InvalidPluginExecutionException("An error occurred in the plug-in.", ex);
}

}

}
}//end class
}//end name space

5. Compile the code and register it on the registration tool provided with sdk.
6. Register it on the post create event of account entity.

Isolation:

This new version adds the concept of isolation called the sandbox.
Plug-ins can now beregistered in normal mode, which means without having any kind of isolation.

In otherwords, this mode will allow full trust on the code execution and full access to the server.

If the plug-in is registered inthe sandbox isolation mode, then it will run in partial trust and it won’t be allowed toaccess to some resources on the server, such as files, registry, database, and so on.

The levelof isolation, however, allows the access to HTTP and HTTPS web resources for externalweb services communication.

Modes:

You can set up plug-ins in synchronous or asynchronous mode.

Synchronous mode starts the execution of the plug-in when the event is fired and blocksthe CRM application process until the executed method finishes.
This option is notrecommended if you are performing a process that might take a long time to execute.
Regardless of the method used, synchronous or asynchronous, there is a timeout limit of2 minutes for plugin executions.




Stages:

Plug-ins can be set up in the Pre or Post stages:

The Pre stage sends control to the plug-in before the real event is executed in the coresystem.

Stage Number
Stage Name
10
Pre-validation
20
Pre-operation
30
Main Operation
40
Post Operation

Stage Number 30 we are not able to register any plugins.

Deployments:
There are three different ways to deploy a plug-in:
. Server
. Offline
. Both
Server means that the plug-in will execute on the server. Execution will occur when usersuse the web client or the Outlook Online client as well as when any workflow is executed.

Offline means the plug-in executes on the client’s user machine where Outlook isrunning. This is especially useful when running in the Outlook client in offline mode.

The Both type executes the plug-in on the server and in the Outlook client in offlinemode.

The Execute method of the IPlugin interface has been updated and the only parameterreceived is the IServiceProvider, unlike the previous version where it was used theIPluginExecutionContext as parameter.
From this parameter, we can get the plugin execution context by typing this line of code:
IPluginExecutionContext context =
(IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));





IExecutionContext:
From this object, you can query all the property values associated with the entity andevent context where the method is being executed.
This class contains the following properties:
. BusinessUnitId
. CorrelationId
. Depth
. InitiatingUserId
. InputParameters
. IsExecutingOffline
. IsInTransaction
. IsOfflinePlayback
. IsolationMode
. MessageName
. Mode
. OperationCreatedOn
. OperationId
. OrganizationId
. OrganizationName
. OutputParameters
. OwningExtension
. PostEntityImages
. PreEntityImages
. PrimaryEntityId
. PrimaryEntityName
. RequestId
. SecondaryEntityName
. SharedVariables
. UserId

BusinessUnitId
This property returns the GUID (Global Unique Identifier) of the business unit of theentity.
CorrelationId
This property returns the GUID of the plug-in event instance. Every time the event fires, itgenerates a new GUID that can be read from this property.
You can use this property for tracking and logging purposes, especially when you havemore than one plug-in attached to the same event to see whether the codes execute forthe same event pipeline.

Depth
This property returns the depth of the originated event. This property is of integer typeand grows as the plug-in execution goes deeper

InitiatingUserId
This property returns the GUID of the user who initially invoked the operation.
InputParameters
This property is a collection of the request parameters associated with the event. You canuse this property to retrieve the entity of which the event is fired:
Entity entity = (Entity)context.InputParameters[“Target”];
IsExecutingOffline
This property is used only for Outlook clients and returns whether the Outlook client isrunning in online or offline mode. This property is a Boolean type where true = offlinemode.
IsInTransaction
This property is used to know whether the operation is participating on a SQL transaction.
This property is a Boolean type where true = is in transaction.
IsOfflinePlayback
This property is used only for Outlook clients and returns whether the Outlook client istransitioning from offline to online mode. This property is a Boolean type where true =synchronizing with the server.
IsolationMode
This property returns the IsolationMode mode in which the plug-in is running.
0 = None
2 = Sandbox
MessageName
This property returns the event’s name that invoked the plug-in. It is a string—for
example, Update, Create, Delete, and so on.
Mode
This property returns the mode in which the plug-in is running. It can be synchronous or
asynchronous. This parameter is an integer type where the following is true:
0 = Synchronous
1 = ASynchronous
OperationId
This property returns the operation GUID when the plug-in is running in asynchronousmode and will give you the ID of the current system job. In synchronous mode, this valuewill be always an empty GUID.
OrganizationId
This property returns the organization GUID where the plug-in is running.
Even though plug-ins are registered by organization ID.


OrganizationName
This property returns the name of the organization where the plug-in is running.
OutputParameters
This property is the collection of properties returned by the event. A common outputparameter is the GUID returned when an entity is created.
Post stage:
GuidmyAccountID = (Guid)context.OutputParameters[“id”];
OwningExtension
This property returns the data associated with the step registration. This property type isan EntityReference class from which we can get, for example, the description of the stepthat is running where we registered the plug-in.
25
PostEntityImages
This property contains the collection of the images with the properties’ names and valuesafter the system executes the core operation.
NOTE
You need to specify the images and what properties you want to have on this collectionwhen you register the plug-in.
PreEntityImages
This property contains the collection of the images with the properties and values beforethe system executes the core operation. This is very useful on Post stages to see whatvalues the associated entity had before an update operation, for example.
NOTE
As with PostEntityImages, you also need to specify the images and what properties you
want to have with this collection when you register the plug-in.
PrimaryEntityId
This property returns the GUID of the entity’s record where the operation is performed. Ifyou are working with Accounts, you should use the following code to get the entity record
identifier:
Guid id = context.PrimaryEntityId;

PrimaryEntityName
This property gets the related primary entity name you specified when you registered theplug-in.
This property is a type of string and returns the name of the associated entity—for
example, account, contact, and so on.
RequestId
This property gets the id (GUID) of the asynchronous operation. It will return null forsynchronous operations.
SecondaryEntityName
This property gets he related secondary entity name if you specified one when registeringthe plug-in.

This entity is commonly used in the Parent Account or Contact of theAccount entity. This property is a type of string and returns the string none if nosecondary entity name is specified.
SharedVariables
This property is used as a common repository to store properties that plug-ins will share. It
is useful when you need to pass a parameter value from one plug-in to another that isbeing executed in the same event pipeline.
UserId
This property returns the GUID of the user who is invoking the operation.



IOrganizationService
Previously, the IPluginExecutionContext had methods to create the CRM and Metadata
Services; now you will see these methods are gone. To use the CRM services you need to
get an instance of the IOrganizationService as follows:
IOrganizationService service = factory.CreateOrganizationService(context.UserId)
The service instance returned by the IOrganizationService has the following methods:
. Associate—Used to create a link between records
. Create—Used to create records
. Delete—Used to delete records
. Disassociate—Used to remove a link between records
. Excecute—Used, for example, to execute Fetch queries
. Retrieve—Used to retrieve a record
. RetrieveMultiple—Used to retrieve more than one record

. Update—Used to update records

Registering a Plugin 

Login dialog for an online deployment

Dialog to register an assembly

Dialog to register a new step


Q. what is the use prevalidate  event in plugin ?
Ans- In pre validate event we dont check security roles also any  CRUD operation taking place cant be rollback while it can be roll back in pre operation.

Q.What care we take in update plugin ?
Ans- We need to use filter attribute .

Q. What is pre image and post image what is its use ?
Ans- 


No comments:

Post a Comment