private void CloseIncident(EntityReference caseReference)
        {
            // First close the Incident

            // Create resolution for the closing incident
            IncidentResolution resolution = new IncidentResolution
            {
                Subject = "Case Closed",
            };

            resolution.IncidentId = caseReference;

            // Create the request to close the incident, and set its resolution to the
            // resolution created above
            CloseIncidentRequest closeRequest = new CloseIncidentRequest();

            closeRequest.IncidentResolution = resolution;

            // Set the requested new status for the closed Incident
            closeRequest.Status =
                new OptionSetValue((int)incident_statuscode.ProblemSolved);

            // Execute the close request
            CloseIncidentResponse closeResponse =
                (CloseIncidentResponse)_serviceProxy.Execute(closeRequest);

            //Check if the incident was successfully closed
            Incident incident = _serviceProxy.Retrieve(Incident.EntityLogicalName,
                                                       _caseIncidentId, new ColumnSet(allColumns: true)).ToEntity <Incident>();

            if (incident.StateCode.HasValue & amp; &amp;
                incident.StateCode == IncidentState.Resolved)
            {
                Console.WriteLine("The incident was closed out as Resolved.");
            }
Ejemplo n.º 2
0
        public bool ResolveTicket(Guid?ticketGuid)
        {
            Entity IncidentResolution = new Entity("incidentresolution");

            IncidentResolution.Attributes["subject"]    = "Subject Closed";
            IncidentResolution.Attributes["incidentid"] = new EntityReference("incident", ticketGuid.Value);
            // Create the request to close the incident, and set its resolution to the
            // resolution created above
            CloseIncidentRequest closeRequest = new CloseIncidentRequest();

            closeRequest.IncidentResolution = IncidentResolution;
            // Set the requested new status for the closed Incident
            closeRequest.Status = new OptionSetValue(5);
            // Execute the close request

            try
            {
                CloseIncidentResponse closeResponse = (CloseIncidentResponse)_service.Execute(closeRequest);
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
        /// <summary>
        /// Closes a Trouble ticket by ID
        /// </summary>
        /// <param name="ticketId">ID of the Ticket to close</param>
        /// <param name="subject">Title of the close ticket record</param>
        /// <param name="description">Description of the closed ticket</param>
        /// <param name="batchId">Optional: if set to a valid GUID, generated by the Create Batch Request Method, will assigned the request to the batch for later execution, on fail, runs the request immediately </param>
        /// <param name="cdsServiceClient">Connected CDS Service Client</param>
        /// <param name="bypassPluginExecution">Adds the bypass plugin behavior to this request. Note: this will only apply if the caller has the prvBypassPlugins permission to bypass plugins.  If its attempted without the permission the request will fault.</param>
        /// <returns>Returns the ID of the closed ticket</returns>
        public static Guid CloseTroubleTicket(this CdsServiceClient cdsServiceClient, Guid ticketId, string subject, string description, Guid batchId = default(Guid), bool bypassPluginExecution = false)
        {
            // ONE OF THEASE SOULD BE MADE THE MASTER

            cdsServiceClient.logEntry.ResetLastError();              // Reset Last Error
            if (cdsServiceClient._CdsService == null)
            {
                cdsServiceClient.logEntry.Log("Crm Service not initialized", TraceEventType.Error);
                return(Guid.Empty);
            }

            if (ticketId == Guid.Empty)
            {
                return(Guid.Empty);
            }

            // Create Incident Resolution Type

            Entity reso = new Entity("incidentresolution");

            Guid closeTicketId = Guid.NewGuid();

            reso.Attributes.Add("activityid", closeTicketId);
            reso.Attributes.Add("incidentid", new EntityReference("incident", ticketId));

            // NEED TO REWORK THIS WITH METAD DATA>
            reso.Attributes.Add("statecode", new OptionSetValue(1));
            reso.Attributes.Add("statuscode", new OptionSetValue(2));
            reso.Attributes.Add("subject", subject);
            reso.Attributes.Add("description", description);

            // Set Close Time Stamp
            reso.Attributes.Add("actualend", DateTime.Now.ToString());

            // Get State close for Resolving a case
            int defaultStateCodeForResolveCase = 1;
            CloseIncidentRequest req4          = new CloseIncidentRequest();

            req4.IncidentResolution = reso;
            req4.Status             = new OptionSetValue(defaultStateCodeForResolveCase);


            if (cdsServiceClient.AddRequestToBatch(batchId, req4, "Calling Close Incident", "Request to Close Incident Queued", bypassPluginExecution))
            {
                return(Guid.Empty);
            }

            CloseIncidentResponse resp4 = (CloseIncidentResponse)cdsServiceClient.CdsCommand_Execute(req4, "Closing a Case in CRM", bypassPluginExecution);

            if (resp4 != null)
            {
                return(closeTicketId);
            }
            else
            {
                return(Guid.Empty);
            }
        }
        /// <summary>
        /// Closes an Incident request in CRM,
        /// this special handling is necessary to support CRM Built In Object.
        /// </summary>
        /// <param name="incidentId">ID of the CRM Incident to close</param>
        /// <param name="fieldList">List of data items to add to the request, By default, subject is required.</param>
        /// <param name="incidentStatusCode">Status code to close the incident with, defaults to resolved</param>
        /// <param name="batchId">Optional: if set to a valid GUID, generated by the Create Batch Request Method, will assigned the request to the batch for later execution, on fail, runs the request immediately </param>
        /// <param name="cdsServiceClient">Connected CDS Service Client</param>
        /// <param name="bypassPluginExecution">Adds the bypass plugin behavior to this request. Note: this will only apply if the caller has the prvBypassPlugins permission to bypass plugins.  If its attempted without the permission the request will fault.</param>
        /// <returns>Guid of the Activity.</returns>
        public static Guid CloseIncident(this CdsServiceClient cdsServiceClient, Guid incidentId, Dictionary <string, CdsDataTypeWrapper> fieldList, int incidentStatusCode = 5, Guid batchId = default(Guid), bool bypassPluginExecution = false)
        {
            cdsServiceClient.logEntry.ResetLastError();              // Reset Last Error
            if (cdsServiceClient._CdsService == null)
            {
                cdsServiceClient.logEntry.Log("Crm Service not initialized", TraceEventType.Error);
                return(Guid.Empty);
            }

            if (incidentId == Guid.Empty)
            {
                return(Guid.Empty);
            }

            Guid   actId = Guid.Empty;
            Entity uEnt  = new Entity("incidentresolution");
            AttributeCollection PropertyList = new AttributeCollection();

            #region MapCode
            if (fieldList != null)
            {
                foreach (KeyValuePair <string, CdsDataTypeWrapper> field in fieldList)
                {
                    cdsServiceClient.AddValueToPropertyList(field, PropertyList);
                }
            }

            // Add the key...
            // check to see if the key is in the import set already
            if (fieldList != null && !fieldList.ContainsKey("incidentid"))
            {
                PropertyList.Add(new KeyValuePair <string, object>("incidentid", new EntityReference("incident", incidentId)));
            }

            if (fieldList != null && fieldList.ContainsKey("activityid"))
            {
                actId = (Guid)fieldList["activityid"].Value;
            }
            else
            {
                actId   = Guid.NewGuid();
                uEnt.Id = actId;
            }
            #endregion
            uEnt.Attributes.AddRange(PropertyList.ToArray());


            CloseIncidentRequest req4 = new CloseIncidentRequest();
            req4.IncidentResolution = uEnt;
            req4.Status             = new OptionSetValue(incidentStatusCode);

            if (cdsServiceClient.AddRequestToBatch(batchId, req4, "Calling Close Incident", "Request to Close Incident Queued", bypassPluginExecution))
            {
                return(Guid.Empty);
            }


            CloseIncidentResponse resp4 = (CloseIncidentResponse)cdsServiceClient.CdsCommand_Execute(req4, "Closing a incidentId in CRM", bypassPluginExecution);
            if (resp4 != null)
            {
                return(actId);
            }
            else
            {
                return(Guid.Empty);
            }
        }
Ejemplo n.º 5
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
                        string          sCodCaseType         = string.Empty;
                        EntityReference erTipoCaso           = null;
                        EntityReference erCategory4          = null;
                        Guid            erincidentId         = Guid.Empty;
                        string          sCodCategory4        = string.Empty;
                        bool            erIsAveria           = false;
                        string          stageId              = null;
                        bool            hiddenConsumeService = false;
                        Guid            nota       = Guid.Empty;
                        int             statuscode = 0;
                        string          networkmassivefaultstatus = string.Empty;

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

                        if (entity.LogicalName != "amxperu_networkincident")
                        {
                            return;
                        }

                        if (entity == null)
                        {
                            return;
                        }

                        if (entity.Attributes.Contains("amxperu_status") && entity["amxperu_status"] != null)
                        {
                            Guid networkincidentId = entity.Id;
                            myTrace.Trace("networkincidentId :" + networkincidentId.ToString());

                            int status = ((OptionSetValue)entity.Attributes["amxperu_status"]).Value;

                            myTrace.Trace("status :" + status);

                            var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                           "<entity name='incident'>" +
                                           "<attribute name='title' />" +
                                           "<attribute name='amxperu_casetype' />" +
                                           "<attribute name='ust_category4' />" +
                                           "<attribute name='ust_complaintphase' />" +
                                           "<attribute name='etel_isdispute' />" +
                                           "<attribute name='incidentid' />" +
                                           "<attribute name='statecode' />" +
                                           "<attribute name='statuscode' />" +
                                           "<attribute name='stageid' />" +
                                           "<attribute name='ust_hiddenconsumeservice' />" +
                                           "<attribute name='ust_networkmassivefaultstatus' />" +
                                           "<attribute name='ust_networkmassivefaultid' />" +
                                           "<order attribute='title' descending='false' />" +
                                           "<filter type='and'>" +
                                           "<condition attribute='ust_networkmassivefaultid' operator='eq' uiname='' uitype='amxperu_networkincident' value='" + entity.Id + "' />" +
                                           "<condition attribute='statuscode' operator='eq' value='864340008' />" + //Solo Pendientes
                                           "</filter>" +
                                           "</entity>" +
                                           "</fetch>";

                            EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml));

                            //myTrace.Trace("result :" + result.Entities.Count.ToString());
                            for (int j = 0; j < result.Entities.Count; j++)
                            {
                                myTrace.Trace("Ingrese :" + result.ToString());

                                if (result[j].Attributes.Contains("amxperu_casetype") && result[j]["amxperu_casetype"] != null)
                                {
                                    erTipoCaso = ((EntityReference)result[j].Attributes["amxperu_casetype"]);

                                    Entity caseType = service.Retrieve("amxperu_casetype", erTipoCaso.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("ust_code"));

                                    if (caseType.Attributes.Contains("ust_code") && caseType.Attributes["ust_code"] != null)
                                    {
                                        //Get the Case Type Code
                                        sCodCaseType = caseType.Attributes["ust_code"].ToString();
                                        //myTrace.Trace("sCodCaseType :" + sCodCaseType.ToString());
                                    }

                                    if (result[j].Attributes.Contains("ust_category4") && result[j]["ust_category4"] != null)
                                    {
                                        erCategory4 = ((EntityReference)result[j].Attributes["ust_category4"]);

                                        var fetchXmlC = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                        "<entity name='amxperu_caseothercategory'>" +
                                                        "<attribute name='amxperu_caseothercategoryid' />" +
                                                        "<attribute name='amxperu_name' />" +
                                                        "<attribute name='createdon' />" +
                                                        "<attribute name='ust_isaveria' />" +
                                                        "<order attribute='amxperu_name' descending='false' />" +
                                                        "<filter type='and'>" +
                                                        "<condition attribute='ust_isaveria' operator='eq' value='1' />" +
                                                        "<condition attribute='amxperu_caseothercategoryid' value='" + erCategory4.Id + "' operator='eq' uitype='amxperu_caseothercategory' />" +
                                                        "</filter>" +
                                                        "</entity>" +
                                                        "</fetch>";

                                        EntityCollection resultC = service.RetrieveMultiple(new FetchExpression(fetchXmlC));
                                        if (resultC.Entities.Count > 0)
                                        {
                                            if (resultC[0].Attributes.Contains("ust_isaveria") && resultC[0]["ust_isaveria"] != null)
                                            {
                                                //myTrace.Trace("erIsAveria :" + resultC[0]["ust_isaveria"].ToString());
                                                erIsAveria = (bool)resultC[0].Attributes["ust_isaveria"];
                                            }
                                            else
                                            {
                                                erIsAveria = false;
                                            }
                                        }
                                        if (result[j].Attributes.Contains("ust_complaintphase") && result[j]["ust_complaintphase"] != null)
                                        {
                                            erComplaintPhase = ((OptionSetValue)result[j].Attributes["ust_complaintphase"]).Value;
                                            //myTrace.Trace("erComplaintPhase :" + erComplaintPhase);
                                        }

                                        if (result[j].Attributes.Contains("stageid") && result[j]["stageid"] != null)
                                        {
                                            stageId = result[j].Attributes["stageid"].ToString();
                                            //myTrace.Trace("stageId :" + stageId);
                                        }

                                        if (result[j].Attributes.Contains("incidentid") && result[j]["incidentid"] != null)
                                        {
                                            //myTrace.Trace("incidentid :" + result[j]["incidentid"]);
                                            erincidentId = ((Guid)result[j]["incidentid"]);
                                        }
                                        if (result[j].Attributes.Contains("statuscode") && result[j]["statuscode"] != null)
                                        {
                                            statuscode = ((OptionSetValue)result[j].Attributes["statuscode"]).Value;
                                        }
                                        if (result[j].Attributes.Contains("ust_networkmassivefaultstatus") && result[j]["ust_networkmassivefaultstatus"] != null)
                                        {
                                            networkmassivefaultstatus = result[j].Attributes["ust_networkmassivefaultstatus"].ToString();
                                        }
                                        string PhaseNameEN = Util.GetCrmConfiguration(service, "NameFaseResearchEnglish");
                                        string PhaseNameES = Util.GetCrmConfiguration(service, "NameFaseResearchSpanish");
                                        string stageName   = Util.GetProcessStageName(service, new Guid(stageId));
                                        //myTrace.Trace("stageName :" + stageName);
                                        //Actualizar el campo de estado de avería masiva a “Cerrado”.
                                        //Concluir el reclamo.
                                        //myTrace.Trace("status :" + sCodCaseType + " " + erIsAveria + " " + erComplaintPhase);
                                        if (status == 250000001 && sCodCaseType == "004" && erIsAveria == true) //Closed and Tipo Caso(Reclamo OSIPTEL) and Categoria and Averia
                                        {
                                            if (erComplaintPhase == 864340000)                                  // Es Averia
                                            {
                                                //myTrace.Trace("Ingreso aqui 1 ");
                                                //TO DO: Validar el stagename
                                                if (stageName == PhaseNameEN || stageName == PhaseNameES)
                                                {
                                                    //myTrace.Trace("Ingreso aqui 2 ");
                                                    Entity obj = new Entity("incident");
                                                    obj.Id = result[j].Id;
                                                    obj["ust_networkmassivefaultstatus"] = "Cerrado";
                                                    service.Update(obj);

                                                    Entity annotation = new Entity("annotation");
                                                    annotation.Attributes.Add("subject", "signature");

                                                    annotation["subject"] = "Reclamo en fase de avería concluido automáticamente tras el cierre de la Averia Masiva";
                                                    annotation.Attributes.Add("objectid", new EntityReference("incident", result[j].Id));
                                                    Guid annotationId = service.Create(annotation);

                                                    //Cerramos el caso
                                                    Entity resolution = new Entity("incidentresolution");
                                                    resolution["subject"]    = "Closed";
                                                    resolution["incidentid"] = new EntityReference(result[j].LogicalName, result[j].Id);

                                                    //Caso Resuelto
                                                    CloseIncidentRequest closecase = new CloseIncidentRequest();

                                                    closecase.IncidentResolution = resolution;
                                                    //myTrace.Trace("statuscode :" + closecase.IncidentResolution.Id);
                                                    closecase.Status = new OptionSetValue(5);

                                                    CloseIncidentResponse closeresponse = (CloseIncidentResponse)service.Execute(closecase);
                                                }
                                                else
                                                {
                                                    //myTrace.Trace("Aqui 2 :");
                                                    //Actualizar el campo de estado de avería masiva.
                                                    Entity obj = new Entity("incident");
                                                    obj.Id = result[j].Id;

                                                    obj["ust_networkmassivefaultstatus"] = "Abierto";
                                                    service.Update(obj);

                                                    networkIncident(service, networkincidentId, result[j].Id);
                                                }
                                            }
                                            else if (erComplaintPhase == 864340001) //Es 1era Instancia
                                            {
                                                if (result[j].Attributes.Contains("ust_hiddenconsumeservice") && result[j]["ust_hiddenconsumeservice"] != null)
                                                {
                                                    hiddenConsumeService = (bool)result[j].Attributes["ust_hiddenconsumeservice"];
                                                }
                                                hiddenConsumeService = true;
                                                //myTrace.Trace("Aqui Instancia :" + hiddenConsumeService);
                                                if (hiddenConsumeService == true)
                                                {
                                                    //if (statuscode != 864340001)
                                                    //{
                                                    //myTrace.Trace("Ingrese 3:" + result.ToString());
                                                    //solamente se cambia a “Con Resolución” cuando la carta de respuesta es generada).
                                                    Entity obj = new Entity("incident");
                                                    obj.Id            = result[j].Id;
                                                    obj["statuscode"] = new OptionSetValue(864340001); //Con Resolucion
                                                    obj["ust_networkmassivefaultstatus"] = "Cerrado";
                                                    service.Update(obj);

                                                    DateTime fechaActual = DateTime.Today;

                                                    Entity annotation = new Entity("annotation");
                                                    annotation.Attributes.Add("subject", "signature");

                                                    annotation["subject"] = "Avería masiva < 123 > asociada a este reclamo concluida en " + fechaActual;
                                                    annotation.Attributes.Add("objectid", new EntityReference("incident", erincidentId));
                                                    Guid annotationId = service.Create(annotation);
                                                    //myTrace.Trace("annotationId :" + annotationId.ToString());
                                                }
                                                else
                                                {
                                                    networkIncident(service, networkincidentId, result[j].Id);
                                                }
                                            }
                                            else
                                            {
                                                networkIncident(service, networkincidentId, result[j].Id);
                                            }
                                        }
                                        else
                                        {
                                            networkIncident(service, networkincidentId, result[j].Id);
                                        }

                                        // throw new InvalidPluginExecutionException("Mensaje de error. ");
                                    }
                                    else
                                    {
                                        networkIncident(service, networkincidentId, result[j].Id);
                                    }
                                }
                                //throw new InvalidPluginExecutionException("Mensaje de error. ");
                            }

                            //throw new InvalidPluginExecutionException("Mensaje de error. ");
                        }
                    }
                }
            }
            catch (ApplicationException ex)
            {
                throw new ApplicationException("Controlled Error: " + ex.Message, ex);
            }
            catch (InvalidPluginExecutionException ex)
            {
                throw new InvalidPluginExecutionException("PlugIn Error: " + ex.Message, ex);
            }
            catch (EndpointNotFoundException ex)
            {
                throw new EndpointNotFoundException("EndPoint Error: " + ex.Message, ex);
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("Crm Service error: " + ex.Message, ex);
            }
            catch (Exception ex)
            {
                throw new Exception("Uncontrolled error: " + ex.Message, ex);;
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// A plug-in that creates a case, queue item and auto-response email record when a new, previously untracked incoming email is created.
        /// Thomas Adams, University of Bath, 29/10/19
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, email entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

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

                string  strEmailDirection, strEmailSubject, strTo, strFrom, strEmailTo, strEmailFrom, strModifiedBy;
                Boolean blnContactFound   = false;
                Boolean blnCloseForDeDupe = false;
                //EntityReference contactID = new EntityReference("contact");
                Guid contactID         = new Guid();
                Guid ownerID           = new Guid();
                Guid queueID           = new Guid();
                Guid caseID            = new Guid();
                Guid queueItemID       = new Guid();
                Guid emailID           = new Guid();
                Guid templateEmailID   = new Guid();
                Guid regardingObjectID = new Guid();
                Guid incidentID        = new Guid();

                string strCategory = "";

                // Verify that the target entity represents an account.
                // If not, this plug-in was not registered correctly.
                if (entity.LogicalName != "incident")
                {
                    return;
                }

                try
                {
                    tracingService.Trace("DeDupeResolveCase starting......");

                    //strEmailTo = "";
                    //strEmailFrom = "";

                    if (context.PostEntityImages.Contains("PostImage") &&
                        context.PostEntityImages["PostImage"] is Entity)
                    {
                        Entity postMessageImage = (Entity)context.PostEntityImages["PostImage"];
                        ////strEmailDirection = postMessageImage.FormattedValues["directioncode"];
                        ////strEmailSubject = postMessageImage.Attributes["subject"].ToString();
                        ////strTo = postMessageImage.Attributes["to"].ToString();
                        ////strFrom = postMessageImage.Attributes["from"].ToString();
                        ////emailID = (Guid)postMessageImage.Attributes["activityid"];
                        ///
                        //regardingObjectID = ((EntityReference)(postMessageImage.Attributes["regardingobjectid"])).Id;
                        incidentID = (Guid)postMessageImage.Attributes["incidentid"];

                        strModifiedBy     = postMessageImage.FormattedValues["modifiedby"];
                        blnCloseForDeDupe = (Boolean)postMessageImage.Attributes["dedupe_closefordedupe"];

                        tracingService.Trace("Modified by: " + strModifiedBy);
                        tracingService.Trace("Incident ID: " + incidentID.ToString());

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

                        if (blnCloseForDeDupe == true)
                        {
                            tracingService.Trace("Going to close case...");
                            //if (strState == "Active")
                            {
                                //logfile.WriteLine("Resolving case...");
                                Entity IncidentResolution = new Entity("incidentresolution");
                                IncidentResolution.Attributes["subject"] = "DeDupe auto-resolve";
                                //IncidentResolution.Attributes["incidentid"] = new EntityReference("incident", incidentID);

                                // Create the request to close the incident, and set its resolution to the
                                // resolution created above
                                CloseIncidentRequest closeRequest = new CloseIncidentRequest();
                                closeRequest.IncidentResolution = IncidentResolution;

                                // Set the requested new status for the closed Incident
                                closeRequest.Status = new OptionSetValue(5);

                                // Execute the close request
                                CloseIncidentResponse closeResponse = (CloseIncidentResponse)svc.Execute(closeRequest);
                            }
                        }
                    }
                    else
                    {
                        tracingService.Trace("Modified not found");
                    }
                }

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

                catch (Exception ex)
                {
                    tracingService.Trace("DeDupeResolveCase Plugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
        }                                                          //Notificado


        #endregion

        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            //Create the context
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);


            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    EntityReference usCaseType = CaseType.Get <EntityReference>(executionContext);
                    OptionSetValue  usEstado   = StatusCode.Get <OptionSetValue>(executionContext);

                    //tracingService.Trace("usCaseType " + CaseType.ToString());
                    //tracingService.Trace("usEstado " + usEstado.Value);

                    //Local Variables
                    int      estado     = usEstado.Value;
                    string   typeCase   = "";
                    DateTime modifiedOn = DateTime.Now;
                    int      estadoC    = 0;

                    Entity entity = (Entity)context.InputParameters["Target"];
                    if (entity.LogicalName != "incident")
                    {
                        return;
                    }
                    if (entity == null)
                    {
                        return;
                    }

                    Entity dataCase = service.Retrieve("incident", entity.Id, new ColumnSet("statuscode", "ust_dateofnotification"));

                    //tracingService.Trace("dataCase " + dataCase.Id);

                    if (dataCase.Attributes.Contains("ust_dateofnotification") && dataCase.Attributes["ust_dateofnotification"] != null)
                    {
                        modifiedOn = (DateTime)dataCase.Attributes["ust_dateofnotification"];
                    }

                    DateTime fechatemp = modifiedOn;
                    int      diaT      = fechatemp.Day;
                    int      mesT      = fechatemp.Month;
                    int      anioT     = fechatemp.Year;

                    Entity caseType = service.Retrieve("amxperu_casetype", usCaseType.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("ust_code"));

                    if (caseType.Attributes.Contains("ust_code") && caseType.Attributes["ust_code"] != null)
                    {
                        tracingService.Trace("ust_code " + caseType.Attributes.Contains("ust_code").ToString());
                        //Get the Case Type Code
                        typeCase = caseType.Attributes["ust_code"].ToString(); //004  Reclamo OSIPTEL
                    }

                    //myTrace.Trace("typeCase :" + typeCase.ToString());
                    tracingService.Trace("estado " + estado.ToString());

                    if (typeCase == "004" && estado == 864340003) //Tipo reclamo OSIPTEL and Estado(Notificado)
                    {
                        //Buscar si hay hijo del reclamo Abierto
                        string codeQueja = "005";

                        var fetchQueja = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                         "<entity name='amxperu_casetype'>" +
                                         "<attribute name='amxperu_casetypeid' />" +
                                         "<attribute name='amxperu_name' />" +
                                         "<attribute name='createdon' />" +
                                         "<order attribute='amxperu_name' descending='false' />" +
                                         "<filter type='and'>" +
                                         "<condition attribute='ust_code' value ='" + codeQueja + "' operator= 'eq' />" +
                                         "</filter>" +
                                         "</entity>" +
                                         "</fetch>";

                        EntityCollection resultQ = service.RetrieveMultiple(new FetchExpression(fetchQueja));
                        foreach (var c in resultQ.Entities)
                        {
                            var fetchXml = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                           "<entity name='incident'>" +
                                           "<attribute name='title' />" +
                                           "<attribute name='ticketnumber' />" +
                                           "<attribute name='createdon' />" +
                                           "<attribute name='caseorigincode' />" +
                                           "<attribute name='etel_isdispute' />" +
                                           "<attribute name='incidentid' />" +
                                           "<attribute name='statuscode' />" +
                                           "<attribute name='statecode' />" +
                                           "<order attribute='title' descending='false' />" +
                                           "<filter type='and'>" +
                                           "<condition attribute='amxperu_casetype' operator='eq' uiname='' uitype='amxperu_casetype' value='" + c.Id + "' />" +
                                           "<condition attribute='statecode' value='0' operator='eq' /> " +
                                           "<condition attribute='parentcaseid' value='" + entity.Id + "' uitype='incident' operator='eq' /> " +
                                           "</filter>" +
                                           "</entity>" +
                                           "</fetch>";

                            EntityCollection result = service.RetrieveMultiple(new FetchExpression(fetchXml));
                            foreach (var d in result.Entities)
                            {
                                var fetchXmlCon = "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>" +
                                                  "<entity name='etel_crmconfiguration'>" +
                                                  "<attribute name='etel_crmconfigurationid' />" +
                                                  "<attribute name='etel_name' />" +
                                                  "<attribute name='createdon' />" +
                                                  "<attribute name='etel_value' />" +
                                                  "<attribute name='statecode' />" +
                                                  "<order attribute='etel_name' descending='false' />" +
                                                  "<filter type='and'>" +
                                                  "<condition attribute='etel_name' operator='eq' uiname='' value='ResolveOSIPTELClaim' />" +
                                                  "</filter>" +
                                                  "</entity>" +
                                                  "</fetch>";

                                EntityCollection resultCon = service.RetrieveMultiple(new FetchExpression(fetchXmlCon));

                                if (resultCon[0].Attributes["etel_value"].ToString() != null)
                                {
                                    double plazo = Convert.ToUInt32(resultCon[0].Attributes["etel_value"]);

                                    for (int i = 0; i < plazo; i++)
                                    {
                                        if (modifiedOn.DayOfWeek == DayOfWeek.Sunday || modifiedOn.DayOfWeek == DayOfWeek.Saturday)
                                        {
                                            plazo = plazo + 1;
                                        }
                                        modifiedOn = modifiedOn.AddDays(1);
                                    }
                                    DateTime fechaUtil = modifiedOn.AddDays(1);

                                    DateTime fechaActual = DateTime.Now;

                                    if (fechaUtil < fechaActual)
                                    {
                                        if (d.Attributes.Contains("statecode") && d["statecode"] != null)
                                        {
                                            estadoC = ((OptionSetValue)dataCase.Attributes["statecode"]).Value;
                                            if (estadoC != 0)
                                            {
                                                Entity resolution = new Entity("incidentresolution");
                                                resolution["subject"]    = "Closed";
                                                resolution["incidentid"] = new EntityReference(dataCase.LogicalName, dataCase.Id);

                                                CloseIncidentRequest closecase = new CloseIncidentRequest();

                                                closecase.IncidentResolution = resolution;
                                                closecase.Status             = new OptionSetValue(5);

                                                CloseIncidentResponse closeresponse = (CloseIncidentResponse)service.Execute(closecase);
                                            }
                                        }
                                        else
                                        {
                                            Entity resolution = new Entity("incidentresolution");
                                            resolution["subject"]    = "Closed";
                                            resolution["incidentid"] = new EntityReference(dataCase.LogicalName, dataCase.Id);

                                            CloseIncidentRequest closecase = new CloseIncidentRequest();

                                            closecase.IncidentResolution = resolution;
                                            closecase.Status             = new OptionSetValue(5);

                                            CloseIncidentResponse closeresponse = (CloseIncidentResponse)service.Execute(closecase);
                                        }
                                    }
                                }
                            }
                        }
                    }

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