Exemplo n.º 1
0
        internal static void AddToQueue(TraceLogger logger, CrmServiceClient service, string filepath)
        {
            const string SEPERATOR = "------------------------------------------------------";

            logger.Log(SEPERATOR, TraceEventType.Information);

            logger.Log("Starting to queue items... this may take a while... ", TraceEventType.Information);

            if (!File.Exists(filepath))
            {
                logger.Log(new FileNotFoundException($"Unable to locate queueitems.json at $filepath"));
                logger.Log(SEPERATOR, TraceEventType.Information);
                return;
            }
            var json = File.ReadAllText(filepath);

            if (string.IsNullOrWhiteSpace(json))
            {
                logger.Log(new FileLoadException("Queueitems.json was empty."));
                logger.Log(SEPERATOR, TraceEventType.Information);
                return;
            }

            try
            {
                dynamic data = JsonConvert.DeserializeObject(json);

                var requests = new OrganizationRequestCollection();

                if (data == null)
                {
                    logger.Log("Json data was null", TraceEventType.Information);
                    logger.Log(SEPERATOR, TraceEventType.Information);
                    return;
                }

                int i = 0, j = 0;
                foreach (var queueitem in data)
                {
                    i++;
                    if (i >= QUEUEITEMBATCHSIZE && i % QUEUEITEMBATCHSIZE == 0)
                    {
                        j++;
                    }

                    var request = new AddToQueueRequest();

                    if (Guid.TryParse(queueitem.queueid.ToString(), out Guid queueid))
                    {
                        if (Guid.TryParse(queueitem.targetid.ToString(), out Guid targetid))
                        {
                            if (!String.IsNullOrEmpty(queueitem.targetentity.ToString()))
                            {
                                try
                                {
                                    request.Target              = new EntityReference(queueitem.targetentity.ToString(), targetid);
                                    request.DestinationQueueId  = queueid;
                                    request.QueueItemProperties = new Entity("queueitem");
                                    requests.Add(request);

                                    if (requests.Count >= QUEUEITEMBATCHSIZE)
                                    {
                                        ExecuteMultipleRequests(logger, service, requests, j);
                                    }
                                }
                                catch (Exception ex)
                                {
                                    logger.Log("Unable to queue current item.");
                                    logger.Log(ex);
                                }
                            }
                            else
                            {
                                logger.Log($"Item {i} - There was an empty target entity in the queueitems.json",
                                           TraceEventType.Information);
                            }
                        }
                        else
                        {
                            logger.Log($"Item {i} - Unable to parse targetid guid: {queueitem.targetid.ToString()}",
                                       TraceEventType.Information);
                        }
                    }
                    else
                    {
                        logger.Log($"Item {i} - Unable to parse queueid guid: {queueitem.queueid.ToString()}",
                                   TraceEventType.Information);
                    }
                }

                if (requests.Count > 0)
                {
                    ExecuteMultipleRequests(logger, service, requests, j);
                }
            }
            catch (Exception ex)
            {
                logger.Log("Unable to queue items.");
                logger.Log(ex);
            }
            finally
            {
                logger.Log(SEPERATOR, TraceEventType.Information);
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// This method creates any entity records that this sample requires.
        /// Create source queue and destination queue.
        /// Create a letter  entity.
        /// Add letter  entity to source queue.
        /// </summary>
        public void CreateRequiredRecords()
        {
            var QueueViewType = new
            {
                Public = 0,
                Private = 1
            };
            //Create new queues and store their returned GUIDs in variables for later use.
            Queue sourceQueue = new Queue
                {
                    Name = "Source Queue",
                    Description = "This is an example queue.",
                    QueueViewType = new OptionSetValue(QueueViewType.Private)
                };

            _sourceQueueId = _serviceProxy.Create(sourceQueue);
            Console.WriteLine("Created {0}", sourceQueue.Name);

            Queue destinationQueue = new Queue
                {
                    Name = "Destination Queue",
                    Description = "This is an example queue.",
                    QueueViewType = new OptionSetValue(QueueViewType.Private)
                };

            _destinationQueueId = _serviceProxy.Create(destinationQueue);
            Console.WriteLine("Created {0}", destinationQueue.Name);


            // Create a letter  entity.
            Letter newLetter = new Letter
            {
                Description = "Example Letter"
            };

            _letterId = _serviceProxy.Create(newLetter);
            Console.WriteLine("Created {0}", newLetter.Description);

            // Use AddToQueue message to add an  entity into a queue, which will associate
            // the letter with the first queue.
            AddToQueueRequest addToSourceQueue = new AddToQueueRequest
            {
                DestinationQueueId = _sourceQueueId,
                Target = new EntityReference(Letter.EntityLogicalName, _letterId)
            };

            _serviceProxy.Execute(addToSourceQueue);
            Console.WriteLine("Added letter record to {0}", sourceQueue.Name);

            // Retrieve/create a user record for assigning the queue item to the user's
            // queue.
            _userId = SystemUserProvider.RetrieveSalesManager(_serviceProxy);

            return;
        }
Exemplo n.º 3
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Move a record from a source queue to a destination queue.
        /// Optionally delete any entity records that were created for this sample.
        /// <para name="organizationFriendlyName">The friendly name of the target 
        /// organization.</para>
        /// <para name="discoveryServer">The name of the discovery server.</para>
        /// <param name="promptForDelete">Indicates whether to prompt the user to 
        /// delete the records created in this sample.</param>
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service. 
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = new OrganizationServiceProxy(serverConfig.OrganizationUri, serverConfig.HomeRealmUri, serverConfig.Credentials, serverConfig.DeviceCredentials))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    Guid CurrentUserId = ((WhoAmIResponse)_serviceProxy.Execute(new WhoAmIRequest())).UserId;



                    //<snippetRetrieveUserQueues>
                    // Get known private queues for the user 
                    // by using RetrieveUserQueuesRequest message.
                    RetrieveUserQueuesRequest retrieveUserQueuesRequest = new RetrieveUserQueuesRequest
                    {
                        UserId = CurrentUserId,
                        IncludePublic = true
                    };
                    RetrieveUserQueuesResponse retrieveUserQueuesResponse =
                        (RetrieveUserQueuesResponse)_serviceProxy.Execute(retrieveUserQueuesRequest);
                    EntityCollection queues = (EntityCollection)retrieveUserQueuesResponse.EntityCollection;

                    Guid sourceQueueId = new Guid();
                    Guid destinationQueueId = new Guid();

                    foreach (Entity entity in queues.Entities)
                    {
                        Queue queue = (Queue)entity;
                        switch (queue.Name)
                        {
                            case "Source Queue":
                                sourceQueueId = queue.Id;
                                break;
                            case "Destination Queue":
                                destinationQueueId = queue.Id;
                                break;
                        }
                    }

                    //<snippetAddToQueue1>
                    // Move a record from a source queue to a destination queue
                    // by using the AddToQueue request message.
                    AddToQueueRequest routeRequest = new AddToQueueRequest
                    {
                        SourceQueueId = sourceQueueId,
                        Target = new EntityReference(Letter.EntityLogicalName, _letterId),
                        DestinationQueueId = destinationQueueId
                    };

                    // Execute the Request
                    _serviceProxy.Execute(routeRequest);
                    //</snippetAddToQueue1>                      

                    Console.WriteLine(@"The letter record has been moved to a new queue.");

                    //</snippetRetrieveUserQueues>
                    DeleteRequiredRecords(promptForDelete);

                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault>)
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
        /// <summary>
        /// Function ensure that the given Queue Item is set to use a Team Queue
        /// and sets the Worked By to the user if the queue item was originall set using a user's default queue
        /// </summary>
        /// <param name="executionContext">Code activity execution context</param>
        /// <param name="crmWorkflowContext">Contains the organisation service and trace service</param>
        public override void ExecuteCRMWorkFlowActivity(CodeActivityContext executionContext, LocalWorkflowContext crmWorkflowContext)
        {
            // Validation
            if (crmWorkflowContext == null)
            {
                throw new ArgumentNullException(nameof(crmWorkflowContext));
            }

            // 1. Get the Queue currently set for the Queue Item we are interested in
            EntityReference queueItemEntityReference = QueueItemEntityReference.Get(executionContext);
            Entity          queueItem = GetQueueItem(crmWorkflowContext, queueItemEntityReference);
            EntityReference queue     = queueItem[Model.QueueItem.Queue] as EntityReference;

            if (queue == null)
            {
                // There is no queue, nothing to do here.
                return;
            }

            // 2. Get the user that has this Queue as a Default Queue
            var user = GetUserForQueue(crmWorkflowContext, queue);

            // 3. If we have a user, it means we need to switch the queue item to use a team queue
            if (user != null)
            {
                if (!user.Attributes.ContainsKey(Model.User.DefaultTeamQueue))
                {
                    // The user does not have a default team queue set, cannot change to use a team queue
                    return;
                }

                var queueToUse = user[Model.User.DefaultTeamQueue] as EntityReference;
                var target     = queueItem[Model.QueueItem.Target] as EntityReference;

                // Is there no default team queue set-up for the user?
                if (queueToUse == null)
                {
                    // No default team queue means we can't change the queue, nothing to do here
                    return;
                }

                // Move a record from a source queue to a destination queue
                // by using the AddToQueue request message.
                AddToQueueRequest routeRequest = new AddToQueueRequest
                {
                    SourceQueueId      = queue.Id,
                    Target             = target,
                    DestinationQueueId = queueToUse.Id
                };
                crmWorkflowContext.OrganizationService.Execute(routeRequest);


                // 4. And finally, set the worked on for the queueitem to be the user.
                // Create an instance of an existing queueitem in order to specify
                // the user that will be working on it using PickFromQueueRequest.
                PickFromQueueRequest pickFromQueueRequest = new PickFromQueueRequest
                {
                    QueueItemId = queueItem.Id,
                    WorkerId    = user.Id
                };
                crmWorkflowContext.OrganizationService.Execute(pickFromQueueRequest);
            }
        }
        private void BusinessLogic(IOrganizationService service, IExecutionContext context)
        {
            // We are hitting Assign button on a Case record so Target will be a Case record
            var caseEntityReference = (EntityReference)context.InputParameters["Target"];

            // Assignee could be a User or Team
            var teamEntityReference = (EntityReference)context.InputParameters["Assignee"];

            // In our requirement it should be a Team, if user it should return
            if (teamEntityReference.LogicalName != "team")
            {
                return;
            }

            // fetchXml to retrieve all the users in a given Team
            var fetchXmlLoggedUserInTeam = @"
            <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='true'>
              <entity name='systemuser'>
                <attribute name='systemuserid' />
                <link-entity name='teammembership' from='systemuserid' to='systemuserid' visible='false' intersect='true'>
                  <link-entity name='team' from='teamid' to='teamid' alias='ac'>
                    <filter type='and'>
                      <condition attribute='teamid' operator='eq' uitype='team' value='{0}' />
                    </filter>
                  </link-entity>
                </link-entity>
              </entity>
            </fetch>";

            // Passing current Team is fetchXml and retrieving Team's user
            var users = service.RetrieveMultiple(new FetchExpression(string.Format(
                                                                         fetchXmlLoggedUserInTeam,
                                                                         teamEntityReference.Id))).Entities;

            // Condition 1
            // If user count is zero case should be assigned to Team's default Queue
            if (users.Count == 0)
            {
                // Retrieving Team's default Queue
                var team = service.Retrieve("team", teamEntityReference.Id, new ColumnSet("queueid"));

                var addToQueueRequest = new AddToQueueRequest
                {
                    // Case record
                    Target = caseEntityReference,
                    // Team's default Queue Id
                    DestinationQueueId = team.GetAttributeValue <EntityReference>("queueid").Id
                };
                service.Execute(addToQueueRequest);
            }
            else
            {
                // Dictionary to save UserId and number of case assigned pair
                var caseCountAssignedToUser = new Dictionary <Guid, int>();

                users.ToList().ForEach(user =>
                {
                    // FetchXml query to retrieve number cases assigned to each user
                    var fetchXmlCaseAssignedToUser = @"
                    <fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                      <entity name='incident'>
                        <attribute name='incidentid' />
                        <link-entity name='systemuser' from='systemuserid' to='owninguser' alias='ab'>
                          <filter type='and'>
                            <condition attribute='systemuserid' operator='eq' uitype='systemuser' value='{0}' />
                          </filter>
                        </link-entity>
                      </entity>
                    </fetch>";

                    var cases = service.RetrieveMultiple(new FetchExpression(string.Format(
                                                                                 fetchXmlCaseAssignedToUser,
                                                                                 user.Id))).Entities.ToList();

                    // Adding user id with number of cases assigned to Dictionay defined above
                    caseCountAssignedToUser.Add(user.Id, cases.Count);
                });

                // Sorting in ascending order by number of cases
                var sortedCaseCount = from entry in caseCountAssignedToUser
                                      orderby entry.Value ascending
                                      select entry;

                // Getting all the users with least sae number of cases
                var allUserWithSameLeastNumberOfCases = sortedCaseCount
                                                        .Where(w => w.Value == sortedCaseCount.First().Value).ToList();

                var targetUser = new Guid();

                // Condition 1
                // Assign case to user with least number of case assigned
                if (allUserWithSameLeastNumberOfCases.Count() == 1)
                {
                    targetUser = sortedCaseCount.First().Key;
                }

                // Condition 2
                // If more than one users are having same least number of users, then it be assigned randomly
                else
                {
                    var randomUser = new Random().Next(0, allUserWithSameLeastNumberOfCases.Count() - 1);
                    targetUser = allUserWithSameLeastNumberOfCases[randomUser].Key;
                }

                var assign = new AssignRequest
                {
                    Assignee = new EntityReference("systemuser", targetUser),
                    Target   = caseEntityReference
                };

                service.Execute(assign);
            }
        }
