Exemple #1
0
        public virtual void Get_OrganizationService(IOrganizationServiceFactory factory)
        {
            // Act
            var userId = Guid.NewGuid();
            var service = factory.CreateOrganizationService(userId);

            // Assert
            service.Should().NotBeNull();

            if (((CuteService)service).Provider.Type == InstanceType.NoInput ||
                ((CuteService)service).Provider.Type == InstanceType.SerializedInput)
            {
                ((CuteService)service).Original.Should().BeNull();
            }
            else
            {
                ((CuteService)service).Original.Should().NotBeNull();
            }

            ((CuteService)service).UserId.Should().Be(userId);

            service.GetType().Should().BeAssignableTo<CuteService>();
            service.GetType().Should().BeAssignableTo<IOrganizationService>();
        }
Exemple #2
0
    protected override void Execute(CodeActivityContext executionContext)
    {
        //Check to see if the EntityReference has been set
        EntityReference loanApplication = this.LoanApplication.Get(executionContext);

        if (loanApplication == null)
        {
            throw new InvalidOperationException("Loan Application has not been specified", new ArgumentNullException("Loan Application"));
        }
        else if (loanApplication.LogicalName != CustomEntity)
        {
            throw new InvalidOperationException("Loan Application must reference a Loan Application entity",
                                                new ArgumentException("Loan Application must be of type Loan Application", "Loan Application"));
        }

        //Retrieve the CrmService so that we can retrieve the loan application
        IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
        IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
        IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.InitiatingUserId);

        //Retrieve the Loan Application Entity
        Entity loanEntity;
        {
            //Create a request
            RetrieveRequest retrieveRequest = new RetrieveRequest();
            retrieveRequest.ColumnSet = new ColumnSet(new string[] { "new_loanapplicationid", "new_loanapplicantid" });
            retrieveRequest.Target    = loanApplication;

            //Execute the request
            RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);

            //Retrieve the Loan Application Entity
            loanEntity = retrieveResponse.Entity as Entity;
        }

        //Retrieve the Contact Entity
        Entity contactEntity;
        {
            //Create a request
            EntityReference loanApplicantId = (EntityReference)loanEntity["new_loanapplicantid"];

            RetrieveRequest retrieveRequest = new RetrieveRequest();
            retrieveRequest.ColumnSet = new ColumnSet(new string[] { "fullname", "new_ssn", "birthdate" });
            retrieveRequest.Target    = loanApplicantId;

            //Execute the request
            RetrieveResponse retrieveResponse = (RetrieveResponse)service.Execute(retrieveRequest);

            //Retrieve the Loan Application Entity
            contactEntity = retrieveResponse.Entity as Entity;
        }

        //Retrieve the needed properties
        string   ssn       = (string)contactEntity["new_ssn"];
        string   name      = (string)contactEntity[ContactAttributes.FullName];
        DateTime?birthdate = (DateTime?)contactEntity[ContactAttributes.Birthdate];
        int      creditScore;

        //This is where the logic for retrieving the credit score would be inserted
        //We are simply going to return a random number
        creditScore = (new Random()).Next(0, 1000);

        //Set the credit score property
        this.CreditScore.Set(executionContext, creditScore);

        //Check to see if the credit score should be saved to the entity
        //If the value of the property has not been set or it is set to true
        if (null != this.UpdateEntity && this.UpdateEntity.Get(executionContext))
        {
            //Create the entity
            Entity updateEntity = new Entity(loanApplication.LogicalName);
            updateEntity["new_loanapplicationid"] = loanEntity["new_loanapplicationid"];
            updateEntity["new_creditscore"]       = this.CreditScore.Get(executionContext);

            //Update the entity
            service.Update(updateEntity);
        }
    }
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService trace = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            sharedMethods = new MShared();
            try
            {
                // Obtain the execution context from the service provider.
                IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                // The InputParameters collection contains all the data passed in the message request.

                /*Esta validación previene la ejecución del Plugin de cualquier
                 * transacción realizada a través del Web API desde Abox*/
                if (context.InitiatingUserId == new Guid("7dbf49f3-8be8-ea11-a817-002248029f77"))
                {
                    return;
                }

                EntityReference targetEntity = null;

                string relationshipName = string.Empty;

                EntityReferenceCollection relatedEntities = null;

                EntityReference doctorRelated = null;

                Entity contact = null;

                UpdatePatientRequest.Request updatePatientRequest = null;

                #region Associate & Disassociate

                // if (context.MessageName.ToLower() == "associate" || context.MessageName.ToLower() == "disassociate")
                if (context.MessageName.ToLower() == "associate" || context.MessageName.ToLower() == "disassociate")
                {
                    contactEntity = new ContactEntity();

                    // Get the “Relationship” Key from context

                    if (context.InputParameters.Contains("Relationship"))

                    {
                        // Get the Relationship name for which this plugin fired
                        relationshipName = ((Relationship)context.InputParameters["Relationship"]).SchemaName;
                    }

                    // Check the "Relationship Name" with your intended one

                    if (relationshipName != ContactFields.ContactxDoctorRelationship)
                    {
                        return;
                    }
                    else
                    {
                        productEntity        = new ProductEntity();
                        updatePatientRequest = new UpdatePatientRequest.Request();
                        ContactMethods contactMethods = new ContactMethods();
                        #region -> Target

                        if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is EntityReference)
                        {
                            helperMethods = new RequestHelpers();
                            targetEntity  = (EntityReference)context.InputParameters["Target"];

                            string[] columnsToGet = new string[] { ContactFields.IdAboxPatient, ContactFields.Country, ContactFields.UserType, ContactFields.IdType, ContactFields.Id, ContactFields.Firstname, ContactFields.SecondLastname, ContactFields.Lastname, ContactFields.Gender, ContactFields.Birthdate };
                            var      columnSet    = new ColumnSet(columnsToGet);
                            contact = service.Retrieve(contactEntity.EntitySingularName, targetEntity.Id, columnSet);

                            var relatedContacts = contactMethods.GetContactChildContacts(contact, service);

                            if (relatedContacts != null)
                            {
                                if (relatedContacts.Entities.Count > 0)
                                {
                                    Exception serviceEx = new Exception("No es posible realizar esta operación en usuarios que tienen pacientes bajo cuido registrados.");
                                    serviceEx.Data["HasFeedbackMessage"] = true;
                                    throw serviceEx;
                                }
                            }


                            string userType = "";

                            if (contact.Attributes.Contains(ContactFields.UserType))
                            {
                                EntityReference userTypeReference = null;
                                userTypeReference = (EntityReference)contact.Attributes[ContactFields.UserType];
                                if (userTypeReference != null)
                                {
                                    userType = sharedMethods.GetUserTypeId(userTypeReference.Id.ToString());
                                }
                            }

                            if (userType == "05")
                            {
                                Exception serviceEx = new Exception("Es necesario cambiar el tipo de usuario de este contacto para poder agregar médicos.");
                                serviceEx.Data["HasFeedbackMessage"] = true;
                                throw serviceEx;
                            }
                            //updatePatientRequest.personalinfo = new UpdatePatientRequest.Request.Personalinfo();



                            updatePatientRequest = helperMethods.GetPatientUpdateStructure(contact, service, trace);
                        }

                        #endregion -> Target

                        #region -> Related

                        doctorEntity    = new DoctorEntity();
                        relatedEntities = context.InputParameters["RelatedEntities"] as EntityReferenceCollection;

                        if (relatedEntities.Count > 0)
                        {
                            if (context.MessageName.ToLower() == "associate")
                            {
                                #region -> Associate

                                int relatedEntitiesCount         = relatedEntities.Count;
                                int contactCurrentRelatedDoctors = 0;
                                System.Collections.Generic.List <UpdatePatientRequest.Request.Medic> medicsToSave = new System.Collections.Generic.List <UpdatePatientRequest.Request.Medic>();
                                if (updatePatientRequest.medication == null)
                                {
                                    updatePatientRequest.medication        = new UpdatePatientRequest.Request.Medication();
                                    updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[relatedEntitiesCount];
                                }
                                else
                                {
                                    if (updatePatientRequest.medication.medics == null)
                                    {
                                        updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[relatedEntitiesCount];
                                    }
                                    else
                                    {
                                        contactCurrentRelatedDoctors = updatePatientRequest.medication.medics.Length;

                                        if (contactCurrentRelatedDoctors > 0)
                                        {
                                            for (int i = 0; i < contactCurrentRelatedDoctors; i++)
                                            {
                                                medicsToSave.Add(updatePatientRequest.medication.medics[i]);
                                            }

                                            updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[relatedEntitiesCount + contactCurrentRelatedDoctors];
                                        }
                                    }
                                }

                                for (int i = 0; i < relatedEntitiesCount; i++)
                                {
                                    doctorRelated = relatedEntities[i];

                                    Entity doctor = service.Retrieve(doctorEntity.EntitySingularName, doctorRelated.Id, new ColumnSet(DoctorFields.DoctorIdKey));
                                    if (doctor.Attributes.Contains(DoctorFields.DoctorIdKey))
                                    {
                                        medicsToSave.Add(new UpdatePatientRequest.Request.Medic
                                        {
                                            medicid = doctor.GetAttributeValue <string>(DoctorFields.DoctorIdKey)
                                        });
                                    }
                                }

                                int totalMedicsToSaveCount = updatePatientRequest.medication.medics.Length;
                                for (int i = 0; i < totalMedicsToSaveCount; i++)
                                {
                                    updatePatientRequest.medication.medics[i] = medicsToSave[i];
                                }

                                #endregion -> Associate
                            }
                            else
                            {
                                #region -> Disassociate

                                if (updatePatientRequest.medication != null)
                                {
                                    if (updatePatientRequest.medication.medics != null)
                                    {
                                        System.Collections.Generic.List <UpdatePatientRequest.Request.Medic> medicsToSave = new System.Collections.Generic.List <UpdatePatientRequest.Request.Medic>();

                                        //Recorrer la lista de medicos que se estan desasociando del contacto
                                        foreach (var relatedItem in relatedEntities)
                                        {
                                            //Obtener la entidad con el Id de Medico
                                            Entity doctorToRemove = service.Retrieve(doctorEntity.EntitySingularName, relatedItem.Id, new ColumnSet(DoctorFields.DoctorIdKey));
                                            int    medicsLength   = updatePatientRequest.medication.medics.Length;

                                            //Buscar en la lista de medicos que tiene el usuario
                                            for (int i = 0; i < medicsLength; i++)
                                            {
                                                //Agregar a la lista de medicos a guardar, aquellos que no fueron desasociados
                                                if (updatePatientRequest.medication.medics[i].medicid != doctorToRemove.GetAttributeValue <string>(DoctorFields.DoctorIdKey))
                                                {
                                                    medicsToSave.Add(updatePatientRequest.medication.medics[i]);
                                                }
                                            }
                                        }

                                        //Enviar como null si no hay pacientes a guardar
                                        if (medicsToSave.Count == 0)
                                        {
                                            updatePatientRequest.medication.medics = null;
                                        }
                                        else
                                        {
                                            //Modificar el tamaño del array y agregar los médicos que se guardarán
                                            updatePatientRequest.medication.medics = new UpdatePatientRequest.Request.Medic[medicsToSave.Count];
                                            int length = updatePatientRequest.medication.medics.Length;
                                            for (int i = 0; i < length; i++)
                                            {
                                                updatePatientRequest.medication.medics[i] = medicsToSave[i];
                                            }
                                        }
                                    }
                                }

                                #endregion -> Disassociate
                            }
                        }

                        #endregion -> Related

                        ///Request service POST
                        ///

                        DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(UpdatePatientRequest.Request));
                        MemoryStream memoryStream             = new MemoryStream();
                        serializer.WriteObject(memoryStream, updatePatientRequest);
                        var jsonObject = Encoding.Default.GetString(memoryStream.ToArray());
                        memoryStream.Dispose();

                        //Valores necesarios para hacer el Post Request
                        WebRequestData wrData = new WebRequestData();
                        wrData.InputData     = jsonObject;
                        wrData.ContentType   = "application/json";
                        wrData.Authorization = "Bearer " + Configuration.TokenForAboxServices;

                        wrData.Url = AboxServices.UpdatePatientService;

                        var serviceResponse = sharedMethods.DoPostRequest(wrData, trace);
                        UpdatePatientRequest.ServiceResponse serviceResponseProperties = null;
                        if (serviceResponse.IsSuccessful)
                        {
                            DataContractJsonSerializer deserializer = new DataContractJsonSerializer(typeof(UpdatePatientRequest.ServiceResponse));

                            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(serviceResponse.Data)))
                            {
                                deserializer = new DataContractJsonSerializer(typeof(UpdatePatientRequest.ServiceResponse));
                                serviceResponseProperties = (UpdatePatientRequest.ServiceResponse)deserializer.ReadObject(ms);
                            }

                            if (serviceResponseProperties.response.code != "MEMCTRL-1014")
                            {
                                trace.Trace(Constants.ErrorMessageCodeReturned + serviceResponseProperties.response.code);

                                Exception serviceEx = new Exception(Constants.GeneralAboxServicesErrorMessage + serviceResponseProperties.response.message);
                                serviceEx.Data["HasFeedbackMessage"] = true;
                                throw serviceEx;
                            }
                            else
                            {
                                //contact.Attributes.Add("new_idaboxpatient", serviceResponseProperties.response.details.idPaciente);
                            }
                        }
                        else
                        {
                            throw new InvalidPluginExecutionException(Constants.GeneralAboxServicesErrorMessage);
                        }
                    }
                }

                #endregion Associate & Disassociate
            }
            catch (Exception ex)
            {
                trace.Trace($"MethodName: {new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + ex.ToString());

                try
                {
                    sharedMethods.LogPluginFeedback(new LogClass
                    {
                        Exception  = ex.ToString(),
                        Level      = "error",
                        ClassName  = this.GetType().ToString(),
                        MethodName = System.Reflection.MethodBase.GetCurrentMethod().Name,
                        Message    = "Excepción en plugin",
                        ProcessId  = ""
                    }, trace);
                }
                catch (Exception e)
                {
                    trace.Trace($"MethodName: {new System.Diagnostics.StackTrace(ex).GetFrame(0).GetMethod().Name}|--|Exception: " + e.ToString());
                }

                if (ex.Data["HasFeedbackMessage"] != null)
                {
                    throw new InvalidPluginExecutionException(ex.Message);
                }
                else
                {
                    throw new InvalidPluginExecutionException(Constants.GeneralPluginErrorMessage);
                }
            }
        }
Exemple #4
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            //ITracingService tracingService = executionContext.GetExtension<ITracingService>();

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

            if (InspectionLookup.Get <EntityReference>(executionContext) != null)
            {
                recordId       = InspectionLookup.Get <EntityReference>(executionContext).Id;
                queryAttribute = "blu_inspectiondetailid";
                isInspection   = true;
            }
            if (OrderLookup.Get <EntityReference>(executionContext) != null)
            {
                recordId       = OrderLookup.Get <EntityReference>(executionContext).Id;
                queryAttribute = "blu_order";
                isOrder        = true;
            }
            if (isInspection == false && isOrder == false)
            {
                return;
            }

            strFirstName = WFHelpers.GetFirstPortalQuestionAsnwerByNumberAndLookupRecord(executionContext
                                                                                         , FirstNameQuestion.Get <string>(executionContext)
                                                                                         , queryAttribute
                                                                                         , recordId
                                                                                         , service);
            strLastName = WFHelpers.GetFirstPortalQuestionAsnwerByNumberAndLookupRecord(executionContext
                                                                                        , LastNameQuestion.Get <string>(executionContext)
                                                                                        , queryAttribute
                                                                                        , recordId
                                                                                        , service);
            strEmailAddress = WFHelpers.GetFirstPortalQuestionAsnwerByNumberAndLookupRecord(executionContext
                                                                                            , EmailAddressQuestion.Get <string>(executionContext)
                                                                                            , queryAttribute
                                                                                            , recordId
                                                                                            , service);
            strMobilePhone = WFHelpers.GetFirstPortalQuestionAsnwerByNumberAndLookupRecord(executionContext
                                                                                           , MobileNumberQuestion.Get <string>(executionContext)
                                                                                           , queryAttribute
                                                                                           , recordId
                                                                                           , service);

            if (strFirstName != String.Empty && strLastName != String.Empty && strEmailAddress != String.Empty && strMobilePhone != String.Empty)
            {
                Entity enContact = new Entity("contact")
                {
                    ["firstname"]     = strFirstName,
                    ["lastname"]      = strLastName,
                    ["emailaddress1"] = strEmailAddress,
                    ["mobilephone"]   = strMobilePhone
                };

                Guid contactId = Guid.Empty;
                //Check if Contact record already exists otherwise create new
                #region query Contact
                var fetchXmlContact = string.Empty;
                fetchXmlContact += "<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>";
                fetchXmlContact += "  <entity name='contact'>";
                fetchXmlContact += "     <attribute name='contactid'/>";
                fetchXmlContact += "     <filter type='and'>";
                fetchXmlContact += "        <condition attribute='firstname' operator='eq' value='" + enContact["firstname"].ToString() + "'/>";
                fetchXmlContact += "        <condition attribute='lastname' operator='eq' value='" + enContact["lastname"].ToString() + "'/>";
                fetchXmlContact += "        <condition attribute='emailaddress1' operator='eq' value='" + enContact["emailaddress1"].ToString() + "'/>";
                fetchXmlContact += "        <condition attribute='mobilephone' operator='eq' value='" + enContact["mobilephone"].ToString() + "'/>";
                fetchXmlContact += "        <condition attribute='statecode' operator='eq' value='0'/>";
                fetchXmlContact += "     </filter>";
                fetchXmlContact += "  </entity>";
                fetchXmlContact += "</fetch>";
                #endregion

                EntityCollection ecContact = service.RetrieveMultiple(new FetchExpression(fetchXmlContact));
                if (ecContact.Entities.Count > 0)
                {
                    foreach (var enContactResult in ecContact.Entities)
                    {
                        contactId = enContactResult.Id;
                    }
                }
                else
                {
                    contactId = service.Create(enContact);
                }

                ContactLookup.Set(executionContext, new EntityReference("contact", contactId));
            }
        }
