/* Jscript */
function ShowPickListItem(listID, value)
{
var objList = document.getElementById(listID);
if (objList.SavedList != null)
{
var selValue = null;
var indexInsertion = 0;
for (var i=0; iif (objList.SavedList[i].value == value)
objList.SavedList[i].Visible = true;
// Keep the selected value so we can reselect it after
if (objList.selectedIndex > -1)
selValue = objList.options[objList.selectedIndex].value;
// Remove all the items in the list
for (var i=objList.options.length - 1; i>=0; i--)
objList.options.remove(i);
// Add the items that must be visible
for (var i=0; i{
if (objList.SavedList[i].Visible)
{
var oOption = document.createElement('option');
oOption.text = objList.SavedList[i].Libelle;
oOption.value = objList.SavedList[i].value;
objList.options.add(oOption);
}
}
// Reselect the item that was selected
for (var i=0; iif (objList.options[i].value == selValue)
objList.selectedIndex = i;
}
}
Show Picklist item in CRM 4.0
Hide picklist item in CRM 4.0
/* Jscript */
function HidePickListItem(listID, value)
{
var objList = document.getElementById(listID);
// If the list has never been saved, save it now
if (objList.SavedList == null)
{
var arrListe = new Array();
for (var i=0; i{
arrListe[i] = new Object();
arrListe[i].value = objList.options[i].value;
arrListe[i].Libelle = objList.options[i].text;
arrListe[i].Visible = true;
}
objList.SavedList = arrListe;
}
for (var i=0; iif (objList.SavedList[i].value == value)
objList.SavedList[i].Visible = false;
for (var i=objList.options.length - 1; i>=0; i--)
if (objList.options[i].value == value)
objList.options.remove(i);
}
Route Message
Moves an entity instance from one queue to another.
Remarks
To use this message, pass an instance of the RouteRequest class as the request parameter in the Execute method.
There are three types of routing behavior as shown in the following table.
Route type Description
User Routes the entity instance to the queue belonging to a user. The field EndpointId must be the ID of a user.
Queue Routes the entity instance to a specific queue. The field EndpointId must be the ID of a queue.
Auto Performs automatic routing using workflow. The field EndpointId is ignored. The field SourceQueueId specifies the ID of the queue that contains the entity instance specified in the Target field.
To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see Route Privileges.
//# The following code example shows how to use the Route message.
// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";
CrmService service = new CrmService();
service.Url = "http://: /mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Create the target object for the request.
TargetQueuedAppointment target = new TargetQueuedAppointment();
// EntityId is the GUID of the appointment being routed.
target.EntityId = new Guid("7E91958D-C8A1-404C-AC2C-9C474FB2427B");
// Create the request object.
RouteRequest route = new RouteRequest();
// Set the properties of the request object.
route.Target = target;
// EndPointId is the GUID of the queue or user the appointment is being routed to.
// The queue cannot be a work in progress queue.
route.EndPointId = new Guid("44E05740-607B-47AA-ABD6-13A007E2DD85");
// RouteType indicates the EntityType of the endpoint.
route.RouteType = RouteType.Queue;
// SourceQueueId is the GUID of the queue that the appointment is coming from.
route.SourceQueueId = new Guid("BD0C1BDD-3310-4ECA-B2B1-131C2F5ED1B2");
// Execute the request.
RouteResponse routed = (RouteResponse)service.Execute(route);
Impersonate Another User
Required Privileges
Alternately, for Active Directory directory service deployments only, user account (A) under which the impersonation code is to run can be added to the PrivUserGroup group in Active Directory. This group is created by Microsoft Dynamics CRM during installation and setup. User account (A) does not have to be associated with a licensed Microsoft Dynamics CRM user. However, the user who is being impersonated (B) must be a licensed Microsoft Dynamics CRM user.
Impersonate a User
Impersonation in Plug-Ins
Plug-ins not executed by either the sandbox or asynchronous service execute under the security account that is specified on the Identity tab of the CRMAppPool Properties dialog box. The dialog box can be accessed by right-clicking the CRMAppPool application pool in Internet Information Services (IIS) Manager and then clicking Properties in the shortcut menu. By default, CRMAppPool uses the Network Service account identity but this can be changed by a system administrator during installation. If the CRMAppPool identity is changed to a system account other than Network Service, the new identity account must be added to the PrivUserGroup group in Active Directory. Refer to the "Change a Microsoft Dynamics CRM service account" topic in the Microsoft Dynamics CRM 2011 Implementation Guidefor complete and detailed instructions.
The two methods that can be employed to impersonate a user are discussed below.
Impersonation during plug-in registration
Whether the calling/logged on user or "system" user is used for impersonation is dependent on the request being processed by the pipeline and is beyond the scope of the SDK documentation. For more information about the "system" user, refer to the next topic.
Note |
---|
When you register a plug-in using the sample plug-in registration tool that is provided in the SDK download, service methods invoked by the plug-in execute under the account of the calling or logged on user by default unless you select a different user in the Run in User's Context dropdown menu. For more information about the tool sample code, refer to the tool code under the SDK\Tools\PluginRegistration folder of the SDK download. |
Impersonation during plug-in execution
The platform passes the impersonated user ID to a plug-in at run time through the UserId property. This property can have one of three different values as shown in the table below.
UserId Value | Condition |
---|---|
Initiating user or "system" user | The SdkMessageProcessingStep.ImpersonatingUserId attribute is set to null or Guid.Empty at plug-in registration. |
Impersonated user | The ImpersonatingUserId property is set to a valid system user ID at plug-in registration. |
"system" user | The current pipeline was executed by the platform, not in direct response to a service method call. |
The InitiatingUserId property of the execution context contains the ID of the system user that called the service method that ultimately caused the plug-in to execute.
Important |
---|
For plug-ins executing offline, any entities created by the plug-in are owned by the logged on user. Impersonation in plug-ins is not supported while in offline mode. |
Handle Exceptions in Plug-Ins
For plug-ins not registered in the sandbox, the exception message (System.Exception.Message) is also written to the Application event log on the server that runs the plug-in. The event log can be viewed by using the Event Viewer administrative tool. Since the Application event log is not available to sandboxed plug-ins, sandboxed plug-ins should use tracing. For more information, seeDebug a Plug-In.
You can optionally display a custom error message in a dialog of the Web application by having your plug-in throw an InvalidPluginExecutionException exception with the custom message as the Message property value. It is recommended that plug-ins only pass an InvalidPluginExecutionException back to the platform.
Pass Data Between Plug-Ins
The name of the parameter that is used for passing information between plug-ins is SharedVariables. This is a collection of key\value pairs. At run time, plug-ins can add, read, or modify properties in the SharedVariables collection. This provides a method of information communication among plug-ins.
This sample shows how to use SharedVariables to pass data from a pre-event registered plug-in to a post-event registered plug-in.
using System; // Microsoft Dynamics CRM namespace(s) using Microsoft.Xrm.Sdk; namespace Microsoft.Crm.Sdk.Samples { /// <summary> /// A plug-in that sends data to another plug-in through the SharedVariables /// property of IPluginExecutionContext. /// </summary> /// <remarks>Register the PreEventPlugin for a pre-event and the /// PostEventPlugin plug-in on a post-event. /// </remarks> public class PreEventPlugin : IPlugin { public void Execute(IServiceProvider serviceProvider) { // Obtain the execution context from the service provider. Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); // Create or retrieve some data that will be needed by the post event // plug-in. You could run a query, create an entity, or perform a calculation. //In this sample, the data to be passed to the post plug-in is // represented by a GUID. Guid contact = new Guid("{74882D5C-381A-4863-A5B9-B8604615C2D0}"); // Pass the data to the post event plug-in in an execution context shared // variable named PrimaryContact. context.SharedVariables.Add("PrimaryContact", (Object)contact.ToString()); } } public class PostEventPlugin : IPlugin { public void Execute(IServiceProvider serviceProvider) { // Obtain the execution context from the service provider. Microsoft.Xrm.Sdk.IPluginExecutionContext context = (Microsoft.Xrm.Sdk.IPluginExecutionContext) serviceProvider.GetService(typeof(Microsoft.Xrm.Sdk.IPluginExecutionContext)); // Obtain the contact from the execution context shared variables. if (context.SharedVariables.Contains("PrimaryContact")) { Guid contact = new Guid((string)context.SharedVariables["PrimaryContact"]); // Do something with the contact. } } } }
For a plug-in registered in stage 20 or 40, to access the shared variables from a stage 10 registered plug-in that executes on create, update, delete, or by a RetrieveExchangeRateRequest, you must access the ParentContext.SharedVariables collection. For all other cases, IPluginExecutionContext.SharedVariables contains the collection.
IPluginExecutionContext
IPluginExecutionContext contains information that describes the run-time environment that the plug-in is executing in, information related to the execution pipeline, and entity business information. The context is contained in the System.IServiceProvider parameter that is passed at run-time to a plug-in through its Execute method.
// Obtain the execution context from the service provider. IPluginExecutionContext context = (IPluginExecutionContext) serviceProvider.GetService(typeof(IPluginExecutionContext));
When a system event is fired for which a plug-in is registered, the system creates and populates the context and passes it to a plug-in through the above mentioned classes and methods. The execution context is passed to each registered plug-in in the pipeline when they are executed. Each plug-in in the execution pipeline is able to modify writable properties in the context. For example, given a plug-in registered for a pre-event and another plug-in registered for a post-event, the post-event plug-in can receive a context that has been modified by the pre-event plug-in. The same situation applies to plug-ins that are registered within the same stage.
All the properties in IPluginExecutionContext are read-only. However, your plug-in can modify the contents of those properties that are collections. For information on infinite loop prevention, refer to Depth.
CRM: Input and Output Parameters
// 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"];Similarly, the OutputParameters property contains the data that is in the response message, for example CreateResponse, currently being passed through the event execution pipeline. However, only synchronous post-event and asynchronous registered plug-ins have OutputParameters populated as the response is the result of the core platform operation. The property is of type ParameterCollection where the keys to access the response data are the names of the actual public properties in the response.
CRM: Pre and Post Entity Images
There are some events where images are not available. For example, only synchronous post-event and asynchronous registered plug-ins have PostEntityImages populated. In addition, the create operation does not support a pre-image and a delete operation does not support a post-image.
CRM 4.0 Plug-in Stages, Pipelines and Execution Modes
Pre-Stage: (synchronous) called before the write to the database.
The main reasons to use a Pre-Stage of Execution are synchronous in nature:
- Modify data before it is written to the database.
- Abort the action being taken
- Server Side Validity checking
Use the Post-Stage of Execution whenever you don't need to use Pre-Stage.
If you don't want the user to wait for the process to finish and there is no race condition use asynchronous.
Triggering Pipeline:
The triggering pipeline is a little less obvious in nature and has an impact on what functionality that you can use in your plugin.
Parent Pipeline: This is the pipeline that is the most common and there are no restrictions imposed in a parent pipeline.
Child Pipeline: This is the pipeline that causes the most confusion and there are limitations that vary with Stage and Execution Mode.
Sometimes a child pipeline is required to trap the event you need, and sometimes you need to trap both the parent and child pipeline for the same entity, message and stage.
Example: Change the quotenumber in the Pre-Stage for the Create of a Quote.
The quotenumber is a field that the CRM web service will not allow you to change after it is written to the database so you need to use the Pre-Stage and modify the context Entity before the end of the Execute method as shown below.
var entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target]; // . . . retrieve data to populate number . . . // Set value before it is written to the database if( entity.Properties.Contains(numberField)) { entity.Properties.Remove(numberField); } var prop = new StringProperty(numberField, newNumber); entity.Properties.Add(prop);
You can create a Quote in a few ways.
- Sales -> Quotes -> New
- (open an Account) -> Quotes -> New Quote
- Sales -> Opportunities (open an opportunity) -> Quotes -> New Quote
Since you are an efficient plugin developer and are using the ICrmService and dynamic entities to access CRM data because it is pre-authenticated and fast. You retrieve some information to help create the number.
ICrmService service = context.CreateCrmService(true); retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);
- Create
- Pre Stage
- Synchronous
- Parent Pipeline
You create your Quote from Sales -> Quotes -> New and it works!
However, in many business processes the user will create a Quote from an opportunity so it will inherit opportunityproduct information.
Now you create your quote from Sales -> Opportunities (open an opportunity) -> Quotes -> New Quote and for some reason your plugin did not fire. That is because this quote was created in a child pipeline.
The entire QOI chain also occurs in a child pipeline. If you create an order from a quote or invoice from an order it is happening in a child pipeline. There are other places that this occurs as well like creation of an account or contact from a lead.
You are in a child pipeline, now what ?
The first thing that you might try is to take your existing plugin and register it against the child pipeline, but it won't work. The ICrmService is not available to you in a child pipeline.If you downloaded the plug-in template for CRM, you have probably seen the following method, which is what you need to use in a child pipeline.
/// <summary> /// Creates a CrmService proxy for plug-ins that execute in the child pipeline. /// </summary> /// <param name="context">The execution context that was passed to the plug-ins Execute method.</param> /// <param name="flag">Set to True to use impersontation.</param> /// <returns>A CrmServce instance.</returns> private static CrmService CreateCrmService(IPluginExecutionContext context, Boolean flag) { var authToken = new CrmAuthenticationToken { AuthenticationType = 0, OrganizationName = context.OrganizationName, CallerId = (flag ? context.UserId : context.InitiatingUserId) }; var corToken = new CorrelationToken { CorrelationId = context.CorrelationId, CorrelationUpdatedTime = context.CorrelationUpdatedTime, Depth = context.Depth }; var regkey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\MSCRM", false); var service = new CrmService { CrmAuthenticationTokenValue = authToken, UseDefaultCredentials = true, Url = String.Concat(regkey.GetValue("ServerUrl").ToString(), "/2007/crmservice.asmx"), CorrelationTokenValue = corToken }; return service; }
There is a comment in the plugin template that doesn't tell the whole story.
// For a plug-in running in the child pipeline, use this statement. // CrmService crmService = CreateCrmService(context, true);
Hard Coded Restrictions:
A CrmService running Synchronously in a child pipeline is limited to the following:
- Create
- Delete
- Update
- RetrieveExchangeRate
Those 4 allowed actions are hard coded by MS whenever the plugin is executed inside a transaction, and it appears that all synchronous child pipeline events occur inside a transaction.
However you can do a query in child pipeline if it is registered as asynchronous.
In review:
- Use ICrmService for all parent pipelines when at all possible.
- Use CrmService for child pipelines in asynchronous execution mode.
- There is very limited functionality allowed with CrmService for any plugin registered in a synchronous child pipeline
- Querying CRM data in a plug-in registered as a synchronous Pre Create in a child process is currently very unsupported. (ie. direct SQL access)
How to add configuration parameters to plugins in CRM 2011
1. Use a "Configuration" custom entity
This is perhaps the most popular method but it can be expensive to maintain. You can create a custom entity containing the configuration information so the plugin will read the data in the custom entity by retrieving the record each time it executes.
PROS:
- Easy to update the value (can be done using the CRM UI).
- Can configure privileges to control who has access to the configuration entity.
- Configuration is data instead of metadata, therefore, the configuration data cannot be transported with the solution. You will need to create the configuration record in each environment.
- You might need to control that only one configuration entity can be created.
2. Use the plugin step "Configuration"
When you register a plugin step, there is a field where you can specify some configuration parameters for the plugin execution:
Then in the Constructor of your plugin class you will get the configuration value which you can use later in the Execute method:
{
private string _secureConfig = null;
private string _unsecureConfig = null;
public BasePlugin(string unsecureConfig, string secureConfig)
{
_secureConfig = secureConfig;
_unsecureConfig = unsecureConfig;
}
public void Execute()
{
// Use the configuration here
}
}
PROS:
- The step configuration is solution-aware so it will be automatically transported with the plugin step.
- You need to use the plugin registration tool or another application to update the step configuration.
- The configuration is step-specific so you have to provide it and/or update it for every step even if the value is the same for all the steps (the configuration is on each step instead of the assembly or plugin type).
- the configuration is just an attribute of the plugin step so you cannot control privileges on the configuration independently from privileges on plugin step entity.
3. Use the plugin step "Secure Configuration"
This is similar to the step Configuration except that the configuration data is stored in a separate entity which can be secured.
PROS:
- The configuration data can be secured as any other entity using the CRM security model. This is useful when the configuration contains sensitive information such as passwords.
- Secure configuration is not solution aware so you will need to configure it for each environment.
- You need to use the plugin registration tool or another application to update the step configuration.
- The configuration is step-specific so you have to provide it and/or update it for every step even if the value is the same for all the steps (the configuration is on each step instead of the assembly or plugin type).
4. Use a Web Resource
You can store configuration information in web resources, for example you might have some XML configuration stored in a web resource and have your plugin read the web resource each time it executes.
PROS:
- Web resources are solution aware and the GUID is preserved across environments so you can hardcode the web resource GUID in your plugin code. You can transport the web resource and the plugin in the same solution.
- Can be easily updated using the CRM UI.
- You cannot secure the configuration since it depends on the web resource access privileges and most users will need at least read access to web resources.
Maximum of 5000 responses from a FetchXml
HKEY_LOCAL_MACHINE\Software\Microsoft\MSCRM
Handle Message
Moves an entity instance from a queue to the In Progress (WIPBin) queue of the user.
//# The following code example demonstrates how to use the Handle message.
// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";
CrmService service = new CrmService();
service.Url = "http://: /mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
// Create the Target Object for the Request
TargetQueuedAppointment target = new TargetQueuedAppointment();
// EntityId is the Guid of the appointment being handled
target.EntityId = new Guid("7B222F98-F48A-4AED-9D09-77A19CB6EE82");
// Create the Request Object
HandleRequest handle = new HandleRequest();
// Set the Request Object's Properties
handle.Target = target;
// SourceQueueId is the Guid of the queue the appointment is coming from
handle.SourceQueueId = sourceQueue;
// Execute the Request
HandleResponse handled = (HandleResponse) service.Execute(handle);
Start Microsoft Word using Jscript
// Start Microsoft Word using Jscript var createDoc = function (msg) { var MsWord = new ActiveXObject("Word.Application"); MsWord.Documents.Add(); MsWord.Selection.TypeParagraph(); MsWord.Selection.TypeText("line 1 text1: " + msg); MsWord.Selection.TypeParagraph(); MsWord.Selection.TypeParagraph(); MsWord.Selection.TypeText("line2 text2: this is line two"); MsWord.Visible = true; };
Assign the queue to a team.
// ** Assign the queue to a team. ** AssignRequest assignRequest = new AssignRequest() { Assignee = new EntityReference { LogicalName = "team", Id = new Guid("_teamGuId") }, Target = new EntityReference("queue", new Guid("_queueGuid")) }; _service.Execute(assignRequest); Console.WriteLine("The queue is owned by the team.");