예제 #1
0
        /// <summary>
        /// Loop through the Validators and check if the lead is valid.  This function
        /// loops through all the validators, even if it finds one that is not valid and
        /// collects all the reasons why a lead does not qualify for being processed by the campaign manager.
        /// </summary>
        /// <param name="leadEntity"></param>
        /// <returns></returns>
        public bool ValidLead(ILeadEntity leadEntity)
        {
            string processContext = "ValidLead";
            bool   allValid       = true;

            _loggerClient.Log(new DefaultLoggerClientObject
            {
                OperationContext = "Validating the Lead",
                ProcessContext   = processContext,
                SolutionContext  = solutionContext
            });
            try
            {
                // Validate the lead using the collection of validators
                // Process all validators before returning.
                foreach (var validator in _campaignManagerValidators)
                {
                    var valid = validator.ValidLead(leadEntity);
                    if (!valid)
                    {
                        allValid = false;
                    }
                }

                if (!allValid)
                {
                    var errorStr = String.Join(",", leadEntity.ErrorList.ToArray());
                    _loggerClient.Log(new DefaultLoggerClientErrorObject
                    {
                        OperationContext = $"Validation failed: {errorStr}.",
                        ProcessContext   = processContext,
                        SolutionContext  = solutionContext,
                        EventType        = LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject
                {
                    OperationContext = "Exception in Validation of Lead in CampaignManager Validator.",
                    ProcessContext   = processContext,
                    SolutionContext  = solutionContext,
                    Exception        = ex,
                    ErrorContext     = ex.Message,
                    EventType        = LoggerClientEventType.LoggerClientEventTypes.Error
                });
                return(false);
            }

            return(true);
        }
예제 #2
0
        /// <summary>
        /// When a lead is received on the Notification Channel, the Campaign Manager
        /// process will be executed.  See Campaign Manager constructor.
        /// </summary>
        /// <param name="receiveAction"></param>
        public void SetupAddOnReceiveActionToChannel(Action <ILeadEntity> receiveAction)
        {
            var processContext = "SetupAddOnReceiveActionToChannel";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Setting up the function to call when subscriber receives a message.", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });

            _notificationSubscriber.AddOnReceiveActionToChannel(receiveAction);
            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Finished setting up the function to call when subscriber receives a message.", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
        }
예제 #3
0
        /// <summary>
        /// Decorate the Lead by adding the Campaign Manager Results List to the Results Collection
        /// </summary>
        /// <param name="leadEntity"></param>
        /// <param name="campaignManagerResultList"></param>
        public void DecorateLead(ILeadEntity leadEntity, List <IResult> campaignManagerResultList)
        {
            if (leadEntity == null)
            {
                throw new ArgumentNullException(nameof(leadEntity));
            }
            if (campaignManagerResultList?.Any() == true)
            {
                string processContext = "DecorateLead";

                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = "Decorating the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });

                // The Results Collection was not created yet - shouldn't happen
                if (leadEntity.ResultCollection == null)
                {
                    leadEntity.ResultCollection = new DefaultResultCollection();
                }

                // Add the decorator result time & status
                campaignManagerResultList.Add(new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampEndKey, DateTime.Now));
                campaignManagerResultList.Add(new DefaultResult(ResultKeys.DecoratorStatusKey, ResultKeys.ResultKeysStatusEnum.Processed.ToString()));

                // If there has been previous CampaignManager results - add them to the list and then assign as array
                if (leadEntity.ResultCollection.CampaignManagerCollection != null)
                {
                    campaignManagerResultList.AddRange(leadEntity.ResultCollection.CampaignManagerCollection.ToList());
                }

                // Assign all Campaign Manager Results that were Recorded
                leadEntity.ResultCollection.CampaignManagerCollection = campaignManagerResultList.ToArray();
            }
        }
예제 #4
0
        public void DecorateLead(ILeadEntity leadEntity, List <IResult> leadCollectorResultList)
        {
            string processContext = "DecorateLead";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Decorating the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
            });

            // Create LeadCollector Results
            if (leadEntity.ResultCollection == null)
            {
                leadEntity.ResultCollection = new DefaultResultCollection();
            }

            // If there has been LeadCollectorCollection Decoration
            if (leadEntity.ResultCollection.LeadCollectorCollection != null)
            {
                leadCollectorResultList.AddRange(leadEntity.ResultCollection.LeadCollectorCollection.ToList());
            }

            // Add Decorator Processed
            leadCollectorResultList.Add(new DefaultResult(ResultKeys.DecoratorStatusKey, ResultKeys.ResultKeysStatusEnum.Processed.ToString()));

            // Assign all Lead Collector Results that were Recorded
            leadEntity.ResultCollection.LeadCollectorCollection = leadCollectorResultList.ToArray();
        }
예제 #5
0
        /// <summary>
        /// Publish Lead to ...... POE? or another Resolver....
        /// </summary>
        /// <param name="leadEntity"></param>
        public void PublishLead(ILeadEntity leadEntity)
        {
            var processContext = "PublishLead";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = JsonConvert.SerializeObject(leadEntity, Newtonsoft.Json.Formatting.Indented), ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
        }
예제 #6
0
        public bool ConstraintMet(ILeadEntity leadEntity)
        {
            string processContext = "ClearedFilter";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Filter the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
            var errorStr = string.Empty;

            try
            {
                //retrieve activityGuid from leadEntity
                var activityGuidValue = leadEntity.Context.SingleOrDefault(item => item.Id == ContextKeys.ActivityGuidKey)?.Value;
                if (activityGuidValue == null)
                {
                    errorStr += "No activityGuid Found In Context of LeadEntityObject\n";
                }
                else
                {
                    Guid.TryParse(activityGuidValue.ToString(), out Guid activityGuid);
                    //Check to see if leadEntity activity Guid exists in array
                    if (_mockedActivityGuidArray.Count(ag => ag == activityGuid) != 0)
                    {
                        errorStr += $"Activity Guid Found in Duplicate Check Filter. Guid: {activityGuid}\n";
                    }
                }
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = ex.Message, ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventType.LoggerClientEventTypes.Error
                });
                return(false);
            }

            if (errorStr != String.Empty)
            {
                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = errorStr, ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
                return(false);
            }
            return(true);
        }
예제 #7
0
        /// <summary>
        /// Constructor for CampaignConfig
        /// The CampaignId is used in the factories to retrieve the controls (i.e. Validators, Controllers (Rules & Filters).
        /// </summary>
        /// <param name="campaignManagerId"></param>
        /// <param name="validatorFactory"></param>
        /// <param name="campaignManagerPublisher"></param>
        /// <param name="loggerClient"></param>
        /// <param name="campaignManagerSubscriber"></param>
        /// <param name="campaignCollection"></param>
        /// <param name="campaignManagerDecorator"></param>
        /// <param name="campaignManagerResolver"></param>
        public CampaignManagerConfig(int campaignManagerId,
                                     IValidatorFactory validatorFactory,
                                     ISubscriber campaignManagerSubscriber,
                                     ICampaign[] campaignCollection,
                                     IDecorator campaignManagerDecorator,
                                     IResolver campaignManagerResolver,
                                     IPublisher campaignManagerPublisher,
                                     ILoggerClient loggerClient)
        {
            if (campaignManagerId <= 0)
            {
                throw new ArgumentException($"Error: {solutionContext}: campaignManagerId = {campaignManagerId}");
            }
            _loggerClient = loggerClient ?? throw new ArgumentNullException(nameof(loggerClient));

            var processContext = "CampaignManagerConfig";

            try
            {
                // Subscriber
                _campaignManagerSubscriber = campaignManagerSubscriber ?? throw new ArgumentNullException(nameof(campaignManagerSubscriber));
                // When the subscriber receives a lead, invoke the CampaignManagerDriver
                //TODO: _campaignManagerSubscriber.SetupAddOnReceiveActionToChannel(CampaignManager.CampaignManagerDriver);
                //Retrieve the applicable Validators from the Factory for this campaign - If they are defined,
                // Create the CampaignManagerValidator that is the wrapper.
                var validatorFactoryIn = validatorFactory ?? throw new ArgumentNullException(nameof(validatorFactory));
                _validators = validatorFactoryIn.BuildCampaignValidators(campaignManagerId);
                if (_campaignManagerValidator == null)
                {
                    CampaignManagerValidator = new CampaignManagerValidator(Validators, _loggerClient);
                }

                // Campaigns that are managed by the Campaign Manager
                _campaignCollection = campaignCollection ?? throw new ArgumentNullException(nameof(campaignCollection));

                // CampaignManager Decorator
                _campaignManagerDecorator = campaignManagerDecorator ??
                                            throw new ArgumentNullException(nameof(campaignManagerDecorator));

                // So this assignment will change and the Resolver will be created if we start changing it to a collection of resolvers.....
                // This Resolver will become a wrapper.
                _campaignManagerResolver = campaignManagerResolver ??
                                           throw new ArgumentNullException(nameof(campaignManagerResolver));

                // Publisher
                _campaignManagerPublisher = campaignManagerPublisher ??
                                            throw new ArgumentNullException(nameof(campaignManagerPublisher));
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = "Exception raised during assembly of Campaign Configuration.", ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventType.LoggerClientEventTypes.Error
                });
                throw;
            }
        }
예제 #8
0
        public bool ConstraintMet(ILeadEntity leadEntity)
        {
            string processContext = "ValidateForRule";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Validating the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
            var errorStr = string.Empty;

            try
            {
                var priorInsuranceValue = leadEntity.Properties.SingleOrDefault(item => item.Id == PropertyKeys.PriorInsuranceKey)?.Value;

                if ((priorInsuranceValue == null) || (!bool.TryParse(priorInsuranceValue.ToString(), out bool priorInsurance)))
                {
                    errorStr += "Prior Insurance not set In Properties of LeadEntityObject\n";
                }
                else
                {
                    if (priorInsurance == _mockedExcludePriorInsurance)
                    {
                        errorStr += $"Lead failed Rules Processing - Prior Insurance set to {_mockedExcludePriorInsurance}.\n";
                    }
                }
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = "\nPrior Insurance", ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventType.LoggerClientEventTypes.Error
                });
                return(false);
            }

            if (errorStr != String.Empty)
            {
                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = errorStr, ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
                return(false);
            }
            return(true);
        }
예제 #9
0
        /// <summary>
        /// Publish Lead to ...... POE?
        /// </summary>
        /// <param name="leadEntity"></param>
        public void PublishLead(ILeadEntity leadEntity)
        {
            var processContext = "PublishLead";

            // TODO - this will publish to a component outside of LMS
            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = JsonConvert.SerializeObject(leadEntity, Newtonsoft.Json.Formatting.Indented), ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
            // Pass leadEntity onto channel to be picked up by Entity sending the notification
            _notificationChannelPublisher.BroadcastMessage(leadEntity);
        }
예제 #10
0
        /// <summary>
        /// Validate the lead using the Collection of Validators
        /// </summary>
        /// <param name="leadEntity"></param>
        /// <returns></returns>
        public bool ValidLead(ILeadEntity leadEntity)
        {
            string processContext = "ValidLead";
            bool   allValid       = true;

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Validating the Lead", ProcessContext = processContext, SolutionContext = solutionContext
            });
            try
            {
                // Validate the lead using the collection of validators
                // Process all validators before returning.
                foreach (var validator in _leadCollectorValidators)
                {
                    var valid = validator.ValidLead(leadEntity);
                    if (!valid)
                    {
                        allValid = false;
                    }
                }
                if (!allValid)
                {
                    _loggerClient.Log(new DefaultLoggerClientErrorObject {
                        OperationContext = "Validation failed", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Error
                    });
                    return(false);
                }
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject
                {
                    OperationContext = "Exception in Validation of Lead", ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Error
                });
                return(false);
            }

            return(true);
        }
예제 #11
0
        public async Task Invoke(HttpContext httpContext)
        {
            httpContext.Request.EnableBuffering();
            var request = await FormatRequest(httpContext.Request);

            _loggerClient.Log(request);

            httpContext.Request.Body.Position = 0;

            await _next(httpContext);

            ///depois
        }
예제 #12
0
        /// <summary>
        /// Persist Lead into DB TBD.
        /// [ApprovedLeadID]
        // TODO
        //,[ProcessedLead_Id] ???????? - Insert into LeadEntity??? / Lookup? Done in Persistor of CM
        //,[LeadEntityGUID]
        //,[CustomerActivityGUID]
        //,[CustomerSessionGUID]
        //,[Brand_ID]
        // TODO
        //,[Insurer_ID] ???????
        //,[Site_ID]
        //,[Product_ID]
        //,[Campaign_ID]
        //,[CampaignManager_ID]
        //,[LeadCreationTime]
        //,[CreationDate]
        /// </summary>
        /// <param name="leadEntity"></param>
        public void PersistLead(ILeadEntity leadEntity)
        {
            // TODO - Implementation & NULL CHECKING!!!! - Check for NULL for each of the collections & values that need to be persisted
            var processContext = "PersistLead..................... TBD";
            var leadEntityGuid = leadEntity.Context.SingleOrDefault(item => item.Id == ContextKeys.LeadEntityGuidKey)?.Value;
            var activityGuid   = leadEntity.Context.SingleOrDefault(item => item.Id == ContextKeys.ActivityGuidKey)?.Value;
            var sessionGuid    = leadEntity.Context.SingleOrDefault(item => item.Id == ContextKeys.SessionGuidKey)?.Value;
            var brandId        = leadEntity.Activity.SingleOrDefault(a => a.Id == ActivityKeys.BrandIdKey)?.Value;
            var siteId         = leadEntity.Context.SingleOrDefault(item => item.Id == ContextKeys.SiteIDKey)?.Value;
            var productId      = leadEntity.Context.SingleOrDefault(item => item.Id == ContextKeys.QuotedProductKey)?.Value;
            // TODO - the leads wont always have these ResultCollections - CHECK!!!!!!!!
            var cmId = leadEntity.ResultCollection.CampaignManagerCollection
                       .SingleOrDefault(item => item.Id == ResultKeys.CampaignManagerKeys.CampaignManagerIdKey)?.Value;
            var cId = leadEntity.ResultCollection.PreferredCampaignCollection
                      .SingleOrDefault(item => item.Id == ResultKeys.CampaignKeys.CampaignIdKey)?.Value;
            // TODO Check existence of collection
            var leadCreationTime = leadEntity.ResultCollection.LeadCollectorCollection
                                   .SingleOrDefault(item => item.Id == ResultKeys.DiagnosticKeys.TimeStampStartKey)?.Value;


            var tmpStrToDb =
                $"ApprovedLeadTable:\nLeadEntityGuid:{leadEntityGuid}\nActivitityGuid:{activityGuid}\n";

            tmpStrToDb += $"SessionGuid:{sessionGuid}\nBrandId:{brandId}\nSiteId:{siteId}\nProductId:{productId}\n";
            tmpStrToDb += $"CampaignManagerId:{cmId}\nCampaign:{cId}\nLeadCreation:{leadCreationTime}\n";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = JsonConvert.SerializeObject(leadEntity, Newtonsoft.Json.Formatting.Indented), ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = tmpStrToDb, ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = JsonConvert.SerializeObject(leadEntity, Newtonsoft.Json.Formatting.Indented), ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
        }
예제 #13
0
        /// <summary>
        /// ConstraintMet function to loop through all the Filters and Rules in the order as instantiated
        /// in the constructor.  If any rule/filter constraint is not met, the function returns false,
        /// else the function returns true.
        /// </summary>
        /// <param name="leadEntity"></param>
        /// <returns></returns>
        public bool ConstraintMet(ILeadEntity leadEntity)
        {
            string processContext = "ConstraintMet";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Check Controller (Filter and Rule) Constraints", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });

            try
            {
                // Check to see if the lead meets all the constraints set up for by campaign by looping through
                // the collection of controllers.
                // Return as soon as a constraint is not met for one of the rules/filters.
                foreach (var controller in _campaignControllers)
                {
                    if (!controller.ConstraintMet(leadEntity))
                    {
                        var errorStr = String.Join(",", leadEntity.ErrorList.ToArray());
                        _loggerClient.Log(new DefaultLoggerClientErrorObject {
                            OperationContext = $"Controller constraint not met: {errorStr}.", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                        });
                        return(false);
                    }
                }
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = ex.Message, ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventType.LoggerClientEventTypes.Error
                });
                return(false);
            }


            return(true);
        }
예제 #14
0
        /// <summary>
        /// Campaign Manager Driver to control campaigns
        /// </summary>
        /// <param name="leadEntity"></param>
        public void CampaignManagerDriver(ILeadEntity leadEntity)
        {
            if (leadEntity == null)
            {
                throw new ArgumentNullException(nameof(leadEntity));
            }

            var processContext = "CampaignManagerDriver";

            _campaignManagerResultList = new List <IResult> {
                new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampStartKey, DateTime.Now)
            };
            _campaignManagerResultList.Add(new DefaultResult(ResultKeys.CampaignManagerKeys.CampaignManagerIdKey, CampaignManagerId));
            // Check that there are Campaigns to be Managed
            if (_campaignManagerConfig.CampaignCollection?.Any() != true)
            {
                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = "There are no Campaigns to be Managed.", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
                _campaignManagerResultList.Add(new DefaultResult(ResultKeys.CampaignManagerKeys.CampaignCountKey, 0));
                _campaignManagerConfig.CampaignManagerDecorator.DecorateLead(leadEntity, _campaignManagerResultList);
                return;
            }

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Validating Lead Within the Campaign Manager.", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
            // Validate the Lead to see if it should be sent through campaigns
            if (_campaignManagerConfig.CampaignManagerValidator != null)
            {
                if (_campaignManagerConfig.CampaignManagerValidator.ValidLead(leadEntity).Equals(false))
                {
                    _campaignManagerResultList.Add(new DefaultResult(ResultKeys.ValidatorStatusKey,
                                                                     ResultKeys.ResultKeysStatusEnum.Failed.ToString()));
                    _loggerClient.Log(new DefaultLoggerClientObject {
                        OperationContext = "Lead is not valid for these Campaigns.", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                    _campaignManagerConfig.CampaignManagerDecorator.DecorateLead(leadEntity, _campaignManagerResultList);
                    return;
                }
            }
            _campaignManagerResultList.Add(new DefaultResult(ResultKeys.ValidatorStatusKey,
                                                             ResultKeys.ResultKeysStatusEnum.Processed.ToString()));

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Lead is valid for these Campaigns - Start Campaigns.", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });

            // Kick off all the campaigns with a task and then resolve following.
            ProcessCampaigns(leadEntity);
        }
예제 #15
0
        public void PublishLead(ILeadEntity leadEntity)
        {
            string processContext = "PublishLead";

            _loggerClient.Log(new DefaultLoggerClientObject
            {
                OperationContext = "Publishing the Lead",
                ProcessContext   = processContext,
                SolutionContext  = solutionContext,
                EventType        = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
            });

            _leadEntity = leadEntity;

            // Pass leadEntity onto channel to be picked up by Subscribed Campaign Managers
            //notificationChannelPublisher.BroadcastMessage(JsonConvert.SerializeObject(leadEntity));
            _notificationChannelPublisher.BroadcastMessage(leadEntity);
        }
예제 #16
0
        /// <summary>
        /// From the classNameList - Build a list of Validators
        /// </summary>
        /// <param name="validatorClassAndAssemblyList"></param>
        /// <returns></returns>
        private List <IValidator> BuildValidators(List <ValidatorClassAndAssemblyData> validatorClassAndAssemblyList)
        {
            string processContext = "BuildValidators";
            var    validatorList  = new List <IValidator>();

            try
            {
                foreach (var validator in validatorClassAndAssemblyList)
                {
                    var  assembly  = System.Reflection.Assembly.LoadFrom(validator.AssemblyName + ".dll");
                    Type classType = (from type in assembly.GetTypes()
                                      where type.IsClass && type.Name == validator.ClassName
                                      select type).Single();
                    // Create an instances of the Validator Class
                    validatorList.Add((IValidator)Activator.CreateInstance(classType));
                }
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = "Exception in Creating Validator Factory", ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventType.LoggerClientEventTypes.Error
                });
            }

            return(validatorList);

            //foreach (var className in validatorClassNameList)
            //{
            //    Type classType =
            //        (from assemblies in AppDomain.CurrentDomain.GetAssemblies()
            //            from type in assemblies.GetTypes()
            //            where type.IsClass && type.Name == className
            //            select type).Single();

            //    // Create an instances of the Validator Class
            //    validatorList.Add((IValidator)Activator.CreateInstance(classType));

            //}
            //return validatorList;
        }
예제 #17
0
        /// <summary>
        /// Constructor for CampaignConfig
        /// The CampaignId is used in the factories to retrieve the controls (i.e. Validators, Controllers (Rules & Filters).
        /// </summary>
        /// <param name="campaignId"></param>
        /// <param name="validatorFactory"></param>
        /// <param name="controllerFactory"></param>
        /// <param name="loggerClient"></param>
        public CampaignConfig(int campaignId, IValidatorFactory validatorFactory, IControllerFactory controllerFactory, ILoggerClient loggerClient)
        {
            if (campaignId <= 0)
            {
                throw new ArgumentException($"Error: {solutionContext}: campaignId = {campaignId}");
            }
            _loggerClient = loggerClient ?? throw new ArgumentNullException(nameof(loggerClient));

            var processContext = "CampaignConfig";

            try
            {
                //Retrieve the applicable Validators from the Factory for this campaign
                var validatorFactoryIn = validatorFactory ?? throw new ArgumentNullException(nameof(validatorFactory));
                _validators = validatorFactoryIn.BuildCampaignValidators(campaignId);
                if (_campaignValidator == null)
                {
                    _campaignValidator = new CampaignValidator(Validators, _loggerClient);
                }

                //Retrieve the applicable Controllers from the Factory for this campaign
                var controllerFactoryIn = controllerFactory ?? throw new ArgumentNullException(nameof(controllerFactory));
                _controllers = controllerFactoryIn.BuildCampaignControllers(campaignId);
                if (_campaignController == null)
                {
                    _campaignController = new CampaignController(Controllers, _loggerClient);
                }
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = "Exception raised during assembly of Campaign Configuration.", ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventType.LoggerClientEventTypes.Error
                });
                throw;
            }
        }
예제 #18
0
        /// <summary>
        /// Process the Lead Collected
        /// </summary>
        /// <param name="leadEntity"></param>
        public void CollectLead(ILeadEntity leadEntity)
        {
            if (leadEntity == null)
            {
                throw new ArgumentNullException(nameof(leadEntity));
            }
            string processContext = "CollectLead";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Collected the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
            });

            // Create the results list

            var leadCollectorResultCollectionList = new List <IResult> {
                new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampStartKey, DateTime.Now)
            };

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Validating the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
            });

            try
            {
                //If the lead is valid, decorate and publish
                if (_leadValidator.ValidLead(leadEntity).Equals(true))
                {
                    leadCollectorResultCollectionList.Add(new DefaultResult(ResultKeys.ValidatorStatusKey, ResultKeys.ResultKeysStatusEnum.Processed.ToString()));

                    // Broadcast to the Campaigns
                    _loggerClient.Log(new DefaultLoggerClientObject {
                        OperationContext = "Publishing the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                    _leadPublisher.PublishLead(leadEntity);
                    leadCollectorResultCollectionList.Add(new DefaultResult(ResultKeys.LeadCollectorKeys.PublisherStatusKey, ResultKeys.ResultKeysStatusEnum.Processed.ToString()));

                    // Decorate
                    _loggerClient.Log(new DefaultLoggerClientObject {
                        OperationContext = "Decorating the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                    leadCollectorResultCollectionList.Add(new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampEndKey, DateTime.Now));
                    _leadDecorator.DecorateLead(leadEntity, leadCollectorResultCollectionList);
                }
                else
                {
                    leadCollectorResultCollectionList.Add(new DefaultResult(ResultKeys.ValidatorStatusKey, ResultKeys.ResultKeysStatusEnum.Failed.ToString()));

                    // Decorate
                    _loggerClient.Log(new DefaultLoggerClientObject {
                        OperationContext = "Decorating the Lead", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                    leadCollectorResultCollectionList.Add(new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampEndKey, DateTime.Now));
                    _leadDecorator.DecorateLead(leadEntity, leadCollectorResultCollectionList);

                    // TODO - Show the lead for demo Remove afterwards and move "//Decorate part below if stmnt
                    _loggerClient.Log(new DefaultLoggerClientObject {
                        OperationContext = JsonConvert.SerializeObject(leadEntity, Newtonsoft.Json.Formatting.Indented), ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                }
            }
            catch (Exception exception)
            {
                // Add results to Lead Entity
                _leadDecorator.DecorateLead(leadEntity, leadCollectorResultCollectionList);
                // Log an Error
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = "Collected the Lead", ProcessContext = processContext, SolutionContext = solutionContext, ErrorContext = exception.Message, Exception = exception, EventType = LoggerClientEventTypeControl.Interface.Constants.LoggerClientEventType.LoggerClientEventTypes.Error
                });
                throw;
            }
        }
예제 #19
0
        /// <summary>
        /// Resolve the leads
        /// Using the results collection list from each of the campaigns - assign the successful campaign to the
        /// Preferred ResultList where the campaign was successful.
        /// </summary>
        /// <param name="leadEntity"></param>
        public void ResolveLead(ILeadEntity leadEntity)
        {
            var processContext = "ResolveLead";

            if ((leadEntity.ResultCollection.CampaignCollection == null) || leadEntity.ResultCollection.CampaignCollection.Length == 0)
            {
                _campaignManagerResultList = new List <IResult> {
                    new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampStartKey, DateTime.Now)
                };
                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = "There are no Leads to resolve", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
                return;
            }

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = "Resolving the campaign results list", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });
            // Choose the campaign info with the highest priority and successful
            var ix              = 0;
            var priorityIx      = 0;
            var highestPriority = Int32.MaxValue;
            var campaignResultCollectionList = leadEntity.ResultCollection.CampaignCollection.ToList();

            foreach (var resultList in campaignResultCollectionList)
            {
                // If the campaign processed successfully, then seek the Campaign that was successful and has the highest priority
                var campaignSuccessStatus = resultList.SingleOrDefault(r => r.Id == ResultKeys.CampaignKeys.LeadSuccessStatusKey)
                                            ?.Value;
                if (campaignSuccessStatus != null)
                {
                    if (campaignSuccessStatus.ToString() == ResultKeys.ResultKeysStatusEnum.Processed.ToString())
                    {
                        var value = resultList
                                    .SingleOrDefault(r => r.Id == ResultKeys.CampaignKeys.CampaignPriorityKey)
                                    ?.Value;
                        var priorityStr = value?.ToString();
                        if (priorityStr != null)
                        {
                            if (Int32.TryParse(priorityStr, out int priorityInt))
                            {
                                if (priorityInt < highestPriority)
                                {
                                    //This is the array position for the campaign with the highest priority
                                    priorityIx      = ix;
                                    highestPriority = priorityInt;
                                }
                            }
                        }
                    }
                }
                ix++;
            }

            // Check that there was a preferred campaign and assign the PreferredCampaignCollection
            if (highestPriority != Int32.MaxValue)
            {
                leadEntity.ResultCollection.PreferredCampaignCollection = leadEntity.ResultCollection.CampaignCollection[priorityIx];
                var campaignName = leadEntity.ResultCollection.PreferredCampaignCollection.SingleOrDefault(r => r.Id == ResultKeys.CampaignKeys.CampaignNameKey)
                                   ?.Value;
                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = $"Lead selected is coming from Campaign: {campaignName} ", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
            }
            else
            {
                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = "Did not find valid priority within Campaign Result List", ProcessContext = processContext, SolutionContext = SolutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
            }
        }
예제 #20
0
        /// <summary>
        /// Process the lead through the Campaign to see if the Lead Qualifies through the
        /// Validators, Controls (Filters and Rules).
        /// The Result List is the return from the Campaign to the Campaign Manager.
        /// The Result List is a key value pair list to indicate if a lead qualifies or not.
        /// The Validators and Controls Components outcomes are logged in the Result List.
        /// Ultimately the ResultKeys.CampaignKeys.LeadSuccessStatusKey indicates the final
        /// outcome following the procesing through the Validators and Controls.
        /// The Campaign Manager uses the Result List to decide if the Lead qualifies for
        /// further processing within the Campaign Manager Resolver.
        /// </summary>
        /// <param name="leadEntity"></param>
        /// <returns>List&lt;IResult&gt;</returns>
        public List <IResult> ProcessLead(ILeadEntityImmutable leadEntity)
        {
            if (leadEntity == null)
            {
                throw new ArgumentNullException(nameof(leadEntity));
            }
            string processContext = "ProcessLead";

            _loggerClient.Log(new DefaultLoggerClientObject {
                OperationContext = $"Processing the Lead in {CampaignDescription}", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
            });

            try
            {
                // Create Campaign Result List and insert Campaign Details
                _campaignResultList = new List <IResult> {
                    new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampStartKey, DateTime.Now)
                };
                _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.CampaignIdKey, CampaignId));
                _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.CampaignNameKey, CampaignDescription));
                _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.CampaignPriorityKey, CampaignPriority));

                // To use the Validators/Controls (Rules and Filters) the provisional mutable leadEntity needs to be passed
                ILeadEntity tmpMutableLeadEntity = new DefaultLeadEntityImmutableProvisionLocal(leadEntity);
                // Validate the Lead
                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = $"Validating the Lead for {CampaignDescription} ", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
                if (_campaignConfig.CampaignValidator.ValidLead(tmpMutableLeadEntity).Equals(true))
                {
                    // Add that Validation passed to ResultsCollection
                    _campaignResultList.Add(new DefaultResult(ResultKeys.ValidatorStatusKey,
                                                              ResultKeys.ResultKeysStatusEnum.Processed.ToString()));
                }
                else
                {
                    // For now show that the lead has not processed successfully through the campaign and should not continue on to the resolver
                    _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.LeadSuccessStatusKey, ResultKeys.ResultKeysStatusEnum.Failed.ToString()));
                    _campaignResultList.Add(new DefaultResult(ResultKeys.ValidatorStatusKey, ResultKeys.ResultKeysStatusEnum.Failed.ToString()));
                    _loggerClient.Log(new DefaultLoggerClientObject {
                        OperationContext = "LeadEntity failed during Campaign Validation", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                    return(_campaignResultList);
                }

                _loggerClient.Log(new DefaultLoggerClientObject {
                    OperationContext = $"Passing lead through CampaignController Constraints in {CampaignDescription} ", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                });
                if (_campaignConfig.CampaignController.ConstraintMet(tmpMutableLeadEntity))
                {
                    _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.ControlStatusKey,
                                                              ResultKeys.ResultKeysStatusEnum.Processed.ToString()));
                }
                else
                {
                    // For now show that the lead has not processed successfully through the campaign and should not continue on to the resolver
                    _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.LeadSuccessStatusKey, ResultKeys.ResultKeysStatusEnum.Failed.ToString()));
                    _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.ControlStatusKey, ResultKeys.ResultKeysStatusEnum.Failed.ToString()));
                    _loggerClient.Log(new DefaultLoggerClientObject {
                        OperationContext = "LeadEntity Failed Constraints in Controller", ProcessContext = processContext, SolutionContext = solutionContext, EventType = LoggerClientEventType.LoggerClientEventTypes.Information
                    });
                    return(_campaignResultList);
                }

                // What else can we retrieve here????
                _campaignResultList.Add((new DefaultResult(ResultKeys.CampaignKeys.CampaignMessageHandlerKey, $"MessageHandlerFor{CampaignDescription}")));

                // The lead processed successfully through the whole campaign and should continue on to the resolver
                _campaignResultList.Add(new DefaultResult(ResultKeys.CampaignKeys.LeadSuccessStatusKey, ResultKeys.ResultKeysStatusEnum.Processed.ToString()));

                // Add the end time to the result list
                _campaignResultList.Add(new DefaultResult(ResultKeys.DiagnosticKeys.TimeStampEndKey, DateTime.Now));
            }
            catch (Exception ex)
            {
                _loggerClient.Log(new DefaultLoggerClientErrorObject {
                    OperationContext = "Exception raised during Campaign Processing.", ProcessContext = processContext, SolutionContext = solutionContext, Exception = ex, ErrorContext = ex.Message, EventType = LoggerClientEventType.LoggerClientEventTypes.Error
                });
                throw;
            }

            return(_campaignResultList);
        }