Exemple #5
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService             tracer         = executionContext.GetExtension <ITracingService>();
            IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            try
            {
                var targetName = context.PrimaryEntityName;

                tracer.Trace("ProcessingOnCreation:Execute retrieve triggering entity to process Artifacts for " + targetName);

                // retrieve all attributes from triggering entities because any field can be configured as a Question Identifier
                var targetEntity = service.Retrieve(targetName, context.PrimaryEntityId, new ColumnSet(true));

                var accountId          = Guid.Empty;
                var contactId          = Guid.Empty;
                var incidentId         = Guid.Empty;
                var artifactLookupName = "";

                switch (targetName)
                {
                // Assuming that the Parent Account and Contact will be created in advance of any incident.

                case "account":
                    artifactLookupName = "mcs_accountid";
                    accountId          = targetEntity.Id;
                    contactId          = targetEntity.Contains("primarycontactid") ? ((EntityReference)targetEntity["primarycontactid"]).Id : Guid.Empty;
                    break;

                case "contact":
                    artifactLookupName = "mcs_contactid";
                    accountId          = targetEntity.Contains("parentcustomerid") ? ((EntityReference)targetEntity["parentcustomerid"]).Id : Guid.Empty;
                    var account = service.Retrieve("account", ((EntityReference)targetEntity["parentcustomerid"]).Id, new ColumnSet(new[] { "primarycontactid" }));
                    contactId = account.Contains("primarycontactid") ? ((EntityReference)account["primarycontactid"]).Id : Guid.Empty;
                    break;

                case "incident":
                    incidentId         = targetEntity.Id;
                    artifactLookupName = "mcs_caseid";
                    accountId          = targetEntity.Contains("customerid") ? ((EntityReference)targetEntity["customerid"]).Id : Guid.Empty;
                    contactId          = targetEntity.Contains("primarycontactid") ? ((EntityReference)targetEntity["primarycontactid"]).Id : Guid.Empty;
                    break;

                // Below handles custom related records based on workflow input parameters
                default:
                    // Retrieve WF arguments
                    artifactLookupName = ArtifactLookupSchemaName.Get(executionContext);
                    var caseLookup = CaseLookupSchemaName.Get(executionContext);

                    if (caseLookup == null || artifactLookupName == null)
                    {
                        return;
                    }

                    // if we have the proper workflow arguments retrieve and set the incidentid, accountid, and contactid associated
                    // with this related record
                    incidentId = ((EntityReference)targetEntity[caseLookup]).Id;
                    using (var xrm = new CrmServiceContext(service))
                    {
                        var e = (from c in xrm.IncidentSet
                                 where c.Id == incidentId
                                 select new Incident()
                        {
                            PrimaryContactId = c.PrimaryContactId,
                            CustomerId = c.CustomerId
                        }).FirstOrDefault();

                        accountId = e.CustomerId != null ? e.CustomerId.Id : Guid.Empty;
                        contactId = e.PrimaryContactId != null ? e.PrimaryContactId.Id : Guid.Empty;
                    }
                    break;
                }

                // Instantiate helper object
                var artifactService = new ArtifactService(service, targetEntity, artifactLookupName, accountId, contactId, incidentId);

                // Create Artifact based on target Entity and Artifact Rule
                foreach (var rule in artifactService.ArtifactRules)
                {
                    // if the question identifier is null then in the context of a create this is a what is called a static rule
                    // which means that the artifact gets created regardless of any criteria on create of the targetEntity
                    if (rule.mcs_QuestionIdentifier == null)
                    {
                        tracer.Trace("ProcessingOnCreation:CreateRequiredDocs create new artifact with no Question Identifier");
                        artifactService.CreateArtifact(rule);
                    }
                    else if (targetEntity.Contains(rule.mcs_QuestionIdentifier))
                    {
                        tracer.Trace(targetEntity.LogicalName + "Check This Question Identifier " + rule.mcs_QuestionIdentifier + " against " + rule.mcs_SuccessIndicator);

                        string attr;
                        string attrLabel = "";

                        // get the appropriate attribute values based on what type of field the question identifier is
                        if (targetEntity[rule.mcs_QuestionIdentifier] is OptionSetValue)
                        {
                            attr      = ((OptionSetValue)targetEntity[rule.mcs_QuestionIdentifier]).Value.ToString();
                            attrLabel = ArtifactService.GetOptionSetText(targetEntity.LogicalName, rule.mcs_QuestionIdentifier, Convert.ToInt32(attr), service);
                        }
                        else if (targetEntity[rule.mcs_QuestionIdentifier] is bool)
                        {
                            attr = ((bool)targetEntity[rule.mcs_QuestionIdentifier]).ToString();
                        }
                        else
                        {
                            attr = (string)targetEntity[rule.mcs_QuestionIdentifier];
                        }

                        tracer.Trace("attr = " + attr);

                        // if the attribute value is equal to the success indicator add the required doc to the context for creation
                        if (attr == rule.mcs_SuccessIndicator || attrLabel == rule.mcs_SuccessIndicator)
                        {
                            artifactService.CreateArtifact(rule);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            //*** Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve the tracing service.");
            }
            //*** Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve the workflow context.");
            }

            tracingService.Trace("{0}.Execute(): ActivityInstanceId: {1}; WorkflowInstanceId: {2}; CorrelationId: {3}; InitiatingUserId: {4} -- Entering", CHILD_CLASS_NAME, executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId, context.CorrelationId, context.InitiatingUserId);

            IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        serviceProxy   = serviceFactory.CreateOrganizationService(context.UserId);

            if (context.InputParameters.Contains(Common.Target) && context.InputParameters[Common.Target] is Entity)
            {
                try {
                    //*** Grab the Target Entity
                    var theEntity = (Entity)context.InputParameters[Common.Target];

                    tracingService.Trace("Active Stage Name: {0}", theEntity.EntityState);
                    //-------------------------------------------------------------------------------------------------------------
                    var processInstancesRequest = new RetrieveProcessInstancesRequest {
                        EntityId          = theEntity.Id,
                        EntityLogicalName = theEntity.LogicalName
                    };

                    var processInstancesResponse = (RetrieveProcessInstancesResponse)serviceProxy.Execute(processInstancesRequest);
                    var processCount             = processInstancesResponse.Processes.Entities.Count;

                    if (processCount > 0)
                    {
                        tracingService.Trace("{0}: Count of Process Instances concurrently associated with the Entity record: {1}", CHILD_CLASS_NAME, processCount);
                        tracingService.Trace("{0}: BPF Definition Name currently set for the Entity record: {1}, Id: {2}", CHILD_CLASS_NAME, processInstancesResponse.Processes.Entities[0].Attributes[CrmEarlyBound.Workflow.Fields.Name], processInstancesResponse.Processes.Entities[0].Id.ToString());

                        var bpfEntityRef = this.BpfEntityReference.Get <EntityReference>(executionContext);
                        var colSet       = new ColumnSet();
                        colSet.AddColumn(CrmEarlyBound.Workflow.Fields.UniqueName);
                        var bpfEntity = serviceProxy.Retrieve(bpfEntityRef.LogicalName, bpfEntityRef.Id, colSet);

                        tracingService.Trace("{0}: Switching to BPF Unique Name: {1}, Id: {2}", CHILD_CLASS_NAME, bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString(), bpfEntity.Id.ToString());

                        var bpfStageName = this.BpfStageName.Get <string>(executionContext).Trim();
                        var qe           = new QueryExpression {
                            EntityName = CrmEarlyBound.Workflow.EntityLogicalName,
                            ColumnSet  = new ColumnSet(new string[] { CrmEarlyBound.Workflow.Fields.Name }),
                            Criteria   = new FilterExpression {
                                Conditions =
                                {
                                    new ConditionExpression {
                                        AttributeName = CrmEarlyBound.Workflow.Fields.UniqueName, Operator = ConditionOperator.Equal, Values ={ bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName] } //new_bpf_472aceaabf7c4f1db4d13ac3c7076c65
                                    }
                                }
                            },
                            NoLock   = true,
                            Distinct = false
                        };

                        #region Convert Query Expression to FetchXML

                        var conversionRequest = new QueryExpressionToFetchXmlRequest {
                            Query = qe
                        };
                        var conversionResponse = (QueryExpressionToFetchXmlResponse)serviceProxy.Execute(conversionRequest);
                        var fetchXml           = conversionResponse.FetchXml;

                        tracingService.Trace("{0}: [{1}], Message: {2}", CHILD_CLASS_NAME, fetchXml, context.MessageName);

                        #endregion Convert the query expression to FetchXML.

                        tracingService.Trace("{0}: Built BPF Query, Now Executing...", CHILD_CLASS_NAME);

                        var entColByQuery = serviceProxy.RetrieveMultiple(qe).Entities; //// Execute Query with Filter Expressions
                        //-------------------------------------------------------------------------------------------------------------
                        if (entColByQuery != null && entColByQuery.Count > 0)           //// Search and handle related entities
                        {
                            tracingService.Trace("{0}: Found matching Business Process Flows...", CHILD_CLASS_NAME);

                            var bpfId         = new Guid();
                            var bpfEntityName = String.Empty;

                            foreach (var entity in entColByQuery) //// Loop related entities and retrieve Workflow Names
                            {
                                bpfId         = entity.Id;
                                bpfEntityName = entity.GetAttributeValue <string>(CrmEarlyBound.Workflow.Fields.Name);
                                break;
                            }

                            if (bpfId != Guid.Empty)
                            {
                                tracingService.Trace("{0}: Successfully retrieved the Business Process Flow that we'll be switching to: {1}, Id: {2}", CHILD_CLASS_NAME, bpfEntityName, bpfId.ToString());

                                System.Threading.Thread.Sleep(2000); // Wait for 2 seconds before switching the process
                                //*** Set to the new or same Business BpfEntityName Flow
                                var setProcReq = new SetProcessRequest {
                                    Target     = new EntityReference(theEntity.LogicalName, theEntity.Id),
                                    NewProcess = new EntityReference(CrmEarlyBound.Workflow.EntityLogicalName, bpfId)
                                };

                                tracingService.Trace("{0}: ***Ready To Update - Business Process Flow", CHILD_CLASS_NAME);
                                var setProcResp = (SetProcessResponse)serviceProxy.Execute(setProcReq);
                                tracingService.Trace("{0}: ***Updated", CHILD_CLASS_NAME);
                            }
                        }
                        else
                        {
                            tracingService.Trace("{0}: No Business Process Flows were found with Unique Name: {1}", CHILD_CLASS_NAME, bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString());
                        }
                        //-------------------------------------------------------------------------------------------------------------
                        //*** Verify if the Process Instance was switched successfully for the Entity record
                        processInstancesRequest = new RetrieveProcessInstancesRequest {
                            EntityId          = theEntity.Id,
                            EntityLogicalName = theEntity.LogicalName
                        };

                        processInstancesResponse = (RetrieveProcessInstancesResponse)serviceProxy.Execute(processInstancesRequest);
                        processCount             = processInstancesResponse.Processes.Entities.Count;

                        if (processCount > 0)
                        {
                            var activeProcessInstance   = processInstancesResponse.Processes.Entities[0]; //*** First Entity record is the Active Process Instance
                            var activeProcessInstanceId = activeProcessInstance.Id;                       //*** Active Process Instance Id to be used later for retrieval of the active path of the process instance

                            tracingService.Trace("{0}: Successfully Switched to '{1}' BPF for the Entity Record.", CHILD_CLASS_NAME, activeProcessInstance.Attributes[CrmEarlyBound.Workflow.Fields.Name]);
                            tracingService.Trace("{0}: Count of process instances concurrently associated with the entity record: {1}.", CHILD_CLASS_NAME, processCount);
                            var message = "All process instances associated with the entity record:";

                            for (var i = 0; i < processCount; i++)
                            {
                                message = message + " " + processInstancesResponse.Processes.Entities[i].Attributes[CrmEarlyBound.Workflow.Fields.Name] + ",";
                            }

                            tracingService.Trace("{0}: {1}", CHILD_CLASS_NAME, message.TrimEnd(message[message.Length - 1]));

                            //*** Retrieve the Active Stage ID of the Active Process Instance
                            var activeStageId       = new Guid(activeProcessInstance.Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].ToString());
                            var activeStagePosition = 0;
                            var newStageId          = new Guid();
                            var newStagePosition    = 0;

                            //*** Retrieve the BPF Stages in the active path of the Active Process Instance
                            var activePathRequest = new RetrieveActivePathRequest {
                                ProcessInstanceId = activeProcessInstanceId
                            };
                            var activePathResponse = (RetrieveActivePathResponse)serviceProxy.Execute(activePathRequest);

                            tracingService.Trace("{0}: Retrieved the BPF Stages in the Active Path of the Process Instance:", CHILD_CLASS_NAME);

                            for (var i = 0; i < activePathResponse.ProcessStages.Entities.Count; i++)
                            {
                                var curStageName = activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.StageName].ToString();

                                tracingService.Trace("{0}: Looping Through Stage #{1}: {2} (StageId: {3}, IndexId: {4})", CHILD_CLASS_NAME, i + 1, curStageName, activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId], i);
                                //*** Retrieve the Active Stage Name and Stage Position based on a successful match of the activeStageId
                                if (activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].Equals(activeStageId))
                                {
                                    activeStagePosition = i;
                                    tracingService.Trace("{0}: Concerning the Process Instance -- Initial Active Stage Name: {1} (StageId: {2})", CHILD_CLASS_NAME, curStageName, activeStageId);
                                }
                                //*** Retrieve the New Stage Id, Stage Name, and Stage Position based on a successful match of the stagename
                                if (curStageName.Equals(bpfStageName, StringComparison.InvariantCultureIgnoreCase))
                                {
                                    newStageId       = new Guid(activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].ToString());
                                    newStagePosition = i;
                                    tracingService.Trace("{0}: Concerning the Process Instance -- Desired New Stage Name: {1} (StageId: {2})", CHILD_CLASS_NAME, curStageName, newStageId);
                                }
                            }
                            //-------------------------------------------------------------------------------------------------------------
                            //***Update the Business Process Flow Instance record to the desired Active Stage
                            Entity    retrievedProcessInstance;
                            ColumnSet columnSet;
                            var       stageShift = newStagePosition - activeStagePosition;

                            if (stageShift > 0)
                            {
                                tracingService.Trace("{0}: Number of Stages Shifting Forward: {1}", CHILD_CLASS_NAME, stageShift);
                                //*** Stages only move in 1 direction --> Forward
                                for (var i = activeStagePosition; i <= newStagePosition; i++)
                                {
                                    System.Threading.Thread.Sleep(1000);
                                    //*** Retrieve the Stage Id of the next stage that you want to set as active
                                    var newStageName = activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.StageName].ToString();
                                    newStageId = new Guid(activePathResponse.ProcessStages.Entities[i].Attributes[CrmEarlyBound.ProcessStage.Fields.ProcessStageId].ToString());

                                    tracingService.Trace("{0}: Setting To Stage #{1}: {2} (StageId: {3}, IndexId: {4})", CHILD_CLASS_NAME, i + 1, newStageName, newStageId, i);
                                    //*** Retrieve the BpfEntityName Instance record to update its Active Stage
                                    columnSet = new ColumnSet();
                                    columnSet.AddColumn(ACTIVE_STAGE_ID);
                                    retrievedProcessInstance = serviceProxy.Retrieve(bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString(), activeProcessInstanceId, columnSet);
                                    //*** Set the next Stage as the Active Stage
                                    retrievedProcessInstance[ACTIVE_STAGE_ID] = new EntityReference(CrmEarlyBound.ProcessStage.EntityLogicalName, newStageId); //(ProcessStage.EntityLogicalName, activeStageId);

                                    try {
                                        tracingService.Trace("{0}: ***Ready To Update -- BPF Stage", CHILD_CLASS_NAME);
                                        serviceProxy.Update(retrievedProcessInstance);
                                        tracingService.Trace("{0}: ***Updated", CHILD_CLASS_NAME);
                                    } catch (FaultException <OrganizationServiceFault> ex) { //*** Determine BPF Stage Requirements
                                        foreach (var stageAttribute in activePathResponse.ProcessStages.Entities[i].Attributes)
                                        {
                                            if (stageAttribute.Key.Equals("clientdata"))
                                            {
                                                tracingService.Trace("{0}: Attribute Key: {1}, Value: {2}", CHILD_CLASS_NAME, stageAttribute.Key, stageAttribute.Value.ToString());
                                                break;
                                            }
                                        }

                                        tracingService.Trace(FullStackTraceException.Create(ex).ToString());
                                        throw;
                                    }
                                }
                            }
                            else
                            {
                                tracingService.Trace("{0}: Number of Stages Shifting Backwards: {1}", CHILD_CLASS_NAME, stageShift);
                            }
                            //-------------------------------------------------------------------------------------------------------------
                            //***Retrieve the Business Process Flow Instance record again to verify its Active Stage information
                            columnSet = new ColumnSet();
                            columnSet.AddColumn(ACTIVE_STAGE_ID);
                            retrievedProcessInstance = serviceProxy.Retrieve(bpfEntity.Attributes[CrmEarlyBound.Workflow.Fields.UniqueName].ToString(), activeProcessInstanceId, columnSet);

                            var activeStageEntityRef = retrievedProcessInstance[ACTIVE_STAGE_ID] as EntityReference;

                            if (activeStageEntityRef != null)
                            {
                                if (activeStageEntityRef.Id.Equals(newStageId))
                                {
                                    tracingService.Trace("{0}: Concerning the Process Instance -- Modified -- Active Stage Name: {1} (StageId: {2})", CHILD_CLASS_NAME, activeStageEntityRef.Name, activeStageEntityRef.Id);
                                }
                            }
                        }
                        else
                        {
                            tracingService.Trace("{0}:The RetrieveProcessInstancesRequest object returned 0", CHILD_CLASS_NAME);
                        }
                    }
                } catch (FaultException <OrganizationServiceFault> ex) {
                    tracingService.Trace("{0}: Fault Exception: An Error Occurred During Workflow Activity Execution", CHILD_CLASS_NAME);
                    tracingService.Trace("{0}: Fault Timestamp: {1}", CHILD_CLASS_NAME, ex.Detail.Timestamp);
                    tracingService.Trace("{0}: Fault Code: {1}", CHILD_CLASS_NAME, ex.Detail.ErrorCode);
                    tracingService.Trace("{0}: Fault Message: {1}", CHILD_CLASS_NAME, ex.Detail.Message);
                    ////localContext.Trace("{0}: Fault Trace: {1}", this.ChildClassName, ex.Detail.TraceText);
                    tracingService.Trace("{0}: Fault Inner Exception: {1}", CHILD_CLASS_NAME, null == ex.Detail.InnerFault ? "No Inner Fault" : "Has Inner Fault");
                    //*** Display the details of the inner exception.
                    if (ex.InnerException != null)
                    {
                        Exception innerEx = ex;
                        var       i       = 0;
                        while (innerEx.InnerException != null)
                        {
                            innerEx = innerEx.InnerException;
                            tracingService.Trace("{0}: Inner Exception: {1}, Message: {2};", CHILD_CLASS_NAME, i++, innerEx.Message);
                        }
                    }

                    throw new InvalidPluginExecutionException(OperationStatus.Failed, ex.Detail.ErrorCode, ex.Message);
                } catch (Exception ex) {
                    tracingService.Trace("{0}: Exception: An Error Occurred During Workflow Activity Execution", CHILD_CLASS_NAME);
                    tracingService.Trace("{0}: Exception Message: {1}", CHILD_CLASS_NAME, ex.Message);
                    //*** Display the details of the inner exception.
                    if (ex.InnerException != null)
                    {
                        Exception innerEx = ex;
                        var       i       = 0;
                        while (innerEx.InnerException != null)
                        {
                            innerEx = innerEx.InnerException;
                            tracingService.Trace("{0}: Inner Exception: {1}, Message: {2};", CHILD_CLASS_NAME, i++, innerEx.Message);
                        }
                    }

                    throw new InvalidPluginExecutionException(OperationStatus.Failed, ex.HResult, ex.Message);
                } finally {
                    tracingService.Trace("{0}.Execute(): ActivityInstanceId: {1}; WorkflowInstanceId: {2}; CorrelationId: {3} -- Exiting", CHILD_CLASS_NAME, executionContext.ActivityInstanceId, executionContext.WorkflowInstanceId, context.CorrelationId);
                    // Uncomment to force plugin failure for Debugging
                    //--> throw new InvalidPluginExecutionException(String.Format("{0}.Execute(): Plug-in Warning: Manually forcing exception for logging purposes.", CHILD_CLASS_NAME));
                }
            }
        }
        protected void Create(IServiceProvider serviceProvider, bool saveEntity, string entityName, string documentBodyAttributeKey, string fileNameAttributeKey)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName != MessageName.Create)
            {
                //Invalid event attached
                return;
            }

            if (context.InputParameters.Contains(CrmConstants.TargetParameterKey) && context.InputParameters[CrmConstants.TargetParameterKey] is Entity)
            {
                try
                {
                    Entity entity = (Entity)context.InputParameters[CrmConstants.TargetParameterKey];
                    if (entity.LogicalName != entityName)
                    {
                        return;
                    }

                    if (!entity.Attributes.Keys.Contains(documentBodyAttributeKey) || string.IsNullOrWhiteSpace((string)entity.Attributes[documentBodyAttributeKey]))
                    {
                        //No binary data
                        return;
                    }

                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    Configuration.IConfigurationProvider configurationProvider = Configuration.Factory.GetConfigurationProvider(service, entityName);
                    if (configurationProvider.StorageProviderType == Providers.BinaryStorageProviderType.CrmDefault)
                    {
                        //In this case, not doing anything with the binary data.
                        return;
                    }

                    //This check is actually a bit useless for sandboxed pluxings.  CRM is bugged and won't allow anything bigger than 5mb, the plugin sandbox will just crash.
                    if (entity.Attributes.Keys.Contains(CrmConstants.FileSizeKey) && (int)entity.Attributes[CrmConstants.FileSizeKey] > configurationProvider.MaxFileSize)
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Failed, string.Format("FileSize Limit of {0} bytes was exceeded.", configurationProvider.MaxFileSize));
                    }

                    Providers.IBinaryStorageProvider storageProvider = Providers.Factory.GetStorageProvider(configurationProvider);

                    byte[] data        = Convert.FromBase64String((string)entity.Attributes[documentBodyAttributeKey]);
                    string fileName    = (string)entity.Attributes[fileNameAttributeKey];
                    string newFileName = string.Format("{0}{1}", Constants.ExternalFilePrefix, fileName);

                    if (storageProvider.Create(entity.Id, fileName, data))
                    {
                        entity.Attributes[fileNameAttributeKey]     = newFileName;
                        entity.Attributes[documentBodyAttributeKey] = Constants.EmptyBodyContent;
                        if (saveEntity)
                        {
                            service.Update(entity);
                        }
                    }
                    else
                    {
                        throw new InvalidPluginExecutionException(OperationStatus.Suspended, string.Format("The storage provider '{0}' failed to when calling 'Create' method.", configurationProvider.StorageProviderType));
                    }
                }
                catch (Exception ex)
                {
                    throw new InvalidPluginExecutionException(OperationStatus.Suspended, ex.ToString());
                }
            }
        }
