public Boolean templateHasExistingCompletedAssessments()
        {
            QueryExpression qe = new QueryExpression("gcbase_fundingcaseriskassessment");

            qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, _riskTemplate.Id);

            var optHelper     = new OptionSetHelper();
            int indexOfStatus = optHelper.getIndexOfLabel("gcbase_fundingcaseriskassessment", "statuscode", "Analyst Completed", _service);

            qe.Criteria.AddCondition("statuscode", ConditionOperator.Equal, indexOfStatus);
            var existingCompletedTemplates = _service.RetrieveMultiple(qe).Entities;

            // throw new InvalidPluginExecutionException("asfsdafasd", ex1);
            if (existingCompletedTemplates.Count() > 0)
            {
                return(true);
            }
            return(false);
        }
 public Boolean generateTotalWeightedRiskScore()
 {
     try
     {
         var             riskTemplateId = _riskTemplate.Id;
         QueryExpression qe             = new QueryExpression("gcbase_risktemplateriskfactor");
         qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, riskTemplateId);
         qe.ColumnSet.AddColumns("gcbase_weight");
         var     rtrfs        = _service.RetrieveMultiple(qe).Entities;
         decimal sumOfWeights = 0;
         foreach (var item in rtrfs)
         {
             var weight = item.GetAttributeValue <decimal>("gcbase_weight");
             sumOfWeights += weight;
         }
         if (sumOfWeights == 1)
         {
             Entity riskTemplate  = _service.Retrieve("gcbase_risktemplate", riskTemplateId, new ColumnSet("statuscode"));
             var    optHelper     = new OptionSetHelper();
             int    indexOfStatus = optHelper.getIndexOfLabel("gcbase_risktemplate", "statuscode", "Active", _service);
             riskTemplate["statuscode"] = new OptionSetValue(indexOfStatus);
             _service.Update(riskTemplate);
         }
         else
         {
             Entity riskTemplate  = _service.Retrieve("gcbase_risktemplate", riskTemplateId, new ColumnSet("statuscode"));
             var    optHelper     = new OptionSetHelper();
             int    indexOfStatus = optHelper.getIndexOfLabel("gcbase_risktemplate", "statuscode", "Incomplete", _service);
             riskTemplate["statuscode"] = new OptionSetValue(indexOfStatus);
             _service.Update(riskTemplate);
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
        public Boolean generateTotalWeightedRiskScoreForRiskAssessment(Entity riskFactorValue)
        {
            try
            {
                //get all risk template risk factor count
                var             fcra = _service.Retrieve("gcbase_fundingcaseriskassessment", riskFactorValue.GetAttributeValue <EntityReference>("gcbase_fundingcaseriskassessment").Id, new ColumnSet("gcbase_risktemplate"));
                QueryExpression qe   = new QueryExpression("gcbase_risktemplateriskfactor");
                qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, fcra.GetAttributeValue <EntityReference>("gcbase_risktemplate").Id);
                qe.ColumnSet.AddColumn("gcbase_risktemplate");
                var qeResult = _service.RetrieveMultiple(qe).Entities;

                int riskTemplateRiskFactorCount = qeResult.Count();

                QueryExpression qe1 = new QueryExpression("gcbase_riskfactorvalue");
                qe1.Criteria.AddCondition("gcbase_fundingcaseriskassessment", ConditionOperator.Equal, riskFactorValue.GetAttributeValue <EntityReference>("gcbase_fundingcaseriskassessment").Id);
                qe1.ColumnSet.AddColumns("statuscode", "gcbase_risktemplateriskfactor", "gcbase_risklevel");
                var relatedRiskFactorValues = _service.RetrieveMultiple(qe1).Entities.ToList();

                int     validRiskFactorValueCount = 0;
                decimal totalWeighted             = 0;
                decimal totalUnWeighted           = 0;

                Guid riskTemplateId = qeResult.First().GetAttributeValue <EntityReference>("gcbase_risktemplate").Id;

                QueryExpression qeMultiplier = new QueryExpression("gcbase_risktemplateriskfactor");
                qeMultiplier.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, riskTemplateId);

                int multiplier = _service.RetrieveMultiple(qeMultiplier).Entities.Count();


                foreach (var item in relatedRiskFactorValues)
                {
                    var optHelper     = new OptionSetHelper();
                    int indexOfStatus = optHelper.getIndexOfLabel("gcbase_riskfactorvalue", "statuscode", "Completed", _service);

                    //get risk factor weight
                    var rf = _service.Retrieve("gcbase_risktemplateriskfactor", item.GetAttributeValue <EntityReference>("gcbase_risktemplateriskfactor").Id, new ColumnSet("gcbase_weight", "gcbase_multiplier"));



                    if (item.GetAttributeValue <OptionSetValue>("statuscode").Value == indexOfStatus)
                    {
                        validRiskFactorValueCount += 1;
                        var weight = rf.GetAttributeValue <decimal>("gcbase_weight");
                        // var multiplier = rf.GetAttributeValue<decimal>("gcbase_multiplier");

                        var riskLevel      = item.GetAttributeValue <OptionSetValue>("gcbase_risklevel");
                        var riskLevelValue = new OptionSetHelper();

                        var riskLevelText = riskLevelValue.getLabelFromField(item, "gcbase_risklevel", _service);
                        int riskVal       = 0;
                        if (riskLevelText == "1-Low")
                        {
                            riskVal = 1;
                        }
                        if (riskLevelText == "2-Medium")
                        {
                            riskVal = 2;
                        }
                        if (riskLevelText == "3-High")
                        {
                            riskVal = 3;
                        }

                        totalWeighted   += ((riskVal * weight) * multiplier);
                        totalUnWeighted += riskVal;
                    }
                }

                if (riskTemplateRiskFactorCount == validRiskFactorValueCount)
                {
                    //calculate assessed risk based on percentage of total risk.
                    var lowRiskMaxScore  = multiplier;
                    var midRiskMaxScore  = (multiplier * 3) - multiplier;
                    var highRiskMaxScore = multiplier * 3;

                    OptionSetValue assessedRisk = new OptionSetValue();

                    if (totalUnWeighted <= multiplier)
                    {
                        assessedRisk = new OptionSetValue(new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_assessedrisk", "1-Low", _service));
                    }
                    if (totalUnWeighted > multiplier && totalUnWeighted <= midRiskMaxScore)
                    {
                        assessedRisk = new OptionSetValue(new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_assessedrisk", "2-Medium", _service));
                    }
                    if (totalUnWeighted > midRiskMaxScore)
                    {
                        assessedRisk = new OptionSetValue(new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_assessedrisk", "3-High", _service));
                    }

                    //  var optHelper = new helpers.OptionSetHelper();
                    // int indexOfStatus = optHelper.getIndexOfLabel("gcbase_fundingcaseriskassessment", "statuscode", "Analyst Completed", _service);
                    // fcra["statuscode"] = new OptionSetValue(indexOfStatus);
                    fcra["gcbase_totalweightedscore"]   = totalWeighted;
                    fcra["gcbase_totalunweightedscore"] = totalUnWeighted;
                    fcra["gcbase_assessedrisk"]         = assessedRisk;
                    _service.Update(fcra);
                    //update funding case risk assessment to analyst completed state.
                }
                else
                {
                    var optHelper     = new OptionSetHelper();
                    int indexOfStatus = optHelper.getIndexOfLabel("gcbase_fundingcaseriskassessment", "statuscode", "Incomplete", _service);
                    fcra["statuscode"] = new OptionSetValue(indexOfStatus);
                    fcra["gcbase_totalweightedscore"]   = null;
                    fcra["gcbase_totalunweightedscore"] = null;
                    fcra["gcbase_assessedrisk"]         = null;
                    _service.Update(fcra);
                }

                return(true);
            }
            catch
            {
                return(false);
            }
        }
        public Boolean templateHasExistingCompletedAssessments()
        {
            QueryExpression qe = new QueryExpression("gcbase_fundingcaseriskassessment");
            qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, _riskTemplate.Id);

            var optHelper = new OptionSetHelper();
            int indexOfStatus = optHelper.getIndexOfLabel("gcbase_fundingcaseriskassessment", "statuscode", "Analyst Completed", _service);

            qe.Criteria.AddCondition("statuscode", ConditionOperator.Equal, indexOfStatus);
            var existingCompletedTemplates = _service.RetrieveMultiple(qe).Entities;
            // throw new InvalidPluginExecutionException("asfsdafasd", ex1);
            if (existingCompletedTemplates.Count() > 0)
            {
                return true;
            }
            return false;
        }
        public Boolean generateTotalWeightedRiskScoreForRiskAssessment(Entity riskFactorValue)
        {
            try
            {
                //get all risk template risk factor count
                var fcra = _service.Retrieve("gcbase_fundingcaseriskassessment", riskFactorValue.GetAttributeValue<EntityReference>("gcbase_fundingcaseriskassessment").Id, new ColumnSet("gcbase_risktemplate"));
                QueryExpression qe = new QueryExpression("gcbase_risktemplateriskfactor");
                qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, fcra.GetAttributeValue<EntityReference>("gcbase_risktemplate").Id);
                qe.ColumnSet.AddColumn("gcbase_risktemplate");
                var qeResult = _service.RetrieveMultiple(qe).Entities;

                int riskTemplateRiskFactorCount = qeResult.Count();

                QueryExpression qe1 = new QueryExpression("gcbase_riskfactorvalue");
                qe1.Criteria.AddCondition("gcbase_fundingcaseriskassessment", ConditionOperator.Equal, riskFactorValue.GetAttributeValue<EntityReference>("gcbase_fundingcaseriskassessment").Id);
                qe1.ColumnSet.AddColumns("statuscode", "gcbase_risktemplateriskfactor", "gcbase_risklevel");
                var relatedRiskFactorValues = _service.RetrieveMultiple(qe1).Entities.ToList();

                int validRiskFactorValueCount = 0;
                decimal totalWeighted = 0;
                decimal totalUnWeighted = 0;

                Guid riskTemplateId = qeResult.First().GetAttributeValue<EntityReference>("gcbase_risktemplate").Id;

                QueryExpression qeMultiplier = new QueryExpression("gcbase_risktemplateriskfactor");
                qeMultiplier.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, riskTemplateId);

                int multiplier = _service.RetrieveMultiple(qeMultiplier).Entities.Count();

                foreach (var item in relatedRiskFactorValues)
                {
                    var optHelper = new OptionSetHelper();
                    int indexOfStatus = optHelper.getIndexOfLabel("gcbase_riskfactorvalue", "statuscode", "Completed", _service);

                    //get risk factor weight
                    var rf = _service.Retrieve("gcbase_risktemplateriskfactor", item.GetAttributeValue<EntityReference>("gcbase_risktemplateriskfactor").Id, new ColumnSet("gcbase_weight", "gcbase_multiplier"));

                    if (item.GetAttributeValue<OptionSetValue>("statuscode").Value == indexOfStatus)
                    {
                        validRiskFactorValueCount += 1;
                        var weight = rf.GetAttributeValue<decimal>("gcbase_weight");
                        // var multiplier = rf.GetAttributeValue<decimal>("gcbase_multiplier");

                        var riskLevel = item.GetAttributeValue<OptionSetValue>("gcbase_risklevel");
                        var riskLevelValue = new OptionSetHelper();

                        var riskLevelText = riskLevelValue.getLabelFromField(item, "gcbase_risklevel", _service);
                        int riskVal = 0;
                        if (riskLevelText == "1-Low")
                        {
                            riskVal = 1;
                        }
                        if (riskLevelText == "2-Medium")
                        {
                            riskVal = 2;
                        }
                        if (riskLevelText == "3-High")
                        {
                            riskVal = 3;
                        }

                        totalWeighted += ((riskVal * weight) * multiplier);
                        totalUnWeighted += riskVal;
                    }
                }

                if (riskTemplateRiskFactorCount == validRiskFactorValueCount)
                {
                    //calculate assessed risk based on percentage of total risk.
                    var lowRiskMaxScore = multiplier;
                    var midRiskMaxScore = (multiplier * 3) - multiplier;
                    var highRiskMaxScore = multiplier * 3;

                    OptionSetValue assessedRisk = new OptionSetValue();

                    if (totalUnWeighted <= multiplier)
                    {
                        assessedRisk = new OptionSetValue(new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_assessedrisk", "1-Low", _service));
                    }
                    if (totalUnWeighted > multiplier && totalUnWeighted <= midRiskMaxScore)
                    {
                        assessedRisk = new OptionSetValue(new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_assessedrisk", "2-Medium", _service));
                    }
                    if (totalUnWeighted > midRiskMaxScore)
                    {
                        assessedRisk = new OptionSetValue(new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_assessedrisk", "3-High", _service));
                    }

                    //  var optHelper = new helpers.OptionSetHelper();
                    // int indexOfStatus = optHelper.getIndexOfLabel("gcbase_fundingcaseriskassessment", "statuscode", "Analyst Completed", _service);
                    // fcra["statuscode"] = new OptionSetValue(indexOfStatus);
                    fcra["gcbase_totalweightedscore"] = totalWeighted;
                    fcra["gcbase_totalunweightedscore"] = totalUnWeighted;
                    fcra["gcbase_assessedrisk"] = assessedRisk;
                    _service.Update(fcra);
                    //update funding case risk assessment to analyst completed state.
                }
                else
                {
                    var optHelper = new OptionSetHelper();
                    int indexOfStatus = optHelper.getIndexOfLabel("gcbase_fundingcaseriskassessment", "statuscode", "Incomplete", _service);
                    fcra["statuscode"] = new OptionSetValue(indexOfStatus);
                    fcra["gcbase_totalweightedscore"] = null;
                    fcra["gcbase_totalunweightedscore"] = null;
                    fcra["gcbase_assessedrisk"] = null;
                    _service.Update(fcra);
                }

                return true;
            }
            catch
            {
                return false;
            }
        }
        public Boolean generateTotalWeightedRiskScore()
        {
            try
            {
                var riskTemplateId = _riskTemplate.Id;
                QueryExpression qe = new QueryExpression("gcbase_risktemplateriskfactor");
                qe.Criteria.AddCondition("gcbase_risktemplate", ConditionOperator.Equal, riskTemplateId);
                qe.ColumnSet.AddColumns("gcbase_weight");
                var rtrfs = _service.RetrieveMultiple(qe).Entities;
                decimal sumOfWeights = 0;
                foreach (var item in rtrfs)
                {
                    var weight = item.GetAttributeValue<decimal>("gcbase_weight");
                    sumOfWeights += weight;
                }
                if (sumOfWeights == 1)
                {
                    Entity riskTemplate = _service.Retrieve("gcbase_risktemplate", riskTemplateId, new ColumnSet("statuscode"));
                    var optHelper = new OptionSetHelper();
                    int indexOfStatus = optHelper.getIndexOfLabel("gcbase_risktemplate", "statuscode", "Active", _service);
                    riskTemplate["statuscode"] = new OptionSetValue(indexOfStatus);
                    _service.Update(riskTemplate);
                }
                else
                {
                    Entity riskTemplate = _service.Retrieve("gcbase_risktemplate", riskTemplateId, new ColumnSet("statuscode"));
                    var optHelper = new OptionSetHelper();
                    int indexOfStatus = optHelper.getIndexOfLabel("gcbase_risktemplate", "statuscode", "Incomplete", _service);
                    riskTemplate["statuscode"] = new OptionSetValue(indexOfStatus);
                    _service.Update(riskTemplate);
                }
                return true;
            }
            catch
            {
                return false;

            }
        }
        /// <summary>
        /// A plug-in that creates a follow-up task activity when a new account is created.
        /// </summary>
        /// <remarks>Register this plug-in on the Create message, account entity,
        /// and asynchronous mode.
        /// </remarks>
        public void Execute(IServiceProvider serviceProvider)
        {
            //Extract the tracing service for use in debugging sandboxed plug-ins.
            ITracingService tracingService =
                (ITracingService)serviceProvider.GetService(typeof(ITracingService));

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

            // The InputParameters collection contains all the data passed in the message request.
            if (context.InputParameters.Contains("Target") &&
                context.InputParameters["Target"] is Entity)
            {

                // Obtain the target entity from the input parameters.
                Entity entity = (Entity)context.InputParameters["Target"];

                if (entity.LogicalName != "gcbase_fundingcase")
                    return;

                FaultException ex1 = new FaultException();
              //  throw new InvalidPluginExecutionException("test", ex1);

                try
                {
                     //// Obtain the organization service reference.
                    IOrganizationServiceFactory serviceFactory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
                    IOrganizationService service = serviceFactory.CreateOrganizationService(context.UserId);

                    AutoNumbering autoNumbering = new AutoNumbering(entity, service);
                    String caseNumber = autoNumbering.getAutoNumber();

                    entity["gcbase_name"] = caseNumber;
                    service.Update(entity);
                    if (entity.Attributes.Contains("gcbase_amountsbyfiscalyearserver"))
                    {

                        char[] delimitedChar = { ';' };

                        Entity fundingAmountByFY = new Entity("gcbase_fundingcaseamountbyfy");
                        string[] yearlyAmounts = entity.Attributes["gcbase_amountsbyfiscalyearserver"].ToString().Split(delimitedChar);
                        EntityReference fundCentre = entity.GetAttributeValue<EntityReference>("gcbase_program");
                        foreach (string ya in yearlyAmounts)
                        {

                            fundingAmountByFY["gcbase_fundingcase"] = new EntityReference("gcbase_fundingcase", entity.Id);
                            //fys[index] = (string)Enum.GetName(typeof(goal_fiscalyear), year);
                            OptionSetValue fy = new OptionSetValue();
                            var indexForFY = ya.IndexOf("Y");
                            var indexForAmount = ya.IndexOf("-");
                            var yearStr = ya.Substring(indexForFY + 1,4);
                            var amountStr = ya.Substring(indexForAmount + 1);
                            tracingService.Trace("year is:" + yearStr);
                            tracingService.Trace("amount is:" + amountStr);
                            Money amount = new Money(decimal.Parse(amountStr));
                            fy.Value = Int32.Parse(yearStr);
                            fundingAmountByFY["gcbase_fiscalyear"] = fy;
                            fundingAmountByFY["gcbase_amount"] = amount;
                            fundingAmountByFY["gcbase_fundcentre"] = fundCentre;
                            tracingService.Trace("PostFundingCasePlugin: Creating the budget item.");
                            service.Create(fundingAmountByFY);
                            tracingService.Trace(ya);
                        }
                    }
                    if (entity.Attributes.Contains("gcbase_program"))
                    {
                        ColumnSet cols = new ColumnSet
                        (
                                new String[] {"gcbase_fundingcaseriskrequired"}
                        );

                        //program configuration options
                        var program = service.Retrieve("gcbase_fundcentre", entity.GetAttributeValue<EntityReference>("gcbase_program").Id, cols);
                        tracingService.Trace("there");
                        if (program.GetAttributeValue<Boolean>("gcbase_fundingcaseriskrequired"))
                        {
                            var ratype = new OptionSetHelper().getIndexOfLabel("gcbase_fundingcaseriskassessment", "gcbase_fundingcaseriskassessmenttype", "Initial", service);
                            OptionSetValue raTypeOpt = new OptionSetValue(ratype);

                            //create initial risk assessment - should be custom class since this will be reused by other plugins
                            if (!new RiskTemplate(null, service).generateRiskAssessment(entity, raTypeOpt))
                            {
                                throw new InvalidPluginExecutionException("The funding program is not fully configured therefore a funding case cannot be created yet", ex1);
                            }

                            //newRA.generateAssessment();
                        }

                        //var results = service.Retrieve("gcbase_fundcentre", entity.GetAttributeValue<Guid>("gcbase_program"), null);

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

                catch (Exception ex)
                {
                    tracingService.Trace("FollowupPlugin: {0}", ex.ToString());
                    throw;
                }
            }
        }