Example #1
0
        public void run(object item)
        {
            Download_Data_Info inf = item as Download_Data_Info;

            //Trend_Analyser_Connector.Trend_Analyser_Module_2_Download_Data(inf.symbol, inf.fYear, inf.fMonth, inf.fDay, inf.tYear, inf.tMonth, inf.tDay);

            if (UpdateEvent != null)
            {
                UpdateEvent.Invoke();
            }

            Interlocked.Increment(ref i);

            if (i == count)
            {
                prog.Close();

                if (CompletedEvent != null)
                {
                    CompletedEvent.Invoke();
                }
            }
            else
            {
                prog.setPercentage(i * 100 / count);
            }
        }
            private void SignalReady()
            {
                switch (signalReadyHitCounter)
                {
                case 0:
                    Trace.ConsoleWriteLine(TraceType, "IS: Invoking SignalReady for MANUAL VendorRepairBegin job.");
                    signalReadyHitCounter++;
                    break;

                case 1:
                    Trace.ConsoleWriteLine(TraceType, "IS: Invoking SignalReady for giving approval to a normal FC's job's StartJobStep.");
                    signalReadyHitCounter++;
                    break;

                case 2:
                    Trace.ConsoleWriteLine(TraceType, "IS: Invoking SignalReady for MANUAL VendorRepairEnd job.");
                    signalReadyHitCounter++;

                    NotificationContext.ImpactedInstances = new List <ImpactedInstance>
                    {
                        new ImpactedInstance("RoleA_IN_1", new List <ImpactReason> {
                            ImpactReason.Reboot
                        })
                    };

                    break;

                case 3:
                    Trace.ConsoleWriteLine(TraceType, "IS: Invoking SignalReady for giving approval to a normal FC's job's CompleteJobStep.");
                    signalReadyHitCounter++;

                    CompletedEvent.Set();
                    break;
                }
            }
        private void WebRequestOperationCompleted(AsyncOperation op)
        {
            UnityWebRequestAsyncOperation remoteReq = op as UnityWebRequestAsyncOperation;
            var webReq = remoteReq.webRequest;

            if (string.IsNullOrEmpty(webReq.error))
            {
                downloadHandler = webReq.downloadHandler as DownloadHandlerAssetBundle;
                provideHandle.Complete(this, true, null);
            }
            else
            {
                downloadHandler = webReq.downloadHandler as DownloadHandlerAssetBundle;
                downloadHandler.Dispose();
                downloadHandler = null;
                if (retries++ < options.RetryCount)
                {
                    UDebug.LogFormat("Web request {0} failed with error '{1}', retrying ({2}/{3})...", webReq.url, webReq.error, retries, options.RetryCount);
                    BeginOperation();
                }
                else
                {
                    var exception = new Exception(string.Format("RemoteAssetBundleProvider unable to load from url {0}, result='{1}'.", webReq.url, webReq.error));
                    CompletedEvent?.Invoke(null, false, exception);
                }
            }
            webReq.Dispose();
        }
            private void SignalReady()
            {
                switch (signalReadyHitCounter)
                {
                case 0:
                    Trace.ConsoleWriteLine(TraceType, "IS: Invoking SignalReady for giving approval to FC's job.");
                    signalReadyHitCounter++;
                    break;

                case 1:
                    Trace.ConsoleWriteLine(TraceType, "IS: Invoking SignalReady after job execution and completion of health check from CM.");
                    Verify.AreEqual(state, State.FromCMAckedCompletedJob,
                                    string.Format(CultureInfo.InvariantCulture, "SignalReady invoked after after health checks from CM to ack completed job: {0}", state));
                    signalReadyHitCounter++;
                    break;

                case 2:
                    Trace.ConsoleWriteLine(TraceType, "IS: Invoking SignalReady 2nd time since MR/FC missed out the previous CompleteJobStep ack.");
                    Verify.AreEqual(state, State.FromISSendSignalReady,
                                    string.Format(CultureInfo.InvariantCulture, "SignalReady invoked 2nd time to re-ack completed job: {0}", state));

                    CompletedEvent.Set();
                    break;
                }
            }
        private async Task HandleReceivedMessage(IReceiverClient receiverClient, ISenderClient senderClient,
                                                 Message message, CancellationToken token)
        {
            var eventName   = message.Label;
            var messageData = Encoding.UTF8.GetString(message.Body);

            await ProcessEvent(eventName, messageData);

            // Complete the message so that it is not received again.
            await receiverClient.CompleteAsync(message.SystemProperties.LockToken);

            var eventType = _subscriptionsManager.GetEventTypeByName(eventName);

            if (eventType != null && eventType != typeof(CompletedEvent))
            {
                var eventData = JObject.Parse(messageData);
                if (Guid.TryParse((string)eventData["Id"], out var eventId))
                {
                    var publisherId = (string)eventData["PublisherId"];

                    var completedEvent = new CompletedEvent(eventId, publisherId);
                    await PublishEventAsync(completedEvent, senderClient);
                }
            }
        }