Exemple #8
0
        //message = update , stage - post operation
        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));

            // Obtain the organization service reference.
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            IOrganizationService service = serviceFactory.CreateOrganizationService(null);



            // 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"];
                // Verify that the target entity represents an account.
                // If not, this plug-in was not registered correctly.
                if (entity.LogicalName != "account")
                {
                    return;
                }

                //if(context.Depth ==1)
                //{
                if (context.PreEntityImages.Contains("PreImage") && context.PreEntityImages["PreImage"] is Entity)
                {
                    preMessageImage = (Entity)context.PreEntityImages["PreImage"];

                    string oldValuecity = (String)preMessageImage.Attributes["address1_city"];

                    string currentValueCity = entity.Attributes.Contains("address1_city").ToString();

                    if (entity.Attributes.Contains("address1_city").ToString() == oldValuecity.ToString())
                    {
                        throw new InvalidPluginExecutionException("The city value are not changed");
                    }

                    //if (entity.Attributes.Contains("address1_city").ToString() != oldValuecity.ToString())
                    //{
                    //    throw new InvalidPluginExecutionException("The city value are changed");
                    //}
                    //Guid AccountID = context.PrimaryEntityId;

                    //Entity accountupdate = new Entity("account");

                    //accountupdate.Attributes["address1_city"] = oldValuecity;
                    //accountupdate.Attributes["accountid"] = AccountID;
                    //service.Update(accountupdate);
                }


                if (context.PostEntityImages.Contains("PostImage") && context.PostEntityImages["PostImage"] is Entity)
                {
                    postMessageImage = (Entity)context.PostEntityImages["PostImage"];

                    string oldValuecity = (String)postMessageImage.Attributes["address1_city"];

                    string currentValueCity = entity.Attributes.Contains("address1_city").ToString();
                }
                //}
                else
                {
                    return;
                }


                //Suppose you registered the Plugin and added a Image with name “PostImage ”

                //if (context.PostEntityImages.Contains("PostImage") && context.PostEntityImages["PostImage"] is Entity)

                //{

                //      postMessageImage = (Entity)context.PostEntityImages["PostImage"];

                //    string  accountnumber = (String)postMessageImage.Attributes["accountnumber"];

                // }
            }
        }
Exemple #9
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (!context.PreEntityImages.Contains("image") || !(context.PreEntityImages["image"] is Entity))
            {
                throw new InvalidPluginExecutionException("Context has no post images");
            }


            try
            {
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);


                tracingService.Trace("PostOrderCreate: Get order object values");
                Entity currentOrder = (Entity)context.InputParameters["Target"];
                //EntityReference currentContact = currentDogovor.GetAttributeValue<EntityReference>("al_contact");

                var orderValues = service.Retrieve(currentOrder.LogicalName, currentOrder.Id, new ColumnSet(new string[] { "al_facted", "al_summa", "al_dogovorid" }));

                tracingService.Trace("PostOrderCreate: Check if order is paid");
                var isPaid = currentOrder.GetAttributeValue <bool>("al_facted");

                // проверка статуса оплачено на объекте счет
                if (isPaid)
                {
                    var contractId = currentOrder.GetAttributeValue <EntityReference>("al_dogovorid").Id;
                    tracingService.Trace("PostOrderCreateUpdate: Get paid orders by contract and sums");

                    // поиск всех оплаченных счетов для данного договора
                    QueryExpression queryExpression = new QueryExpression();
                    queryExpression.EntityName = "al_order";
                    queryExpression.ColumnSet  = new ColumnSet(new string[] { "al_summa" });
                    queryExpression.Criteria   = new FilterExpression
                    {
                        Conditions =
                        {
                            new ConditionExpression
                            {
                                AttributeName = "al_dogovorid",
                                Operator      = ConditionOperator.Equal,
                                Values        = { contractId }
                            },
                            new ConditionExpression
                            {
                                AttributeName = "al_facted",
                                Operator      = ConditionOperator.Equal,
                                Values        = { true       }
                            }
                        }
                    };

                    var entityCollection = service.RetrieveMultiple(queryExpression);

                    // общая сумма счетов
                    var commonSum = 0;

                    // подсчёт общей суммы счетов
                    foreach (var ent in entityCollection.Entities)
                    {
                        commonSum = commonSum + (int)ent.Attributes["al_summa"];
                    }

                    tracingService.Trace("PostOrderCreateUpdate: Set fact summa in contract object.");

                    // объект договор связанный со счетами
                    var contractValues = service.Retrieve("al_dogovor", contractId, new ColumnSet(new string[] { "al_summa" }));

                    Entity contractToUpdate = new Entity("al_dogovor", contractId);

                    // общая сумма в договоре
                    var contractSum = contractValues.GetAttributeValue <Money>("al_summa");

                    // проверка не превышает ли общая сумма счетов общей суммы в договоре
                    if ((decimal)commonSum > contractSum.Value)
                    {
                        throw new InvalidPluginExecutionException("Common sum of bills greater than contract sum");
                    }

                    // обновление общей суммы в объекте договор
                    contractToUpdate["al_factsumma"] = new Money((decimal)commonSum);
                    service.Update(contractToUpdate);
                }
            }

            catch (Exception ex)
            {
                tracingService.Trace("PostOrderDelete in: {0}", ex.ToString());
                throw;
            }
        }
