Show Picklist item in CRM 4.0

 
/* Jscript */

function ShowPickListItem(listID, value)
{
var objList = document.getElementById(listID);

if (objList.SavedList != null)
{
var selValue = null;
var indexInsertion = 0;

for (var i=0; i if (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; i if (objList.options[i].value == selValue)
objList.selectedIndex = i;
}
}

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; i if (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

Impersonation is used to execute business logic (code) on behalf of another Microsoft Dynamics CRM user to provide a desired feature or service using the appropriate role and object-based security of that impersonated user. This is necessary because the Microsoft Dynamics CRM Web services can be called by various clients and services on behalf of a Microsoft Dynamics CRM user, for example, in a workflow or custom ISV solution. Impersonation involves two different user accounts: one user account (A) is used when executing code to perform some task on behalf of another user (B).

Required Privileges

User account (A) needs the privilege prvActOnBehalfOfAnotherUser, which is included in the Delegate role.
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

To impersonate a user, set the CallerId property on an instance of OrganizationServiceProxy before calling the service's Web methods.

Impersonation in Plug-Ins

Impersonation is used to execute business logic (custom code) on behalf of a Microsoft Dynamics CRM system user to provide a desired feature or service for that user. Any business logic executed within a plug-in, including Web service method calls and data access, is governed by the security privileges of the impersonated user.
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

One method to impersonate a system user within a plug-in is by specifying the impersonated user during plug-in registration. When registering a plug-in programmatically, if the SdkMessageProcessingStep.ImpersonatingUserId attribute is set to a specific Microsoft Dynamics CRM system user, Web service calls made by the plug-in execute on behalf of the impersonated user. If ImpersonatingUserId is set to a value of null or Guid.Empty during plug-in registration, the calling/logged on user or the standard "system" user is the impersonated user.
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.
noteNote
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

Impersonation that was defined during plug-in registration can be altered in a plug-in at run time. Even if impersonation was not defined at plug-in registration, plug-in code can still use impersonation. The following discussion identifies the key properties and methods that play a role in impersonation when making Web service method calls in a plug-in.
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.

ImportantImportant
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 synchronous plug-ins, the Microsoft Dynamics CRM platform handles exceptions passed back to the platform by displaying an error message in a dialog of the Web application user interface. The exception message for asynchronous registered plug-ins is written to a System Job (AsyncOperation) entity.
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 message pipeline model defines a parameter collection of custom data values in the execution context that is passed through the pipeline and shared among registered plug-ins, even from different 3rd party developers. This collection of data can be used by different plug-ins to communicate information between plug-ins and enable chain processing where data processed by one plug-in can be processed by the next plug-in in the sequence and so on. This feature is especially useful in pricing engine scenarios where multiple pricing plug-ins pass data between one another to calculate the total price for a sales order or invoice. Another potential use for this feature is to communicate information between a plug-in registered for a pre-event and a plug-in registered for a post-event.
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.             }         }     } } 
It is important that any type of data added to the shared variables collection be serializable otherwise the server will not know how to serialize the data and plug-in execution will fail.
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 property contains the data that is in the request message currently being processed by the event execution pipeline. Your plug-in code can access this data. The property is of type ParameterCollection where the keys to access the request data are the names of the actual public properties in the request. As an example, take a look at CreateRequest. One property of CreateRequest is named Target which is of type Entity. This is the entity currently being operated upon by the platform. To access the data of the entity you would use the name "Target" as the key in the input parameter collection. You also need to cast the returned instance.
// 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

PreEntityImages and PostEntityImages contain snapshots of the primary entity's attributes before (pre) and after (post) the core platform operation. Microsoft Dynamics CRM populates the pre-entity and post-entity images based on the security privileges of the impersonated system user. Only entity attributes that are set to a value or null are available in the pre or post entity images. You can specify to have the platform populate these PreEntityImages and PostEntityImages properties when you register your plug-in. The entity alias value you specify during plug-in registration is used as the key into the image collection in your plug-in code.
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


 

Stage of Execution:
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
Post-Stage: (synchronous or asynchronous)
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);
So far so good. This will work in any Pre-Create pipeline!
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
Do you think that Creating a Quote always happens in the same pipeline?
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);
You register your plugin using the handy plugin registration tool for the Quote entity with the following settings:
  • Create
  • Pre Stage
  • Synchronous
  • Parent Pipeline
 CreateQuoteParent
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; }
You may find another method called GetCrmProxyUsingEndpointUrlInChildPipeline. It is essentially the same.
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);
What it doesn't mention is that what you are allowed to do with that service depends on what your execution mode is.
Hard Coded Restrictions:
A CrmService running Synchronously in a child pipeline is limited to the following:
  • Create
  • Delete
  • Update
  • RetrieveExchangeRate
However a child plugin running in Asynchronous Execution Mode is not limited this way.
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



How to add configuration parameters to plugins in CRM 2011


When you design plugins, you often need an input parameter or a configuration for the plugin execution which can be easily updated without having to re-compile and/or re-register the plugin. For example, I have a plugin that sends a request to a SharePoint web service and I would like the endpoint URL for the web service to be configurable. In that case you have the following options:

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.
CONS:
  • 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:
image
Then in the Constructor of your plugin class you will get the configuration value which you can use later in the Execute method:
public abstract class BasePlugin : IPlugin
{
    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.
CONS:
  • 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.
CONS:
  • 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.
CONS:
  • 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

Edit the registry
  • Click Start, click Run, type regedit in the Open box, and then click OK.
  • Locate and then select the following registry subkey:

    HKEY_LOCAL_MACHINE\Software\Microsoft\MSCRM

  • On the Edit menu, point to New, and then click DWORD Value.
  • Type TurnOffFetchThrottling, and then press ENTER.
  • Right-click TurnOffFetchThrottling, and then click Modify.
  • Type a number other than 0 in the Value data box, and then click OK.Note Step 6 lets you retrieve the number of records specified in the Count attribute of your fetch statement.
  • On the File menu, click Exit.

  • 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

    This is pretty old trick to use Active X Control to get an instance of application.
    // 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.

    This C# code assigns a queue to a team, we just need the Guid for team & queue.
    // ** 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.");