Example #6
0
        protected override void Run(CancellationToken cancellationToken)
        {
            var tenantJob = TenantJobHelper.CreateNewTenantJob();

            PolicyAgentService.CreateTenantJob(tenantJob);

            RepairManager.CompletedEvent.WaitOne();
            CompletedEvent.Set();
        }
            private void SignalError(string errorDescription)
            {
                Trace.ConsoleWriteLine(TraceType,
                                       "IS: Invoking SignalError after job execution and task failure from CM. Error description: {0}", errorDescription);
                Verify.AreEqual(state, State.FromCMHealthCheckFailed,
                                string.Format(CultureInfo.InvariantCulture, "SignalError invoked after health checks from CM failed. Workflow state: {0}", state));

                CompletedEvent.Set();
            }
            protected override void AfterUpdateRepairExecutionState(Guid activityId, MockRepairTask repairTask)
            {
                base.AfterUpdateRepairExecutionState(activityId, repairTask);

                if (repairTask.State == RepairTaskState.Completed)
                {
                    CompletedEvent.Set();
                }
            }
Example #9
0
        protected override void Run(CancellationToken cancellationToken)
        {
            IRepairTask repairTask = CreateRepairTask();

            RepairManager.CreateRepairTaskAsync(Guid.NewGuid(), repairTask).GetAwaiter().GetResult();

            RepairManager.CompletedEvent.WaitOne();
            PolicyAgentService.CompletedEvent.WaitOne();
            CompletedEvent.Set();
        }
        protected override void Run(CancellationToken cancellationToken)
        {
            var tenantJob = TenantJobHelper.CreateNewTenantJob(ImpactActionEnum.PlatformUpdate); // Root HE

            // this kicks things off
            PolicyAgentService.CreateTenantJob(tenantJob);

            RepairManager.CompletedEvent.WaitOne();
            CompletedEvent.Set();
        }
        private void HandleJobCompleted(object sender, CompletedEvent e)
        {
            var job = (Job)sender;

            _hubContext.Clients.Group(job.Id).jobCompleted(job.Id);

            job.ProgressChanged -= HandleJobProgressChanged;
            job.Completed -= HandleJobCompleted;
            job.VerboseReport -= HandleJobVerboseMessage;
        }