Exemple #10
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity targetEntity = (Entity)context.InputParameters["Target"];


                    var vesselInfo = targetEntity.GetAttributeValue <EntityReference>("dia_vessel");

                    var quantity = targetEntity.GetAttributeValue <decimal?>("dia_quantity") == null ? 0 : targetEntity.GetAttributeValue <decimal>("dia_quantity");

                    var type = targetEntity.GetAttributeValue <OptionSetValue>("dia_type");

                    var batch = targetEntity.GetAttributeValue <EntityReference>("dia_batch");

                    var occupation = targetEntity.GetAttributeValue <decimal>("dia_batch");

                    #region Update Vessel. Job type Intake
                    if (type.Value == 914440002 && vesselInfo != null)
                    {
                        var vesselCapacity = service.Retrieve(vesselInfo.LogicalName, vesselInfo.Id, new ColumnSet("dia_capacity"));

                        if (vesselCapacity != null && vesselCapacity.Contains("dia_capacity"))
                        {
                            var remainingCapacity = vesselCapacity.GetAttributeValue <decimal>("dia_capacity") - quantity;
                            var vesselUpdate      = new Entity(vesselInfo.LogicalName);
                            vesselUpdate.Id = vesselInfo.Id;
                            vesselUpdate.Attributes["dia_occupation"]        = quantity;
                            vesselUpdate.Attributes["dia_remainingcapacity"] = remainingCapacity;

                            service.Update(vesselUpdate);
                        }
                    }
                    #endregion


                    #region create transaction
                    {
                        var createTransaction = new Entity("dia_vesselstocktransactions");

                        createTransaction.Attributes["dia_quantity"] = quantity;

                        createTransaction.Attributes["dia_batch"] = batch;

                        service.Create(createTransaction);
                    }
                    #endregion


                    #region Assign composition from batch to vessel

                    var batchComposition = batch != null?service.Retrieve(batch.LogicalName, batch.Id, new ColumnSet("dia_batchcomposition")) : null;

                    if (type.Value == 914440002 && batchComposition != null)
                    {
                        if (vesselInfo != null)
                        {
                            var name = targetEntity.GetAttributeValue <string>("dia_name");
                            //var occupation = targetEntity.GetAttributeValue<decimal>("dia_occupation");
                            var location          = targetEntity.GetAttributeValue <EntityReference>("dia_location");
                            var batchVessel       = targetEntity.GetAttributeValue <EntityReference>("dia_batch");
                            var compositionVessel = targetEntity.GetAttributeValue <EntityReference>("dia_batchcomposition");
                            var capacityVessel    = targetEntity.GetAttributeValue <EntityReference>("dia_capacity");

                            var createVessel = new Entity("dia_vessel");

                            createVessel.Attributes["dia_name"] = name;
                            //createVessel.Attributes["dia_occupation"] = occupation;
                            createVessel.Attributes["dia_location"]         = location;
                            createVessel.Attributes["dia_batch"]            = batchVessel;
                            createVessel.Attributes["dia_batchcomposition"] = compositionVessel;
                            createVessel.Attributes["dia_capacity"]         = capacityVessel;

                            service.Create(createVessel);
                        }
                    }
                    #endregion


                    #region Completed Action
                    Entity jobDestination = (Entity)context.InputParameters["Target"];
                    var    jobRef         = (EntityReference)jobDestination["dia_job"];


                    var Vessel = service.Retrieve("dia_vessel", vesselInfo.Id, new ColumnSet("dia_occupation", "dia_capacity", "dia_name", "dia_remainingcapacity"));


                    var JobEntity = (EntityReference)jobDestination["dia_job"];
                    var JobInfo   = service.Retrieve(jobRef.LogicalName, JobEntity.Id, new ColumnSet("statuscode", "dia_quantity", "dia_type"));
                    var jobtype   = JobInfo.GetAttributeValue <OptionSetValue>("dia_type") != null?JobInfo.GetAttributeValue <OptionSetValue>("dia_type") : null;

                    var jobstatuscode = JobInfo.GetAttributeValue <OptionSetValue>("statuscode") != null?JobInfo.GetAttributeValue <OptionSetValue>("statuscode") : null;

                    var jobquantity = JobInfo.GetAttributeValue <OptionSetValue>("dia_quantity") != null?JobInfo.GetAttributeValue <OptionSetValue>("dia_quantity") : null;

                    var BatchEntity = targetEntity.GetAttributeValue <EntityReference>("dia_batch");
                    var BatchInfo   = service.Retrieve(BatchEntity.LogicalName, BatchEntity.Id, new ColumnSet("dia_batchcomposition", "dia_quantity", "dia_type"));



                    if (jobtype != null && jobtype.Value == 914440002 && jobstatuscode.Value == 914440000)
                    {
                        var VesselUpdate = new Entity(vesselInfo.LogicalName);
                        VesselUpdate.Id = vesselInfo.Id;
                        VesselUpdate.Attributes["dia_occupation"]       = occupation;
                        VesselUpdate.Attributes["dia_batch"]            = occupation;
                        VesselUpdate.Attributes["dia_batchcomposition"] = BatchInfo.GetAttributeValue <EntityReference>("dia_batchcomposition");

                        service.Update(VesselUpdate);
                    }

                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracer  = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);


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

                //EntityReference alquiler = (EntityReference)context.InputParameters["Alquiler"];

                //bool devolverOk = (bool)context.OutputParameters["DevolucionOk"];


                //OrganizationRequest request = new OrganizationRequest() { RequestName = "SetState" };

                //int state = ((OptionSetValue)request["SetState"]).Value;

                SetStateRequest setStateReq = new SetStateRequest();
                setStateReq.EntityMoniker       = new EntityReference("dao_alquiler", entity.Id);
                setStateReq.State               = new OptionSetValue(1);
                setStateReq.Status              = new OptionSetValue(2);
                entity.Attributes["statecode"]  = setStateReq.State;
                entity.Attributes["statuscode"] = setStateReq.Status;

                service.Update(entity);


                /*SetStateResponse response = (SetStateResponse)_connection.CrmService.Execute(setStateReq);
                 *
                 * /*if (entity.Attributes.Contains("statecode"))
                 * {
                 *  //OptionSetValue status = (OptionSetValue)entity.Attributes["statuscode"];
                 *  int valorState = ((OptionSetValue)entity.Attributes["statecode"]).Value;
                 *  OptionSetValue statecode = new OptionSetValue {Value = 810700000};
                 *  entity.Attributes["statecode"] = statecode;
                 *  service.Update(entity);
                 * }
                 *
                 * if (entity.Attributes.Contains("statuscode"))
                 * {
                 *  //OptionSetValue status = (OptionSetValue)entity.Attributes["statuscode"];
                 *  int valorStatus = ((OptionSetValue)entity.Attributes["statuscode"]).Value;
                 *  OptionSetValue status = new OptionSetValue {Value = 810700000};
                 *  entity.Attributes["statuscode"] = status;
                 *
                 * }*/
                //var statecode = entity.Attributes["statecode"];


                //var statecode = entity.Attributes["statecode"];
                //var statuscode = entity.Attributes["statuscode"];

                //TODO: Do stuff



                //TODO: Do stuff


                ///////*/
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
        public static List <RecentlyViewedItem> RetrieveRecentItemsForUsers(List <Guid> users, IOrganizationServiceFactory factory, string conditionAttribute, object conditionValue, ConditionOperator conditionType)
        {
            var result = new List <RecentlyViewedItem>();
            var recentlyViewedRecords = new List <Entity>();

            foreach (var userId in users)
            {
                try
                {
                    var service = factory.CreateOrganizationService(userId);
                    recentlyViewedRecords.AddRange(service.RetrieveMultiple(
                                                       new FetchExpression($@"
                            <fetch distinct='false' no-lock='false' mapping='logical'>
                              <entity name='userentityuisettings'>
                                <attribute name='recentlyviewedxml' />
                                <attribute name='ownerid' />
                                <filter type='and'>
                                  <condition attribute='ownerid' operator='eq' value='{userId}' />
                                </filter>
                              </entity>
                            </fetch>")).Entities.ToList());
                    foreach (var recentlyViewedRecord in recentlyViewedRecords)
                    {
                        if (string.IsNullOrEmpty(recentlyViewedRecord.GetAttributeValue <string>(RecentlyViewedXml.RootNode)))
                        {
                            continue;
                        }

                        var recentlyViewedItemXml = XElement.Parse(recentlyViewedRecord.GetAttributeValue <string>(RecentlyViewedXml.RootNode));
                        var recentlyViewedItems   = recentlyViewedItemXml.Descendants(RecentlyViewedXml.ItemNode);
                        foreach (var r in recentlyViewedItems)
                        {
                            var recentlyViewItem = new RecentlyViewedItem
                            {
                                User = recentlyViewedRecord.GetAttributeValue <EntityReference>(
                                    RecentlyViewedXml.OwnerId),
                                Type     = (RecentlyViewedType)int.Parse(r.Element(RecentlyViewedXml.ItemType).Value),
                                ObjectId = Guid.TryParse(r.Element(RecentlyViewedXml.ObjectId)?.Value, out Guid o)
                                    ? o
                                    : (Guid?)null,
                                EntityTypeCode = int.Parse(r.Element(RecentlyViewedXml.EntityTypeCode)?.Value),
                                DisplayName    =
                                    r.Element(RecentlyViewedXml.DisplayName)?.Value == "System Form"
                                        ? "Dashboard"
                                        : r.Element(RecentlyViewedXml.DisplayName)?.Value,
                                Title             = r.Element(RecentlyViewedXml.Title)?.Value,
                                Action            = r.Element(RecentlyViewedXml.Action)?.Value,
                                IconPath          = r.Element(RecentlyViewedXml.IconPath)?.Value,
                                PinStatus         = bool.Parse(r.Element(RecentlyViewedXml.PinStatus)?.Value),
                                ProcessInstanceId =
                                    Guid.TryParse(r.Element(RecentlyViewedXml.ProcessInstanceId)?.Value, out var pi)
                                        ? pi
                                        : (Guid?)null,
                                ProcessId = Guid.TryParse(r.Element(RecentlyViewedXml.ProcessId)?.Value, out var p)
                                    ? p
                                    : (Guid?)null,
                                LastAccessed = DateTime.Parse(r.Element(RecentlyViewedXml.LastAccessed)?.Value,
                                                              new CultureInfo("en-US", false)).ToLocalTime()
                            };
                            if (conditionAttribute == null || (conditionAttribute == RecentItem.Type &&
                                                               conditionType == ConditionOperator.Equal &&
                                                               recentlyViewItem.Type == (RecentlyViewedType)conditionValue &&
                                                               !result.Exists(x => x.ObjectId == recentlyViewItem.ObjectId &&
                                                                              x.User.Id == recentlyViewItem.User.Id &&
                                                                              x.LastAccessed.Equals(recentlyViewItem.LastAccessed))))
                            {
                                result.Add(recentlyViewItem);
                            }
                            ;
                        }
                    }
                }
                catch
                {
                    // ignored
                }
            }

            var sorted = (from r in result
                          orderby r.LastAccessed descending, r.User.Name
                          select r).ToList();

            return(sorted);
        }
Exemple #13
0
        protected override void Execute(CodeActivityContext executionContext)
        {
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

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


            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity entity) // ds_testresult
            {
                if (entity.LogicalName == "ds_testresult" && entity.GetAttributeValue <bool>("ds_status"))
                {
                    var jsonAnswers = entity.GetAttributeValue <string>("ds_jsonanswers");

                    if (jsonAnswers != null)
                    {
                        var deserializedAnswers = SerializerWrapper.Deserialize <List <AnswersQuestion> >(jsonAnswers);

                        var questionCost = GetQuestionTypeCost(deserializedAnswers.Count);

                        double resultScore = 0.0;

                        foreach (var item in deserializedAnswers)
                        {
                            var question = service
                                           .Retrieve("ds_testquestion", item.QuestionId,
                                                     new ColumnSet("ds_correctvar", "ds_questionlevel"));

                            var questionLevel =
                                question?.GetAttributeValue <OptionSetValue>("ds_questionlevel")
                                .Value;
                            var questionCorrectVar = question
                                                     ?.GetAttributeValue <OptionSetValueCollection>("ds_correctvar")
                                                     .Select(x => x.Value).ToList();


                            if (!(item.AnswerCode.Count > questionCorrectVar?.Count))
                            {
                                var numContains = NumContains(questionCorrectVar, item.AnswerCode);

                                if (!(item.AnswerCode.Count > numContains))
                                {
                                    if (questionCorrectVar != null)
                                    {
                                        switch (questionLevel)
                                        {
                                        case 717590000:
                                            resultScore += questionCost.EasyQuestionCost;
                                            break;

                                        case 717590001:
                                            resultScore += questionCost.MiddleQuestionCost;
                                            break;

                                        case 717590002:
                                            resultScore += questionCost.HardQuestionCost;
                                            break;
                                        }
                                    }
                                }
                            }
                        }

                        service.Update(new Entity(entity.LogicalName)
                        {
                            Id = entity.Id,
                            ["ds_resultscore"] = Convert.ToInt32(resultScore),
                        });
                    }
                }
            }
        }
Exemple #14
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Extract the tracing service for use in debugging sandboxed plug-ins.
            // If you are not registering the plug-in in the sandbox, then you do
            // not have to add any tracing service related code.
            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"))
            {
                // Obtain the target entity from the input parameters.


                // Verify that the target entity represents an entity type you are expecting.
                // For example, an account. If not, the plug-in was not registered correctly.

                Entity          targetEntity    = ((context.InputParameters["Target"] is Entity)) ? (Entity)context.InputParameters["Target"] : null;
                EntityReference targetReference = ((context.InputParameters["Target"] is EntityReference)) ? (EntityReference)context.InputParameters["Target"] : null;

                if (targetEntity?.LogicalName == "new_specialentity" || targetReference?.LogicalName == "new_specialentity")// audit entity
                {
                    return;
                }

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                #region sample

                //it was in sample
                //{
                //    Entity followupTask = new Entity("task");
                //    followupTask["subject"] = "send e-mail to the new customer";
                //    followupTask["description"] = "follow up with the customer";
                //    followupTask["scheduledstart"] = DateTime.Now.AddDays(7);
                //    followupTask["scheduledend"] = DateTime.Now.AddDays(7);
                //    followupTask["category"] = context.PrimaryEntityName;
                //    if (context.OutputParameters.Contains("id")) {
                //        Guid regardingId = new Guid(context.OutputParameters["id"].ToString());
                //        string regardingType = "account";
                //        followupTask["regardingobjectid"] = new EntityReference(regardingType, regardingId);
                //    }
                //    // Obtain the organization service reference which you will need for
                //    // web service calls.
                //    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                //    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);


                //    try {
                //        // Plug-in business logic goes here.
                //        service.Create(followupTask);
                //    } catch (FaultException<OrganizationServiceFault> ex) {
                //        throw new InvalidPluginExecutionException("An error occurred in MyPlug-in.", ex);
                //    } catch (Exception ex) {
                //        tracingService.Trace("MyPlugin: {0}", ex.ToString());
                //        throw;
                //    }

                //}
                #endregion

                Entity auditEntity = null;
                //create operation
                #region Create operation
                if (context.PostEntityImages.Contains("create"))
                {
                    //if not created
                    if (!context.OutputParameters.Contains("id"))
                    {
                        throw new InvalidPluginExecutionException("can't see id in output");
                    }

                    //Entity preEntity = (Entity)context.PreEntityImages["create"];
                    Entity postEntity = (Entity)context.PostEntityImages["create"];

                    auditEntity                 = new Entity("new_specialentity");
                    auditEntity["new_name"]     = targetEntity.LogicalName;
                    auditEntity["new_spaction"] = "created";
                    //author
                    Guid   authorId   = new Guid(context.InitiatingUserId.ToString());
                    string authorType = "systemuser";
                    auditEntity["new_spauthor"] = new EntityReference(authorType, authorId);
                    //name
                    //Entity details = service.Retrieve(entity.LogicalName, entity.Id,new Microsoft.Xrm.Sdk.Query.ColumnSet("name"));
                    //string accountName = details.Attributes.Contains("name") ? ((String)details["name"]) : "empty name";
                    string name = "empty name";
                    name = extractName(postEntity);

                    auditEntity["new_spentity"] = name;
                    //
                }
                #endregion

                //delete operation
                #region Delete operation
                if (context.PreEntityImages.Contains("delete"))
                {
                    Entity preEntity = (Entity)context.PreEntityImages["delete"];

                    auditEntity                 = new Entity("new_specialentity");
                    auditEntity["new_name"]     = targetReference.LogicalName;
                    auditEntity["new_spaction"] = "deleted";
                    //author
                    Guid   authorId   = new Guid(context.InitiatingUserId.ToString());
                    string authorType = "systemuser";
                    auditEntity["new_spauthor"] = new EntityReference(authorType, authorId);
                    //name
                    //Entity details = service.Retrieve(entity.LogicalName, entity.Id,new Microsoft.Xrm.Sdk.Query.ColumnSet("name"));
                    //string accountName = details.Attributes.Contains("name") ? ((String)details["name"]) : "empty name";

                    auditEntity["new_spentity"] = extractName(preEntity);
                    //
                }
                #endregion

                //update operation
                #region Update operation
                if (context.PreEntityImages.Contains("update"))
                {
                    string new_spdescription = "";

                    Entity preEntity  = (Entity)context.PreEntityImages["update"];
                    Entity postEntity = (Entity)context.PostEntityImages["update"];
                    new_spdescription = updateString(preEntity, postEntity);

                    auditEntity                 = new Entity("new_specialentity");
                    auditEntity["new_name"]     = targetEntity.LogicalName;
                    auditEntity["new_spaction"] = "updated";
                    //author
                    Guid   authorId   = new Guid(context.InitiatingUserId.ToString());
                    string authorType = "systemuser";
                    auditEntity["new_spauthor"] = new EntityReference(authorType, authorId);
                    //name
                    //Entity details = service.Retrieve(entity.LogicalName, entity.Id,new Microsoft.Xrm.Sdk.Query.ColumnSet("name"));
                    //string accountName = details.Attributes.Contains("name") ? ((String)details["name"]) : "empty name";

                    auditEntity["new_spentity"]      = extractName(postEntity);
                    auditEntity["new_spdescription"] = new_spdescription;
                }
                #endregion


                if (auditEntity != null)
                {
                    try {
                        // Plug-in business logic goes here.
                        service.Create(auditEntity);
                    } catch (FaultException <OrganizationServiceFault> ex) {
                        throw new InvalidPluginExecutionException("An error occurred in MyPlugin.", ex);
                    } catch (Exception ex) {
                        tracingService.Trace("MyPlugin: {0}", ex.ToString());
                        throw;
                    }
                }
            }
        }
Exemple #15
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the tracing service
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService)); // Enables writing to the tracing log

            // Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)     // provides access to the context for the event that executes Plugin
                                              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"];

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    // Plug-in business logic goes here.
                    // Create a task activity to follow up with the account customer in 7 days.
                    Entity followup = new Entity("task");

                    followup["subject"]     = "Send e-mail to the new customer.";
                    followup["description"] =
                        "Follow up with the customer. Check if there are any new issues that need resolution.";
                    followup["scheduledstart"] = DateTime.Now.AddDays(7);
                    followup["scheduledend"]   = DateTime.Now.AddDays(7);
                    followup["category"]       = context.PrimaryEntityName;

                    // Refer to the account in the task activity.
                    if (context.OutputParameters.Contains("id"))
                    {
                        Guid   regardingobjectid     = new Guid(context.OutputParameters["id"].ToString());
                        string regardingobjectidType = "account";

                        followup["regardingobjectid"] =
                            new EntityReference(regardingobjectidType, regardingobjectid);
                    }

                    // Create the task in Microsoft Dynamics CRM.
                    tracingService.Trace("FollowupPlugin: Creating the task activity.");
                    service.Create(followup);
                }

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

                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }
            }
            //  throw new NotImplementedException();
        }