Exemplo n.º 6
0
 public TestDataQueue(AddToQueueRequest request, AddToQueueResponse response)
 {
     Request  = request;
     Response = response;
 }
Exemplo n.º 7
0
        [STAThread] // Added to support UX
        static void Main(string[] args)
        {
            CrmServiceClient service = null;

            try
            {
                service = SampleHelpers.Connect("Connect");
                if (service.IsReady)
                {
                    #region Sample Code
                    //////////////////////////////////////////////
                    #region Set up
                    SetUpSample(service);
                    #endregion Set up
                    #region Demonstrate

                    Guid CurrentUserId = ((WhoAmIResponse)service.Execute(new WhoAmIRequest())).UserId;



                    // Get known private queues for the user
                    // by using RetrieveUserQueuesRequest message.
                    RetrieveUserQueuesRequest retrieveUserQueuesRequest = new RetrieveUserQueuesRequest
                    {
                        UserId        = CurrentUserId,
                        IncludePublic = true
                    };
                    RetrieveUserQueuesResponse retrieveUserQueuesResponse =
                        (RetrieveUserQueuesResponse)service.Execute(retrieveUserQueuesRequest);
                    EntityCollection queues = (EntityCollection)retrieveUserQueuesResponse.EntityCollection;

                    Guid sourceQueueId      = new Guid();
                    Guid destinationQueueId = new Guid();

                    foreach (Entity entity in queues.Entities)
                    {
                        Queue queue = (Queue)entity;
                        switch (queue.Name)
                        {
                        case "Source Queue":
                            sourceQueueId = queue.Id;
                            break;

                        case "Destination Queue":
                            destinationQueueId = queue.Id;
                            break;
                        }
                    }

                    // Move a record from a source queue to a destination queue
                    // by using the AddToQueue request message.
                    AddToQueueRequest routeRequest = new AddToQueueRequest
                    {
                        SourceQueueId      = sourceQueueId,
                        Target             = new EntityReference(Letter.EntityLogicalName, _letterId),
                        DestinationQueueId = destinationQueueId
                    };

                    // Execute the Request
                    service.Execute(routeRequest);

                    Console.WriteLine(@"The letter record has been moved to a new queue.");



                    #region Clean up
                    CleanUpSample(service);
                    #endregion Clean up
                }
                #endregion Demonstrate
                #endregion Sample Code
                else
                {
                    const string UNABLE_TO_LOGIN_ERROR = "Unable to Login to Dynamics CRM";
                    if (service.LastCrmError.Equals(UNABLE_TO_LOGIN_ERROR))
                    {
                        Console.WriteLine("Check the connection string values in cds/App.config.");
                        throw new Exception(service.LastCrmError);
                    }
                    else
                    {
                        throw service.LastCrmException;
                    }
                }
            }

            catch (Exception ex)
            {
                SampleHelpers.HandleException(ex);
            }

            finally
            {
                if (service != null)
                {
                    service.Dispose();
                }

                Console.WriteLine("Press <Enter> to exit.");
                Console.ReadLine();
            }
        }