Example #12
0
        private void OnComplete(AsyncOperationHandle <IList <object> > handle)
        {
            handle.Completed -= OnComplete;
            if (!_isDisposed && handle.Status == AsyncOperationStatus.Succeeded)
            {
                Assets = handle.Result.ToList();
            }

            CompletedEvent?.Invoke(this, handle.Status);
        }
        protected override void Run(CancellationToken cancellationToken)
        {
            var tenantJob = TenantJobHelper.CreateNewTenantJob(ImpactActionEnum.PlatformMaintenance);

            // this kicks things off
            PolicyAgentService.CreateTenantJob(tenantJob);

            ProcessCloser.ExitEvent.WaitOne();

            CompletedEvent.Set();
        }
        public async Task <ResultWrapper <CompletedEvent> > CreateEvent(CompletedEvent newEvent, TokenDto token)
        {
            if (!TokenValidation.ValidateToken(token, _unitOfWork))
            {
                List <ErrorResult> error = new List <ErrorResult>();
                error.Add(new ErrorResult(401, "Invalid token."));
                _unitOfWork.tokenRepo.Remove(_unitOfWork.tokenRepo.Find(tk => tk.token.Equals(token.AccessToken)).FirstOrDefault());
                return(new ResultWrapper <CompletedEvent>(null, error));
            }

            var errors = eventValid.ValidateEventCreation(newEvent);

            if (errors.Count() > 0)
            {
                return(new ResultWrapper <CompletedEvent>(null, errors));
            }

            CompletedEvent existEvent = null;

            if (newEvent.EventId.HasValue)
            {
                existEvent = await GetEvent(newEvent.EventId.Value);
            }

            if (existEvent != null)
            {
                return(await UpdateEvent(existEvent, newEvent, token));
            }

            Event    ev       = Mapper.Map <Event>(newEvent);
            Location location = Mapper.Map <Location>(newEvent.Location);

            // Insert a new location in DB
            _unitOfWork.LocationRepo.AddAsync(location);
            await _unitOfWork.LocationRepo.SaveAsync();

            // Get user from token
            var userId = TokenValidation.GetUserIdFromToken(token, _unitOfWork);

            ev.Author   = userId;
            ev.Location = location.LocationId;
            _unitOfWork.EventRepo.AddAsync(ev);
            await _unitOfWork.EventRepo.SaveAsync();

            Category           c   = _unitOfWork.categoriesRepo.Find(e => e.Category1.Equals(newEvent.Category)).FirstOrDefault();
            EventHasCategories ehc = new EventHasCategories();

            ehc.EventId    = ev.EventId;
            ehc.CategoryId = c.CategoryId;
            _unitOfWork.eventHasCategories.Add(ehc);
            await _unitOfWork.eventHasCategories.SaveAsync();

            return(new ResultWrapper <CompletedEvent>(newEvent, null));
        }
Example #15
0
        public virtual void SetCompleted(bool success, ResultError errorCode)
        {
            Success   = success;
            ErrorCode = errorCode;

#if DEBUG
#elif TRACE
            Traces = Debugging.CollectTraces();
#endif
            CompletedEvent.Set();
        }
        protected override void Run(CancellationToken cancellationToken)
        {
            IRepairTask repairTask = CreateRepairTask();

            RepairManager.CreateRepairTaskAsync(Guid.NewGuid(), repairTask).GetAwaiter().GetResult();

            ((MockRepairTask)repairTask).CreatedTimestamp = DateTime.UtcNow;

            RepairManager.CompletedEvent.WaitOne();
            CompletedEvent.Set();
        }
 private PatientInfo CreatePatientInfoFromEvent(CompletedEvent completedEvent)
 {
     return(new PatientInfo
     {
         NHSNumber = completedEvent.Period.Pathway.Patient.NHSNumber,
         PatientName = completedEvent.Period.Pathway.Patient.Name,
         DateOfBirth = completedEvent.Period.Pathway.Patient.DateOfBirth,
         Age = completedEvent.Period.Pathway.Patient.GetAgeAt(_clock.TodayDate),
         Hospital = completedEvent.Clinician.Hospital.Name,
         PpiNumber = completedEvent.Period.Pathway.PPINumber,
         PeriodId = completedEvent.Period.Id
     });
 }
        private async Task <ResultWrapper <CompletedEvent> > UpdateEvent(CompletedEvent existingEvent, CompletedEvent newEvent, TokenDto token)
        {
            var tokenOwnerId = TokenValidation.GetUserIdFromToken(token, _unitOfWork);

            if (tokenOwnerId != existingEvent.Author.UserId)
            {
                List <ErrorResult> error = new List <ErrorResult>();
                error.Add(new ErrorResult(401, "Unauthorized operation."));
                return(new ResultWrapper <CompletedEvent>(null, error));
            }

            // Update Location
            var location = _unitOfWork.LocationRepo.Find(l => l.LocationId == existingEvent.Location.LocationId).FirstOrDefault();

            location.Latitude  = newEvent.Location.Latitude;
            location.Longitude = newEvent.Location.Longitude;
            location.Address   = newEvent.Location.Address;

            await _unitOfWork.LocationRepo.SaveAsync();

            // Update Event
            var eventToUpdate = _unitOfWork.EventRepo.Find(x => x.EventId == existingEvent.EventId).FirstOrDefault();

            eventToUpdate.Description = newEvent.Description;
            eventToUpdate.StartDate   = newEvent.StartDate;
            eventToUpdate.EndDate     = newEvent.EndDate;
            eventToUpdate.Radius      = newEvent.Radius;
            eventToUpdate.Name        = newEvent.Name;

            await _unitOfWork.EventRepo.SaveAsync();

            EventHasCategories evCategories = _unitOfWork.eventHasCategories.Find(evt => evt.EventId == newEvent.EventId).FirstOrDefault();
            Category           cf           = _unitOfWork.categoriesRepo.Get(evCategories.CategoryId);

            if (!cf.Category1.Equals(newEvent.Category))
            {
                Category newCate = _unitOfWork.categoriesRepo.Find(ct => ct.Category1.Equals(newEvent.Category)).FirstOrDefault();
                _unitOfWork.eventHasCategories.Remove(evCategories);

                EventHasCategories newCategory = new EventHasCategories
                {
                    CategoryId = newCate.CategoryId,
                    EventId    = evCategories.EventId
                };

                _unitOfWork.eventHasCategories.Add(newCategory);
                await _unitOfWork.eventHasCategories.SaveAsync();
            }

            return(new ResultWrapper <CompletedEvent>(newEvent, null));
        }