Exemple #16
0
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;

            sda = new SqlDataAccess();
            sda.openConnection(Globals.ConnectionString);

            try
            {
                #region | SERVICE |
                IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                #region | Validate Request |
                //Target yoksa veya Entity tipinde değilse, devam etme.
                if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                {
                    return;
                }
                #endregion

                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                #region |DEFINE IMAGE IF EXISTS|
                Entity preImage = null;
                if (context.PreEntityImages.Contains("PreImage") && context.PreEntityImages["PreImage"] is Entity)
                {
                    preImage = (Entity)context.PreEntityImages["PreImage"];
                }
                #endregion

                #endregion

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

                Guid            contactId           = Guid.Empty;
                EntityReference userGrantUpdateUser = null;

                OptionSetValue grantBeforeValue = null;
                OptionSetValue grantNewValue    = null;

                contactId = entity.Id;

                #region | CREAE USER GRANT UPDATE HISTORY |

                if (entity.Contains("new_marketinggrant"))
                {
                    try
                    {
                        #region | SET USER GRANT UPDATE USER |

                        if (entity.Contains("new_grantupdatesystemuserid") && entity["new_grantupdatesystemuserid"] != null)
                        {
                            userGrantUpdateUser = (EntityReference)entity["new_grantupdatesystemuserid"];
                        }
                        else
                        {
                            userGrantUpdateUser = new EntityReference("systemuser", context.UserId);
                        }

                        #endregion


                        #region | SET USER GRANT BEFORE & NEW VALUE |

                        if (preImage.Contains("new_marketinggrant") && preImage["new_marketinggrant"] != null)
                        {
                            grantBeforeValue = (OptionSetValue)preImage["new_marketinggrant"];
                        }

                        if (entity.Contains("new_marketinggrant") && entity["new_marketinggrant"] != null)
                        {
                            grantNewValue = (OptionSetValue)entity["new_marketinggrant"];
                        }

                        #endregion

                        #region | CREATE HISTORY |

                        Entity entGrantHistory = new Entity("new_usergranthistory");
                        entGrantHistory["new_name"]         = DateTime.Now.ToString("dd.MM.yyyy HH:mm");
                        entGrantHistory["new_systemuserid"] = userGrantUpdateUser;
                        entGrantHistory["new_contactid"]    = entity.ToEntityReference();

                        if (grantBeforeValue != null)
                        {
                            entGrantHistory["new_previousvalue"] = grantBeforeValue;
                        }

                        if (grantNewValue != null)
                        {
                            entGrantHistory["new_newvalue"] = grantNewValue;
                        }

                        service.Create(entGrantHistory);

                        #endregion
                    }
                    catch (Exception ex)
                    {
                    }
                }

                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            string DEV_ENVIRONMENT_URL       = "http://SMARTCRMSync.1800dentist.com/api";
            string STAGE_ENVIRONMENT_URL     = "http://SMARTCRMSyncStage.1800dentist.com/api";
            string PROD_ENVIRONMENT_URL      = "http://SMARTCRMSyncProd.1800dentist.com/api";
            string smartCrmSyncWebServiceUrl = PROD_ENVIRONMENT_URL;

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

            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            int step = 0;

            if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity && context.Depth == 1)
            {
                try
                {
                    step = 1;
                    Entity account_context = (Entity)context.InputParameters["Target"];

                    if (account_context.LogicalName != "account")
                    {
                        return;
                    }

                    #region Declare and Initialize required Variables
                    step = 11;
                    IOrganizationServiceFactory serviceFactory      = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service             = serviceFactory.CreateOrganizationService(context.UserId);
                    IOrganizationService        impersonatedService = serviceFactory.CreateOrganizationService(null);

                    step = 13;
                    string address1_line1                = null;
                    string address1_city                 = null;
                    string address1_country              = null;
                    string fdx_zippostalcodeid           = null;
                    string fdx_stateprovinceid           = null;
                    string old_fdx_goldmineaccountnumber = null;
                    string companyname    = null;
                    Guid   fdx_zipid      = Guid.Empty;
                    Guid   fdx_stateid    = Guid.Empty;
                    int    new_fdx_gonogo = 0;

                    //Declare URL with the website link to call the Web API

                    string url = smartCrmSyncWebServiceUrl + "/lead/updatelead?";

                    string apiParm = "";
                    #endregion

                    #region Initialize variables with Context Values
                    step = 15;
                    if (account_context.Attributes.Contains("address1_line1"))
                    {
                        address1_line1 = account_context.Attributes["address1_line1"].ToString();
                    }

                    step = 17;
                    if (account_context.Attributes.Contains("address1_city"))
                    {
                        address1_city = account_context.Attributes["address1_city"].ToString();
                    }

                    step = 19;
                    if (account_context.Attributes.Contains("address1_country"))
                    {
                        address1_country = account_context.Attributes["address1_country"].ToString();
                    }

                    step = 21;
                    if (account_context.Attributes.Contains("fdx_zippostalcodeid"))
                    {
                        fdx_zippostalcodeid = (service.Retrieve("fdx_zipcode", ((EntityReference)account_context.Attributes["fdx_zippostalcodeid"]).Id, new ColumnSet("fdx_zipcode"))).Attributes["fdx_zipcode"].ToString();
                        fdx_zipid           = ((EntityReference)account_context.Attributes["fdx_zippostalcodeid"]).Id;
                    }

                    step = 23;
                    if (account_context.Attributes.Contains("fdx_stateprovinceid"))
                    {
                        step = 230;
                        if (account_context.Attributes["fdx_stateprovinceid"] != null)
                        {
                            step = 2300;
                            fdx_stateprovinceid = (service.Retrieve("fdx_state", ((EntityReference)account_context.Attributes["fdx_stateprovinceid"]).Id, new ColumnSet("fdx_statecode"))).Attributes["fdx_statecode"].ToString();
                            fdx_stateid         = ((EntityReference)account_context.Attributes["fdx_stateprovinceid"]).Id;
                        }
                    }

                    step = 25;
                    if (account_context.Attributes.Contains("name"))
                    {
                        companyname = account_context.Attributes["name"].ToString();
                    }
                    #endregion

                    #region Query CRM Account for required Address Attributes
                    step = 27;
                    QueryExpression queryExp = CRMQueryExpression.getQueryExpression("account", new ColumnSet("fdx_goldmineaccountnumber", "fdx_gonogo", "address1_line1", "address1_city", "address1_country", "fdx_zippostalcodeid", "fdx_stateprovinceid", "address1_line2", "address1_line3", "telephone1", "telephone2", "name"), new CRMQueryExpression[] { new CRMQueryExpression("accountid", ConditionOperator.Equal, account_context.Id) });

                    EntityCollection accountCollection = service.RetrieveMultiple(queryExp);
                    tracingService.Trace("Querying Account Details!");
                    #endregion
                    step = 29;
                    //This condition will return success only if there exist an Account with the GUID in context.
                    //Generally is successful always
                    if (accountCollection.Entities.Count > 0)
                    {
                        tracingService.Trace("Account details fetched!");
                        #region Fetch values from Account whichever do not exist in Context and create Update API String
                        step = 290;
                        Entity account = new Entity();
                        account = accountCollection.Entities[0];

                        step = 292;
                        //if (account.Attributes.Contains("fdx_gonogo"))
                        //    old_fdx_gonogo = ((OptionSetValue)account.Attributes["fdx_gonogo"]).Value;

                        step = 294;
                        if (account.Attributes.Contains("fdx_goldmineaccountnumber"))
                        {
                            old_fdx_goldmineaccountnumber = account.Attributes["fdx_goldmineaccountnumber"].ToString();
                            //Encoding the GM Account Number to resolve issue with Special Characters
                            apiParm += string.Format("&AccountNo_in={0}", WebUtility.UrlEncode(old_fdx_goldmineaccountnumber));
                        }

                        step = 296;
                        if (address1_line1 == null)
                        {
                            if (account.Attributes.Contains("address1_line1"))
                            {
                                step           = 2960;
                                address1_line1 = account.Attributes["address1_line1"].ToString();
                                apiParm       += string.Format("&Address1={0}", address1_line1);
                            }
                        }
                        else
                        {
                            step     = 2962;
                            apiParm += string.Format("&Address1={0}", address1_line1);
                        }

                        step = 298;
                        if (address1_city == null)
                        {
                            if (account.Attributes.Contains("address1_city"))
                            {
                                step          = 2980;
                                address1_city = account.Attributes["address1_city"].ToString();
                                apiParm      += string.Format("&City={0}", address1_city);
                            }
                        }
                        else
                        {
                            step     = 2982;
                            apiParm += string.Format("&City={0}", address1_city);
                        }

                        step = 230;
                        if (address1_country == null)
                        {
                            if (account.Attributes.Contains("address1_country"))
                            {
                                step             = 2302;
                                address1_country = account.Attributes["address1_country"].ToString();
                                apiParm         += string.Format("&Country={0}", address1_country);
                            }
                        }
                        else
                        {
                            step     = 2304;
                            apiParm += string.Format("&Country={0}", address1_country);
                        }
                        step = 232;
                        if (fdx_zippostalcodeid == null)
                        {
                            if (account.Attributes.Contains("fdx_zippostalcodeid"))
                            {
                                step = 2320;
                                fdx_zippostalcodeid = (service.Retrieve("fdx_zipcode", ((EntityReference)account.Attributes["fdx_zippostalcodeid"]).Id, new ColumnSet("fdx_zipcode"))).Attributes["fdx_zipcode"].ToString();
                                fdx_zipid           = ((EntityReference)account.Attributes["fdx_zippostalcodeid"]).Id;
                                apiParm            += string.Format("&Zip={0}", fdx_zippostalcodeid);
                            }
                        }
                        else
                        {
                            step     = 2322;
                            apiParm += string.Format("&Zip={0}", fdx_zippostalcodeid);
                        }
                        step = 234;
                        if (fdx_stateprovinceid == null && !account_context.Attributes.Contains("fdx_stateprovinceid"))
                        {
                            if (account.Attributes.Contains("fdx_stateprovinceid"))
                            {
                                step = 2340;
                                if (account.Attributes["fdx_stateprovinceid"] != null)
                                {
                                    step = 2342;
                                    fdx_stateprovinceid = (service.Retrieve("fdx_state", ((EntityReference)account.Attributes["fdx_stateprovinceid"]).Id, new ColumnSet("fdx_statecode"))).Attributes["fdx_statecode"].ToString();
                                    fdx_stateid         = ((EntityReference)account.Attributes["fdx_stateprovinceid"]).Id;
                                    apiParm            += string.Format("&State={0}", fdx_stateprovinceid);
                                }
                            }
                        }
                        else if (fdx_stateprovinceid != null)
                        {
                            step     = 2344;
                            apiParm += string.Format("&State={0}", fdx_stateprovinceid);
                        }
                        step = 236;
                        if (companyname == null)
                        {
                            if (account.Attributes.Contains("name"))
                            {
                                step        = 2360;
                                companyname = account.Attributes["name"].ToString();
                                apiParm    += string.Format("&Company={0}", companyname);
                            }
                        }
                        else
                        {
                            step     = 2362;
                            apiParm += string.Format("&Company={0}", companyname);
                        }
                        #endregion

                        #region Make a Web API Call for the Updated GoYPR scoring, and set the latest GoNogo status in to Account Context
                        step = 238;
                        url += apiParm.Remove(0, 1);

                        #region Commented in order to implement this web api call using PUT instead of POST

                        /*APIResponse accountObj = new APIResponse();
                         * step = 240;
                         * const string token = "8b6asd7-0775-4278-9bcb-c0d48f800112";
                         * var uri = new Uri(url);
                         * var request = WebRequest.Create(uri);
                         * request.Method = WebRequestMethods.Http.Post;
                         * request.ContentType = "application/json";
                         * request.ContentLength = 0;
                         * request.Headers.Add("Authorization", token);
                         * step = 242;
                         * using (var getResponse = request.GetResponse())
                         * {
                         *  step = 2420;
                         *  DataContractJsonSerializer serializer =
                         *              new DataContractJsonSerializer(typeof(APIResponse));
                         *
                         *  accountObj = (APIResponse)serializer.ReadObject(getResponse.GetResponseStream());
                         *  step = 2422;
                         *  account_context["fdx_gonogo"] = accountObj.goNoGo ? new OptionSetValue(756480000) : new OptionSetValue(756480001);
                         *  step = 2424;
                         *  new_fdx_gonogo = accountObj.goNoGo ? 756480000 : 756480001;
                         * }*/
                        #endregion

                        tracingService.Trace(url);

                        API_PutResponse accountObj = new API_PutResponse();
                        step = 240;
                        const string token   = "8b6asd7-0775-4278-9bcb-c0d48f800112";
                        var          uri     = new Uri(url);
                        var          request = WebRequest.Create(uri);
                        request.Method        = WebRequestMethods.Http.Put;
                        request.ContentType   = "application/json";
                        request.ContentLength = 0;
                        request.Headers.Add("Authorization", token);
                        step = 242;
                        using (var getResponse = request.GetResponse())
                        {
                            step = 2420;
                            DataContractJsonSerializer serializer =
                                new DataContractJsonSerializer(typeof(API_PutResponse));

                            accountObj = (API_PutResponse)serializer.ReadObject(getResponse.GetResponseStream());
                            step       = 2422;
                            account_context["fdx_gonogo"] = accountObj.goNoGo ? new OptionSetValue(756480000) : new OptionSetValue(756480001);
                            step           = 2424;
                            new_fdx_gonogo = accountObj.goNoGo ? 756480000 : 756480001;
                        }
                        EntityCollection priceLists     = GetPriceListByName(accountObj.priceListName, service);
                        EntityCollection prospectGroups = GetProspectGroupByName(accountObj.prospectGroup, service);
                        ProspectData     prospectData   = GetProspectDataFromWebService(accountObj);
                        prospectData.PriceListName = accountObj.priceListName;
                        if (priceLists.Entities.Count == 1)
                        {
                            prospectData.PriceListId = priceLists.Entities[0].Id;
                        }
                        if (prospectGroups.Entities.Count == 1)
                        {
                            prospectData.ProspectGroupId = prospectGroups.Entities[0].Id;
                        }
                        tracingService.Trace(GetProspectDataString(prospectData));
                        tracingService.Trace(Convert.ToString(account_context.Id));
                        UpdateProspectDataOnAccountUsingImpersonatedService(account_context.Id, prospectData, impersonatedService);
                        #endregion

                        #region Select Leads related to Account and Update the latest GoNogo Status and Address attributes
                        step = 244;
                        if (new_fdx_gonogo != 0 && old_fdx_goldmineaccountnumber != null)
                        {
                            step = 2440;
                            QueryExpression leadQuery = CRMQueryExpression.getQueryExpression("lead", new ColumnSet("fdx_gonogo", "parentaccountid"), new CRMQueryExpression[] { new CRMQueryExpression("fdx_goldmineaccountnumber", ConditionOperator.Equal, old_fdx_goldmineaccountnumber) });
                            step = 2442;
                            EntityCollection leadEntities = service.RetrieveMultiple(leadQuery);
                            step = 2444;
                            for (int i = 0; i < leadEntities.Entities.Count; i++)
                            {
                                step = 24440;
                                if (leadEntities.Entities[i].Attributes.Contains("parentaccountid"))
                                {
                                    step = 244400;
                                    if (((EntityReference)leadEntities.Entities[i].Attributes["parentaccountid"]).Id == account_context.Id)
                                    {
                                        step = 2444000;
                                        Entity lead = new Entity("lead")
                                        {
                                            Id = leadEntities.Entities[i].Id
                                        };
                                        step = 2444002;
                                        lead["fdx_gonogo"] = new OptionSetValue(new_fdx_gonogo);
                                        step = 2444004;
                                        lead["address1_line1"] = address1_line1;
                                        step = 2444006;
                                        lead["address1_city"] = address1_city;
                                        step = 2444008;
                                        lead["address1_country"] = address1_country;
                                        step = 2444010;
                                        if (fdx_stateid != Guid.Empty)
                                        {
                                            lead["fdx_stateprovince"] = new EntityReference("fdx_state", fdx_stateid);
                                        }
                                        else
                                        {
                                            lead["fdx_stateprovince"] = null;
                                        }
                                        step = 2444012;
                                        lead["fdx_zippostalcode"] = new EntityReference("fdx_zipcode", fdx_zipid);
                                        step = 2444014;
                                        lead["companyname"] = companyname;
                                        step = 2444016;
                                        if (account_context.Attributes.Contains("address1_line2"))
                                        {
                                            step = 24440160;
                                            lead["address1_line2"] = account_context.Attributes["address1_line2"].ToString();
                                        }
                                        else if (account.Attributes.Contains("address1_line2"))
                                        {
                                            step = 24440162;
                                            lead["address1_line2"] = account.Attributes["address1_line2"].ToString();
                                        }
                                        else
                                        {
                                            step = 24440164;
                                            lead["address1_line2"] = null;
                                        }
                                        step = 2444018;
                                        if (account_context.Attributes.Contains("address1_line3"))
                                        {
                                            step = 24440180;
                                            lead["address1_line3"] = account_context.Attributes["address1_line3"].ToString();
                                        }
                                        else if (account.Attributes.Contains("address1_line3"))
                                        {
                                            step = 24440182;
                                            lead["address1_line3"] = account.Attributes["address1_line3"].ToString();
                                        }
                                        else
                                        {
                                            step = 24440184;
                                            lead["address1_line3"] = null;
                                        }
                                        step = 2444020;
                                        if (account_context.Attributes.Contains("telephone1"))
                                        {
                                            step = 24440200;
                                            lead["telephone2"] = Regex.Replace(account_context.Attributes["telephone1"].ToString(), @"[^0-9]+", "");
                                            //lead["telephone2"] = account_context.Attributes["telephone1"].ToString();
                                        }
                                        else if (account.Attributes.Contains("telephone1"))
                                        {
                                            step = 24440202;
                                            lead["telephone2"] = Regex.Replace(account.Attributes["telephone1"].ToString(), @"[^0-9]+", "");
                                            //lead["telephone2"] = account.Attributes["telephone1"].ToString();
                                        }
                                        else
                                        {
                                            step = 24440204;
                                            lead["telephone2"] = null;
                                        }
                                        step = 2444022;
                                        if (account_context.Attributes.Contains("telephone2"))
                                        {
                                            step = 24440220;
                                            lead["telephone3"] = Regex.Replace(account_context.Attributes["telephone2"].ToString(), @"[^0-9]+", "");
                                            //lead["telephone3"] = account_context.Attributes["telephone2"].ToString();
                                        }
                                        else if (account.Attributes.Contains("telephone2"))
                                        {
                                            step = 24440222;
                                            lead["telephone3"] = Regex.Replace(account.Attributes["telephone2"].ToString(), @"[^0-9]+", "");
                                            //lead["telephone3"] = account.Attributes["telephone2"].ToString();
                                        }
                                        else
                                        {
                                            step = 24440224;
                                            lead["telephone3"] = null;
                                        }
                                        //Holds some value in this field, to indicate that the Lead is updated by Account Plugin and not by Form
                                        step = 2444024;
                                        lead["fdx_accountcontext"] = "1";
                                        step = 2444026;
                                        UpdateProspectDataOnLead(lead, prospectData);
                                        impersonatedService.Update(lead);
                                        tracingService.Trace("Prospect Data Updated on Lead!");
                                    }
                                }
                            }
                        }
                        #endregion

                        #region Select Opportunities related to Account and Update the latest GoNogo Status
                        step = 246;
                        if (new_fdx_gonogo != 0 && old_fdx_goldmineaccountnumber != null)
                        {
                            step = 2460;
                            QueryExpression opportunityQuery = CRMQueryExpression.getQueryExpression("opportunity", new ColumnSet("fdx_gonogo", "parentaccountid", "statecode"), new CRMQueryExpression[] { new CRMQueryExpression("fdx_goldmineaccountnumber", ConditionOperator.Equal, old_fdx_goldmineaccountnumber) });
                            step = 2462;
                            EntityCollection opportunityEntities = service.RetrieveMultiple(opportunityQuery);
                            step = 2464;
                            for (int i = 0; i < opportunityEntities.Entities.Count; i++)
                            {
                                tracingService.Trace("Count of Ops- " + opportunityEntities.Entities.Count);
                                step = 24640;
                                if (opportunityEntities.Entities[i].Attributes.Contains("parentaccountid"))
                                {
                                    tracingService.Trace("Account has Data");
                                    step = 246400;
                                    tracingService.Trace("Opp Account Guid : " + ((EntityReference)opportunityEntities.Entities[i].Attributes["parentaccountid"]).Id + "ContextAccountGuid : " + account_context.Id);
                                    tracingService.Trace("If Result: " + (((EntityReference)opportunityEntities.Entities[i].Attributes["parentaccountid"]).Id == account_context.Id));
                                    if (((EntityReference)opportunityEntities.Entities[i].Attributes["parentaccountid"]).Id == account_context.Id)
                                    {
                                        tracingService.Trace("Inside Opportunity Loop");
                                        step = 2464000;
                                        Entity opportunity = new Entity("opportunity")
                                        {
                                            Id = opportunityEntities.Entities[i].Id
                                        };
                                        step = 2464002;
                                        opportunity["fdx_gonogo"] = new OptionSetValue(new_fdx_gonogo);
                                        step = 2464004;
                                        if (((OptionSetValue)opportunityEntities.Entities[i]["statecode"]).Value == 0)
                                        {
                                            UpdateProspectDataOnOpportunity(opportunity, prospectData);
                                            opportunity["fdx_prospectscoreblankmessage"] = prospectData.ProspectScoreBlankMessage;
                                            tracingService.Trace("error- " + prospectData.ProspectScoreBlankMessage);
                                            impersonatedService.Update(opportunity);
                                            tracingService.Trace("Prospect Data Updated on Opportunity!");
                                        }
                                        else
                                        {
                                            service.Update(opportunity);
                                        }
                                    }
                                }
                            }
                        }
                        step = 248;
                        #endregion
                        //Thread.Sleep(120000);
                        //System.Threading.Thread.Sleep(new TimeSpan(0, 1, 0));
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException(string.Format("An error occurred in the Updating Go/No-go Status to Account in plug-in at Step {0}. " + ex.Message, step), ex);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Account_AddressUpdateHandler: step {0}, {1}", step, ex.ToString());
                    throw;
                }
            }
        }
Exemple #18
0
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            if (context.MessageName.ToLower() == "update" &&
                context.Mode == Convert.ToInt32(MeuEnum.Mode.Synchronous) &&
                context.Stage == Convert.ToInt32(MeuEnum.Stage.PosOperation))
            {
                IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                var serviceAdmin = factory.CreateOrganizationService(null);

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

                trace.Trace("Inicio Plugin");
                Entity entidadeContexto = null;
                Entity entidadePre      = null;

                if (context.InputParameters.Contains("Target"))
                {
                    entidadeContexto = (Entity)context.InputParameters["Target"];
                }

                if (context.PreEntityImages.Contains("preImagem"))
                {
                    entidadePre = (Entity)context.PreEntityImages["preImagem"];
                }

                if (entidadeContexto == null || entidadePre == null)
                {
                    return;
                }

                if ((entidadeContexto.Contains("primarycontactid") && entidadePre.Contains("primarycontactid")) &&
                    (entidadeContexto["primarycontactid"]) != (entidadePre["primarycontactid"]))
                {
                    throw new InvalidPluginExecutionException("Não é possivel altear o contato primário");
                }
            }
            else if (context.MessageName.ToLower() == "create" &&
                     context.Mode == Convert.ToInt32(MeuEnum.Mode.Synchronous) &&
                     context.Stage == Convert.ToInt32(MeuEnum.Stage.PreOperation))
            {
                IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                var serviceProsxyUserService = factory.CreateOrganizationService(context.UserId);

                Entity entidadeContexto = null;

                if (context.InputParameters.Contains("Target"))
                {
                    entidadeContexto = (Entity)context.InputParameters["Target"];
                }
                {
                    if (entidadeContexto != null)
                    {
                        Guid   contactid = new Guid();
                        Entity entidade  = new Entity("contact");
                        entidade.Attributes.Add("firstname", string.Format("Contato - > {0}", DateTime.Now.ToString("dd/MM/yyyy")));
                        entidade.Attributes.Add("lastname", "Sobrenome");

                        contactid = serviceProsxyUserService.Create(entidade);

                        if (contactid != Guid.Empty)
                        {
                            EntityReference reference = new EntityReference("contact", contactid);

                            entidadeContexto.Attributes.Add("primarycontactid", reference);
                        }
                    }
                }
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered AddTabelArrangementProductToBooking.Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace("AddTabelArrangementProductToBooking.Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

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

            Xrm xrm = new Xrm(service);


            tracingService.Trace("Creating AddTabelArrangementProductToBooking...");

            try
            {
                var bookingResRef = BookableResourceRef.Get <EntityReference>(executionContext);

                var br = xrm.BookableResourceSet.FirstOrDefault(b => b.BookableResourceId.Value == bookingResRef.Id);

                EntityReferenceCollection enColl = new EntityReferenceCollection();
                var udstyr = (from u in xrm.dyna_udstyrSet
                              join ur in xrm.dyna_dyna_udstyr_bookableresourceSet on u.dyna_udstyrId equals ur.dyna_udstyrid
                              where ur.bookableresourceid.Value == bookingResRef.Id
                              select u).ToList();

                foreach (var item in udstyr)
                {
                    var be = new dyna_bookingequipment()
                    {
                        dyna_name                      = item.dyna_name,
                        dyna_Amount                    = 1,
                        dyna_UseEquipmentAs            = false,
                        dyna_EquipmentId               = item.ToEntityReference(),
                        dyna_BookableResourceBookingId = new EntityReference(BookableResourceBooking.EntityLogicalName, context.PrimaryEntityId)
                    };

                    service.Create(be);
                }

                tracingService.Trace("Done.");
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0} - {1}", e.ToString(), e.StackTrace);
                // Handle the exception.
                throw;
            }

            tracingService.Trace("Exiting AddTabelArrangementProductToBooking.Execute(), Correlation Id: {0}", context.CorrelationId);
        }
Exemple #20
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracer  = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);

            try
            {
                Entity parentDistribute = (Entity)context.InputParameters["Target"];
                Entity postImage        = context.PostEntityImages["postImage"];

                //Retrieve the child records
                FetchExpression query = new FetchExpression(@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
																  <entity name='lat_distributeentity'>
																	<attribute name='lat_distributeentityid' />
																	<filter type='and'>
																		<condition attribute='lat_parentdistribute' operator='eq' uitype='lat_distributeentity' value='"                                                                         + parentDistribute.Id + @"'/>
																	</filter>
																</entity>
															</fetch>"                                                            );

                EntityCollection results = service.RetrieveMultiple(query);

                //Distribute the value & set the status of each child record
                foreach (Entity distribute in results.Entities)
                {
                    distribute["lat_distributedvalue"] = new Money(postImage.GetAttributeValue <Money>("lat_valuetodistribute").Value / results.Entities.Count);

                    if (distribute.GetAttributeValue <Money>("lat_distributedvalue").Value > 1000)
                    {
                        distribute["lat_valuestatus"] = new OptionSetValue(807990000);                         //Good
                    }
                    else if (distribute.GetAttributeValue <Money>("lat_distributedvalue").Value < 1000 && distribute.GetAttributeValue <Money>("lat_distributedvalue").Value > 500)
                    {
                        distribute["lat_valuestatus"] = new OptionSetValue(807990001);                         //Neutral
                    }
                    else
                    {
                        distribute["lat_valuestatus"] = new OptionSetValue(807990002);                         //Bad
                    }

                    service.Update(distribute);
                }

                //Set the status on the parent record
                Entity distributeToUpdate = new Entity("lat_distributeentity")
                {
                    Id = parentDistribute.Id
                };
                if (results.Entities[0].GetAttributeValue <Money>("lat_distributedvalue").Value > 1000)
                {
                    distributeToUpdate["lat_valuestatus"] = new OptionSetValue(807990000);                     //Good
                }
                else if (results.Entities[0].GetAttributeValue <Money>("lat_distributedvalue").Value < 1000 && results.Entities[0].GetAttributeValue <Money>("lat_distributedvalue").Value > 500)
                {
                    distributeToUpdate["lat_valuestatus"] = new OptionSetValue(807990001);                     //Neutral
                }
                else
                {
                    distributeToUpdate["lat_valuestatus"] = new OptionSetValue(807990002);                     //Bad
                }

                service.Update(distributeToUpdate);
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
Exemple #21
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracer  = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(null);

            Entity changeOrderEntity = null;

            if (!context.InputParameters.Contains(Constants.TARGET))
            {
                return;
            }
            if (((Entity)context.InputParameters[Constants.TARGET]).LogicalName != Constants.ChangeOrders.LogicalName)
            {
                return;
            }

            try
            {
                switch (context.MessageName)
                {
                case Constants.Messages.Create:
                    if (context.InputParameters.Contains(Constants.TARGET) && context.InputParameters[Constants.TARGET] is Entity)
                    {
                        changeOrderEntity = context.InputParameters[Constants.TARGET] as Entity;
                    }
                    else
                    {
                        return;
                    }
                    break;
                }

                if (changeOrderEntity is Entity)
                {
                    Entity tmp = new Entity(changeOrderEntity.LogicalName);
                    tmp.Id = changeOrderEntity.Id;
                    tmp[Constants.ChangeOrders.Revision] = 0;

                    if (!changeOrderEntity.Attributes.Contains(Constants.ChangeOrders.Currency))
                    {
                        tracer.Trace("Default Transaction Currency NOT found.");

                        Entity orgEntity = service.Retrieve("organization", context.OrganizationId, new ColumnSet(true));
                        if (orgEntity is Entity && orgEntity.Attributes.Contains("basecurrencyid"))
                        {
                            tracer.Trace("Default Transaction Currency found in Org Record.");
                            tmp[Constants.ChangeOrders.Currency] = orgEntity.GetAttributeValue <EntityReference>("basecurrencyid");
                        }
                    }

                    service.Update(tmp);
                    //Force Calculate Rollup Field
                    CommonMethods.CalculateRollup(service, Constants.ChangeOrders.TotalAmount, changeOrderEntity.ToEntityReference());
                }
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
Exemple #22
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService             tracer  = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            IPluginExecutionContext     context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service = factory.CreateOrganizationService(context.UserId);

            try
            {
                Entity projectTaskEntity = null;
                switch (context.MessageName)
                {
                case Constants.Messages.Create:
                    if (context.InputParameters[Constants.TARGET] is Entity)
                    {
                        if (((Entity)context.InputParameters[Constants.TARGET]).LogicalName != Constants.ProjectTasks.LogicalName)
                        {
                            return;
                        }
                        else
                        {
                            projectTaskEntity = context.InputParameters[Constants.TARGET] as Entity;
                        }
                    }
                    break;
                }

                if (projectTaskEntity is Entity && projectTaskEntity.Attributes.Contains(Constants.ProjectTasks.Project) && projectTaskEntity.Attributes.Contains(Constants.ProjectTasks.WBSID))
                {
                    string strSequence = projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.WBSID);
                    strSequence = strSequence.RemoveAllButFirst(".");
                    decimal decSequence = 0;
                    if (decimal.TryParse(strSequence, out decSequence))
                    {
                        projectTaskEntity[Constants.ProjectTasks.Sequence] = decSequence;
                    }


                    tracer.Trace($"Project Task contains Project as well as WBSID.");
                    Entity projectEntity = service.Retrieve(projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.Project).LogicalName,
                                                            projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.Project).Id, new ColumnSet(true));

                    if (projectEntity is Entity && projectEntity.Attributes.Contains(Constants.Projects.ProjectTemplate) && projectEntity.Attributes.Contains(Constants.Projects.Unit))
                    {
                        int timeZoneCode = CommonMethods.RetrieveCurrentUsersSettings(service);

                        DateTime unitStatusChange = DateTime.Now;
                        if (projectEntity.Attributes.Contains(Constants.Projects.StartDate))
                        {
                            unitStatusChange = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, projectEntity.GetAttributeValue <DateTime>(Constants.Projects.StartDate));
                        }

                        tracer.Trace($"Project contains Project Template.");
                        Entity projectTemplateTaskEntity = RetrieveProjectTemplateTask(service, tracer, projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.ProjectTemplate),
                                                                                       projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.WBSID));

                        if (projectTemplateTaskEntity is Entity)
                        {
                            projectTaskEntity[Constants.ProjectTasks.TaskIdentifier] = projectTemplateTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.TaskIdentifier);
                        }
                        else if (projectTaskEntity.Attributes.Contains(Constants.ProjectTasks.TaskIdentifier) && string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.TaskIdentifier).Name))
                        {
                            Entity taskIdentiEntity = service.Retrieve(projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.TaskIdentifier).LogicalName, projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.TaskIdentifier).Id, new ColumnSet(true));
                            if (taskIdentiEntity is Entity && taskIdentiEntity.Attributes.Contains(Constants.TaskIdentifiers.Name))
                            {
                                projectTaskEntity[Constants.ProjectTasks.TaskIdentifier] = new EntityReference()
                                {
                                    Name = taskIdentiEntity.GetAttributeValue <string>(Constants.TaskIdentifiers.Name), Id = taskIdentiEntity.Id, LogicalName = taskIdentiEntity.LogicalName
                                }
                            }
                            ;
                        }

                        //Map Property Information...
                        Entity unitEntity = service.Retrieve(projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.Unit).LogicalName, projectEntity.GetAttributeValue <EntityReference>(Constants.Projects.Unit).Id, new ColumnSet(true));
                        if (unitEntity is Entity)
                        {
                            tracer.Trace($"Unit Found. {unitEntity.Id.ToString()}");
                            //if (unitEntity.Attributes.Contains(Constants.Units.MoveOutDate))
                            //    moveOutDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, unitEntity.GetAttributeValue<DateTime>(Constants.Units.MoveOutDate));

                            //Map Unit
                            projectTaskEntity[Constants.ProjectTasks.UnitId] = unitEntity.ToEntityReference();

                            //Access Notes
                            if (unitEntity.Attributes.Contains(Constants.Units.AccessNotes) && !string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.AccessNotes)))
                            {
                                projectTaskEntity[Constants.ProjectTasks.AccessNotes] = unitEntity.GetAttributeValue <string>(Constants.Units.AccessNotes);
                            }
                            //LockBox Removed
                            if (unitEntity.Attributes.Contains(Constants.Units.LockBoxRemoved) && !string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.LockBoxRemoved)))
                            {
                                projectTaskEntity[Constants.ProjectTasks.LockBoxRemoved] = unitEntity.GetAttributeValue <DateTime>(Constants.Units.LockBoxRemoved);
                            }
                            //Mechanical Lockbox
                            if (unitEntity.Attributes.Contains(Constants.Units.MechanicalLockBox) && !string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBox)))
                            {
                                projectTaskEntity[Constants.ProjectTasks.MechanicalLockBox] = unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBox);
                            }
                            //Mechanical Lockbox Note
                            if (unitEntity.Attributes.Contains(Constants.Units.MechanicalLockBoxNote) && !string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBoxNote)))
                            {
                                projectTaskEntity[Constants.ProjectTasks.MechanicalLockBoxNote] = unitEntity.GetAttributeValue <string>(Constants.Units.MechanicalLockBoxNote);
                            }
                            //Property Gate Code
                            if (unitEntity.Attributes.Contains(Constants.Units.PropertyGateCode) && !string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.PropertyGateCode)))
                            {
                                projectTaskEntity[Constants.ProjectTasks.PropertyGateCode] = unitEntity.GetAttributeValue <string>(Constants.Units.PropertyGateCode);
                            }
                            //Rently Lockbox
                            if (unitEntity.Attributes.Contains(Constants.Units.RentlyLockBox) && !string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBox)))
                            {
                                projectTaskEntity[Constants.ProjectTasks.RentlyLockBox] = unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBox);
                            }
                            //Access Notes
                            if (unitEntity.Attributes.Contains(Constants.Units.RentlyLockBoxNote) && !string.IsNullOrEmpty(unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBoxNote)))
                            {
                                projectTaskEntity[Constants.ProjectTasks.RentlyLockBoxNote] = unitEntity.GetAttributeValue <string>(Constants.Units.RentlyLockBoxNote);
                            }

                            if (projectTaskEntity.Attributes.Contains(Constants.ProjectTasks.TaskIdentifier) && !string.IsNullOrEmpty(projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.TaskIdentifier).Name))
                            {
                                tracer.Trace($"Project Task with Task Identifier ID : {projectTaskEntity.GetAttributeValue<EntityReference>(Constants.ProjectTasks.TaskIdentifier).Id.ToString()}.");
                                tracer.Trace($"Project Task with Task Identifier : {projectTaskEntity.GetAttributeValue<EntityReference>(Constants.ProjectTasks.TaskIdentifier).Name}.");
                                if (projectTaskEntity.GetAttributeValue <EntityReference>(Constants.ProjectTasks.TaskIdentifier).Name.StartsWith("TurnAround"))
                                {
                                    DateTime scheduledStartDate, scheduledEndDate;
                                    DateTime Date2 = unitStatusChange;
                                    if (projectEntity.Attributes.Contains(Constants.Projects.InitialJSONDataPayLoad))
                                    {
                                        try
                                        {
                                            DataPayLoad dataPayLoad = CommonMethods.Deserialize <DataPayLoad>(projectEntity.GetAttributeValue <string>(Constants.Projects.InitialJSONDataPayLoad));
                                            if (dataPayLoad is DataPayLoad)
                                            {
                                                tracer.Trace($"Initial Data PayLoad . {projectEntity.GetAttributeValue<string>(Constants.Projects.InitialJSONDataPayLoad)}");
                                                if (!DateTime.TryParse(dataPayLoad.Date2, out Date2))
                                                {
                                                    Date2 = unitStatusChange;
                                                }
                                                tracer.Trace($"Initial Data PayLoad Date 2. {Date2.ToString()}");
                                            }
                                            else
                                            {
                                                Date2 = unitStatusChange;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            tracer.Trace($"Error Thrown during Deserialing Initial Data PayLoad :  {projectEntity.GetAttributeValue<string>(Constants.Projects.InitialJSONDataPayLoad)} {Environment.NewLine} Error : {ex.Message}");
                                        }
                                    }
                                    //DateTime SchStartDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, projectTaskEntity.GetAttributeValue<DateTime>(Constants.ProjectTasks.ScheduledStart));

                                    Date2 = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, Date2);
                                    Date2 = Date2.ChangeTime(6, 0, 0, 0);
                                    tracer.Trace($"Local Date 2. {Date2.ToString()}");

                                    switch (projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.WBSID))
                                    {
                                    case "1":               // RESIDENT NOTICE TO MOVE OUT RECEIVED
                                        projectTaskEntity[Constants.ProjectTasks.ActualStart]    = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ActualEnd]      = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.Progress]       = new decimal(100);
                                        projectTaskEntity[Constants.Status.StatusCode]           = new OptionSetValue(963850001);
                                        break;

                                    case "2":               //TurnAround : ASSIGN PROJECT MANAGER
                                        scheduledEndDate = (Date2.AddDays(-37) > unitStatusChange) ? Date2.AddDays(-37) : ((Date2 > unitStatusChange) ? Date2 : unitStatusChange);
                                        //Date2 = (Date2.AddDays(-37) > DateTime.Now) ? ((Date2.AddDays(-37) > unitStatusChange) ? Date2.AddDays(-37) : unitStatusChange.AddHours(24)) : ((unitStatusChange > DateTime.Now) ? unitStatusChange.AddHours(24) : DateTime.Now);
                                        tracer.Trace($"Scheduled Start Date : {unitStatusChange}");
                                        tracer.Trace($"Scheduled End Date : {scheduledEndDate}");
                                        projectTaskEntity[Constants.ProjectTasks.ActualStart]    = unitStatusChange; //(unitStatusChange.Date < scheduledEndDate.Date) ? unitStatusChange : unitStatusChange.AddDays(-1);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange; // (unitStatusChange.Date < scheduledEndDate.Date) ? unitStatusChange : unitStatusChange.AddDays(-1);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = scheduledEndDate;
                                        projectTaskEntity[Constants.ProjectTasks.Progress]       = new decimal(1);
                                        projectTaskEntity[Constants.Status.StatusCode]           = new OptionSetValue(963850000);
                                        break;

                                    case "3":               //CORPORATE RENEWALS
                                        tracer.Trace($"Scheduled Start Date : {unitStatusChange}");
                                        //tracer.Trace($"Scheduled End Date : {scheduledEndDate}");
                                        projectTaskEntity[Constants.ProjectTasks.ActualStart]    = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (Date2 > unitStatusChange) ? Date2 : unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.Progress]       = new decimal(1);
                                        projectTaskEntity[Constants.Status.StatusCode]           = new OptionSetValue(963850000);
                                        break;

                                    case "4":               //MARKET SCHEDULES PRE-MOVE-OUT
                                        scheduledEndDate = (Date2.AddDays(-30) > unitStatusChange) ? Date2.AddDays(-30) : ((Date2 > unitStatusChange) ? Date2 : unitStatusChange);
                                        //Date2 = (Date2.AddDays(-30) > DateTime.Now) ? ((Date2.AddDays(-30) > unitStatusChange) ? Date2.AddDays(-30) : unitStatusChange.AddHours(24)) : ((unitStatusChange > DateTime.Now) ? unitStatusChange.AddHours(24) : DateTime.Now.AddHours(24));
                                        tracer.Trace($"Scheduled Start Date : {unitStatusChange}");
                                        tracer.Trace($"Scheduled End Date : {scheduledEndDate}");
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = scheduledEndDate;
                                        break;

                                    case "5":               //PRE-MOVE-OUT INSPECTION
                                        scheduledEndDate   = (Date2.AddDays(-1) > unitStatusChange) ? Date2.AddDays(-1) : ((Date2 > unitStatusChange) ? Date2 : unitStatusChange);
                                        scheduledStartDate = (Date2.AddDays(-30) > unitStatusChange) ? Date2.AddDays(-30) : ((Date2 > unitStatusChange) ? Date2 : unitStatusChange);
                                        //scheduledStartDate = (Date2.AddDays(-30) > DateTime.Now) ? ((Date2.AddDays(-30) > unitStatusChange) ? Date2.AddDays(-30) : unitStatusChange.AddHours(-24)) : ((unitStatusChange > DateTime.Now) ? unitStatusChange.AddHours(-24) : DateTime.Now.AddHours(-24));
                                        //Date2 = (Date2.AddDays(-30) > DateTime.Now) ? ((Date2.AddDays(-30) > unitStatusChange) ? Date2.AddDays(-30) : unitStatusChange.AddHours(24)) : ((unitStatusChange > DateTime.Now) ? unitStatusChange.AddHours(24) : DateTime.Now.AddHours(24));
                                        tracer.Trace($"Scheduled Start Date : {scheduledStartDate}");
                                        tracer.Trace($"Scheduled End Date : {scheduledEndDate}");
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = scheduledStartDate;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = scheduledEndDate;
                                        break;

                                    case "6":               //MOVE-OUT INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2;
                                        break;

                                    case "7":               //BUDGET START
                                        tracer.Trace($"BUDGET START Date 2. {Date2.ToString()}");
                                        tracer.Trace($"BUDGET START ScheduledStart. {Date2.ToString()}");
                                        tracer.Trace($"BUDGET START ScheduledEnd. {Date2.AddHours(24).ToString()}");

                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddHours(24);
                                        break;

                                    case "8":               //BUDGET APPROVAL
                                        tracer.Trace($"BUDGET APPROVAL Date 2. {Date2.ToString()}");
                                        tracer.Trace($"BUDGET APPROVAL ScheduledStart. {Date2.AddSeconds(1).ToString()}");
                                        tracer.Trace($"BUDGET APPROVAL ScheduledEnd. {Date2.AddHours(24).ToString()}");

                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddSeconds(1);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddHours(24);
                                        break;

                                    case "9":               //JOB ASSIGNMENT TO VENDOR(S) IN CONTRACT CREATOR
                                        tracer.Trace($"JOB ASSIGNMENT TO VENDOR(S) IN CONTRACT CREATOR Date 2. {Date2.ToString()}");
                                        tracer.Trace($"JOB ASSIGNMENT TO VENDOR(S) IN CONTRACT CREATOR ScheduledStart. {Date2.AddSeconds(2).ToString()}");
                                        tracer.Trace($"JOB ASSIGNMENT TO VENDOR(S) IN CONTRACT CREATOR ScheduledEnd. {Date2.AddHours(24).ToString()}");

                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddSeconds(2);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddHours(24);
                                        break;

                                    case "10":              //JOB AND CONTRACT(S) SUBMITTED TO YARDI
                                        tracer.Trace($"JOB AND CONTRACT(S) SUBMITTED TO YARDI Date 2. {Date2.ToString()}");
                                        tracer.Trace($"JOB AND CONTRACT(S) SUBMITTED TO YARDI ScheduledStart. {Date2.AddSeconds(3).ToString()}");
                                        tracer.Trace($"JOB AND CONTRACT(S) SUBMITTED TO YARDI ScheduledEnd. {Date2.AddHours(24).ToString()}");

                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddSeconds(3);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddHours(24);
                                        break;

                                    case "11":              //VENDOR(S) SAYS JOB STARTED
                                        tracer.Trace($"VENDOR(S) SAYS JOB STARTED Date 2. {Date2.ToString()}");
                                        tracer.Trace($"VENDOR(S) SAYS JOB STARTED ScheduledStart. {Date2.AddDays(1).ToString()}");
                                        tracer.Trace($"VENDOR(S) SAYS JOB STARTED ScheduledEnd. {Date2.AddDays(1).ToString()}");

                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(1);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(1);
                                        break;

                                    case "12":              //WORK IN PROGRESS
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(2);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(3);
                                        break;

                                    case "13":              //VENDOR SAYS JOB?S COMPLETE
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(3);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(4);
                                        break;

                                    case "14":              //QUALITY CONTROL INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(4);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(5);
                                        break;

                                    case "15":              //JOB COMPLETED
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(5);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(6);
                                        break;

                                    case "16":              //HERO SHOT PICTURE
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(6);
                                        break;

                                    case "17":              //MARKETING INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(6);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(7);
                                        break;

                                    case "18":              //BI-WEEKLY INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(19);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(20);
                                        break;

                                    case "19":              //MOVE-IN INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = Date2.AddDays(44);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = Date2.AddDays(45);
                                        break;
                                    }
                                }
                                else
                                {
                                    DateTime scheduledClosingDate = unitStatusChange, scheduledDDDate = unitStatusChange;
                                    bool     schClosingDateFound = true, schDDDateFound = true;
                                    if (projectEntity.Attributes.Contains(Constants.Projects.InitialJSONDataPayLoad))
                                    {
                                        try
                                        {
                                            DataPayLoad dataPayLoad = CommonMethods.Deserialize <DataPayLoad>(projectEntity.GetAttributeValue <string>(Constants.Projects.InitialJSONDataPayLoad));
                                            if (dataPayLoad is DataPayLoad)
                                            {
                                                tracer.Trace($"Initial Data PayLoad . {projectEntity.GetAttributeValue<string>(Constants.Projects.InitialJSONDataPayLoad)}");
                                                if (!DateTime.TryParse(dataPayLoad.Date2, out scheduledClosingDate))
                                                {
                                                    scheduledClosingDate = unitStatusChange;
                                                    schClosingDateFound  = false;
                                                }
                                                if (!DateTime.TryParse(dataPayLoad.Date3, out scheduledDDDate))
                                                {
                                                    scheduledDDDate = unitStatusChange;
                                                    schDDDateFound  = false;
                                                }
                                            }
                                            else
                                            {
                                                scheduledClosingDate = unitStatusChange;
                                                scheduledDDDate      = unitStatusChange;
                                                schClosingDateFound  = false;
                                                schDDDateFound       = false;
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            tracer.Trace($"Error Thrown during Deserialing Initial Data PayLoad :  {projectEntity.GetAttributeValue<string>(Constants.Projects.InitialJSONDataPayLoad)} {Environment.NewLine} Error : {ex.Message}");
                                            schClosingDateFound = false;
                                            schDDDateFound      = false;
                                        }
                                    }

                                    //DateTime SchStartDate = CommonMethods.RetrieveLocalTimeFromUTCTime(service, timeZoneCode, projectTaskEntity.GetAttributeValue<DateTime>(Constants.ProjectTasks.ScheduledStart));
                                    switch (projectTaskEntity.GetAttributeValue <string>(Constants.ProjectTasks.WBSID))
                                    {
                                    case "1":               //IR : OFFER_ACCEPTED
                                        projectTaskEntity[Constants.ProjectTasks.ActualStart]    = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ActualEnd]      = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.Progress]       = new decimal(100);
                                        projectTaskEntity[Constants.Status.StatusCode]           = new OptionSetValue(963850001);
                                        break;

                                    case "2":               //IR : ASSIGN_PROJECT_MANAGER
                                        projectTaskEntity[Constants.ProjectTasks.ActualStart]    = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = unitStatusChange.AddDays(1);
                                        projectTaskEntity[Constants.ProjectTasks.Progress]       = new decimal(1);
                                        projectTaskEntity[Constants.Status.StatusCode]           = new OptionSetValue(963850000);
                                        break;

                                    case "3":               //IR : SCHEDULE_DUE_DILLIGENCE_INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = unitStatusChange.AddDays(2);
                                        break;

                                    case "4":               //IR : BUDGET_START
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange.AddDays(2);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = unitStatusChange.AddDays(3);
                                        break;

                                    case "5":               //IR : BUDGET_APPROVAL
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schDDDateFound) ? scheduledDDDate.AddDays(-2) : unitStatusChange.AddDays(3);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schDDDateFound) ? scheduledDDDate.AddDays(-1) : unitStatusChange.AddDays(4);
                                        break;

                                    case "6":               //IR : OFFER_REJECTED_OR_APPROVAL
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schDDDateFound) ? scheduledDDDate.AddDays(-1) : unitStatusChange.AddDays(4);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schDDDateFound) ? scheduledDDDate : unitStatusChange.AddDays(5);
                                        break;

                                    case "7":               //IR : JOB_ASSIGNMENT_TO_VENDORS_IN_CONTRACT_CREATOR
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schDDDateFound) ? scheduledDDDate : unitStatusChange.AddDays(5);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(-3) : unitStatusChange.AddDays(6);
                                        break;

                                    case "8":               //IR : CLOSE_ESCROW
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate : unitStatusChange.AddDays(6);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate : unitStatusChange.AddDays(7);
                                        break;

                                    case "9":               //IR : JOB_AND_CONTRACTS_SUBMITTED_TO_YARDI
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate : unitStatusChange.AddDays(6);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(1) : unitStatusChange.AddDays(7);
                                        break;

                                    case "10":               //IR : VENDORS_SAYS_JOB_STARTED
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(1) : unitStatusChange.AddDays(7);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(1) : unitStatusChange.AddDays(8);
                                        break;

                                    case "11":               //IR : WORK_IN_PROGRESS
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(1) : unitStatusChange.AddDays(9);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(3) : unitStatusChange.AddDays(10);
                                        break;

                                    case "12":               //IR : VENDOR_SAYS_JOBS_COMPLETE
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(9) : unitStatusChange.AddDays(16);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(10) : unitStatusChange.AddDays(17);
                                        break;

                                    case "13":               //IR : QUALITY_CONTROL_INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(3) : unitStatusChange.AddDays(17);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(11) : unitStatusChange.AddDays(18);
                                        break;

                                    case "14":               //IR : JOB_COMPLETED
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(10) : unitStatusChange.AddDays(17);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(11) : unitStatusChange.AddDays(18);
                                        break;

                                    case "15":               //IR : HERO_SHOT_PICTURE
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = unitStatusChange;
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(11) : unitStatusChange.AddDays(18);
                                        break;

                                    case "16":               //IR : MARKETING_INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(11) : unitStatusChange.AddDays(18);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(12) : unitStatusChange.AddDays(19);
                                        break;

                                    case "17":               //IR : BI_WEEKLY_INSPECTION
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(24) : unitStatusChange.AddDays(32);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(25) : unitStatusChange.AddDays(33);
                                        break;

                                    case "18":               //IR : MOVE_IN_INSPECTION_COMPLETED
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledStart] = (schClosingDateFound) ? scheduledClosingDate.AddDays(49) : unitStatusChange.AddDays(49);
                                        projectTaskEntity[Constants.ProjectTasks.ScheduledEnd]   = (schClosingDateFound) ? scheduledClosingDate.AddDays(50) : unitStatusChange.AddDays(50);
                                        break;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        tracer.Trace($"Project does NOT contains Project Template.");
                    }
                }
                else
                {
                    tracer.Trace($"Project Task does NOT contains Project or WBSID.");
                }

                //TODO: Do stuff
            }
            catch (Exception e)
            {
                throw new InvalidPluginExecutionException(e.Message);
            }
        }