Exemplo n.º 8
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);

            IOrganizationService iServices = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(new Guid?(context.UserId));

            myTrace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    if (context.MessageName == "Update")
                    {
                        EntityReference ownerId = null;
                        Guid            colaid  = Guid.Empty;
                        Entity          target  = (Entity)context.InputParameters["Target"];

                        if ((target.Attributes.Contains("ust_flagdiagnosischanged") && target["ust_flagdiagnosischanged"] != null) || (target.Attributes.Contains("ust_flagsendlabcentral") && target["ust_flagsendlabcentral"] != null))
                        {
                            Entity ostPresential = service.Retrieve("ust_ostpresential", target.Id, new ColumnSet("ownerid"));

                            if (ostPresential != null)
                            {
                                if (ostPresential.Attributes.Contains("ownerid") && ostPresential["ownerid"] != null)
                                {
                                    ownerId = ((EntityReference)ostPresential.Attributes["ownerid"]);
                                }

                                var fetchQueue = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                 "<entity name='queue'>" +
                                                 "<attribute name='name' />" +
                                                 "<attribute name='emailaddress' />" +
                                                 "<attribute name='queueid' />" +
                                                 "<order attribute='emailaddress' descending='false' />" +
                                                 "<filter type='and'>" +
                                                 "<condition attribute='name' operator='like' value='%" + ownerId.Name + "%' />" +
                                                 "</filter>" +
                                                 "</entity>" +
                                                 "</fetch>";

                                EntityCollection resultQ = service.RetrieveMultiple(new FetchExpression(fetchQueue));

                                if (resultQ[0].Attributes.Contains("queueid") && resultQ[0]["queueid"] != null)
                                {
                                    colaid = (Guid)resultQ[0].Attributes["queueid"];
                                }

                                AddToQueueRequest moverOST = new AddToQueueRequest()
                                {
                                    Target = new EntityReference()
                                    {
                                        LogicalName = "ust_ostpresential", Id = target.Id
                                    },
                                    DestinationQueueId = colaid
                                };

                                service.Execute(moverOST);

                                //throw new Exception("El registro de OST se ha derivado a la cola de CSR Team :" );
                            }

                            //throw new InvalidPluginExecutionException("Mensaje de error. ");
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemplo n.º 9
0
        /// <summary>
        /// Create and configure the organization service proxy.
        /// Initiate the method to create any data that this sample requires.
        /// Move a record from a source queue to a destination queue.
        /// Optionally delete any entity records that were created for this sample.
        /// <para name="organizationFriendlyName">The friendly name of the target
        /// organization.</para>
        /// <para name="discoveryServer">The name of the discovery server.</para>
        /// <param name="promptForDelete">Indicates whether to prompt the user to
        /// delete the records created in this sample.</param>
        /// </summary>
        public void Run(ServerConnection.Configuration serverConfig, bool promptForDelete)
        {
            try
            {
                // Connect to the Organization service.
                // The using statement assures that the service proxy will be properly disposed.
                using (_serviceProxy = ServerConnection.GetOrganizationProxy(serverConfig))
                {
                    // This statement is required to enable early-bound type support.
                    _serviceProxy.EnableProxyTypes();

                    CreateRequiredRecords();

                    Guid CurrentUserId = ((WhoAmIResponse)_serviceProxy.Execute(new WhoAmIRequest())).UserId;



                    //<snippetRetrieveUserQueues>
                    // Get known private queues for the user
                    // by using RetrieveUserQueuesRequest message.
                    RetrieveUserQueuesRequest retrieveUserQueuesRequest = new RetrieveUserQueuesRequest
                    {
                        UserId        = CurrentUserId,
                        IncludePublic = true
                    };
                    RetrieveUserQueuesResponse retrieveUserQueuesResponse =
                        (RetrieveUserQueuesResponse)_serviceProxy.Execute(retrieveUserQueuesRequest);
                    EntityCollection queues = (EntityCollection)retrieveUserQueuesResponse.EntityCollection;

                    Guid sourceQueueId      = new Guid();
                    Guid destinationQueueId = new Guid();

                    foreach (Entity entity in queues.Entities)
                    {
                        Queue queue = (Queue)entity;
                        switch (queue.Name)
                        {
                        case "Source Queue":
                            sourceQueueId = queue.Id;
                            break;

                        case "Destination Queue":
                            destinationQueueId = queue.Id;
                            break;
                        }
                    }

                    //<snippetAddToQueue1>
                    // Move a record from a source queue to a destination queue
                    // by using the AddToQueue request message.
                    AddToQueueRequest routeRequest = new AddToQueueRequest
                    {
                        SourceQueueId      = sourceQueueId,
                        Target             = new EntityReference(Letter.EntityLogicalName, _letterId),
                        DestinationQueueId = destinationQueueId
                    };

                    // Execute the Request
                    _serviceProxy.Execute(routeRequest);
                    //</snippetAddToQueue1>

                    Console.WriteLine(@"The letter record has been moved to a new queue.");

                    //</snippetRetrieveUserQueues>
                    DeleteRequiredRecords(promptForDelete);
                }
            }
            // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
            catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> )
            {
                // You can handle an exception here or pass it back to the calling method.
                throw;
            }
        }
Exemplo n.º 10
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);

            IOrganizationService iServices = ((IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory))).CreateOrganizationService(new Guid?(context.UserId));

            // Get a reference to the tracing service.
            myTrace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            //myTrace.Trace("Inicio:");

            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    if (context.MessageName == "Update")
                    {
                        //Variables Locales
                        EntityReference ownerId               = null;
                        Guid            colaId                = Guid.Empty;
                        Guid            teamId                = Guid.Empty;
                        string          name                  = string.Empty;
                        EntityReference originpos             = null;
                        int             diagnosticlab         = 0;
                        var             fetchXmlPoint         = "";
                        var             fetchXmlTeam          = "";
                        EntityReference teamadvisorspdv       = null;
                        EntityReference teamcentrallaboratory = null;

                        Entity target = (Entity)context.InputParameters["Target"];

                        if (target.Attributes.Contains("ust_flagsetteampos") && target["ust_flagsetteampos"] != null)
                        {
                            //flagrunplugin = (bool)target.Attributes["ust_flagrunplugin"];

                            //condicion validar el  Lab ust_diagnosticlab option set (Local (864,340,000), Central(864,340,001 ) si es vacio (null))
                            //ust_originpos obtener
                            //Si es lab Local enviar registro de equipo Collection Team

                            // Y si es central enviar registro de equipo Credit Area

                            Entity ostPresential = service.Retrieve("ust_ostpresential", target.Id, new ColumnSet("ownerid", "ust_originpos", "ust_diagnosticlab"));

                            if (ostPresential != null)
                            {
                                if (ostPresential.Attributes.Contains("ownerid") && ostPresential["ownerid"] != null)
                                {
                                    ownerId = ((EntityReference)ostPresential.Attributes["ownerid"]);
                                }
                                if (ostPresential.Attributes.Contains("ust_originpos") && ostPresential["ust_originpos"] != null)
                                {
                                    originpos = ((EntityReference)ostPresential.Attributes["ust_originpos"]);
                                    //myTrace.Trace("originpos :" + originpos.Id);
                                }
                                if (ostPresential.Attributes.Contains("ust_diagnosticlab") && ostPresential["ust_diagnosticlab"] != null)
                                {
                                    diagnosticlab = ((OptionSetValue)ostPresential.Attributes["ust_diagnosticlab"]).Value;
                                    //myTrace.Trace("diagnosticlab1 :" + diagnosticlab);
                                }

                                if (originpos != null)
                                {
                                    if (diagnosticlab == 864340000) //Local
                                    {
                                        myTrace.Trace("diagnosticlab :" + diagnosticlab);

                                        fetchXmlPoint = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                        "<entity name='amxperu_pointofsales'>" +
                                                        "<attribute name='amxperu_pointofsalesid' />" +
                                                        "<attribute name='amxperu_name' />" +
                                                        "<attribute name='createdon' />" +
                                                        "<attribute name='ust_teamlocallaboratory' />" +
                                                        "<attribute name='ust_teamcentrallaboratory' />" +
                                                        "<attribute name='ust_teamadvisorspdv' />" +
                                                        "<order attribute='amxperu_name' descending='false' />" +
                                                        "<filter type='and'>" +
                                                        "<condition attribute='amxperu_pointofsalesid' operator='eq' uitype='amxperu_pointofsales' value = '" + originpos.Id + "' />" +
                                                        "</filter>" +
                                                        "</entity>" +
                                                        "</fetch>";

                                        EntityCollection resultP = service.RetrieveMultiple(new FetchExpression(fetchXmlPoint));
                                        if (resultP[0].Attributes.Contains("ust_teamadvisorspdv") && resultP[0]["ust_teamadvisorspdv"] != null)
                                        {
                                            teamadvisorspdv = ((EntityReference)resultP[0].Attributes["ust_teamadvisorspdv"]);
                                            myTrace.Trace("teamadvisorspdv :" + teamadvisorspdv.Name);
                                        }

                                        fetchXmlTeam = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                       "<entity name='team'>" +
                                                       "<attribute name='name' />" +
                                                       "<attribute name='businessunitid' />" +
                                                       "<attribute name='teamid' />" +
                                                       "<attribute name='teamtype' />" +
                                                       "<attribute name='queueid' />" +
                                                       "<order attribute='name' descending='false' />" +
                                                       "<filter type='and'>" +
                                                       "<condition attribute='name' operator='eq' value='" + teamadvisorspdv.Name + "' />" +
                                                       "</filter>" +
                                                       "</entity>" +
                                                       "</fetch>";

                                        EntityCollection resulT = service.RetrieveMultiple(new FetchExpression(fetchXmlTeam));
                                        if (resulT[0].Attributes.Contains("teamid") && resulT[0]["teamid"] != null)
                                        {
                                            teamId = (Guid)resulT[0].Attributes["teamid"];
                                            //myTrace.Trace("teamId :" + teamId);
                                        }
                                        if (resulT[0].Attributes.Contains("name") && resulT[0]["name"] != null)
                                        {
                                            name = resulT[0].Attributes["name"].ToString();
                                            //myTrace.Trace("name :" + name);
                                        }
                                    }
                                    if (diagnosticlab == 864340001) //Central
                                    {
                                        fetchXmlPoint = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                        "<entity name='amxperu_pointofsales'>" +
                                                        "<attribute name='amxperu_pointofsalesid' />" +
                                                        "<attribute name='amxperu_name' />" +
                                                        "<attribute name='createdon' />" +
                                                        "<attribute name='ust_teamlocallaboratory' />" +
                                                        "<attribute name='ust_teamcentrallaboratory' />" +
                                                        "<attribute name='ust_teamadvisorspdv' />" +
                                                        "<order attribute='amxperu_name' descending='false' />" +
                                                        "<filter type='and'>" +
                                                        "<condition attribute='amxperu_pointofsalesid' operator='eq' uitype='amxperu_pointofsales' value = '" + originpos.Id + "' />" +
                                                        "</filter>" +
                                                        "</entity>" +
                                                        "</fetch>";

                                        EntityCollection resultP = service.RetrieveMultiple(new FetchExpression(fetchXmlPoint));
                                        if (resultP[0].Attributes.Contains("ust_teamcentrallaboratory") && resultP[0]["ust_teamcentrallaboratory"] != null)
                                        {
                                            teamcentrallaboratory = ((EntityReference)resultP[0].Attributes["ust_teamcentrallaboratory"]);
                                        }

                                        fetchXmlTeam = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                       "<entity name='team'>" +
                                                       "<attribute name='name' />" +
                                                       "<attribute name='businessunitid' />" +
                                                       "<attribute name='teamid' />" +
                                                       "<attribute name='teamtype' />" +
                                                       "<attribute name='queueid' />" +
                                                       "<order attribute='name' descending='false' />" +
                                                       "<filter type='and'>" +
                                                       "<condition attribute='name' operator='eq' value='" + teamcentrallaboratory.Name + "' />" +
                                                       "</filter>" +
                                                       "</entity>" +
                                                       "</fetch>";

                                        EntityCollection resultT = service.RetrieveMultiple(new FetchExpression(fetchXmlTeam));

                                        if (resultT[0].Attributes.Contains("teamid") && resultT[0]["teamid"] != null)
                                        {
                                            teamId = (Guid)resultT[0].Attributes["teamid"];
                                            //myTrace.Trace("teamId :" + teamId);
                                        }
                                        if (resultT[0].Attributes.Contains("name") && resultT[0]["name"] != null)
                                        {
                                            name = resultT[0].Attributes["name"].ToString();
                                            //myTrace.Trace("name :" + name);
                                        }
                                    }

                                    if (teamId != null)
                                    {
                                        var fetchQueue = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                         "<entity name='queue'>" +
                                                         "<attribute name='name' />" +
                                                         "<attribute name='emailaddress' />" +
                                                         "<attribute name='queueid' />" +
                                                         "<order attribute='emailaddress' descending='false' />" +
                                                         "<filter type='and'>" +
                                                         "<condition attribute='name' operator='like' value='%" + name + "%' />" +
                                                         "</filter>" +
                                                         "</entity>" +
                                                         "</fetch>";

                                        EntityCollection resultQ = service.RetrieveMultiple(new FetchExpression(fetchQueue));

                                        if (resultQ[0].Attributes.Contains("queueid") && resultQ[0]["queueid"] != null)
                                        {
                                            colaId = (Guid)resultQ[0].Attributes["queueid"];
                                            //myTrace.Trace("colaId :" + colaId);
                                        }

                                        AddToQueueRequest moverOST = new AddToQueueRequest()
                                        {
                                            Target = new EntityReference()
                                            {
                                                LogicalName = "ust_ostpresential", Id = target.Id
                                            },
                                            DestinationQueueId = colaId
                                        };

                                        service.Execute(moverOST);
                                    }

                                    //throw new InvalidPluginExecutionException("Mensaje de error. ");
                                }
                            }
                            //throw new InvalidPluginExecutionException("Mensaje de error. ");
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }