/// <summary>
 /// Initializes a new instance of class PluginServices
 /// </summary>
 /// <param name="serviceProvider">Service provider</param>
 public PluginServices(IServiceProvider serviceProvider)
 {
     // Instanciation des services
     _executionContext = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
     _serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
     _tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
 }
Example #2
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>();
        }
Example #3
0
        public static IOrganizationService CreateOrganizationService(this IServiceProvider serviceProvider, Guid?userId)
        {
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));

            return(serviceFactory.CreateOrganizationService(userId));
        }
Example #4
0
        private static bool BusinessLogic(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

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


            // ensure we have something to look at

            // var guid = (Guid)context.OutputParameters["id"];
            //#region License Validation
            //OrganizationRequest Req = new OrganizationRequest("hdn_ValidateLicense");
            //Req["ProductName"] = "BareBonesSalesCore"; //pass in the Solution Name
            //OrganizationResponse Response = service.Execute(Req);
            //if (Response.Results.ContainsKey("IsValid") && Response.Results["IsValid"].ToString() != "True")
            //{
            //    throw new InvalidPluginExecutionException("The license for BareBones Sales Core is invalid");
            //}
            //#endregion

            if (context.PrimaryEntityName != "hdn_opportunityclose")
            {
                tracingService.Trace("primary entity isn't Opportunity Close");
                return(true);
            }

            tracingService.Trace(context.PrimaryEntityId.ToString());
            var targetEntity = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet("hdn_opportunity", "hdn_closurereason", "hdn_closedate"));

            // resolved cases can only be closed by creating a resolved case record. This sets the status and adds a link to the resolution record.

            if (!targetEntity.Contains("hdn_closurereason"))
            {
                throw new InvalidPluginExecutionException(OperationStatus.Failed, 10, "Opportunity cannot be closed");
            }
            if (!targetEntity.Contains("hdn_opportunity"))
            {
                throw new InvalidPluginExecutionException(OperationStatus.Failed, 10, "Opportunity not specified be closed");
            }

            var    oppId     = targetEntity.GetAttributeValue <EntityReference>("hdn_opportunity");
            Entity closedOpp = new Entity(oppId.LogicalName, oppId.Id);

            closedOpp.Attributes.Add("statecode", new OptionSetValue(1));
            var statuscode = targetEntity.GetAttributeValue <OptionSetValue>("hdn_closurereason").Value;

            tracingService.Trace(statuscode.ToString());
            closedOpp.Attributes.Add("statuscode", targetEntity.GetAttributeValue <OptionSetValue>("hdn_closurereason"));
            closedOpp.Attributes.Add("hdn_opportunityclose", new EntityReference(context.PrimaryEntityName, context.PrimaryEntityId));
            if (targetEntity.Contains("hdn_closedate"))
            {
                closedOpp.Attributes.Add("hdn_actualclosedate", targetEntity.GetAttributeValue <DateTime>("hdn_closedate"));
            }
            service.Update(closedOpp);
            return(true);
        }
Example #5
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"];

                #region | SET TITLECASE |
                if (entity.Attributes.Contains("firstname") && !string.IsNullOrEmpty(entity["firstname"].ToString()))
                {
                    entity["firstname"] = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(entity["firstname"].ToString().ToLower());
                }
                if (entity.Attributes.Contains("lastname") && !string.IsNullOrEmpty(entity["lastname"].ToString()))
                {
                    entity["lastname"] = CultureInfo.CurrentCulture.TextInfo.ToTitleCase(entity["lastname"].ToString().ToLower());
                }
                #endregion

                #region | CHECK DUPLICATE |
                if (entity.Attributes.Contains("new_tcidentitynumber"))
                {
                    if (entity["new_tcidentitynumber"] != null)
                    {
                        string oldIdentity    = preImage.Attributes.Contains("new_tcidentitynumber") ? preImage["new_tcidentitynumber"].ToString() : string.Empty;
                        string identityNumber = entity["new_tcidentitynumber"].ToString();

                        if (identityNumber != oldIdentity)
                        {
                            MsCrmResult identityResult = ContactHelper.CheckDuplicateIdentity(identityNumber, sda);
                            if (!identityResult.Success)
                            {
                                throw new Exception(identityResult.Result);
                            }
                        }
                    }
                }

                if (entity.Attributes.Contains("emailaddress1"))
                {
                    if (entity["emailaddress1"] != null)
                    {
                        string oldMail = preImage.Attributes.Contains("emailaddress1") ? preImage["emailaddress1"].ToString() : string.Empty;
                        string email   = entity["emailaddress1"].ToString();

                        if (email != oldMail)
                        {
                            MsCrmResult emailResult = ContactHelper.CheckDuplicateEmail(email, sda);
                            if (!emailResult.Success)
                            {
                                throw new Exception(emailResult.Result);
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Email adresi boş bırakılamaz!");
                    }
                }

                if (entity.Attributes.Contains("mobilephone"))
                {
                    if (entity["mobilephone"] != null)
                    {
                        string oldPhone    = preImage.Attributes.Contains("mobilephone") ? preImage["mobilephone"].ToString() : string.Empty;
                        string mobilePhone = entity["mobilephone"].ToString();

                        if (oldPhone != mobilePhone)
                        {
                            MsCrmResult phoneResult = ContactHelper.CheckDuplicatePhone(mobilePhone, sda);
                            if (!phoneResult.Success)
                            {
                                throw new Exception(phoneResult.Result);
                            }

                            TelephoneNumber number = GeneralHelper.CheckTelephoneNumber(mobilePhone);
                            if (number.isFormatOK)
                            {
                                entity["new_countrycodemobilephone"] = number.countryCode;
                                entity["new_cellphonenumber"]        = number.phoneNo;
                            }
                            else
                            {
                                throw new Exception("Lütfen doğru bir telefon giriniz!");
                            }
                        }
                    }
                    else
                    {
                        throw new Exception("Cep Telefonu boş bırakılamaz!");
                    }
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
Example #6
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);

            tracingService.Trace("{0}{1}", "Start Custom Workflow Activity: CheckPRFSSurroundingSchools", DateTime.Now.ToLongTimeString());

            var recordId = context.PrimaryEntityId;

            var projectRequestRecord = service.Retrieve(context.PrimaryEntityName, recordId, new ColumnSet("caps_municipalrequirements", "caps_submissioncategorycode")) as caps_Project;

            EntityReference capitalPlanReference = this.capitalPlan.Get(executionContext);

            var capitalPlan = service.Retrieve(capitalPlanReference.LogicalName, capitalPlanReference.Id, new ColumnSet("caps_callforsubmission")) as caps_Submission;

            var callForSubmission = service.Retrieve(capitalPlan.caps_CallforSubmission.LogicalName, capitalPlan.caps_CallforSubmission.Id, new ColumnSet("caps_capitalplanyear")) as caps_CallForSubmission;

            var capitalPlanYear = service.Retrieve(callForSubmission.caps_CapitalPlanYear.LogicalName, callForSubmission.caps_CapitalPlanYear.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("edu_startyear")) as edu_Year;

            var startYear = capitalPlanYear.edu_StartYear.Value;

            var fetchXML = "<fetch version = '1.0' output-format = 'xml-platform' mapping = 'logical' distinct = 'false' >" +
                           "<entity name = 'caps_estimatedyearlycapitalexpenditure' >" +
                           "<attribute name = 'caps_estimatedyearlycapitalexpenditureid' />" +
                           "<attribute name = 'caps_name' />" +
                           "<attribute name = 'createdon' />" +
                           "<order attribute = 'caps_name' descending = 'false' />" +
                           "<filter type = 'and' >" +
                           "<condition attribute = 'statecode' operator= 'eq' value = '0' />" +
                           "<condition attribute = 'caps_project' operator= 'eq' value = '{" + recordId + "}' />" +
                           "<condition attribute = 'caps_yearlyexpenditure' operator='not-null' />" +
                           "<condition attribute = 'caps_yearlyexpenditure' operator='gt' value='0' />" +
                           "</filter>" +
                           "<link-entity name='edu_year' from='edu_yearid' to='caps_year' link-type='inner' alias='ad' >" +
                           "<filter type = 'and' >" +
                           "<condition attribute = 'edu_startyear' operator= 'ge' value='" + startYear + "' />" +
                           "<condition attribute = 'edu_startyear' operator= 'le' value = '" + (startYear + 2) + "' />" +
                           "<condition attribute = 'edu_type' operator= 'eq' value = '757500000' />" +
                           "</filter></link-entity></entity></fetch>";

            tracingService.Trace("{0}", "Calling Fetch");
            //Find out if there is cash flow in any of those 5 years
            var estimatedExpenditures = service.RetrieveMultiple(new FetchExpression(fetchXML));

            if (estimatedExpenditures.Entities.Count() > 0 || projectRequestRecord.caps_SubmissionCategoryCode == "LEASE")
            {
                //check if there is at least one alternative option
                var fetchAlterativeOptions = "<fetch version=\"1.0\" output-format=\"xml-platform\" mapping=\"logical\" distinct=\"false\">" +
                                             "<entity name=\"caps_prfsalternativeoption\" > " +
                                             "<attribute name = \"caps_prfsalternativeoptionid\" /> " +
                                             "<attribute name = \"caps_name\" /> " +
                                             "<attribute name = \"createdon\" /> " +
                                             "<order attribute = \"caps_name\" descending = \"false\" /> " +
                                             "<filter type = \"and\" > " +
                                             "<condition attribute = 'statecode' operator= 'eq' value = '0' />" +
                                             "<condition attribute = \"caps_projectrequest\" operator= \"eq\" value = \"{" + recordId + "}\" /> " +
                                             "</filter>" +
                                             "</entity> " +
                                             "</fetch>";

                tracingService.Trace("Fetch: {0}", fetchAlterativeOptions);

                var alternativeOptions = service.RetrieveMultiple(new FetchExpression(fetchAlterativeOptions));

                if (alternativeOptions.Entities.Count() > 0)
                {
                    tracingService.Trace("{0}", "Alternative Options records found");
                    this.displayError.Set(executionContext, false);
                }
                else
                {
                    tracingService.Trace("{0}", "No Alternative Options records found");
                    this.displayError.Set(executionContext, true);
                }
            }
            else
            {
                tracingService.Trace("{0}", "No cashflow in the first 3 years");
                this.displayError.Set(executionContext, false);
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            _assemblyTypeName = this.GetType().AssemblyQualifiedName;
            _tracingService   = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            var context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

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

            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {
                // Obtain the target entity from the input parameters.
                Entity targetEntity = (Entity)context.InputParameters["Target"];

                // Verify that the target entity represents an account.
                // If not, this plug-in was not registered correctly.
                if (targetEntity.LogicalName != "defra_lobserviceuserlink")
                {
                    return;
                }
                try
                {
                    if (targetEntity.Attributes.Contains("defra_servicerole") && targetEntity.Attributes["defra_servicerole"] != null)
                    {
                        EntityReference serviceRoleEntityRef = (EntityReference)targetEntity.Attributes["defra_servicerole"];
                        QueryExpression serviceQuery         = new QueryExpression("defra_lobservice");
                        serviceQuery.Criteria.AddCondition(new ConditionExpression("statecode", ConditionOperator.Equal, 0));
                        // take all columns
                        serviceQuery.ColumnSet = new ColumnSet(true);
                        // this is the intersect condition
                        LinkEntity serviceLink = new LinkEntity("defra_lobservice", "defra_lobserivcerole", "defra_lobserviceid", "defra_lobservice", JoinOperator.Inner);
                        // this is the condition to use the specific Team
                        ConditionExpression queryCondition  = new ConditionExpression("defra_lobserivceroleid", ConditionOperator.Equal, serviceRoleEntityRef.Id);
                        ConditionExpression queryCondition1 = new ConditionExpression("statecode", ConditionOperator.Equal, 0);
                        // add the condition to the intersect
                        serviceLink.LinkCriteria.AddCondition(queryCondition);
                        serviceLink.LinkCriteria.AddCondition(queryCondition1);
                        // add the intersect to the query
                        serviceQuery.LinkEntities.Add(serviceLink);

                        //get the results
                        EntityCollection retrievedServices = service.RetrieveMultiple(serviceQuery);
                        _tracingService.Trace("services record count" + retrievedServices.Entities.Count);
                        if (retrievedServices.Entities.Count > 0)
                        {
                            Entity serviceEntity = retrievedServices.Entities[0];
                            if (serviceEntity.Attributes.Contains("defra_ownerbu") && serviceEntity.Attributes["defra_ownerbu"] != null)
                            {
                                EntityReference serviceBusinessUnit = (EntityReference)serviceEntity.Attributes["defra_ownerbu"];
                                if (serviceBusinessUnit != null)
                                {
                                    string ownerBusinessUnitName = serviceBusinessUnit.Name;
                                    _tracingService.Trace("Service Business Unit Name" + ownerBusinessUnitName);
                                    string ownerTeam = ownerBusinessUnitName + "-CM-OWNER";
                                    _tracingService.Trace("Service Business Unit Owner team" + ownerTeam);
                                    QueryExpression teamQuery = new QueryExpression("team");
                                    teamQuery.ColumnSet = new ColumnSet(true);
                                    teamQuery.Criteria.AddCondition("name", ConditionOperator.Equal, ownerTeam);

                                    EntityCollection entities   = service.RetrieveMultiple(teamQuery);
                                    Entity           teamEntity = entities.Entities.Count > 0 ? entities[0] : null;

                                    if (teamEntity != null)
                                    {
                                        _tracingService.Trace("Enrloment Owner Team ID:" + teamEntity.Id);
                                        //Share the contact record
                                        if (targetEntity.Attributes.Contains("defra_serviceuser") && targetEntity.Attributes["defra_serviceuser"] != null)
                                        {
                                            EntityReference serviceUser = (EntityReference)targetEntity.Attributes["defra_serviceuser"];
                                            ShareRecord(teamEntity.Id, serviceUser);
                                        }

                                        //Assign the ownership
                                        SetRecordOwner(teamEntity.Id, targetEntity);
                                    }
                                }
                            }
                        }
                    }
                }

                // Catch any service fault exceptions that Microsoft Dynamics CRM throws.
                catch (FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
                {
                    // You can handle an exception here or pass it back to the calling method.
                    throw ex;
                }
            }
        }
Example #8
0
 public void StartService()
 {
     factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
     service = factory.CreateOrganizationService(context.UserId);
 }
 /// <summary>
 /// Enables proxy types for a workflow IOrganizationServiceFactory.
 /// </summary>
 /// <param name="serviceFactory">The service factory.</param>
 public static void EnableWorkflowProxyTypes(IOrganizationServiceFactory serviceFactory)
 {
     var type = Type.GetType("Microsoft.Crm.Workflow.SynchronousRuntime.WorkflowContext, Microsoft.Crm.Workflow, Version=5.0.0.0");
     type.GetProperty("ProxyTypesAssembly").SetValue(serviceFactory, GetEarlyBoundProxyAssembly(), null);
 }
Example #10
0
        public void Execute(IServiceProvider serviceProvider)
        {
            #region Setup
            tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            service        = serviceFactory.CreateOrganizationService(context.UserId);
            #endregion

            if (context.InputParameters.Equals(null))
            {
                return;
            }
            try
            {
                string bidSheetId    = context.InputParameters["bidSheetId"].ToString();
                var    opportunityId = context.InputParameters["opportunityId"].ToString();
                if (opportunityId.Equals("") || opportunityId.Equals(null) || bidSheetId.Equals("") || bidSheetId.Equals(null))
                {
                    return;
                }

                //Nazish - Fetching all products which are associated to Bill of Material
                var fetchData = new
                {
                    ig1_bidsheet = bidSheetId
                };
                var fetchXmlBOMProducts          = $@"
                                <fetch>
                                  <entity name='product'>
                                    <attribute name='defaultuomid' />
                                    <attribute name='productid' />
                                    <attribute name='name' />
                                    <link-entity name='ig1_bidsheetpricelistitem' from='ig1_product' to='productid'>
                                      <attribute name='ig1_materialcost' alias='materialCost'/>
                                      <attribute name='ig1_sdt' alias='sdt'/>
                                      <filter type='and'>
                                        <condition attribute='ig1_bidsheet' operator='eq' value='{fetchData.ig1_bidsheet}'/>
                                      </filter>
                                      <link-entity name='ig1_associatedcost' from='ig1_bidsheetcategory' to='ig1_category' link-type='outer'>
                                        <attribute name='ig1_margin' alias='margin'/>
                                        <filter type='and'>
                                          <condition attribute='ig1_bidsheet' operator='eq' value='{fetchData.ig1_bidsheet}'/>
                                        </filter>
                                      </link-entity>
                                    </link-entity>
                                  </entity>
                                </fetch>";
                EntityCollection BOMProductsData = service.RetrieveMultiple(new FetchExpression(fetchXmlBOMProducts));
                var unitId = new Guid();
                if (BOMProductsData.Entities.Count > 0)
                {
                    foreach (var item in BOMProductsData.Entities)
                    {
                        var productId         = new Guid();
                        var materialCost      = new Money(0);
                        var totalMaterialCost = new Money(0);
                        var margin            = new decimal(0);

                        if (item.Attributes.Contains("productid"))
                        {
                            productId = (Guid)item.Attributes["productid"];
                        }
                        if (item.Attributes.Contains("defaultuomid"))
                        {
                            var unit = (EntityReference)item.Attributes["defaultuomid"];
                            unitId = (Guid)unit.Id;
                        }
                        if (item.Attributes.Contains("materialCost"))
                        {
                            materialCost = (Money)((AliasedValue)item.Attributes["materialCost"]).Value;
                        }
                        if (item.Attributes.Contains("margin"))
                        {
                            margin = (decimal)((AliasedValue)item.Attributes["margin"]).Value;
                        }
                        if (margin > 0)
                        {
                            totalMaterialCost = new Money(materialCost.Value / (1 - margin / 100));
                        }
                        else
                        {
                            totalMaterialCost = new Money(materialCost.Value);
                        }
                        if (item.KeyAttributes.Contains("sdt"))
                        {
                            totalMaterialCost = new Money((decimal)totalMaterialCost.Value + (decimal)((AliasedValue)item.Attributes["sdt"]).Value);
                        }
                        CreatePriceListItem(opportunityId, productId, unitId, totalMaterialCost);
                        CreateOpportunityLine(productId, opportunityId, unitId);
                    }
                }
                //CreateProjectCostAllowancesPriceListItem(opportunityId, unitId, bidSheetId);
                //CreateProjectCostAllowancesOpportunityLine(opportunityId, unitId);
            }
            catch (Exception ex)
            {
                Entity errorLog = new Entity("ig1_pluginserrorlogs");
                errorLog["ig1_name"]             = "Error";
                errorLog["ig1_errormessage"]     = ex.Message;
                errorLog["ig1_errordescription"] = ex.InnerException;
                service.Create(errorLog);
                throw;
            }
        }
Example #11
0
        private static bool BusinessLogic(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

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

            tracingService.Trace(context.OrganizationName);

            // Call LicensePower Validation code
            //#region License Validation
            //OrganizationRequest Req = new OrganizationRequest("hdn_ValidateLicense");
            //Req["ProductName"]="BareBonesServiceCore"; //pass in the Solution Name
            //OrganizationResponse Response = service.Execute(Req);
            //if (Response.Results.ContainsKey("IsValid") && Response.Results["IsValid"].ToString() != "True")
            //{
            //    throw new InvalidPluginExecutionException("The license for BareBones Service Core is invalid");
            //}
            //#endregion


            if (context.PrimaryEntityName != "hdn_case")
            {
                tracingService.Trace("primary entity isn't case");
                return(true);
            }
            // this runs after case creation as we cannot reassign the case before creating it.
            // so we need to pull information back.
            var targetEntity = service.Retrieve(context.PrimaryEntityName, context.PrimaryEntityId, new ColumnSet("hdn_parentcasetype", "hdn_childcasetype", "hdn_customer"));


            EntityReference caseTypeId = null;

            if (targetEntity.Contains("hdn_customer"))
            {
            }
            if (targetEntity.Contains("hdn_parentcasetype"))
            {
                caseTypeId = targetEntity.GetAttributeValue <EntityReference>("hdnm_parentcasetype");
            }
            if (targetEntity.Contains("hdn_childcasetype"))
            {
                if (targetEntity.GetAttributeValue <EntityReference>("hdn_childcasetype") != null)
                {
                    caseTypeId = targetEntity.GetAttributeValue <EntityReference>("hdn_childcasetype");
                }
            }



            bool needToUpdate  = false;
            var  updateEntity  = new Entity(context.PrimaryEntityName, context.PrimaryEntityId);
            int  priorityValue = -1;


            #region Update Owner / prioity flag based on case type.
            if (caseTypeId != null)
            {
                needToUpdate = true;
                updateEntity.Attributes["hdn_casetype"] = caseTypeId;
                var caseType = service.Retrieve(caseTypeId.LogicalName, caseTypeId.Id, new ColumnSet("hdn_priority", "hdn_responsetime", "hdn_reassign", "ownerid"));
                if (caseType.Contains("hdn_reassign") && caseType.GetAttributeValue <bool>("hdn_reassign"))
                {
                    EntityReference caseOwner = caseType.GetAttributeValue <EntityReference>("ownerid");
                    updateEntity.Attributes["ownerid"] = caseOwner;
                }
                else
                {
                    //
                    if (targetEntity.Contains("hdn_customer"))
                    {
                        var customerOwner = AutoSetOwner.GetCustomerOwner(service, tracingService, targetEntity.GetAttributeValue <EntityReference>("hdn_customer"));
                        if (customerOwner != null)
                        {
                            updateEntity.Attributes["ownerid"] = customerOwner;
                        }
                    }
                }
                if (caseType.Contains("hdn_priority"))
                {
                    priorityValue = caseType.GetAttributeValue <OptionSetValue>("hdn_priority").Value;
                    updateEntity.Attributes["hdn_priority"] = caseType.GetAttributeValue <OptionSetValue>("hdn_priority");
                }
            }
            #endregion
            if (priorityValue > 0)
            {
                var date = DueDate.SetNewDeadline(service, tracingService, priorityValue, DateTime.Now, null, false);
                if (date != null)
                {
                    updateEntity.Attributes.Add("hdn_duedate", date);
                    needToUpdate = true;
                }
            }
            if (needToUpdate)
            {
                service.Update(updateEntity);
            }
            return(true);
        }
Example #12
0
        private ParameterCollection ExecuteCustomAction(IPluginExecutionContext context, IOrganizationServiceFactory serviceFactory, IOrganizationService service, ITracingService tracing)
        {
            var outputs = new ParameterCollection();

            //YOUR CUSTOM ACTION BEGIN HERE

            return(outputs);
        }
Example #13
0
        public void Execute(IServiceProvider serviceProvider)
        {
            SqlDataAccess sda = null;


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

                #region | Service |
                if (serviceProvider == null)
                {
                    throw new ArgumentNullException("serviceProvider");
                }

                IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(Globals.AdministratorId);
                OrganizationServiceContext  orgContext     = new OrganizationServiceContext(service);

                #endregion

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

                    Guid projectId     = entity.Contains("new_projectid") ? ((EntityReference)entity.Attributes["new_projectid"]).Id : Guid.Empty;
                    Guid phoneCallId   = entity.Contains("new_phonecallid") ? ((EntityReference)entity.Attributes["new_phonecallid"]).Id : Guid.Empty;
                    Guid appointmentId = entity.Contains("new_appointmentid") ? ((EntityReference)entity.Attributes["new_appointmentid"]).Id : Guid.Empty;
                    if (projectId == Guid.Empty)
                    {
                        return;
                    }
                    if (phoneCallId == Guid.Empty && appointmentId == Guid.Empty)
                    {
                        return;
                    }

                    #region | GET CONTACT |
                    ConditionExpression con1 = new ConditionExpression();
                    con1.AttributeName = "activityid";
                    con1.Operator      = ConditionOperator.Equal;
                    if (appointmentId != Guid.Empty)
                    {
                        con1.Values.Add(appointmentId);
                    }
                    else if (phoneCallId != Guid.Empty)
                    {
                        con1.Values.Add(phoneCallId);
                    }

                    ConditionExpression con2 = new ConditionExpression();
                    con2.AttributeName = "partyobjecttypecode";
                    con2.Operator      = ConditionOperator.Equal;
                    con2.Values.Add(2);//Contact

                    FilterExpression filter = new FilterExpression();
                    filter.FilterOperator = LogicalOperator.And;
                    filter.Conditions.Add(con1);
                    filter.Conditions.Add(con2);

                    QueryExpression Query = new QueryExpression("activityparty");
                    Query.ColumnSet = new ColumnSet("partyid");
                    Query.Criteria.FilterOperator = LogicalOperator.And;
                    Query.Criteria.Filters.Add(filter);
                    EntityCollection Result = service.RetrieveMultiple(Query);
                    #endregion

                    #region | ASSOCIATE |
                    if (Result.Entities.Count > 0)
                    {
                        EntityReference contact = (EntityReference)Result.Entities[0].Attributes["partyid"];

                        MsCrmResult contactHasThisProject = InterestedProjectHelper.ContactHasThisProject(contact.Id, projectId, sda);

                        if (!contactHasThisProject.Success)
                        {
                            EntityReferenceCollection relatedEntities = new EntityReferenceCollection();
                            relatedEntities.Add(contact);

                            // Add the Account Contact relationship schema name
                            Relationship relationship = new Relationship("new_contact_new_project");

                            // Associate the contact record to Account
                            service.Associate("new_project", projectId, relationship, relatedEntities);
                        }
                    }
                    else
                    {
                        return;
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                throw new InvalidPluginExecutionException(ex.Message);
            }
            finally
            {
                if (sda != null)
                {
                    sda.closeConnection();
                }
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Email       = EmailId.Get(executionContext);
            EntityReference Attachment  = AttachmentId.Get(executionContext);

            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", LogFilePath);
                }

                // Create a CRM Service in Workflow.
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

                if (Logging)
                {
                    Log("Retrieving Attahment", LogFilePath);
                }

                // Retrieve the Attachment from the given template.
                Entity TempAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(true));
                if (TempAttachment != null)
                {
                    if (Logging)
                    {
                        Log("Creating New Attachment", LogFilePath);
                    }

                    // Create new Attachment under Email Activity.
                    Entity NewAttachment = new Entity("activitymimeattachment");
                    if (TempAttachment.Contains("subject"))
                    {
                        NewAttachment.Attributes.Add("subject", TempAttachment["subject"]);
                    }
                    if (TempAttachment.Contains("filename"))
                    {
                        NewAttachment.Attributes.Add("filename", TempAttachment["filename"]);
                    }
                    if (TempAttachment.Contains("mimetype"))
                    {
                        NewAttachment.Attributes.Add("mimetype", TempAttachment["mimetype"]);
                    }
                    if (TempAttachment.Contains("documentbody"))
                    {
                        NewAttachment.Attributes.Add("body", TempAttachment["documentbody"]);
                    }
                    NewAttachment.Attributes.Add("objectid", new EntityReference(Email.LogicalName, Email.Id));
                    NewAttachment.Attributes.Add("objecttypecode", "email");
                    NewAttachment.Attributes.Add("attachmentnumber", 1);
                    service.Create(NewAttachment);

                    if (Logging)
                    {
                        Log("New Attachment Added To Email", LogFilePath);
                    }
                }
                else
                {
                    if (Logging)
                    {
                        Log("Temp Attachment does not exist", LogFilePath);
                    }
                }
                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
Example #15
0
 private async System.Threading.Tasks.Task initfunc()
 {
     context = (IPluginExecutionContext)Provider.GetService(typeof(IPluginExecutionContext));
     factory = (IOrganizationServiceFactory)Provider.GetService(typeof(IOrganizationServiceFactory));
     service = factory.CreateOrganizationService(context.UserId);
 }
Example #16
0
 public void Check_Service_Type(IOrganizationServiceFactory factory, InstanceType expected)
 {
     // Assert
     ((CuteFactory)factory).Provider.Type.Should().Be(expected);
 }
        /// <summary>
        /// A plug-in that creates a fallow up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plugin- on the create message, account entity
        /// and asynchronous mode</remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));

            tracingService.Trace("FollowupPlugin  Tracing Strated At \t" + DateTime.Now.ToString("yyyy-MM-dd h:mm:ss tt"));
            //Obtain the execution context from the service provider.
            IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));

            // the input parameters 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"];
                tracingService.Trace("entity.LogicalName \t" + entity.LogicalName);

                //Verify that the target entity represents an account.
                //If not, this plug-in was not registred correctly.
                if (entity.LogicalName != "account")
                {
                    return;
                }
                try
                {
                    // 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." + entity.LogicalName;
                    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);
                    tracingService.Trace("DateTime.Now.AddDays(7)" + DateTime.Now.AddDays(7));

                    tracingService.Trace(context.PrimaryEntityName + "context.PrimaryEntityName");
                    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());
                        tracingService.Trace("context.OutputParameters['id'].ToString() \t" + context.OutputParameters["id"].ToString());

                        string regardingobjectidType = context.PrimaryEntityName.ToString();

                        tracingService.Trace("context.PrimaryEntityName;\t" + context.PrimaryEntityName);

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

                    //Obtain the organization service refrence.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                    service.Create(followup);
                    tracingService.Trace("Task Created Successfully");
                }
                catch (FaultException <OrganizationServiceFault> ex)
                {
                    throw new InvalidPluginExecutionException("An error occurred in the FollowupPlugin plug-in.", ex);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Folloup Plugin: {0}", ex.ToString());
                    throw;
                }
            }
            tracingService.Trace("FollowupPlugin  Tracing END At \t" + DateTime.Now.ToString("yyyy-MM-dd h:mm:ss tt"));
        }
        // Si la actividad devuelve un valor, se debe derivar de CodeActivity<TResult>
        // y devolver el valor desde el método Execute.
        protected override void Execute(CodeActivityContext executionContext)
        {
            //Create the tracing service
            ITracingService tracingService = executionContext.GetExtension <ITracingService>();

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

            try
            {
                EntityReference erCaseType = CaseType.Get <EntityReference>(executionContext);

                // Obtain la entidad con los cambios
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    // GUID of target record (case)
                    Guid   gCaseId  = context.PrimaryEntityId;
                    string typeCase = erCaseType.Name;
                    string CaseType = "";

                    if (erCaseType != null)
                    {
                        typeCase = erCaseType.Name;
                    }

                    //Create the phase vars
                    int comPhaseCod = 0;

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

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

                    EntityReference erTipoCaso = null;

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

                    if (dataCase.Attributes.Contains("ust_complaintphase") && dataCase.Attributes["ust_complaintphase"] != null)
                    {
                        //Get the SAR  response
                        comPhaseCod = ((OptionSetValue)dataCase.Attributes["ust_complaintphase"]).Value;
                    }

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

                    if (caseType.Attributes.Contains("ust_code") && caseType.Attributes["ust_code"] != null)
                    {
                        //Get the Case Type Code
                        CaseType = caseType.Attributes["ust_code"].ToString();

                        if (CaseType == "004" && comPhaseCod == 864340000) //RECLAMO OSIPTEL
                        {
                            comPhaseCod = 864340001;                       //1st Instance
                        }

                        //Procedemos a actualizar el complaint phase.
                        UpdateStatusCode(gCaseId, comPhaseCod, service);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            tracing        = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            service        = serviceFactory.CreateOrganizationService(null);
            try
            {
                if (!context.InputParameters.Contains("Target") || !(context.InputParameters["Target"] is Entity))
                {
                    return;
                }
                var entity = (Entity)context.InputParameters["Target"];
                if (entity.LogicalName == "ig1_projectrecordcost")
                {
                    if ((entity.Attributes.Contains("ig1_actualdate") && !string.IsNullOrEmpty(entity.Attributes["ig1_actualdate"].ToString())) ||
                        (entity.Attributes.Contains("ig1_costtype") && !string.IsNullOrEmpty(entity.Attributes["ig1_costtype"].ToString())))
                    {
                        Entity actualCost = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("ig1_name"));
                        if (entity.Attributes.Contains("ig1_actualdate") && !string.IsNullOrEmpty(entity.Attributes["ig1_actualdate"].ToString()))
                        {
                            actualCost.Attributes["ig1_date"] = Convert.ToDateTime(entity.Attributes["ig1_actualdate"]);
                        }
                        if (entity.Attributes.Contains("ig1_name") && !string.IsNullOrEmpty(entity.Attributes["ig1_name"].ToString()))
                        {
                            Guid projectRecord = Guid.Empty;
                            projectRecord = GetProjectRecord(entity.Attributes["ig1_name"].ToString());
                            if (projectRecord != Guid.Empty)
                            {
                                actualCost.Attributes["ig1_projectrecord"] = new EntityReference("ig1_projectrecord", projectRecord);
                            }
                        }
                        if (entity.Attributes.Contains("ig1_costtype") && !string.IsNullOrEmpty(entity.Attributes["ig1_costtype"].ToString()))
                        {
                            Guid   expenseType = Guid.Empty;
                            string type        = entity.Attributes["ig1_costtype"].ToString();
                            if (type != "Sales Cost" && type != "Design Cost" && type != "PM Cost")
                            {
                                expenseType = GetExpenseType("Installer Cost");
                            }
                            else
                            {
                                expenseType = GetExpenseType(type);
                            }
                            if (expenseType != Guid.Empty)
                            {
                                actualCost.Attributes["ig1_expensetype"] = new EntityReference("ig1_expensecategories", expenseType);
                            }
                        }
                        service.Update(actualCost);
                    }
                }
                else if (entity.LogicalName == "ig1_projectrecordhours")
                {
                    if (entity.Attributes.Contains("ig1_actualdate") && !string.IsNullOrEmpty(entity.Attributes["ig1_actualdate"].ToString()))
                    {
                        var actualHours = service.Retrieve(entity.LogicalName, entity.Id, new ColumnSet("ig1_name"));
                        actualHours.Attributes["ig1_date"] = Convert.ToDateTime(entity.Attributes["ig1_actualdate"].ToString());

                        if (entity.Attributes.Contains("ig1_name") && !string.IsNullOrEmpty(entity.Attributes["ig1_name"].ToString()))
                        {
                            Guid projectRecord = Guid.Empty;
                            projectRecord = GetProjectRecord(entity.Attributes["ig1_name"].ToString());
                            if (projectRecord != Guid.Empty)
                            {
                                actualHours.Attributes["ig1_projectrecord"] = new EntityReference("ig1_projectrecord", projectRecord);
                            }
                        }
                        service.Update(actualHours);
                    }
                }
                else if (entity.LogicalName == "ig1_projectrecord")
                {
                    if (entity.Attributes.Contains("ig1_projectnumber") && !string.IsNullOrEmpty(entity.Attributes["ig1_projectnumber"].ToString()))
                    {
                        string projectNumber = entity.Attributes["ig1_projectnumber"].ToString();
                        UpdateActualCost(entity.Id, projectNumber);
                        UpdateActualHours(entity.Id, projectNumber);
                    }
                }
            }
            catch (Exception ex)
            {
                Entity errorLog = new Entity("ig1_pluginserrorlogs");
                errorLog["ig1_name"]             = "An error occurred in UpdateActualCostAndHours Plug-in";
                errorLog["ig1_errormessage"]     = ex.Message;
                errorLog["ig1_errordescription"] = ex.ToString();
                service.Create(errorLog);
            }
        }
Example #20
0
        public void Create(IServiceProvider serviceProvider)
        {
            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 != CrmConstants.AnnotationEntityName && entity.LogicalName != CrmConstants.AttachmentEntityName)
                    {
                        return;
                    }

                    if (!entity.Attributes.Keys.Contains(GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]) || string.IsNullOrWhiteSpace((string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.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, entity.LogicalName, unsecurePluginStepConfiguration, securePluginStepConfiguration);
                    if (configurationProvider.StorageProviderType == Providers.StorageProviderType.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[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]]);
                    string fileName = (string)entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.FileNameAttributeKey]];
                    if (storageProvider.Create(entity.Id, fileName, data))
                    {
                        entity.Attributes[GenericConstants.Constants[entity.LogicalName][GenericConstants.DocumentBodyAttributeKey]] = GenericConstants.EmptyBodyContent;
                        //If the plugin is running in async mode and is for attachment, we have to make a call to save the attachment.
                        if (context.Stage == CrmConstants.PostOperationStateNumber && entity.LogicalName == CrmConstants.AttachmentEntityName)
                        {
                            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());
                }
            }
        }
Example #21
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 leadPreImageEntity = ((context.PreEntityImages != null) && context.PreEntityImages.Contains("leadpre")) ? context.PreEntityImages["leadpre"] : null;

                Entity leadEntity = new Entity
                {
                    LogicalName = "lead",
                    Id          = leadPreImageEntity.Id
                };

                step = 3;
                if (leadPreImageEntity.LogicalName != "lead")
                {
                    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;
                    leadEntity["fdx_lastassignedowner"] = new EntityReference("systemuser", ((EntityReference)leadPreImageEntity.Attributes["ownerid"]).Id);

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

                    step = 9;
                    service.Update(leadEntity);

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

                    step = 11;
                    if (lead.Attributes.Contains("parentaccountid"))
                    {
                        step = 12;
                        Entity account = new Entity
                        {
                            Id          = ((EntityReference)lead.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 Lead_OnAssign plug-in at Step {0}.", step), ex);
                }
                catch (Exception ex)
                {
                    tracingService.Trace("Lead_OnAssign: step {0}, {1}", step, ex.ToString());
                    throw;
                }
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);

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

            tracing.Trace(" **************** CreateWorkHistoryOnQItemUpdat *************plugin triggered ");

            BusinessLogic CommonLogic = new BusinessLogic(serviceFactory, tracing);

            if (string.Equals(context.MessageName, "create", StringComparison.OrdinalIgnoreCase))
            {
                Entity caseContext = (Entity)context.InputParameters["Target"];
                CommonLogic.PreCreateWH(caseContext);
            }
            else if (string.Equals(context.MessageName, "update", StringComparison.OrdinalIgnoreCase))
            {
                try
                {
                    if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                    {
                        Entity CaseTarget = (Entity)context.InputParameters["Target"];
                        //Entity CasePreImage = context.PreEntityImages["PreImage"];
                        Entity Case = CommonLogic.RecordFetch(service, CaseTarget.LogicalName, CaseTarget.Id, Modal.caseColumns);

                        if (Case.FormattedValues["cr32a_typeofcase"].ToString().ToUpper().Equals(IncidentCaseType.ToUpper()))
                        {
                            CaseId = CaseTarget.Id;
                            tracing.Trace("before fetching previous workHistory method");
                            Entity _prevWorkHistory = CommonLogic.FetchPreviousWorkHistory(service, CaseId, tracing);
                            tracing.Trace("after fetching previous workHistory method");
                            tracing.Trace("before calling update workHistory method");

                            if (CaseTarget.Attributes.Contains("ownerid"))
                            {
                                tracing.Trace("Assign Scenario Entering");
                                bool IsMadeInactive = CommonLogic.UpdateWorkHistory(_prevWorkHistory, Case, tracing);
                                tracing.Trace("after calling update workHistory method");
                                if (IsMadeInactive)
                                {
                                    tracing.Trace("before calling create workHistory method");
                                    Guid NewWorkHistoryID = CommonLogic.CreateWorkHistory(_prevWorkHistory,
                                                                                          Case, service);
                                    tracing.Trace("Created new Work history:" + NewWorkHistoryID.ToString());
                                    tracing.Trace("after calling create workHistory method");
                                }
                            }
                            else if (CaseTarget.Attributes.Contains("cr32a_casestatusreason"))
                            {
                                string CaseStatusID = CaseTarget.GetAttributeValue <EntityReference>("cr32a_casestatusreason").Id.ToString();
                                if (CaseStatusID.ToUpper().Equals(ClosedID.ToUpper()))
                                {
                                    //resolved or closed
                                    CommonLogic.UpdateWorkHistory(_prevWorkHistory, CaseTarget, tracing);
                                }
                                else if (CaseStatusID.ToUpper().Equals(ActiveID.ToUpper()))
                                {
                                    //reopened - create a  new work history
                                    CommonLogic.CreateWorkHistory(_prevWorkHistory,
                                                                  Case, service);
                                }
                            }
                        }
                        else
                        {
                            return;
                        }
                    }
                }
                catch (Exception ex)
                {
                    tracing.Trace("Exception Occured" + ex.Message);
                    tracing.Trace("Exception StackTrace" + ex.StackTrace);
                    tracing.Trace("InnerException.Message" + ex.InnerException.Message);
                    tracing.Trace("InnerException.StackTrace" + ex.InnerException.StackTrace);
                }
            }
        }
        public void Execute(IServiceProvider serviceProvider)
        {
            #region Fill Mapping List
            mappingList = new List <JobSheetFieldMapping>();
            //Travelling To Vessel
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_traveltovslnormaltime", ServiceCategoryId = "SER-TNH-S", AutomationCategoryId = "ASP-TNH-S", GroupName = "TNH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_traveltovslovertime", ServiceCategoryId = "SER-TOH-S", AutomationCategoryId = "ASP-TOH-S", GroupName = "TOH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_traveltovslholidaytime", ServiceCategoryId = "SER-THH-S", AutomationCategoryId = "ASP-THH-S", GroupName = "THH"
            });
            //Travelling To Vessel 1
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_traveltovslnormaltime1", ServiceCategoryId = "SER-TNH-S", AutomationCategoryId = "ASP-TNH-S", GroupName = "TNH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_traveltovslovertime1", ServiceCategoryId = "SER-TOH-S", AutomationCategoryId = "ASP-TOH-S", GroupName = "TOH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_traveltovslholidaytime1", ServiceCategoryId = "SER-THH-S", AutomationCategoryId = "ASP-THH-S", GroupName = "THH"
            });
            //Waiting
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingnormaltime", ServiceCategoryId = "SER-WNH-S", AutomationCategoryId = "ASP-WNH-S", GroupName = "WNH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingovertime", ServiceCategoryId = "SER-WOH-S", AutomationCategoryId = "ASP-WOH-S", GroupName = "WOH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingholidaytime", ServiceCategoryId = "SER-WHH-S", AutomationCategoryId = "ASP-WHH-S", GroupName = "WHH"
            });
            //Waiting 1
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingnormaltime1", ServiceCategoryId = "SER-WNH-S", AutomationCategoryId = "ASP-WNH-S", GroupName = "WNH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingovertime1", ServiceCategoryId = "SER-WOH-S", AutomationCategoryId = "ASP-WOH-S", GroupName = "WOH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingholidaytime1", ServiceCategoryId = "SER-WHH-S", AutomationCategoryId = "ASP-WHH-S", GroupName = "WHH"
            });
            //Working
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingnormaltime", ServiceCategoryId = "SER-NH-S", AutomationCategoryId = "ASP-NH-S", GroupName = "NH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingovertime", ServiceCategoryId = "SER-OHL-S", AutomationCategoryId = "ASP-OHL-S", GroupName = "OHL"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingholidaytime", ServiceCategoryId = "SER-HH-S", AutomationCategoryId = "ASP-HH-S", GroupName = "HH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingoutstationday", ServiceCategoryId = "SER-OND-S", AutomationCategoryId = "ASP-OND-S", GroupName = "OND"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingoutstation", ServiceCategoryId = "SER-OH-S", AutomationCategoryId = "ASP-OH-S", GroupName = "OH"
            });
            //Working 1
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingnormaltime1", ServiceCategoryId = "SER-NH-S", AutomationCategoryId = "ASP-NH-S", GroupName = "NH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingovertime1", ServiceCategoryId = "SER-OHL-S", AutomationCategoryId = "ASP-OHL-S", GroupName = "OHL"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingholidaytime1", ServiceCategoryId = "SER-HH-S", AutomationCategoryId = "ASP-HH-S", GroupName = "HH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingoutstationdaynormal1", ServiceCategoryId = "SER-OND-S", AutomationCategoryId = "ASP-OND-S", GroupName = "OND"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workingoutstationdayholiday1", ServiceCategoryId = "SER-OH-S", AutomationCategoryId = "ASP-OH-S", GroupName = "OH"
            });
            //Travelling From Vessel
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_travelfmvslnormaltime", ServiceCategoryId = "SER-TNH-S", AutomationCategoryId = "ASP-TNH-S", GroupName = "TNH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_travelfmvslovertime", ServiceCategoryId = "SER-TOH-S", AutomationCategoryId = "ASP-TOH-S", GroupName = "TOH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_travelfmvslholidaytime", ServiceCategoryId = "SER-THH-S", AutomationCategoryId = "ASP-THH-S", GroupName = "THH"
            });
            //Travelling From Vessel 1
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_travelfmvslnormaltime1", ServiceCategoryId = "SER-TNH-S", AutomationCategoryId = "ASP-TNH-S", GroupName = "TNH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_travelfmvslovertime1", ServiceCategoryId = "SER-TOH-S", AutomationCategoryId = "ASP-TOH-S", GroupName = "TOH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_travelfmvslholidaytime1", ServiceCategoryId = "SER-THH-S", AutomationCategoryId = "ASP-THH-S", GroupName = "THH"
            });
            //Workshop
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workshopnormaltime", ServiceCategoryId = "SER-WNH001-S", AutomationCategoryId = "ASP-WNH001-S", GroupName = "WNH001"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workshopovertime", ServiceCategoryId = "SER-WOH001-S", AutomationCategoryId = "ASP-WOH001-S", GroupName = "WOH001"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workshopholidaytime", ServiceCategoryId = "SER-WOH001-S", AutomationCategoryId = "ASP-WOH001-S", GroupName = "WOH001"
            });
            //Workshop 1
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workshopnormaltime1", ServiceCategoryId = "SER-WNH001-S", AutomationCategoryId = "ASP-WNH001-S", GroupName = "WNH001"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workshopovertime1", ServiceCategoryId = "SER-WOH001-S", AutomationCategoryId = "ASP-WOH001-S", GroupName = "WOH001"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_workshopholidaytime1", ServiceCategoryId = "SER-WOH001-S", AutomationCategoryId = "ASP-WOH001-S", GroupName = "WOH001"
            });
            //Waiting 2
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingnormaltime2", ServiceCategoryId = "SER-WNH-S", AutomationCategoryId = "ASP-WNH-S", GroupName = "WNH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingovertime2", ServiceCategoryId = "SER-WOH-S", AutomationCategoryId = "ASP-WOH-S", GroupName = "WOH"
            });
            mappingList.Add(new JobSheetFieldMapping {
                FieldSchemaName = "elc_waitingoutstationdaynormal2", ServiceCategoryId = "SER-WHH-S", AutomationCategoryId = "ASP-WHH-S", GroupName = "WHH"
            });
            #endregion
            try
            {
                #region Object Instances
                context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
                tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
                Entity entity = context.InputParameters["Target"] as Entity;;
                orgFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                orgService = orgFactory.CreateOrganizationService(context.UserId);
                Entity entityPostImage = null;
                List <JobSheetFieldMapping> GroupedFieldList = new List <JobSheetFieldMapping>();
                #endregion

                if (context.Depth > 2)
                {
                    return;
                }

                if (context.MessageName.ToUpper() == "CREATE")
                {
                    entityPostImage = context.PostEntityImages["PostCreateForJobSheetTiming"] as Entity;
                }
                if (context.MessageName.ToUpper() == "UPDATE")
                {
                    entityPostImage = context.PostEntityImages["PostUpdateForJobSheetTiming"] as Entity;
                }

                foreach (var item in entityPostImage.Attributes)
                {
                    if (mappingList.Where(x => x.FieldSchemaName == item.Key).Count() > 0)
                    {
                        GroupedFieldList.AddRange(mappingList.Where(x => x.FieldSchemaName == item.Key));
                    }
                }

                //Group By All Mapping by Group Name
                var groupedFieldMappingList = GroupedFieldList.GroupBy(u => u.GroupName).Select(grp => grp);

                foreach (var item in groupedFieldMappingList)
                {
                    //Calculate total hours For Specifc Group
                    int EachHours = 0;
                    item.Select(x => x.FieldSchemaName).ToList().ForEach(a => { EachHours = EachHours + Convert.ToInt32(entityPostImage.Attributes.Where(x => x.Key == a).Sum(b => Convert.ToInt32(b.Value))); });

                    //Check for Automation Code or Service Code to pick up
                    string ServiceCategoryId = string.Empty;
                    if (((string)entityPostImage["msdyn_name"]).Contains("AUS"))
                    {
                        ServiceCategoryId = mappingList.Where(x => x.FieldSchemaName == item.Select(a => a.FieldSchemaName).FirstOrDefault()).Select(x => x.AutomationCategoryId).FirstOrDefault();
                    }
                    else
                    {
                        ServiceCategoryId = mappingList.Where(x => x.FieldSchemaName == item.Select(a => a.FieldSchemaName).FirstOrDefault()).Select(x => x.ServiceCategoryId).FirstOrDefault();
                    }

                    //Get Category Id from Category Number
                    string GetCategoryFetchExpression = string.Format(GetCategoriesFetchXML, ServiceCategoryId,
                                                                      entityPostImage.Contains(LegalEntityEntitySchemaName) ? ((EntityReference)entityPostImage[LegalEntityEntitySchemaName]).Id.ToString() : DefaultLegalEntity);
                    var Category = orgService.RetrieveMultiple(new FetchExpression(GetCategoryFetchExpression));

                    if (Category.Entities.Count > 0)
                    {
                        if (context.MessageName.ToUpper() == "UPDATE")
                        {
                            //Get Service Hours For Updated Service Order
                            string GetServiceHoursFetchExpression = string.Format(GetServiceHoursForUpdate, Category.Entities[0].Id, entity.Id);
                            var    ServicesHours = orgService.RetrieveMultiple(new FetchExpression(GetServiceHoursFetchExpression));
                            //If No Service Hours Created, Create One
                            if (ServicesHours.Entities.Count == 0)
                            {
                                Entity CreateServiceHour = new Entity(ServiceHourEntitySchemaName);
                                CreateServiceHour[ProjectCategoryEntitySchemaName] = new EntityReference(ProjectCategoryEntitySchemaName, Category.Entities[0].Id);
                                CreateServiceHour["msdyn_workorder"]           = new EntityReference("msdyn_workorder", entity.Id);
                                CreateServiceHour[LegalEntityEntitySchemaName] = new EntityReference("businessunit", entityPostImage.Contains(LegalEntityEntitySchemaName) ? ((EntityReference)entityPostImage[LegalEntityEntitySchemaName]).Id : new Guid(DefaultLegalEntity));
                                CreateServiceHour["msdyn_duration"]            = EachHours * 60;
                                orgService.Create(CreateServiceHour);
                            }
                            //If Service Hours is in system check value of duration, Update only if Not same as new value
                            else if (ServicesHours.Entities[0].Contains("msdyn_duration") && Convert.ToInt32(ServicesHours.Entities[0]["msdyn_duration"]) != EachHours * 60)
                            {
                                Entity UpdateServiceHour = new Entity(ServiceHourEntitySchemaName, ServicesHours.Entities[0].Id);
                                UpdateServiceHour["msdyn_duration"] = EachHours * 60;
                                orgService.Update(UpdateServiceHour);
                            }
                        }
                        if (context.MessageName.ToUpper() == "CREATE")
                        {
                            Entity CreateServiceHour = new Entity(ServiceHourEntitySchemaName);
                            CreateServiceHour[ProjectCategoryEntitySchemaName] = new EntityReference(ProjectCategoryEntitySchemaName, Category.Entities[0].Id);
                            CreateServiceHour["msdyn_workorder"]           = new EntityReference("msdyn_workorder", entity.Id);
                            CreateServiceHour[LegalEntityEntitySchemaName] = new EntityReference("businessunit", entityPostImage.Contains(LegalEntityEntitySchemaName) ? ((EntityReference)entityPostImage[LegalEntityEntitySchemaName]).Id : new Guid(DefaultLegalEntity));
                            CreateServiceHour["msdyn_duration"]            = EachHours * 60;
                            orgService.Create(CreateServiceHour);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
        protected override void Execute(CodeActivityContext context)
        {
            // Get the context service.
            IWorkflowContext            Icontext       = context.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = context.GetExtension <IOrganizationServiceFactory>();

            // Use the context service to create an instance of IOrganizationService.
            IOrganizationService service = serviceFactory.CreateOrganizationService(Icontext.UserId); // user = SDU\SQLCRMDynWorkF


            // get current record
            var fakProjekt = service.Retrieve(Icontext.PrimaryEntityName, Icontext.PrimaryEntityId, new ColumnSet(true));

            var projectStartDate = fakProjekt.GetAttributeValue <DateTime>("sdu_projektstart");
            var projectEndDate   = fakProjekt.GetAttributeValue <DateTime>("sdu_projektslut");

            // put the difference in years into list
            List <int> years = new List <int>();

            if (projectStartDate != null && projectEndDate != null)
            {
                for (int i = projectStartDate.ToLocalTime().Year; i <= projectEndDate.ToLocalTime().Year; i++)
                {
                    years.Add(i);
                }
            }

            // get bevilling + medf SDU
            var bevilling = fakProjekt.GetAttributeValue <Money>("sdu_bevillingtilsdu")?.Value;
            var medf      = fakProjekt.GetAttributeValue <Money>("sdupro_medfinansieringbevilling")?.Value;

            decimal amountBev;
            decimal amountMedf;

            // amount to distribute
            if (years.Count > 0)
            {
                if (bevilling != null)
                {
                    amountBev = (decimal)bevilling / years.Count;
                }
                else
                {
                    amountBev = 0;
                }

                if (medf != null)
                {
                    amountMedf = (decimal)medf / years.Count;
                }
                else
                {
                    amountMedf = 0;
                }
            }
            else
            {
                amountMedf = 0;
                amountBev  = 0;
            }

            // definition
            var fieldIndexDefinition = new List <Tuple <int, string> >
            {
                new Tuple <int, string>(0, "sdu_er_budgetlinje_year1"),
                new Tuple <int, string>(1, "sdu_er_budgetlinje_year2"),
                new Tuple <int, string>(2, "sdu_er_budgetlinje_year3"),
                new Tuple <int, string>(3, "sdu_er_budgetlinje_year4"),
                new Tuple <int, string>(4, "sdu_er_budgetlinje_year5"),
                new Tuple <int, string>(5, "sdu_er_budgetlinje_year6"),
                new Tuple <int, string>(6, "sdu_er_budgetlinje_year7"),
                new Tuple <int, string>(7, "sdu_er_budgetlinje_year8"),
                new Tuple <int, string>(8, "sdu_er_budgetlinje_year9"),
                new Tuple <int, string>(9, "sdu_er_budgetlinje_year10")
            };

            // loop through 10 years MAX and field the corresponding logical name in the definition.
            for (int i = 0; i < years.Count; i++)
            {
                // get the field name corresponding to the item1 in definition
                var crmFieldName = fieldIndexDefinition.Find(tuple => tuple.Item1 == i)?.Item2;
                if (!String.IsNullOrEmpty(crmFieldName) && (amountBev != 0 || amountMedf != 0))
                {
                    var crmField = fakProjekt.GetAttributeValue <EntityReference>(crmFieldName);

                    CreateOrUpdateBudgetLines(service, years[i].ToString(), amountBev, amountMedf, fakProjekt, crmField, crmFieldName);
                }
            }

            CheckForExtraYears(service, fakProjekt, years.Count, fieldIndexDefinition);
        }
Example #25
0
        protected List <Entity> RetrieveAnnotationEntity(CodeActivityContext context, ColumnSet noteColumns, int maxRecords = 1)
        {
            double                      miunutesOld     = 0;
            List <Entity>               returnValue     = new List <Entity>();
            IWorkflowContext            workflowContext = context.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory  = context.GetExtension <IOrganizationServiceFactory>();
            IOrganizationService        service         = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);

            int?objectTypeCode = this.RetrieveEntityObjectTypeCode(workflowContext, service);

            if (objectTypeCode == null)
            {
                throw new ArgumentException($"Objecttypecode not found in metadata for entity {workflowContext.PrimaryEntityName}");
            }

            ExecuteFetchResponse fetchResponse = null;
            ExecuteFetchRequest  request       = new ExecuteFetchRequest();

            try
            {
                if (String.IsNullOrWhiteSpace(this.FileName.Get(context)))
                {
                    request.FetchXml =
                        $@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
                              <entity name=""annotation"">
                                <attribute name=""annotationid"" />
                                <attribute name=""createdon"" />
                                <filter type=""and"">
                                  <condition attribute=""isdocument"" operator=""eq"" value=""1"" />
                                  <condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEntityId}"" />
                                  <condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
                                </filter>
                                <order attribute=""createdon"" descending=""true"" />
                              </entity>
                            </fetch>";
                }
                else
                {
                    request.FetchXml =
                        $@"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
                              <entity name=""annotation"">
                                <attribute name=""annotationid"" />
                                <attribute name=""createdon"" />
                                <filter type=""and"">
                                  <condition attribute=""filename"" operator=""like"" value=""%{this.FileName.Get(context)}%"" />
                                  <condition attribute=""isdocument"" operator=""eq"" value=""1"" />
                                  <condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEntityId}"" />
                                  <condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
                                </filter>
                                <order attribute=""createdon"" descending=""true"" />
                              </entity>
                            </fetch>";
                }

                fetchResponse = service.Execute(request) as ExecuteFetchResponse;

                XmlDocument queryResults = new XmlDocument();
                queryResults.LoadXml(fetchResponse.FetchXmlResult);
                int days    = 0;
                int minutes = 0;
                for (int i = 0; i < queryResults["resultset"].ChildNodes.Count; i++)
                {
                    if (queryResults["resultset"].ChildNodes[i]["createdon"] != null && !String.IsNullOrWhiteSpace(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText))
                    {
                        DateTime createdon = DateTime.Parse(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText);
                        if (createdon.Kind == DateTimeKind.Local)
                        {
                            createdon = createdon.ToUniversalTime();
                        }
                        TimeSpan difference = DateTime.Now.ToUniversalTime() - createdon;
                        miunutesOld = difference.TotalMinutes;
                        switch (this.TimeSpanOption.Get(context).Value)
                        {
                        case 222540000:
                            minutes = this.TimeSpanValue.Get(context);
                            break;

                        case 222540001:
                            minutes = this.TimeSpanValue.Get(context) * 60;
                            break;

                        case 222540002:
                            days = this.TimeSpanValue.Get(context);
                            break;

                        case 222540003:
                            days = this.TimeSpanValue.Get(context) * 7;
                            break;

                        case 222540004:
                            days = this.TimeSpanValue.Get(context) * 365;
                            break;
                        }
                        TimeSpan allowedDifference = new TimeSpan(days, 0, minutes, 0);
                        if (difference <= allowedDifference)
                        {
                            returnValue.Add(service.Retrieve("annotation", Guid.Parse(queryResults["resultset"].ChildNodes[i]["annotationid"].InnerText), noteColumns));
                        }
                    }

                    if (returnValue.Count >= maxRecords)
                    {
                        break;
                    }
                }
            }
            catch (System.ServiceModel.FaultException <Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                throw new ArgumentException("There was an error executing the FetchXML. Message: " + ex.Message);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(returnValue);
        }
        protected override void Execute(CodeActivityContext context)
        {
            // Obtain the execution context from the service provider.
            // Get the context service.
            IWorkflowContext            Icontext       = context.GetExtension <IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = context.GetExtension <IOrganizationServiceFactory>();

            // Use the context service to create an instance of IOrganizationService.
            IOrganizationService service = serviceFactory.CreateOrganizationService(Icontext.InitiatingUserId);

            // get current record
            var systemUser = service.Retrieve(Icontext.PrimaryEntityName, Icontext.PrimaryEntityId, new ColumnSet("defaultmailbox", "sdu_brugeradministration", "domainname", "businessunitid"));

            var username = systemUser.GetAttributeValue <string>("domainname").Split('\\')[1];

            // search for brugeradministration
            var query = new QueryExpression("contact")
            {
                ColumnSet = new ColumnSet("sdu_brugernavn", "sdu_adgange")
            };

            var condition = new ConditionExpression("sdu_brugernavn", ConditionOperator.Equal, username);

            query.Criteria.AddCondition(condition);

            var result = service.RetrieveMultiple(query);

            // only if one result
            if (result.Entities.Count == 1)
            {
                var contact      = result.Entities[0];
                var brugeradmRef = contact.GetAttributeValue <EntityReference>("sdu_adgange");

                var SystemUser = new Entity(Icontext.PrimaryEntityName)
                {
                    Id = Icontext.PrimaryEntityId
                };
                SystemUser["sdu_brugeradministration"] = brugeradmRef;

                service.Update(SystemUser);
            }


            // get the business unit
            var businessUnitRef    = systemUser.GetAttributeValue <EntityReference>("businessunitid");
            var businessUnitEntity = service.Retrieve(businessUnitRef.LogicalName, businessUnitRef.Id, new ColumnSet("name"));
            var nameOfBU           = businessUnitEntity.GetAttributeValue <string>("name");

            // update issendasallow attribute on user settings
            var userSettings = new Entity("usersettings")
            {
                Id = Icontext.PrimaryEntityId
            };

            userSettings["issendasallowed"] = true;

            if (nameOfBU == "ASS_930 Bestilling af specialkonti")
            {
                userSettings["homepagearea"]    = "Settings";
                userSettings["homepagesubarea"] = "sdu_kontobestilling";
            }
            else if (nameOfBU.StartsWith("ASS_"))
            {
                userSettings["homepagearea"]    = "Workplace";
                userSettings["homepagesubarea"] = "Dashboards";
            }

            service.Update(userSettings);


            // update delivery method of default mailbox
            var defaultMailBox = new Entity("mailbox")
            {
                Id = systemUser.GetAttributeValue <EntityReference>("defaultmailbox").Id
            };

            defaultMailBox["outgoingemaildeliverymethod"] = new OptionSetValue(2);

            service.Update(defaultMailBox);
        }
Example #27
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 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
                {
                    // 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;
                }
            }
        }
Example #28
0
        public void Execute(IServiceProvider serviceProvider)
        {
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));


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



            tracingService.Trace("Entered in CustomAddress");

            if (context != null)
            {
                //tracingService.Trace(context)
            }
            if (context.Depth > 1)
            {
                tracingService.Trace("depth is greter than 1 returned");
                return;
            }
            //Entity entity = context.PostEntityImages["PostImage"];
            if (context.PostEntityImages.Contains("PostImage") &&
                context.PostEntityImages["PostImage"] is Entity)
            {
                Entity entity = (Entity)context.PostEntityImages["PostImage"];

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

                try {
                    CrmDataHelper    objHelper         = new CrmDataHelper();
                    Guid             customerAddressId = Guid.Empty;
                    Guid             parentId;
                    int              addressNumber;
                    int              objectTypeCode;
                    Entity           customAddressObject;
                    EntityCollection addresscollection = objHelper.GetCustomerAddress(service, entity.Id);
                    if (entity.LogicalName == "contact")
                    {
                        objectTypeCode = 2;
                    }
                    else
                    {
                        objectTypeCode = 1;
                    }
                    foreach (Entity e in addresscollection.Entities)
                    {
                        addressNumber = (int)e[AddressAttributes.addressnumber];
                        tracingService.Trace("Object Type code" + objectTypeCode);
                        tracingService.Trace("message" + context.MessageName);
                        parentId          = ((EntityReference)e[AddressAttributes.parentid]).Id;
                        customerAddressId = objHelper.GetParentIdCustomerAddress(service, addressNumber, entity.Id, objectTypeCode);

                        if (context.MessageName == "Create" || context.MessageName == "Update")
                        {
                            if (customerAddressId == Guid.Empty)
                            {
                                customAddressObject = CreateCustomerAddressObject(e, objectTypeCode, entity, addressNumber, service, tracingService);
                                service.Create(customAddressObject);
                            }
                            else
                            {
                                customAddressObject    = CreateCustomerAddressObject(e, objectTypeCode, entity, addressNumber, service, tracingService);
                                customAddressObject.Id = customerAddressId;
                                service.Update(customAddressObject);
                            }
                        }
                    }
                    tracingService.Trace("check adress");
                    if (objectTypeCode == 1 && entity.Attributes.Contains(AddressAttributes.gk_shiptoaddresstype) && entity.Attributes[AddressAttributes.gk_shiptoaddresstype] != null)
                    {
                        tracingService.Trace("Address3");
                        addressNumber     = 3;
                        customerAddressId = objHelper.GetParentIdCustomerAddress(service, addressNumber, entity.Id, objectTypeCode);
                        if (customerAddressId == Guid.Empty)
                        {
                            tracingService.Trace("createaddress3");
                            customAddressObject = CreateCustomerAddressObject(null, objectTypeCode, entity, addressNumber, service, tracingService);
                            service.Create(customAddressObject);
                        }
                        else
                        {
                            tracingService.Trace("updateaddress3");
                            customAddressObject    = CreateCustomerAddressObject(null, objectTypeCode, entity, addressNumber, service, tracingService);
                            customAddressObject.Id = customerAddressId;
                            service.Update(customAddressObject);
                        }
                    }
                }
                catch (Exception ex)
                {
                    tracingService.Trace("HandleCustomAddress: {0}", ex.ToString());
                    throw;
                }
                //catch (FaultException<OrganizationServiceFault> ex)
                //{
                //    throw new InvalidPluginExecutionException("An error occurred in HandleCustomAddress.", ex);
                //}
            }
        }
        protected override void Execute(CodeActivityContext executionContext)
        {
            Boolean         Logging     = EnableLogging.Get(executionContext);
            string          LogFilePath = LogFile.Get(executionContext);
            EntityReference Letter      = LetterId.Get(executionContext);
            EntityReference Attachment  = AttachmentId.Get(executionContext);

            try
            {
                if (Logging)
                {
                    Log("Workflow Execution Start", LogFilePath);
                }
                IWorkflowContext            context        = executionContext.GetExtension <IWorkflowContext>();
                IOrganizationServiceFactory serviceFactory = executionContext.GetExtension <IOrganizationServiceFactory>();
                IOrganizationService        service        = serviceFactory.CreateOrganizationService(context.UserId);
                if (Logging)
                {
                    Log("Retrieving Attahment", LogFilePath);
                }
                Entity TempAttachment = service.Retrieve("annotation", Attachment.Id, new ColumnSet(true));
                if (TempAttachment != null)
                {
                    if (Logging)
                    {
                        Log("Creating New Attachment", LogFilePath);
                    }
                    Entity NewAttachment = new Entity("annotation");
                    if (TempAttachment.Contains("subject"))
                    {
                        NewAttachment.Attributes.Add("subject", TempAttachment["subject"]);
                    }
                    if (TempAttachment.Contains("filename"))
                    {
                        NewAttachment.Attributes.Add("filename", TempAttachment["filename"]);
                    }
                    if (TempAttachment.Contains("notetext"))
                    {
                        NewAttachment.Attributes.Add("notetext", TempAttachment["notetext"]);
                    }
                    if (TempAttachment.Contains("mimetype"))
                    {
                        NewAttachment.Attributes.Add("mimetype", TempAttachment["mimetype"]);
                    }
                    if (TempAttachment.Contains("documentbody"))
                    {
                        NewAttachment.Attributes.Add("documentbody", TempAttachment["documentbody"]);
                    }
                    NewAttachment.Attributes.Add("objectid", new EntityReference(Letter.LogicalName, Letter.Id));
                    service.Create(NewAttachment);
                    if (Logging)
                    {
                        Log("New Attachment Added To Letter", LogFilePath);
                    }
                }
                else
                {
                    if (Logging)
                    {
                        Log("Temp Attachment doesnot exist", LogFilePath);
                    }
                }
                if (Logging)
                {
                    Log("Workflow Executed Successfully", LogFilePath);
                }
            }
            catch (Exception ex)
            {
                Log(ex.Message, LogFilePath);
            }
        }
Example #30
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);
                    }
                }
                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"];

                // }
            }
        }
Example #31
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);
            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));

            // if (context.Depth > 1) return;

            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    //tracingService.Trace("2");

                    if (context.MessageName == "Update")
                    {
                        //Variables Locales
                        string sCodCaseType = string.Empty;
                        int    iResponse    = 0;
                        string codigo       = null;
                        bool   flagTipoCaso = false;
                        //

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

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

                        if (entity == null)
                        {
                            return;
                        }

                        Entity entOpo = service.Retrieve("incident", entity.Id, new ColumnSet("amxperu_casetype", "ust_sarresponse", "ust_flagtipocaso"));

                        EntityReference erTipoCaso = null;

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

                        if (erTipoCaso == null)
                        {
                            return;                    //If CaseType is not registered plugIn abort.
                        }
                        Entity caseType = service.Retrieve("amxperu_casetype", erTipoCaso.Id, new Microsoft.Xrm.Sdk.Query.ColumnSet("ust_code"));

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

                        if (entOpo.Attributes.Contains("ust_sarresponse") && entOpo.Attributes["ust_sarresponse"] != null)
                        {
                            //Get the SAR  response
                            iResponse = ((OptionSetValue)entOpo.Attributes["ust_sarresponse"]).Value;
                        }
                        if (entOpo.Attributes.Contains("ust_flagtipocaso"))
                        {
                            //Get the SAR  response
                            flagTipoCaso = (bool)entOpo.Attributes["ust_flagtipocaso"];
                        }

                        if (string.IsNullOrEmpty(sCodCaseType))
                        {
                            throw new ApplicationException("There is not configured a CaseTypeCode in the TCRM. Please contact with the Administrator.");
                        }

                        string strFieldName = null;
                        bool   isAccepted   = false;
                        //bool flagTipoCase = false;
                        bool isSAR = false;

                        if (sCodCaseType != null)
                        {
                            if (flagTipoCaso == false)
                            {
                                if (sCodCaseType == "003" && iResponse == 864340001) //Si es SAR OSIPTEL y respuesta "No Aceptada"
                                {
                                    codigo       = "01";                             //< -- 1 = Correlation SAR --!>
                                    strFieldName = "ust_correlationsar";
                                    isAccepted   = false;
                                }
                                else if (sCodCaseType == "003" && iResponse == 864340000)//Si es SAR OSIPTEL y respuesta "Aceptada"
                                {
                                    codigo       = "01";
                                    strFieldName = "ust_correlationsar";
                                    isAccepted   = true;
                                }
                                else if (sCodCaseType == "004" && iResponse == 864340001) // Si es Reclamo OSIPTEL y respuesta "No Aceptada"
                                {
                                    codigo       = "02";                                  //< -- 2 = Correlation Claims --!>
                                    strFieldName = "ust_osiptelcomplaintid";
                                    isAccepted   = false;
                                }
                                else if (sCodCaseType == "004") // Reclamo OSIPTEL
                                {
                                    codigo       = "02";        //< --  2 = Correlation Claims --!>
                                    strFieldName = "ust_osiptelcomplaintid";
                                    isAccepted   = false;
                                    isSAR        = true;
                                }
                                else if (sCodCaseType == "005") //Queja OSIPTEL
                                {
                                    codigo       = "04";        //COMPLAINTS CODE
                                    strFieldName = "ust_grievanceinternalid";
                                    isAccepted   = false;
                                }
                                else if (sCodCaseType == "007") //Reclamo LDR
                                {
                                    codigo       = "05";        //Correlation LDR
                                    strFieldName = "ust_indecopicomplaintid";
                                    isAccepted   = false;
                                }
                                //myTrace.Trace("Codigo:" + codigo);
                                //myTrace.Trace("Campo:" + strFieldName);

                                if (codigo != null)
                                {
                                    string strAutoNumberCode = getAutoNumberService(codigo, isAccepted);

                                    // myTrace.Trace("NumberCode :" + strAutoNumberCode);
                                    if (!string.IsNullOrEmpty(strAutoNumberCode) && !string.IsNullOrEmpty(strFieldName))
                                    {
                                        entity.Attributes[strFieldName]       = strAutoNumberCode;
                                        entity.Attributes["ust_flagtipocaso"] = true;
                                        if (isSAR)
                                        {
                                            entity.Attributes["ust_saraid"] = strAutoNumberCode + "/SARA";
                                        }

                                        //service.Update(entity);
                                    }
                                }
                            }
                            // throw new InvalidPluginExecutionException("Mensaje de error. ");
                        }
                    }
                }
            }
            catch (ApplicationException ex)
            {
                throw new ApplicationException("Controlled Error: " + ex.Message, ex);
            }
            catch (InvalidPluginExecutionException ex)
            {
                throw new InvalidPluginExecutionException("PlugIn Error: " + ex.Message, ex);
            }
            catch (EndpointNotFoundException ex)
            {
                throw new EndpointNotFoundException("EndPoint Error: " + ex.Message, ex);
            }
            catch (FaultException <OrganizationServiceFault> ex)
            {
                throw new InvalidPluginExecutionException("Crm Service error: " + ex.Message, ex);
            }
            catch (Exception ex)
            {
                throw new Exception("Uncontrolled error: " + ex.Message, ex);;
            }
        }
Example #32
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);
            }
        }
Example #33
0
 private void ExecuteWorkflow(CodeActivityContext executionContext, IWorkflowContext workflowContext, IOrganizationServiceFactory serviceFactory, IOrganizationService service, ITracingService tracing)
 {
     //YOUR WORKFLOW-CODE GO HERE
 }
        public void Execute(IServiceProvider serviceProvider)
        {
            #region Initializations
            IPluginExecutionContext     context        = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
            IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
            IOrganizationService        _service       = (IOrganizationService)serviceFactory.CreateOrganizationService(context.UserId);
            ITracingService             tracingService = (ITracingService)serviceProvider.GetService(typeof(ITracingService));
            #endregion

            try
            {
                if (context.InputParameters.Contains("Target") && context.InputParameters["Target"] is Entity)
                {
                    Entity          entity               = (Entity)context.InputParameters["Target"];
                    EntityReference requestIntiator      = new EntityReference();
                    string          requestIntiatorField = "";

                    if (entity.LogicalName != "ldv_launchrequest")
                    {
                        return;
                    }
                    if (context.MessageName.ToLower() == "create" && (entity.Attributes.Contains("ldv_customerid") || entity.Attributes.Contains("ldv_leadid")))
                    {
                        Entity UpdateRequest = new Entity("ldv_launchrequest");
                        UpdateRequest.Id = entity.Id;

                        var             launchRequest  = _service.Retrieve("ldv_launchrequest", entity.Id, new ColumnSet(true));
                        var             unitRequested  = _service.Retrieve("new_unit", ((EntityReference)launchRequest["ldv_unitid"]).Id, new ColumnSet(true));
                        EntityReference currentProject = (EntityReference)unitRequested["new_project"];

                        if (launchRequest.Attributes.Contains("ldv_customerid") && launchRequest["ldv_customerid"] != null)
                        {
                            requestIntiator = (EntityReference)launchRequest["ldv_customerid"];
                            tracingService.Trace("6.1");
                        }
                        else if (launchRequest.Attributes.Contains("ldv_leadid") && launchRequest["ldv_leadid"] != null)
                        {
                            requestIntiator = (EntityReference)launchRequest["ldv_leadid"];
                            tracingService.Trace("6.2");
                        }

                        if (requestIntiator.LogicalName == "lead")
                        {
                            requestIntiatorField = "ldv_leadid";
                            tracingService.Trace("6.4");
                        }
                        else if (requestIntiator.LogicalName == "contact")
                        {
                            requestIntiatorField = "ldv_customerid";
                            tracingService.Trace("6.5");
                        }

                        //retrieve requests for this customer
                        string fetchXml = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='ldv_launchrequest'>
                                    <attribute name='ldv_launchrequestid' />
                                    <attribute name='ldv_unitid' />
                                    <attribute name='ldv_statuscode' />
                                    <attribute name='statecode' />
                                    <attribute name='ownerid' />
                                    <attribute name='ldv_order' />
                                    <attribute name='ldv_leadid' />
                                    <attribute name='ldv_customerid' />
                                    <attribute name='ldv_prioritycode' />
                                    <order attribute='ldv_order' descending='true' />
                                    <filter type='and'>
                                      <condition attribute='ldv_order' operator='not-null' />
                                      <condition attribute='{requestIntiatorField}' operator='eq'  value='{requestIntiator.Id}' />
                                    </filter>
                                    <link-entity name='new_unit' from='new_unitid' to='ldv_unitid' link-type='inner' alias='aa'>
                                      <link-entity name='new_project' from='new_projectid' to='new_project' link-type='inner' alias='ab'>
                                        <filter type='and'>                                          
                                          <condition attribute='new_projectid' operator='eq' value='{currentProject.Id}' />
                                        </filter>
                                      </link-entity>
                                    </link-entity>
                                  </entity>
                                </fetch>";

                        // Run the query with the FetchXML.
                        var fetchExpression = new FetchExpression(fetchXml);
                        EntityCollection customerPrevRequests =
                            _service.RetrieveMultiple(fetchExpression);

                        if (customerPrevRequests.Entities.Count > 0)
                        {
                            int customerOrderNumber = (int)customerPrevRequests.Entities[0]["ldv_order"];
                            UpdateRequest["ldv_order"] = customerOrderNumber;
                        }
                        else
                        {
                            string fetchXmlAll = $@"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='ldv_launchrequest'>
                                    <attribute name='ldv_launchrequestid' />
                                    <attribute name='ldv_unitid' />
                                    <attribute name='ldv_statuscode' />
                                    <attribute name='statecode' />
                                    <attribute name='ownerid' />
                                    <attribute name='ldv_order' />
                                    <attribute name='ldv_leadid' />
                                    <attribute name='ldv_customerid' />
                                    <attribute name='ldv_prioritycode' />
                                    <order attribute='ldv_order' descending='true' />
                                    <filter type='and'>
                                      <condition attribute='ldv_order' operator='not-null' />                                      
                                    </filter>
                                    <link-entity name='new_unit' from='new_unitid' to='ldv_unitid' link-type='inner' alias='aa'>
                                      <link-entity name='new_project' from='new_projectid' to='new_project' link-type='inner' alias='ab'>
                                        <filter type='and'>                                          
                                          <condition attribute='new_projectid' operator='eq' value='{currentProject.Id}' />
                                        </filter>
                                      </link-entity>
                                    </link-entity>
                                  </entity>
                                </fetch>";

                            EntityCollection allPrevRequests = _service.RetrieveMultiple(new FetchExpression(fetchXmlAll));

                            if (allPrevRequests.Entities.Count > 0)
                            {
                                int nextcustomerOrderNumber = (int)allPrevRequests.Entities[0]["ldv_order"] + 1;

                                UpdateRequest["ldv_order"] = nextcustomerOrderNumber;
                            }
                            else
                            {
                                UpdateRequest["ldv_order"] = 1;
                            }
                        }
                        _service.Update(UpdateRequest);
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #35
0
 /// <summary>
 /// Initialize a new instance of CrmLogger.
 /// </summary>
 /// <param name="osFactory">Factory to get OrganizationService.</param>
 /// <param name="settings">Settings <see cref="CrmLoggerSettings"/></param>
 public CrmLogger(IOrganizationServiceFactory osFactory, CrmLoggerSettings settings)
 {
     _osFactory = osFactory;
     _settings = settings;
 }