Esempio n. 1
0
 /// <summary>
 /// Initializes a new instance of Actor1
 /// </summary>
 /// <param name="actorService">The Microsoft.ServiceFabric.Actors.Runtime.ActorService that will host this actor instance.</param>
 /// <param name="actorId">The Microsoft.ServiceFabric.Actors.ActorId for this actor instance.</param>
 public Timer1(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
     m_tc = new TelemetryClient();
     m_tc.InstrumentationKey        = "1dc0d5c5-f513-4539-8311-9c0d91f0ea14";
     m_tc.Context.Component.Version = "4.0";
     m_tc.Context.User.Id           = actorId.ToString();
     m_tc.TrackEvent($"Timer1 - {actorId.ToString()}");
 }
Esempio n. 2
0
        async Task <bool> ISession.CreateSessionAsync(ActorId UserActorId, string DeviceIdString)
        {
            try
            {
                SessionState state = await this.GetStateAsync <SessionState>();

                if (state.isCreated)
                {
                    return(false);
                }
                //Try to create login state
                state.UserActorId    = UserActorId;
                state.DeviceIdString = DeviceIdString;
                state.SessionKey     = UserActorId.ToString() + this.Id.ToString();
                state.SessionHash    = state.SessionKey.ToSHA256Hash();
                state.isCreated      = true;
                await this.SetStateAsync(state);

                return(true);
            }
            catch (Exception E)
            {
                this.Log(E);
                return(false);
            }
        }
        public async Task <IEnumerable <string> > Get(long id)
        {
            // Note that even this GET creates an Actor based on the id
            // passed in because of the OnActivateAsync() method. The
            // OnActivateAsync() method gets triggered the first time
            // any of the Actor methods are invoked. In this case, the
            // GetCameraAsync() method is called below. This means the
            // OnActivateSync() method gets triggered, which creates
            // the actor before the execution of GetCameraAsync.
            // This is something you need to watch out for.
            CameraObject        camera      = null;
            ActorId             actorId     = new ActorId(id);
            IBackEndCameraActor cameraActor = ActorProxy.Create <IBackEndCameraActor>(actorId, backEndCameraActorServiceUri);

            try
            {
                camera = await cameraActor.GetCameraAsync();

                System.Diagnostics.Trace.WriteLine("Getting Camera {0}.", actorId.ToString());
            }
            catch (Exception exc)
            {
                System.Diagnostics.Trace.WriteLine(String.Format("Error: {0}", exc.Message));
            }

            //return new string[] { JsonConvert.SerializeObject(camera) };
            return(new string[] { camera.Location });
        }
        public async Task <FundingServiceOutputs> ProcessFunding(string correlationId, Message message, MessageLearner[] learners)
        {
            var stopwatch = new Stopwatch();

            message.Learner = learners;
            using (var childLifeTimeScope = _parentLifeTimeScope.BeginLifetimeScope("childLifeTimeScope"))
            {
                var logger = childLifeTimeScope.Resolve <ILogger>();

                try
                {
                    logger.StartContext(correlationId, _actorId.ToString());
                    var fundingService = childLifeTimeScope.Resolve <IFundingService>();
                    logger.LogInfo($"Start ALB Actor processing :{DateTime.Now} ");
                    stopwatch.Start();
                    var results = fundingService.ProcessFunding(message);
                    //                    var fundingService = childLifeTimeScope.Resolve<IFundingService>();
                    //                    var results = fundingService.ProcessFunding(message);
                    stopwatch.Stop();
                    var completedTime = stopwatch.Elapsed;
                    logger.LogInfo($"Completed ALB Actor processing :{completedTime} ");
                    return(results);
                }
                catch (Exception ex)
                {
                    logger.LogError("Error in ALB Actor processFunding", ex);
                    //throw;
                    return(null);
                }
            }
        }
Esempio n. 5
0
 internal void ActorMethodThrewException(
     string exception,
     long methodExecutionTimeTicks,
     string methodName,
     string methodSignature,
     string actorType,
     ActorId actorId,
     ServiceContext serviceContext)
 {
     this.ActorMethodThrewException(
         exception,
         methodExecutionTimeTicks,
         methodName,
         methodSignature,
         actorType,
         actorId.ToString(),
         actorId.Kind,
         serviceContext.ReplicaOrInstanceId,
         serviceContext.PartitionId,
         serviceContext.ServiceName.OriginalString,
         serviceContext.CodePackageActivationContext.ApplicationName,
         serviceContext.ServiceTypeName,
         serviceContext.CodePackageActivationContext.ApplicationTypeName,
         serviceContext.NodeContext.NodeName);
 }
Esempio n. 6
0
        public HttpResponseMessage GetActorID()
        {
            //TODO: Add error handling.

            HttpResponseMessage httpResponse = new HttpResponseMessage();

            httpResponse.Content = new StringContent(actorId.ToString(), Encoding.UTF8, "text/html");
            return(httpResponse);
        }
Esempio n. 7
0
        public IConnection Get(ActorId id)
        {
            if (IsLocal(ref id))
                return localConnection;

            var s = id.ToString().Split('/');
            var computer = NormalizedComputerName(s[0]);
            return Get(new Cls.Connections.EndPoint(computer));
        }
Esempio n. 8
0
        public RemovedLearnerService(ActorService actorService, ActorId actorId, IRemovedLearnerAimIdentificationService removedLearnerAimIdentificationService) : base(actorService, actorId)
        {
            this.removedLearnerAimIdentificationService = removedLearnerAimIdentificationService;

            if (!long.TryParse(actorId.ToString(), out ukprn))
            {
                throw new InvalidCastException($"Unable to cast Actor Id {Id} to valid ukprn");
            }
        }
        private async Task <KeyValuePair <string, string> > GetRandomIdsAsync()
        {
            ServiceUriBuilder serviceUri = new ServiceUriBuilder(this.GetSetting(DeviceServiceName));
            Uri fabricServiceName        = serviceUri.ToUri();

            CancellationTokenSource cts        = new CancellationTokenSource(TimeSpan.FromMinutes(5));
            CancellationToken       token      = cts.Token;
            FabricClient            fc         = new FabricClient();
            ServicePartitionList    partitions = await fc.QueryManager.GetPartitionListAsync(fabricServiceName);

            string doctorId = null;

            while (!token.IsCancellationRequested && doctorId == null)
            {
                try
                {
                    foreach (Partition p in partitions)
                    {
                        long partitionKey = ((Int64RangePartitionInformation)p.PartitionInformation).LowKey;
                        token.ThrowIfCancellationRequested();
                        ContinuationToken queryContinuationToken = null;
                        IActorService     proxy = ActorServiceProxy.Create(fabricServiceName, partitionKey);
                        PagedResult <ActorInformation> result = await proxy.GetActorsAsync(queryContinuationToken, token);

                        foreach (ActorInformation info in result.Items)
                        {
                            token.ThrowIfCancellationRequested();

                            ActorId      deviceActorId = info.ActorId;
                            IDeviceActor deviceActor   = ActorProxy.Create <IDeviceActor>(deviceActorId, fabricServiceName);

                            try
                            {
                                doctorId = (await deviceActor.GetAssociatedDoctorAsync()).ToString();

                                return(new KeyValuePair <string, string>(deviceActorId.ToString(), doctorId));
                            }
                            catch (Exception e)
                            {
                                ServiceEventSource.Current.Message("Exception when obtaining actor ID. No State? " + e.ToString());
                                continue;
                            }
                        }
                        //otherwise we will bounce around other partitions until we find an actor
                    }
                }
                catch (Exception e)
                {
                    ServiceEventSource.Current.Message("Exception when obtaining actor ID: " + e.ToString());
                    continue;
                }
            }

            throw new InvalidOperationException("Couldn't find actor within timeout");
        }
Esempio n. 10
0
 public ChessFabrickActor(ActorService actorService, ActorId actorId)
     : base(actorService, actorId)
 {
     this.gameId       = actorId.ToString();
     this.proxyFactory = new ServiceProxyFactory((c) =>
     {
         return(new FabricTransportServiceRemotingClientFactory());
     });
     this.chessStatefulUri = new Uri($"{actorService.Context.CodePackageActivationContext.ApplicationName}/ChessFabrickStateful");
     this.rand             = new Random();
 }
        public async Task <string> Validate(ValidationActorModel validationActorModel, CancellationToken cancellationToken)
        {
            var jsonSerializationService = _parentLifeTimeScope.Resolve <IJsonSerializationService>();

            var internalDataCache = jsonSerializationService.Deserialize <InternalDataCache>(Encoding.UTF8.GetString(validationActorModel.InternalDataCache));
            var externalDataCache = jsonSerializationService.Deserialize <ExternalDataCache>(Encoding.UTF8.GetString(validationActorModel.ExternalDataCache));
            var fileDataCache     = jsonSerializationService.Deserialize <FileDataCache>(Encoding.UTF8.GetString(validationActorModel.FileDataCache));
            var message           = jsonSerializationService.Deserialize <Message>(new MemoryStream(validationActorModel.Message));

            cancellationToken.ThrowIfCancellationRequested();

            var validationContext = new ValidationContext
            {
                Input = message
            };

            using (var childLifeTimeScope = _parentLifeTimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(validationContext).As <IValidationContext>();
                c.RegisterInstance(new Cache <IMessage> {
                    Item = message
                }).As <ICache <IMessage> >();
                c.RegisterInstance(internalDataCache).As <IInternalDataCache>();
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
                c.RegisterInstance(fileDataCache).As <IFileDataCache>();
            }))
            {
                var executionContext = (ExecutionContext)childLifeTimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = validationActorModel.JobId;
                executionContext.TaskKey = _actorId.ToString();
                var logger = childLifeTimeScope.Resolve <ILogger>();
                try
                {
                    logger.LogDebug($"Validation Actor {executionContext.TaskKey} started learners: {validationContext.Input.Learners.Count}");
                    var preValidationOrchestrationService = childLifeTimeScope
                                                            .Resolve <IRuleSetOrchestrationService <ILearner, IValidationError> >();

                    var errors = await preValidationOrchestrationService.Execute(cancellationToken);

                    logger.LogDebug($"Validation Actor {executionContext.TaskKey} validation done");

                    var errorString = jsonSerializationService.Serialize(errors);
                    logger.LogDebug($"Validation Actor {executionContext.TaskKey} completed job");
                    return(errorString);
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    logger.LogError("Error while processing Actor job", ex);
                    throw;
                }
            }
        }
 public static void LogDependency(this ILogger logger, string service, string method,
                                  DateTime started, TimeSpan duration, bool success, ActorId actorId)
 {
     logger.LogInformation(ServiceFabricEvent.ServiceRequest,
                           $"The call to {{{DependencyProperties.Type}}} actor {{{DependencyProperties.DependencyTypeName}}} with id {{{nameof(ActorId)}}} named {{{DependencyProperties.Name}}} finished in {{{DependencyProperties.DurationInMs}}} ms (success: {{{DependencyProperties.Success}}}) ({{{DependencyProperties.StartTime}}})",
                           "ServiceFabric",
                           service,
                           actorId.ToString(),
                           method,
                           duration.TotalMilliseconds,
                           success,
                           started);
 }
Esempio n. 13
0
        internal String ToPM()
        {
            StringBuilder sb = new StringBuilder(ActorId.ToString()).Append(';');

            sb.Append(Name).Append(';');
            sb.Append(Look).Append(';');
            sb.Append(Color1).Append(';');
            sb.Append(Color2).Append(';');
            sb.Append(Color3).Append(';');
            sb.Append(InventoryCache.SerializeAsDisplayEquipment()).Append(';');
            sb.Append(Life).Append(',').Append(MaxLife).Append(';');
            sb.Append(Initiative).Append(';');
            sb.Append(myStats.GetTotal(EffectEnum.AddProspection)).Append(';');
            sb.Append(1);
            return(sb.ToString());
        }
Esempio n. 14
0
 internal void ActorSaveStateStart(
     string actorType,
     ActorId actorId,
     ServiceContext serviceContext)
 {
     this.ActorSaveStateStart(
         actorType,
         actorId.ToString(),
         actorId.Kind,
         serviceContext.ReplicaOrInstanceId,
         serviceContext.PartitionId,
         serviceContext.ServiceName.OriginalString,
         serviceContext.CodePackageActivationContext.ApplicationName,
         serviceContext.ServiceTypeName,
         serviceContext.CodePackageActivationContext.ApplicationTypeName,
         serviceContext.NodeContext.NodeName);
 }
Esempio n. 15
0
 internal void ActorMethodCallsWaitingForLock(
     long countOfWaitingMethodCalls,
     string actorType,
     ActorId actorId,
     ServiceContext serviceContext)
 {
     this.ActorMethodCallsWaitingForLock(
         countOfWaitingMethodCalls,
         actorType,
         actorId.ToString(),
         actorId.Kind,
         serviceContext.ReplicaOrInstanceId,
         serviceContext.PartitionId,
         serviceContext.ServiceName.OriginalString,
         serviceContext.CodePackageActivationContext.ApplicationName,
         serviceContext.ServiceTypeName,
         serviceContext.CodePackageActivationContext.ApplicationTypeName,
         serviceContext.NodeContext.NodeName);
 }
        public async Task <IEnumerable <string> > Get(long id)
        {
            CameraObject        camera      = null;
            ActorId             actorId     = new ActorId(id);
            IBackEndCameraActor cameraActor = ActorProxy.Create <IBackEndCameraActor>(actorId, backEndCameraActorServiceUri);

            try
            {
                camera = await cameraActor.GetCameraAsync();

                System.Diagnostics.Trace.WriteLine("Getting Camera {0}.", actorId.ToString());
            }
            catch (Exception exc)
            {
                System.Diagnostics.Trace.WriteLine(String.Format("Error: {0}", exc.Message));
            }

            //return new string[] { JsonConvert.SerializeObject(camera) };
            return(new string[] { camera.Location });
        }
Esempio n. 17
0
        public override string ToString()
        {
            string actor_str = ActorName == null?ActorId.ToString() : ActorName;

            string timestamp_str = Timestamp == DateTimeOffset.MinValue ? "No Timestamp" : Timestamp.ToString("u");
            string info_str      = string.IsNullOrEmpty(Info) ? string.Empty : $" - {Info}";
            string descr_str     = string.IsNullOrEmpty(Reason) ? string.Empty : $" `{Reason}`";

            SocketGuild guild = BotCore.Client.GetGuild(GuildId);

            if (guild != null)
            {
                SocketGuildUser actor = guild.GetUser(ActorId);
                if (actor != null)
                {
                    actor_str = actor.Mention;
                }
            }
            return($"[**{Type}** - {timestamp_str} - {actor_str}{info_str}]{descr_str}");
        }
        public async Task <IActionResult> Post()
        {
            CameraObject        camera      = null;
            ActorId             actorId     = ActorId.CreateRandom();
            IBackEndCameraActor cameraActor = ActorProxy.Create <IBackEndCameraActor>(actorId, backEndCameraActorServiceUri);

            try
            {
                camera = await cameraActor.GetCameraAsync();

                System.Diagnostics.Trace.WriteLine("Getting Camera {0}.", actorId.ToString());
            }
            catch (Exception exc)
            {
                System.Diagnostics.Trace.WriteLine(String.Format("Error: {0}", exc.Message));
            }

            //return new string[] { JsonConvert.SerializeObject(camera) };
            return(this.Ok(String.Format("Camera ID: {0}, Location: {1}, Status {2}", actorId, camera.Location, camera.Status.ToString())));
        }
        public async Task <string> Validate(string correlationId, Message message, MessageLearner[] shreddedLearners)
        {
            using (var childLifeTimeScope = _parentLifeTimeScope.BeginLifetimeScope())
            {
                var logger = childLifeTimeScope.Resolve <ILogger>();
                logger.StartContext(correlationId, _actorId.ToString());
                logger.LogInfo("Started Validation learnerActor");
                var validationService = childLifeTimeScope.Resolve <IValidationService>();

                message.Learner = shreddedLearners;

                var stopwatch = new Stopwatch();
                stopwatch.Start();

                var results = await validationService.Validate(message);

                //IEnumerable<string> productIDs = await StateManager.GetStateNamesAsync();
                var jsonResult = JsonConvert.SerializeObject(results);
                logger.LogInfo($"Completed Validation LearnerActor in :{stopwatch.ElapsedMilliseconds} ");

                return(jsonResult);
            }
        }
Esempio n. 20
0
 public static ActorId[] Get(ActorId id)
 {
     var s = id.ToString().Split('/');
     var names = Get(new Cls.Connections.EndPoint(s[0]));
     return names.Select(n=> new ActorId(n + "/" + string.Join("/", s.Skip(1)))).ToArray();
 }
        private FM25Global RunFunding(FundingDto actorModel, CancellationToken cancellationToken)
        {
            if (ExecutionContext is ExecutionContext executionContextObj)
            {
                executionContextObj.JobId   = "-1";
                executionContextObj.TaskKey = ActorId.ToString();
            }

            ILogger logger = LifetimeScope.Resolve <ILogger>();

            IExternalDataCache externalDataCache;
            FM25Global         condensedResults;

            try
            {
                logger.LogDebug($"{nameof(FM25Actor)} {ActorId} starting");

                externalDataCache = BuildExternalDataCache(actorModel.ExternalDataCache);

                logger.LogDebug($"{nameof(FM25Actor)} {ActorId} finished getting input data");

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                logger.LogError($"Error while processing {nameof(FM25Actor)}", ex);
                throw;
            }

            using (var childLifetimeScope = LifetimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
            }))
            {
                ExecutionContext executionContext = (ExecutionContext)childLifetimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = actorModel.JobId.ToString();
                executionContext.TaskKey = ActorId.ToString();
                ILogger jobLogger = childLifetimeScope.Resolve <ILogger>();

                try
                {
                    jobLogger.LogDebug($"{nameof(FM25Actor)} {ActorId} {GC.GetGeneration(actorModel)} started processing");

                    IEnumerable <FM25Global>          fm25Results;
                    IEnumerable <PeriodisationGlobal> fm25PeriodisationResults;

                    using (var fundingServiceLifetimeScope = childLifetimeScope.BeginLifetimeScope(c =>
                    {
                        c.RegisterInstance(new FM25RulebaseProvider()).As <IRulebaseStreamProvider <FM25LearnerDto> >();
                    }))
                    {
                        jobLogger.LogDebug("FM25 Rulebase Starting");

                        IFundingService <FM25LearnerDto, IEnumerable <FM25Global> > fundingService = fundingServiceLifetimeScope.Resolve <IFundingService <FM25LearnerDto, IEnumerable <FM25Global> > >();

                        var learners = BuildLearners <FM25LearnerDto>(actorModel.ValidLearners);

                        fm25Results = fundingService.ProcessFunding(actorModel.UKPRN, learners, cancellationToken).ToList();

                        jobLogger.LogDebug("FM25 Rulebase Finishing");
                    }

                    using (var fundingServiceLifetimeScope = childLifetimeScope.BeginLifetimeScope(c =>
                    {
                        c.RegisterInstance(new FM25PeriodisationRulebaseProvider()).As <IRulebaseStreamProvider <FM25Global> >();
                    }))
                    {
                        jobLogger.LogDebug("FM25 Periodisation Rulebase Starting");

                        IFundingService <FM25Global, IEnumerable <PeriodisationGlobal> > periodisationService = fundingServiceLifetimeScope.Resolve <IFundingService <FM25Global, IEnumerable <PeriodisationGlobal> > >();

                        fm25PeriodisationResults = periodisationService.ProcessFunding(actorModel.UKPRN, fm25Results, cancellationToken).ToList();

                        jobLogger.LogDebug("FM25 Periodisation Rulebase Finishing");

                        IFM25FundingOutputCondenserService <FM25Global, PeriodisationGlobal> condenser = fundingServiceLifetimeScope.Resolve <IFM25FundingOutputCondenserService <FM25Global, PeriodisationGlobal> >();

                        condensedResults = condenser.CondensePeriodisationResults(fm25Results, fm25PeriodisationResults);
                    }

                    jobLogger.LogDebug($"{nameof(FM25Actor)} {ActorId} {GC.GetGeneration(actorModel)} completed processing");
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    jobLogger.LogError($"Error while processing {nameof(FM25Actor)}", ex);
                    throw;
                }
            }

            externalDataCache = null;

            return(condensedResults);
        }
        private async Task <IEnumerable <IValidationError> > RunValidation(ValidationActorModel actorModel, CancellationToken cancellationToken)
        {
            if (_executionContext is ExecutionContext executionContextObj)
            {
                executionContextObj.JobId   = "-1";
                executionContextObj.TaskKey = _actorId.ToString();
            }

            ILogger logger = _parentLifeTimeScope.Resolve <ILogger>();

            InternalDataCache              internalDataCache;
            ExternalDataCache              externalDataCacheGet;
            ExternalDataCache              externalDataCache;
            FileDataCache                  fileDataCache;
            Message                        message;
            IEnumerable <string>           tasks;
            ValidationContext              validationContext;
            IEnumerable <IValidationError> errors;

            try
            {
                logger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} starting");

                internalDataCache    = _jsonSerializationService.Deserialize <InternalDataCache>(actorModel.InternalDataCache);
                externalDataCacheGet = _jsonSerializationService.Deserialize <ExternalDataCache>(actorModel.ExternalDataCache);
                fileDataCache        = _jsonSerializationService.Deserialize <FileDataCache>(actorModel.FileDataCache);
                message = _jsonSerializationService.Deserialize <Message>(actorModel.Message);
                tasks   = _jsonSerializationService.Deserialize <IEnumerable <string> >(actorModel.TaskList);

                externalDataCache = new ExternalDataCache
                {
                    LearningDeliveries = externalDataCacheGet.LearningDeliveries.ToCaseInsensitiveDictionary(),
                    EPAOrganisations   = externalDataCacheGet.EPAOrganisations.ToCaseInsensitiveDictionary(),
                    ERNs = externalDataCacheGet.ERNs,
                    FCSContractAllocations = externalDataCacheGet.FCSContractAllocations,
                    Frameworks             = externalDataCacheGet.Frameworks,
                    Organisations          = externalDataCacheGet.Organisations,
                    Postcodes          = externalDataCacheGet.Postcodes.ToCaseInsensitiveHashSet(),
                    ONSPostcodes       = externalDataCacheGet.ONSPostcodes,
                    Standards          = externalDataCacheGet.Standards,
                    StandardValidities = externalDataCacheGet.StandardValidities,
                    ULNs              = externalDataCacheGet.ULNs,
                    ValidationErrors  = externalDataCacheGet.ValidationErrors.ToCaseInsensitiveDictionary(),
                    CampusIdentifiers = externalDataCacheGet.CampusIdentifiers
                };

                validationContext = new ValidationContext
                {
                    Input = message
                };

                logger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} finished getting input data");

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                logger.LogError($"Error while processing {nameof(ValidationActor)}", ex);
                throw;
            }

            using (var childLifeTimeScope = _parentLifeTimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(validationContext).As <IValidationContext>();
                c.RegisterInstance(new Cache <IMessage> {
                    Item = message
                }).As <ICache <IMessage> >();
                c.RegisterInstance(internalDataCache).As <IInternalDataCache>();
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
                c.RegisterInstance(fileDataCache).As <IFileDataCache>();
            }))
            {
                ExecutionContext executionContext = (ExecutionContext)childLifeTimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = actorModel.JobId;
                executionContext.TaskKey = _actorId.ToString();
                ILogger jobLogger = childLifeTimeScope.Resolve <ILogger>();
                try
                {
                    jobLogger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} started learners: {validationContext.Input.Learners.Count}");
                    IRuleSetOrchestrationService <ILearner, IValidationError> preValidationOrchestrationService = childLifeTimeScope
                                                                                                                  .Resolve <IRuleSetOrchestrationService <ILearner, IValidationError> >();

                    errors = await preValidationOrchestrationService.ExecuteAsync(tasks, cancellationToken);

                    jobLogger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} validation done");
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    jobLogger.LogError($"Error while processing {nameof(ValidationActor)}", ex);
                    throw;
                }
            }

            internalDataCache = null;
            externalDataCache = null;
            fileDataCache     = null;
            message           = null;
            validationContext = null;

            return(errors);
        }
        private async Task <IEnumerable <IValidationError> > RunValidation(ValidationActorModel actorModel, CancellationToken cancellationToken)
        {
            if (_executionContext is ExecutionContext executionContextObj)
            {
                executionContextObj.JobId   = "-1";
                executionContextObj.TaskKey = _actorId.ToString();
            }

            ILogger logger = _parentLifeTimeScope.Resolve <ILogger>();

            InternalDataCache internalDataCache;
            ExternalDataCache externalDataCache;
            FileDataCache     fileDataCache;
            Message           message;
            ValidationContext validationContext;
            IEnumerable <IValidationError> errors;

            try
            {
                logger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} starting");

                internalDataCache = _jsonSerializationService.Deserialize <InternalDataCache>(Encoding.UTF8.GetString(actorModel.InternalDataCache));
                externalDataCache = _jsonSerializationService.Deserialize <ExternalDataCache>(Encoding.UTF8.GetString(actorModel.ExternalDataCache));
                fileDataCache     = _jsonSerializationService.Deserialize <FileDataCache>(Encoding.UTF8.GetString(actorModel.FileDataCache));
                message           = _jsonSerializationService.Deserialize <Message>(new MemoryStream(actorModel.Message));

                validationContext = new ValidationContext
                {
                    Input = message
                };

                logger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} finished getting input data");

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                logger.LogError($"Error while processing {nameof(ValidationActor)}", ex);
                throw;
            }

            using (var childLifeTimeScope = _parentLifeTimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(validationContext).As <IValidationContext>();
                c.RegisterInstance(new Cache <IMessage> {
                    Item = message
                }).As <ICache <IMessage> >();
                c.RegisterInstance(internalDataCache).As <IInternalDataCache>();
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
                c.RegisterInstance(fileDataCache).As <IFileDataCache>();
            }))
            {
                ExecutionContext executionContext = (ExecutionContext)childLifeTimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = actorModel.JobId;
                executionContext.TaskKey = _actorId.ToString();
                ILogger jobLogger = childLifeTimeScope.Resolve <ILogger>();
                try
                {
                    jobLogger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} started learners: {validationContext.Input.Learners.Count}");
                    IRuleSetOrchestrationService <ILearner, IValidationError> preValidationOrchestrationService = childLifeTimeScope
                                                                                                                  .Resolve <IRuleSetOrchestrationService <ILearner, IValidationError> >();

                    errors = await preValidationOrchestrationService.Execute(cancellationToken);

                    jobLogger.LogDebug($"{nameof(ValidationActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} validation done");
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    jobLogger.LogError($"Error while processing {nameof(ValidationActor)}", ex);
                    throw;
                }
            }

            internalDataCache = null;
            externalDataCache = null;
            fileDataCache     = null;
            message           = null;
            validationContext = null;

            return(errors);
        }
Esempio n. 24
0
 public StartupEvent(ActorId caller, ActorId replyTo)
 {
     Console.WriteLine($"Got here StartupEvent constructor {caller.ToString()}");
     Caller = caller;
     this.replyTo = replyTo;
 }
Esempio n. 25
0
 public StartupEvent(ActorId caller)
 {
     Console.WriteLine($"Got here StartupEvent constructor {caller.ToString()}");
     Caller = caller;
 }
Esempio n. 26
0
        public void Verify_ToString(string id)
        {
            ActorId actorId = new ActorId(id);

            Assert.Equal(id, actorId.ToString());
        }
        private async Task <IEnumerable <IValidationError> > RunValidation(ValidationDPActorModel actorModel, CancellationToken cancellationToken)
        {
            if (_executionContext is ExecutionContext executionContextObj)
            {
                executionContextObj.JobId   = "-1";
                executionContextObj.TaskKey = _actorId.ToString();
            }

            ILogger logger = _parentLifeTimeScope.Resolve <ILogger>();

            InternalDataCache internalDataCache;
            ExternalDataCache externalDataCacheGet;
            ExternalDataCache externalDataCache;
            FileDataCache     fileDataCache;
            Message           message;
            IEnumerable <IValidationError> errors;

            try
            {
                logger.LogDebug($"{nameof(ValidationDPActor)} {_actorId} {GC.GetGeneration(actorModel)} starting");

                internalDataCache    = _jsonSerializationService.Deserialize <InternalDataCache>(actorModel.InternalDataCache);
                externalDataCacheGet = _jsonSerializationService.Deserialize <ExternalDataCache>(actorModel.ExternalDataCache);
                fileDataCache        = _jsonSerializationService.Deserialize <FileDataCache>(actorModel.FileDataCache);
                message = _jsonSerializationService.Deserialize <Message>(actorModel.Message);

                externalDataCache = new ExternalDataCache
                {
                    ULNs             = externalDataCacheGet.ULNs,
                    ValidationErrors = externalDataCacheGet.ValidationErrors.ToCaseInsensitiveDictionary(),
                    ValidationRules  = externalDataCacheGet.ValidationRules,
                    ReturnPeriod     = externalDataCacheGet.ReturnPeriod
                };

                logger.LogDebug($"{nameof(ValidationDPActor)} {_actorId} {GC.GetGeneration(actorModel)} finished getting input data");

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                logger.LogError($"Error while processing {nameof(ValidationDPActor)}", ex);
                throw;
            }

            using (var childLifeTimeScope = _parentLifeTimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(new Cache <IMessage> {
                    Item = message
                }).As <ICache <IMessage> >();
                c.RegisterInstance(internalDataCache).As <IInternalDataCache>();
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
                c.RegisterInstance(fileDataCache).As <IFileDataCache>();
            }))
            {
                ExecutionContext executionContext = (ExecutionContext)childLifeTimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = actorModel.JobId;
                executionContext.TaskKey = _actorId.ToString();
                ILogger jobLogger = childLifeTimeScope.Resolve <ILogger>();
                try
                {
                    jobLogger.LogDebug($"{nameof(ValidationDPActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} started Destination and Progressions: {message.LearnerDestinationAndProgressions.Count}");
                    IRuleSetOrchestrationService <IRule <ILearnerDestinationAndProgression>, ILearnerDestinationAndProgression> preValidationOrchestrationService = childLifeTimeScope
                                                                                                                                                                    .Resolve <IRuleSetOrchestrationService <IRule <ILearnerDestinationAndProgression>, ILearnerDestinationAndProgression> >();

                    errors = await preValidationOrchestrationService.ExecuteAsync(message.LearnerDestinationAndProgressions, cancellationToken);

                    jobLogger.LogDebug($"{nameof(ValidationDPActor)} {_actorId} {GC.GetGeneration(actorModel)} {executionContext.TaskKey} Destination and Progression validation done");
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    jobLogger.LogError($"Error while processing {nameof(ValidationDPActor)}", ex);
                    throw;
                }
            }

            internalDataCache = null;
            externalDataCache = null;
            fileDataCache     = null;
            message           = null;

            return(errors);
        }
Esempio n. 28
0
        private FM35Global RunFunding(FundingDto actorModel, CancellationToken cancellationToken)
        {
            if (ExecutionContext is ExecutionContext executionContextObj)
            {
                executionContextObj.JobId   = "-1";
                executionContextObj.TaskKey = ActorId.ToString();
            }

            ILogger logger = LifetimeScope.Resolve <ILogger>();

            IExternalDataCache externalDataCache;
            FM35Global         results;

            try
            {
                logger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} starting");

                externalDataCache = BuildExternalDataCache(actorModel.ExternalDataCache);

                logger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} finished getting input data");

                cancellationToken.ThrowIfCancellationRequested();
            }
            catch (Exception ex)
            {
                ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                logger.LogError($"Error while processing {nameof(FM35Actor)}", ex);
                throw;
            }

            using (var childLifetimeScope = LifetimeScope.BeginLifetimeScope(c =>
            {
                c.RegisterInstance(externalDataCache).As <IExternalDataCache>();
            }))
            {
                ExecutionContext executionContext = (ExecutionContext)childLifetimeScope.Resolve <IExecutionContext>();
                executionContext.JobId   = actorModel.JobId.ToString();
                executionContext.TaskKey = ActorId.ToString();
                ILogger jobLogger = childLifetimeScope.Resolve <ILogger>();

                try
                {
                    jobLogger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} started processing");
                    IFundingService <FM35LearnerDto, FM35Global> fundingService = childLifetimeScope.Resolve <IFundingService <FM35LearnerDto, FM35Global> >();

                    var learners = BuildLearners <FM35LearnerDto>(actorModel.ValidLearners);

                    results = fundingService.ProcessFunding(actorModel.UKPRN, learners, cancellationToken);
                    jobLogger.LogDebug($"{nameof(FM35Actor)} {ActorId} {GC.GetGeneration(actorModel)} completed processing");
                }
                catch (Exception ex)
                {
                    ActorEventSource.Current.ActorMessage(this, "Exception-{0}", ex.ToString());
                    jobLogger.LogError($"Error while processing {nameof(FM35Actor)}", ex);
                    throw;
                }
            }

            externalDataCache = null;

            return(results);
        }
 private static string ToStringWithKind(ActorId id)
 {
     return(string.Format(CultureInfo.InvariantCulture, "{0}_{1}", id.Kind.ToString(), id.ToString()));
 }