Example #19
0
        protected override void Run(CancellationToken cancellationToken)
        {
            var tenantJob = TenantJobHelper.CreateNewTenantJob(ImpactActionEnum.PlatformMaintenance);

            // this kicks things off
            PolicyAgentService.CreateTenantJob(tenantJob);

            ProcessCloser.ExitEvent.WaitOne();

            var elapsed = DateTimeOffset.UtcNow - startTime;

            Assert.IsTrue(elapsed >= TimeSpan.FromSeconds(MaxRetryDurationInSeconds), "Verifying if max retry duration is exceeded");
            CompletedEvent.Set();
        }
Example #20
0
        private DateTime?ComputeDateReference(DestinationEvent destinationEvent, CompletedEvent currentCompletedEvent, Period period)
        {
            var destinationEventForDateReferenceForTarget = destinationEvent.EventForDateReferenceForTarget == null ? (EventCode?)null : destinationEvent.EventForDateReferenceForTarget.Code;

            var eventReference = period.CompletedEvents
                                 .OrderByDescending(e => e.EventDate)
                                 .FirstOrDefault(e => e.Period.Pathway.PPINumber == currentCompletedEvent.Period.Pathway.PPINumber && e.Name.Code == destinationEventForDateReferenceForTarget);

            if (eventReference != null)
            {
                return(eventReference.EventDate);
            }
            return(null);
        }
            protected override void AfterUpdateRepairExecutionState(Guid activityId, MockRepairTask repairTask)
            {
                base.AfterUpdateRepairExecutionState(activityId, repairTask);

                if (repairTask.State == RepairTaskState.Claimed && !repairTask.ClaimedTimestamp.HasValue)
                {
                    repairTask.ClaimedTimestamp = DateTime.UtcNow;
                }

                if (repairTask.State == RepairTaskState.Completed && repairTask.ResultStatus == RepairTaskResult.Cancelled)
                {
                    CompletedEvent.Set();
                }
            }
Example #22
0
        public void Dispose()
        {
            CompletedEvent.RemoveAllListeners();

            SetUrl(string.Empty);

            if (mAsyncOperation != default)
            {
                mAsyncOperation.completed -= CheckResult;
            }
            mAsyncOperation = default;
            mRequester      = default;
            ResultData      = default;
            Assets          = default;
        }
Example #23
0
        public virtual void Execute()
        {
            var cts = new CancellationTokenSource();

            Coordinator.RunAsync(0, cts.Token);

            CompletedEvent.WaitOne(TimeSpan.FromSeconds(TestExecutionTimeInSeconds));

            cts.Cancel();

            // Wait for the IS to return gracefully
            Task.Delay(TimeSpan.FromSeconds(2)).Wait();

            traceType.ConsoleWriteLine("Completed executing workflow. Time taken: {0}", stopwatch.Elapsed);
        }
Example #24
0
        private DateTime?GetTargetReferenceDate(CompletedEvent currentCompletedEvent, UnitOfWork unitOfWork)
        {
            var destinationEvent = unitOfWork.DestinationEvents.FirstOrDefault(e => e.DestinationName.Code == currentCompletedEvent.Name.Code);

            if (destinationEvent == null || destinationEvent.TargetNumberOfDays == null || destinationEvent.EventForDateReferenceForTarget == null)
            {
                return(null);
            }

            var referenceEventForTargetDate = currentCompletedEvent.Period.CompletedEvents.OrderBy(ev => ev.EventDate).ToList().LastOrDefault(ev => ev.Name.Code == destinationEvent.EventForDateReferenceForTarget.Code);

            if (referenceEventForTargetDate == null)
            {
                return(null);
            }
            return(referenceEventForTargetDate.EventDate.AddDays((int)destinationEvent.TargetNumberOfDays).AddDays(currentCompletedEvent.Period.GetNumberOfPausedDays(currentCompletedEvent.EventDate, referenceEventForTargetDate.EventDate)));
        }
        private void OnPlayAssetPackRequestCompleted(string assetPackName, PlayAssetPackRequest request)
        {
            if (request.Error != AssetDeliveryErrorCode.NoError)
            {
                CompletedEvent?.Invoke(this, false, new Exception($"Error downloading error pack: {request.Error}"));
                return;
            }
            if (request.Status != AssetDeliveryStatus.Available)
            {
                CompletedEvent?.Invoke(this, false, new Exception($"Error downloading status: {request.Status}"));
                return;
            }
            var assetLocation = request.GetAssetLocation(assetPackName);

            requestOperation            = AssetBundle.LoadFromFileAsync(assetLocation.Path, /* crc= */ 0, assetLocation.Offset);
            requestOperation.completed += LocalRequestOperationCompleted;
        }
Example #26
0
        void Complete()
        {
            StopAllCoroutines();
            textTMP.text = current.Text;
            completed    = true;
            queue.Dequeue();
            CompletedEvent?.Invoke(this);

            if (queue.Count > 0)
            {
                ShowNext();
            }
            else
            {
                Hide();
            }
        }
Example #27
0
        private void BeginOperation(string assetPackName)
        {
            Debug.LogFormat("[{0}.{1}] assetPackName={2}", nameof(AssetPackBundleSyncResource), nameof(BeginOperation), assetPackName);
            playAssetPackRequest = PlayAssetDelivery.RetrieveAssetPackAsync(assetPackName);
            Exception exception = null;

            if (playAssetPackRequest.IsDone)
            {
                var assetLocation = playAssetPackRequest.GetAssetLocation(assetPackName);
                assetBundle = AssetBundle.LoadFromFile(assetLocation.Path, /* crc= */ 0, assetLocation.Offset);
            }
            else
            {
                exception = new Exception($"Asset Pack was not retrieved Synchronously: '{assetPackName}'.");
            }
            CompletedEvent?.Invoke(this, assetBundle != null, exception);
        }
        public IEnumerable <ErrorResult> ValidateEventCreation(CompletedEvent _event)
        {
            IEnumerable <ErrorResult> errors = new List <ErrorResult>();

            if (_event.StartDate != null && _event.EndDate != null)
            {
                errors.Union(ValidateDates(_event.StartDate, _event.EndDate));
            }

            if (_event.Location == null)
            {
                // TODO Validar locations
            }

            errors.Union(ValidateLocation(_event.Location.Longitude, _event.Location.Latitude));

            return(errors);
        }
Example #29
0
        public async Task Execute(BehaviorContext <RequestState, RequestCompleted> context, Behavior <RequestState, RequestCompleted> next)
        {
            if (!context.Instance.ExpirationTime.HasValue || context.Instance.ExpirationTime.Value > DateTime.UtcNow)
            {
                if (!context.TryGetPayload(out ConsumeContext <RequestCompleted> consumeContext))
                {
                    throw new ArgumentException("The ConsumeContext was not present", nameof(context));
                }

                string body = GetResponseBody(consumeContext, context.Instance);

                IPipe <SendContext> pipe = new CompletedMessagePipe(context.GetPayload <ConsumeContext <RequestCompleted> >(), context.Instance, body);

                var endpoint = await context.GetSendEndpoint(context.Instance.ResponseAddress).ConfigureAwait(false);

                var scheduled = new CompletedEvent();

                await endpoint.Send(scheduled, pipe).ConfigureAwait(false);
            }

            await next.Execute(context).ConfigureAwait(false);
        }
        private bool IsCompletedEventMatched(CompletedEvent completedEvent, PeriodEventsFilterInputInfo periodEventsFilterInput)
        {
            if (periodEventsFilterInput == null)
            {
                return(true);
            }
            var isCompletedEventMatched = (String.IsNullOrEmpty(periodEventsFilterInput.Specialty) || completedEvent.Clinician.Specialty.Name.ToLowerInvariant().Contains(periodEventsFilterInput.Specialty.ToLowerInvariant())) &&
                                          (periodEventsFilterInput.TargetYear == null || (completedEvent.TargetDate != null && completedEvent.TargetDate.Value.Year == periodEventsFilterInput.TargetYear)) &&
                                          (periodEventsFilterInput.ActualYear == null || completedEvent.EventDate.Year == periodEventsFilterInput.ActualYear) &&
                                          (string.IsNullOrEmpty(periodEventsFilterInput.EventDescription) || completedEvent.Name.Description.Contains(periodEventsFilterInput.EventDescription));

            if (periodEventsFilterInput.Breaches == null)
            {
                return(isCompletedEventMatched);
            }
            if (periodEventsFilterInput.Breaches < 0)
            {
                return(isCompletedEventMatched && completedEvent.PostBreachDays != null && completedEvent.PostBreachDays.Value > 0);
            }

            return(false);
        }
Example #31
0
        public async Task <JsonResult> CreateEvent([FromBody] CreateEventDto newEvent)
        {
            DateTime startEventTime;
            DateTime endEventTime;

            if (newEvent == null || newEvent.Token == null || newEvent.Event == null || newEvent.Event.Location == null || !DateTime.TryParse(newEvent.Event.StartDate, out startEventTime) ||
                !DateTime.TryParse(newEvent.Event.EndDate, out endEventTime))
            {
                Response.StatusCode = 400;
                return(new JsonResult("Bad Request"));
            }

            TokenDto token = TokenInDto.ConvertFromDTO(newEvent.Token);

            // EventDto to Model
            CompletedEvent completedEvent = new CompletedEvent
            {
                Description = newEvent.Event.Description,
                Name        = newEvent.Event.Name,
                Location    = newEvent.Event.Location,
                State       = newEvent.Event.State,
                StartDate   = startEventTime,
                EndDate     = endEventTime,
                Radius      = newEvent.Event.Radius,
                Category    = newEvent.Event.Category,
                EventId     = newEvent.Event.EventId != null ? newEvent.Event.EventId : 0
            };

            var events = await this._eventService.CreateEvent(completedEvent, token);

            if (events.Errors != null)
            {
                Response.StatusCode = 401;
                return(new JsonResult(events.Errors));
            }

            Response.StatusCode = 200;
            return(new JsonResult(events.Result));
        }
Example #32
0
 private void CompletedARequest(object sender, CompletedEvent e)
 {
     BeginInvoke((Action)(() => statusStrip.Items[0].Text = e.Method + " completed!"));
 }
 protected virtual void OnCompleted(CompletedEvent completedEvent)
 {
     var handler = Completed;
     if (handler != null) handler(this, completedEvent);
 }