Exemple #23
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the tracing service
            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 contact = (Entity)context.InputParameters["Target"];

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    // Plug-in business logic goes here.

                    string firstName = contact.Attributes["firstname"].ToString();

                    string email = contact.Attributes["emailaddress1"].ToString();

                    // There are many ways of retrieving data from API
                    // 1. QueryExpression
                    // 2. QueryByAttribute
                    // 3. FetchXML
                    // 4. LINQ

                    // SQL statement
                    // select * from contact where emailaddress1 = email

                    QueryExpression query = new QueryExpression("contact");
                    query.ColumnSet.AddColumn("emailaddress1");
                    query.Criteria.AddCondition("emailaddress1", ConditionOperator.Equal, email);

                    EntityCollection collection = service.RetrieveMultiple(query);

                    if (collection.Entities.Count > 0)
                    {
                        throw new InvalidPluginExecutionException("Enter unique email address!");
                    }
                }

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

                catch (Exception ex)
                {
                    tracingService.Trace("FollowUpPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
Exemple #24
0
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins....
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            if (context.InputParameters.Contains("Target"))
            {
                step = 2;
                Entity opportunityPreImageEntity = ((context.PreEntityImages != null) && context.PreEntityImages.Contains("opppre")) ? context.PreEntityImages["opppre"] : null;

                Entity opportunityEntity = new Entity
                {
                    LogicalName = "opportunity",
                    Id          = opportunityPreImageEntity.Id
                };

                step = 3;
                if (opportunityPreImageEntity.LogicalName != "opportunity")
                {
                    return;
                }

                try
                {
                    step = 5;
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                    //Get current user information....
                    step = 6;
                    WhoAmIResponse response = (WhoAmIResponse)service.Execute(new WhoAmIRequest());

                    step = 7;
                    opportunityEntity["fdx_lastassignedowner"] = new EntityReference("systemuser", ((EntityReference)opportunityPreImageEntity.Attributes["ownerid"]).Id);

                    step = 8;
                    opportunityEntity["fdx_lastassigneddate"] = DateTime.UtcNow;

                    step = 9;
                    service.Update(opportunityEntity);

                    //Update last assign date on account if exist....
                    step = 10;
                    Entity opportunity = new Entity();
                    opportunity = service.Retrieve("opportunity", opportunityPreImageEntity.Id, new ColumnSet(true));

                    step = 11;
                    if (opportunity.Attributes.Contains("parentaccountid"))
                    {
                        step = 12;
                        Entity account = new Entity
                        {
                            Id          = ((EntityReference)opportunity.Attributes["parentaccountid"]).Id,
                            LogicalName = "account"
                        };

                        step = 13;
                        account["fdx_lastassigneddate"] = DateTime.UtcNow;

                        step = 14;
                        service.Update(account);
                    }
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException(string.Format("An error occurred in the Opportunity_OnAssign plug-in at Step {0}.", step), ex);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Opportunity_OnAssign: step {0}, {1}", step, ex.ToString());
                    throw;
                }
            }
        }
Exemple #25
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Extract the tracing service for use in debugging sandboxed plug-ins.
            // If you are not registering the plug-in in the sandbox, then you do
            // not have to add any tracing service related code.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            // Obtain the organization service reference which you will need for
            // web service calls.
            IOrganizationServiceFactory serviceFactory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);



            // 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"];


                try
                {
                    // Plug-in business logic goes here.

                    //context.SharedVariables.Add("Key1", "Some Info");



                    string firstName = string.Empty;

                    // Read form attribute values
                    if (entity.Attributes.Contains("firstname"))
                    {
                        firstName = entity.Attributes["firstname"].ToString();
                    }

                    string lastName = entity.Attributes["lastname"].ToString();

                    // Assign data to attributes.
                    entity.Attributes.Add("description", "Hello World " + firstName + lastName);
                }

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

                catch (Exception ex)
                {
                    tracingService.Trace("MyPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
Exemple #26
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Extract the tracing service for use in debugging sandboxed plug-ins.
            // If you are not registering the plug-in in the sandbox, then you do
            // not have to add any tracing service related code.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            tracingService.Trace("In RSVPPlugin");


            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Get the entity being operated om
                Entity entity = (Entity)context.InputParameters["Target"];

                // Obtain the organization service reference which you will need for
                // web service calls.
                IOrganizationServiceFactory serviceFactory =
                    (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                try
                {
                    tracingService.Trace("Running for entity {0}", entity.LogicalName);

                    // Should only run for the RSVP entity
                    if (entity.LogicalName != CRMExtensions.ORM.msdev_rsvp.EntityLogicalName)
                    {
                        throw new InvalidPluginExecutionException("Unsupported registration");
                    }


                    Dynamics365Context svc = new Dynamics365Context(service);

                    var rsvp = entity.ToEntity <msdev_rsvp>();

                    // Need to ensure we do not exceed max attendance. If this RSVP is not attending,
                    // no need to check
                    if (rsvp.msdev_Attending.GetValueOrDefault(false))
                    {
                        // Get max attendance for the event and compare against number of attending RSVPs
                        var rsvpEvent = svc.msdev_meetupSet.First(e => e.msdev_meetupId == rsvp.msdev_MeetupId.Id);

                        var eventAttendees = svc.msdev_rsvpSet.Where(
                            r => r.msdev_MeetupId != null &&
                            r.msdev_MeetupId.Id == rsvpEvent.Id &&
                            r.msdev_Attending == true)
                                             .ToList();

                        if ((eventAttendees.Count + 1) > rsvpEvent.msdev_MaxAttendees.GetValueOrDefault(Int32.MaxValue))
                        {
                            throw new InvalidPluginExecutionException("Maximum attendance exceeded");
                        }
                    }
                }

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

                catch (Exception ex)
                {
                    tracingService.Trace("MyPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }
Exemple #27
0
        public void Execute(IServiceProvider serviceProvider)

        {
            String RelatedRecordLogicalName;

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

            IPluginExecutionContext context = (IPluginExecutionContext)
                                              serviceProvider.GetService(typeof(IPluginExecutionContext));

            tracingService.Trace("OnPreValidateAssocoateOwnerTeam before assingning teams.");
            EntityReferenceCollection RelatedRecords = (EntityReferenceCollection)context.InputParameters["RelatedEntities"];

            Relationship relationship = (Relationship)context.InputParameters["Relationship"];

            if (relationship.SchemaName != "teammembership_association")
            {
                return;
            }
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

            if (context.MessageName == "Associate" || context.MessageName == "Disassociate")
            {
                if (context.InputParameters.Contains("Target") &&
                    context.InputParameters["Target"] is EntityReference)
                {
                    EntityReference entityReference = (EntityReference)context.InputParameters["Target"];

                    tracingService.Trace("contains target entity");
                    tracingService.Trace("logical name:" + entityReference.LogicalName);

                    if (entityReference.LogicalName != "team" && entityReference.LogicalName != "systemuser")
                    {
                        return;
                    }

                    OrganizationServiceContext orgSvcContext = new OrganizationServiceContext(service);
                    //get team name
                    tracingService.Trace("after getting related records");

                    String  OwnerTeamName;
                    Boolean IsUserPartOfAnyOtherTeam = false;
                    int     index;
                    String  BusinessUnitName;
                    //process records only if its not a default team

                    if (context.MessageName == "Associate" && entityReference.LogicalName == "team")
                    {
                        Entity  TeamDetails        = service.Retrieve("team", entityReference.Id, new ColumnSet("name", "isdefault", "businessunitid"));
                        String  MemberShipTeamName = (String)TeamDetails["name"];
                        Boolean IsDefaultTeam      = (Boolean)TeamDetails["isdefault"];
                        if (MemberShipTeamName.EndsWith("CM-MEMBER"))
                        {
                            index = MemberShipTeamName.LastIndexOf("-");
                            if (index > 0)
                            {
                                OwnerTeamName = MemberShipTeamName.Substring(0, index) + "-OWNER";
                                tracingService.Trace("team found");
                                Guid?TeamId = GetTeamId(OwnerTeamName, orgSvcContext);
                                //Associate Team with User
                                tracingService.Trace("before handling membership team");
                                AddMembersToTeam(TeamId, RelatedRecords, service);
                                tracingService.Trace("after handling membership team");
                            }
                        }
                        {
                            tracingService.Trace("not a member team");
                        }
                    }
                    else if (context.MessageName == "Disassociate" && entityReference.LogicalName == "systemuser")
                    {
                        Guid UserId = entityReference.Id;

                        tracingService.Trace("getting system user details");
                        Entity UserDetails = service.Retrieve("systemuser", entityReference.Id, new ColumnSet("businessunitid"));
                        tracingService.Trace("related record type" + RelatedRecords.FirstOrDefault().LogicalName);
                        tracingService.Trace("getting team details");

                        Entity TeamDetails = service.Retrieve("team", RelatedRecords.FirstOrDefault().Id, new ColumnSet("name", "isdefault", "businessunitid"));
                        tracingService.Trace("after team details");

                        String MemberShipTeamName = (String)TeamDetails["name"];
                        if (MemberShipTeamName.EndsWith("CM-MEMBER"))
                        {
                            tracingService.Trace("its a member team");

                            //check if user is associated with any other team other than owner team
                            Guid   BusinessUnitId       = ((EntityReference)TeamDetails["businessunitid"]).Id;
                            String TeamBusinessUnitName = (String)service.Retrieve("businessunit", BusinessUnitId, new ColumnSet("name")).Attributes["name"];
                            Guid?  OwnerTeam            = GetTeamId(TeamBusinessUnitName + "-CM-OWNER", orgSvcContext);

                            //IsUserPartOfAnyOtherTeam = false;
                            IsUserPartOfAnyOtherTeam =
                                CheckIfUserIsMemberofAnyOtherTeam(TeamDetails.Id, OwnerTeam, UserId,
                                                                  ((EntityReference)TeamDetails["businessunitid"]).Id,
                                                                  orgSvcContext);
                            if (!IsUserPartOfAnyOtherTeam)
                            {
                                tracingService.Trace("before handling remove team member");
                                //if user is not part of any other team then remove that user

                                Guid[] Users = new Guid[1];
                                Users[0] = UserId;
                                RemoveMembersFromTeam(OwnerTeam, Users, service);
                                tracingService.Trace("after handling remove team member");
                            }
                        }

                        else
                        {
                            tracingService.Trace("not a meber team");
                        }
                    }

                    //}
                    //else //handle default team
                    //{
                    //    //CHEMS - UK - REACH - IT
                    //    MemberShipTeamName = (string)TeamDetails["name"] + "-CM-MEMBER";
                    //    tracingService.Trace("team found");
                    //    Guid? TeamId = GetTeamId(MemberShipTeamName, orgSvcContext);//GetMemberTeam.FirstOrDefault().teamid;
                    //                                                                //Associate Team with User
                    //    tracingService.Trace("before handling default team");
                    //    AddMembersToTeam(TeamId, RelatedRecords, service);
                    //    tracingService.Trace("after handling default team");

                    //}
                    tracingService.Trace("PreCreateAccountSetMultiSelectOptionSet after assinging values.");
                }
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            try
            {
                IPluginExecutionContext context =
                    (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

                //verify that this the correct event
                if (context.MessageName.ToUpper() != "UPDATE")
                {
                    return;
                }

                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity entity = (Entity)context.InputParameters["Target"];

                    //verify that this is the target entity
                    if (entity.LogicalName.ToUpper() != "OPPORTUNITY")
                    {
                        return;
                    }

                    //the entity contains fields that have been updated
                    //iterate through list to see if any airport fields have changed
                    List <string> fields = new List <string>();
                    fields.Add("dev_departairport");
                    fields.Add("dev_arrive1");
                    fields.Add("dev_arrive2");
                    fields.Add("dev_arrive3");
                    fields.Add("dev_arrive4");
                    bool airportChange = false;
                    foreach (KeyValuePair <string, object> item in entity.Attributes)
                    {
                        if (fields.Contains(item.Key))
                        {
                            airportChange = true;
                            break;
                        }
                    }
                    //this keep the plugin code from recalculating data
                    if (!airportChange)
                    {
                        return;
                    }

                    //organizational service reference for web service calls
                    IOrganizationServiceFactory serviceFactory =
                        (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                    TripInfo tripInfo = GetTripInfo(entity.Id, service);

                    string distance1 = "";
                    if (tripInfo.TripLegs >= 1)
                    {
                        double distance = GetDistance(tripInfo.DepartAirport, tripInfo.Arrival1, service);
                        distance1 = Math.Round(distance, 1).ToString() + " NM";
                    }

                    string distance2 = "";
                    if (tripInfo.TripLegs >= 2)
                    {
                        double distance = GetDistance(tripInfo.Arrival1, tripInfo.Arrival2, service);
                        distance2 = Math.Round(distance, 1).ToString() + " NM";
                    }
                    string distance3 = "";
                    if (tripInfo.TripLegs >= 3)
                    {
                        double distance = GetDistance(tripInfo.Arrival2, tripInfo.Arrival3, service);
                        distance3 = Math.Round(distance, 1).ToString() + " NM";
                    }
                    string distance4 = "";
                    if (tripInfo.TripLegs == 4)
                    {
                        double distance = GetDistance(tripInfo.Arrival3, tripInfo.Arrival4, service);
                        distance4 = Math.Round(distance, 1).ToString() + " NM";
                    }

                    Entity updateOpportunity = new Entity("opportunity");
                    updateOpportunity.Id = entity.Id;
                    updateOpportunity.Attributes["dev_distance1"] = distance1;
                    updateOpportunity.Attributes["dev_distance2"] = distance2;
                    updateOpportunity.Attributes["dev_distance3"] = distance3;
                    updateOpportunity.Attributes["dev_distance4"] = distance4;
                    service.Update(updateOpportunity);
                }
            }
            catch (Exception ex)
            {
                tracingService.Trace("Plugin: {0}, Error: {1}", "DistanceCalulator", ex.Message);
            }
        }
Exemple #29
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));

            try
            {
                //Campos  flag
                bool            flagEmail  = false;
                EntityReference customerId = null;

                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    if (context.MessageName == "Update")
                    {
                        Entity entity = (Entity)context.InputParameters["Target"];

                        if (entity.LogicalName != "incident")
                        {
                            return;                                   //Casos
                        }
                        if (entity == null)
                        {
                            return;
                        }

                        if (entity.Attributes.Contains("ust_flagtaskemailnotification") && entity.Attributes["ust_flagtaskemailnotification"] != null)
                        {
                            //flagEmail = entCase.GetAttributeValue<bool>("ust_flagtaskemailnotification");  // obtiene el valor true
                            flagEmail = (bool)entity.Attributes["ust_flagtaskemailnotification"];

                            Entity entCase = service.Retrieve("incident", entity.Id, new ColumnSet("ust_flagtaskemailnotification", "customerid", "amxperu_casetype", "ust_osiptelcomplaintid", "ust_indecopicomplaintid", "ust_osiptelnotificationemail"));

                            if (flagEmail == true)
                            {
                                //crear un actividad de tipo Email.
                                if (entCase.Attributes.Contains("customerid") && entCase.Attributes["customerid"] != null)
                                {
                                    customerId = ((EntityReference)entCase.Attributes["customerid"]);

                                    EntityReference LookUpTypeCase = (EntityReference)entCase.Attributes["amxperu_casetype"];

                                    var TypeCaseLookupId    = LookUpTypeCase.Id;
                                    var TypeCaselogicalName = LookUpTypeCase.LogicalName;

                                    // var Osiptelcomplaintid = entity.GetAttributeValue<String>("ust_osiptelcomplaintid");
                                    // var Indecopicomplaintid = entity.GetAttributeValue<String>("ust_indecopicomplaintid");
                                    string OsiptelNotificationEmail = entCase.Attributes["ust_osiptelnotificationemail"].ToString();
                                    //myTrace.Trace("OsiptelNotificationEmail " + OsiptelNotificationEmail);

                                    // Create the 'From:' activity party for the email
                                    Entity party1 = new Entity("activityparty");
                                    //party1["partyid"] = new EntityReference("contact", customerId.Id);
                                    party1["addressused"] = OsiptelNotificationEmail;

                                    // Create a new EntityCollection and add the 2 parties
                                    EntityCollection to = new EntityCollection();
                                    to.Entities.Add(party1);

                                    // Create an email with the EntityCollection

                                    Entity email = new Entity("email");
                                    email["from"]        = new EntityReference("systemuser", context.UserId);
                                    email["subject"]     = "Email de notificación del " + TypeCaselogicalName + " NRO:XXXXXXX";
                                    email["to"]          = to;
                                    email["description"] = "OK";
                                    email["ust_sendemailnotification"] = true;
                                    email["regardingobjectid"]         = new EntityReference("incident", entity.Id);

                                    email.Id = service.Create(email);

                                    //myTrace.Trace("creo actividad correo" + email.Id);
                                }
                            }
                            //throw new InvalidPluginExecutionException("Mensaje de error. ");
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
Exemple #30
0
        public void Execute(IServiceProvider serviceProvider)
        {
            // Obtain the execution context from the service provider.
            IPluginExecutionContext context =
                (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            // Get a reference to the Organization service.
            IOrganizationServiceFactory factory =
                (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            IOrganizationService service = factory.CreateOrganizationService(context.UserId);

            if (context.Depth > 1)
            {
                return;
            }
            // 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"];

                if (entity.LogicalName == Constant.EntityName)
                {
                    try
                    {
                        // get the Account latest number from counter entity record
                        Entity CounterEntity  = GetLatestAccountNumber(service);
                        int    sequenceNumber = (int)CounterEntity["rel_sequencenumber"];
                        int    incrementVal   = (int)CounterEntity["rel_increment"];
                        if (sequenceNumber == 0)
                        {
                            int totAccount = GetTotalAccountCount(service);
                            tracingService.Trace("accountPlugin: {0}", totAccount.ToString());
                            entity.Attributes["rel_totalaccounts"] = totAccount + incrementVal; // assign value in total account counts
                            CounterEntity["rel_sequencenumber"]    = totAccount + incrementVal;
                            tracingService.Trace("Account number updated when sequence is 0");
                        }
                        else
                        {
                            tracingService.Trace("accountPlugin: {0}", sequenceNumber.ToString());
                            entity.Attributes["rel_totalaccounts"] = sequenceNumber + incrementVal;
                            CounterEntity["rel_sequencenumber"]    = sequenceNumber + incrementVal;;
                            tracingService.Trace("Account number updated when sequence is greater than 0");
                        }
                        service.Update(CounterEntity);
                    }
                    catch (Exception ex)
                    {
                        tracingService.Trace("Plugin Exception: " + ex);
                        throw new InvalidPluginExecutionException(ex.ToString());
                    }
                }
                else
                {
                    return;
                }
            }
        }
Exemple #31
0
        /// <summary>
        /// Executes the workflow activity.
        /// </summary>
        /// <param name="executionContext">The execution context.</param>
        protected override void Execute(CodeActivityContext executionContext)
        {
            // Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

            if (tracingService == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve tracing service.");
            }

            tracingService.Trace("Entered " + _processName + ".Execute(), Activity Instance Id: {0}, Workflow Instance Id: {1}",
                                 executionContext.ActivityInstanceId,
                                 executionContext.WorkflowInstanceId);

            // Create the context
            IWorkflowContext context = executionContext.GetExtension <IWorkflowContext>();

            if (context == null)
            {
                throw new InvalidPluginExecutionException("Failed to retrieve workflow context.");
            }

            tracingService.Trace(_processName + ".Execute(), Correlation Id: {0}, Initiating User: {1}",
                                 context.CorrelationId,
                                 context.InitiatingUserId);

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

            try
            {
                string keyName = KeyName.Get(executionContext);

                //look up team template by name
                QueryByAttribute querybyexpression = new QueryByAttribute("new_keyvaluepair");
                querybyexpression.ColumnSet = new ColumnSet("new_name",
                                                            "new_stringvalue",
                                                            "new_decimalvalue",
                                                            "new_integervalue",
                                                            "new_datevalue",
                                                            "new_dateandtimevalue",
                                                            "new_valuetype"
                                                            );
                querybyexpression.Attributes.AddRange("new_name");
                querybyexpression.Values.AddRange(keyName);
                EntityCollection retrieved = service.RetrieveMultiple(querybyexpression);

                //if we find something, we're set
                if (retrieved.Entities.Count > 0)
                {
                    Entity kvp = retrieved.Entities[0];
                    StringValue.Set(executionContext, (string)kvp["new_stringvalue"]);
                    IntegerValue.Set(executionContext, (int)kvp["new_integervalue"]);
                    DecimalValue.Set(executionContext, (decimal)kvp["new_decimalvalue"]);
                    DateValue.Set(executionContext, (DateTime)kvp["new_datevalue"]);
                    DateTimeValue.Set(executionContext, (DateTime)kvp["new_dateandtimevalue"]);
                }
                else
                {
                    //throw exception if unable to find a matching template
                    throw new Exception("could not find key-value pair for: " + keyName);
                }
            }
            catch (FaultException <OrganizationServiceFault> e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());

                // Handle the exception.
                throw;
            }
            catch (Exception e)
            {
                tracingService.Trace("Exception: {0}", e.ToString());
                throw;
            }

            tracingService.Trace("Exiting " + _processName + ".Execute(), Correlation Id: {0}", context.CorrelationId);
        }