Exemplo n.º 1
0
        async Task MessageConsumer_TestCompletedOnSourceAsync(TestCompletedOnSourceMessage arg)
        {
            using var scope = ScopeFactory.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService <RunnerContext>();

            var runInfo = await db.TestRuns
                          .IncludeGroup(API.Models.EntityGroups.ALL, db)
                          .FirstAsync(r => r.TestId == arg.TestId);

            var result = runInfo.Results
                         .FirstOrDefault(r => r.Id == arg.ResultId);

            if (result != null) // because it could have been deleted
            {
                if (result.ResultBase.Result != RunResult.Aborted)
                {
                    arg.Result.TestId        = arg.TestId;
                    arg.Result.TestName      = runInfo.TestName;
                    arg.Result.StartedByUser = result.ResultBase.StartedByUser;
                    result.ResultBase        = arg.Result;
                    await db.SaveChangesAsync();

                    MessageProducer.FireTestCompleted(new TestCompletedMessage()
                    {
                        TestId = runInfo.TestName,
                        Result = arg.Result
                    });
                }
            }
        }
Exemplo n.º 2
0
        protected override void DoStartAsync(object stoppingToken)
        {
            Logger.LogInformation($"{openWeatherMapOptions.Cities.Length} connected sensor(s)");
            client.BaseAddress = new Uri("http://api.openweathermap.org/data/2.5/");

            for (int i = 0; i < openWeatherMapOptions.Cities.Length; i++)
            {
                string rom = openWeatherMapOptions.Cities[i].ToString();
                using (var scope = ScopeFactory.CreateScope())
                {
                    IUnitOfWork <Sensor> sensorsUnitOfWork = scope.ServiceProvider.GetRequiredService <IUnitOfWork <Sensor> >();
                    var dbSensor = sensorsUnitOfWork.GetRepository().Query().FirstOrDefault(sn => sn.ROM == rom);

                    if (dbSensor == null)
                    {
                        Sensors.Add(new SensorDTO()
                        {
                            SensorID = -i - 1, ROM = rom, DeviceName = $"OpenWeather sensor for city id {rom}"
                        });
                    }
                    else
                    {
                        Sensors.Add(new SensorDTO()
                        {
                            SensorID = dbSensor.snID, ROM = rom, DeviceName = $"OpenWeather sensor for city id {rom}"
                        });
                    }
                    Logger.LogInformation($"Added to list sensor with ROM (CityID): {rom}");
                }
            }
        }
Exemplo n.º 3
0
        private void HistoryDeleteButton_Click(object sender, EventArgs e)
        {
            if (!(historyDataGridView.CurrentRow?.DataBoundItem is Job job))
            {
                return;
            }

            using (var scope = ScopeFactory.CreateScope())
            {
                var db = scope.ServiceProvider.GetService <BibleContext>();
                if (db.Jobs.Any(i => i.Id == job.Id))
                {
                    db.Jobs.Attach(job);
                    db.Jobs.Remove(job);
                    db.SaveChanges();
                }
            }

            // 취소 불가능하면 바로 제거
            if (FindHistoryDataGridViewRow(job).Tag == null)
            {
                jobHistory.RemoveAt(FindHistoryDataGridViewRow(job).Index);
            }
            // 취소 가능하면 취소로 제거
            else
            {
                Builder.Cancel(job);
            }
        }
        /// <summary>
        /// Set a custom state on the session which can be later retrieved using <see cref="GetSessionStateAsync"/>
        /// </summary>
        ///
        /// <param name="sessionState">A <see cref="BinaryData"/> of session state</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <remarks>This state is stored on Service Bus forever unless you set an empty state on it.</remarks>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        public virtual async Task SetSessionStateAsync(
            BinaryData sessionState,
            CancellationToken cancellationToken = default)
        {
            Argument.AssertNotDisposed(IsClosed, nameof(ServiceBusSessionReceiver));
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
            Logger.SetSessionStateStart(Identifier, SessionId);
            using DiagnosticScope scope = ScopeFactory.CreateScope(
                      DiagnosticProperty.SetSessionStateActivityName,
                      sessionId: SessionId);
            scope.Start();

            try
            {
                await InnerReceiver.SetStateAsync(sessionState, cancellationToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Logger.SetSessionStateException(Identifier, exception.ToString());
                scope.Failed(exception);
                throw;
            }

            Logger.SetSessionStateComplete(Identifier);
        }
Exemplo n.º 5
0
        public static async Task <TResponse> SendAsync <TResponse>(IRequest <TResponse> request)
        {
            var scope    = ScopeFactory.CreateScope();
            var mediator = scope.ServiceProvider.GetService <IMediator>();

            return(await mediator.Send(request));
        }
        async Task daemon()
        {
            await ThreadingUtils.ContinueAtDedicatedThread();

            while (true)
            {
                try
                {
                    using var scope = ScopeFactory.CreateScope();
                    using var db    = scope.ServiceProvider.GetRequiredService <TestsContext>();
                    var threshold = DateTime.UtcNow.AddDays(-3);
                    var legacy    = await db.Cases
                                    .Where(c => c.State == TestCaseState.RecordedButNotSaved && c.CreationDate < threshold)
                                    .ToArrayAsync();

                    foreach (var e in legacy)
                    {
                        e.IsDeleted = true;
                    }
                    await db.SaveChangesAsync();

                    Logger.LogInformation($"{legacy.Length} cases have been deleted");
                }
                catch (Exception ex)
                {
                    Logger.LogError(ex, "Could not cleanup");
                }

                await Task.Delay(3600 * 1000);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// Renews the lock on the message. The lock will be renewed based on the setting specified on the queue.
        /// </summary>
        ///
        /// <remarks>
        /// When a message is received in <see cref="ReceiveMode.PeekLock"/> mode, the message is locked on the server for this
        /// receiver instance for a duration as specified during the Queue/Subscription creation (LockDuration).
        /// If processing of the message requires longer than this duration, the lock needs to be renewed.
        /// For each renewal, it resets the time the message is locked by the LockDuration set on the Entity.
        /// </remarks>
        ///
        /// <param name="lockToken">The lockToken of the <see cref="ServiceBusReceivedMessage"/> to renew the lock for.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        public virtual async Task <DateTimeOffset> RenewMessageLockAsync(
            string lockToken,
            CancellationToken cancellationToken = default)
        {
            ThrowIfLockTokenIsEmpty(lockToken);
            Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusReceiver));
            ThrowIfNotPeekLockMode();
            ThrowIfSessionReceiver();
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
            Logger.RenewMessageLockStart(Identifier, 1, lockToken);
            using DiagnosticScope scope = ScopeFactory.CreateScope(
                      DiagnosticProperty.RenewMessageLockActivityName,
                      lockToken: lockToken);
            scope.Start();

            DateTimeOffset lockedUntil;

            try
            {
                lockedUntil = await InnerReceiver.RenewMessageLockAsync(
                    lockToken,
                    cancellationToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Logger.RenewMessageLockException(Identifier, exception.ToString());
                scope.Failed(exception);
                throw;
            }

            Logger.RenewMessageLockComplete(Identifier);
            scope.AddAttribute(DiagnosticProperty.LockedUntilAttribute, lockedUntil);
            return(lockedUntil);
        }
Exemplo n.º 8
0
        /// <summary>
        /// Receives a <see cref="IList{ServiceBusReceivedMessage}"/> of deferred messages identified by <paramref name="sequenceNumbers"/>.
        /// </summary>
        ///
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        /// <param name="sequenceNumbers">An <see cref="IEnumerable{T}"/> containing the sequence numbers to receive.</param>
        ///
        /// <returns>Messages identified by sequence number are returned. Returns null if no messages are found.
        /// Throws if the messages have not been deferred.</returns>
        /// <seealso cref="DeferMessageAsync(ServiceBusReceivedMessage, IDictionary{string, object}, CancellationToken)"/>
        /// <seealso cref="DeferMessageAsync(string, IDictionary{string, object}, CancellationToken)"/>
        public virtual async Task <IList <ServiceBusReceivedMessage> > ReceiveDeferredMessagesAsync(
            IEnumerable <long> sequenceNumbers,
            CancellationToken cancellationToken = default)
        {
            Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusReceiver));
            Argument.AssertNotNullOrEmpty(sequenceNumbers, nameof(sequenceNumbers));
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
            var sequenceNumbersList = sequenceNumbers.ToList();

            Logger.ReceiveDeferredMessageStart(Identifier, sequenceNumbersList);
            using DiagnosticScope scope = ScopeFactory.CreateScope(DiagnosticProperty.ReceiveDeferredActivityName);
            scope.AddAttribute(
                DiagnosticProperty.SequenceNumbersAttribute,
                string.Join(",", sequenceNumbers));
            scope.Start();

            IList <ServiceBusReceivedMessage> deferredMessages = null;

            try
            {
                deferredMessages = await InnerReceiver.ReceiveDeferredMessagesAsync(
                    sequenceNumbersList,
                    cancellationToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Logger.ReceiveDeferredMessageException(Identifier, exception.ToString());
                scope.Failed(exception);
                throw;
            }

            Logger.ReceiveDeferredMessageComplete(Identifier, deferredMessages.Count);
            scope.SetMessageData(deferredMessages);
            return(deferredMessages);
        }
Exemplo n.º 9
0
        public async void ImportPaymentsVippsFiles(IFileListEntry[] files)
        {
            ErrorMessage = "";

            using (var scope = ScopeFactory.CreateScope())
            {
                var db = scope.ServiceProvider.GetService <TandemBookingContext>();

                foreach (var file in files)
                {
                    try
                    {
                        await ImportPaymentsVippsFile(db, file);

                        await db.SaveChangesAsync();
                    }
                    catch (Exception ex)
                    {
                        ErrorMessage += " " + ex.Message;
                    }
                }
            }

            await Load();
        }
Exemplo n.º 10
0
        public async Task <TResult> ExecureAsync <TResult>(
            Expression <Func <PosState, Task <TResult> > > serviceMethod,
            Func <TResult, Task> efterbehandling = null
            )
        {
            try
            {
                var serviceMethodCall = serviceMethod.Compile();
                using var serviceScope = ScopeFactory.CreateScope();
                //var service = posState;
                var service = PosState; // serviceScope.ServiceProvider.GetService<PosState>();
                if (!service.IsInitilized)
                {
                    service.Init(Id);
                }

                var result = await serviceMethodCall(service);

                if (efterbehandling != null)
                {
                    await efterbehandling(result);
                }
                return(result);
            } catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
        }
        protected override void DoStartAsync(object stoppingToken)
        {
            Logger.LogInformation($"{sensorsCount} connected sensor(s)");

            for (int i = 0; i < sensorsCount; i++)
            {
                int rndROM = 111111111 + i;
                using (var scope = ScopeFactory.CreateScope())
                {
                    IUnitOfWork <Sensor> sensorsUnitOfWork = scope.ServiceProvider.GetRequiredService <IUnitOfWork <Sensor> >();
                    var dbSensor = sensorsUnitOfWork.GetRepository().Query().FirstOrDefault(sn => sn.ROM == rndROM.ToString());

                    if (dbSensor == null)
                    {
                        Sensors.Add(new SensorDTO()
                        {
                            SensorID = rndROM, Name = $"Dummy sensor {i}", ROM = rndROM.ToString(), DeviceName = $"Sensor {rndROM}"
                        });
                    }
                    else
                    {
                        Sensors.Add(new SensorDTO()
                        {
                            SensorID = dbSensor.snID, Name = dbSensor.Name, ROM = dbSensor.ROM, DeviceName = $"Sensor {rndROM}"
                        });
                    }
                    Logger.LogInformation($"Added to list sensor with ROM: {rndROM}");
                }
            }
        }
Exemplo n.º 12
0
        internal async Task ProcessMessage(string label, string body, Func <Task> markCompleted, Func <string, Task> abort)
        {
            bool MessageExpired(TimeEvent m)
            {
                var age = DateTime.Now.Subtract(DateTime.Parse(m.Time));

                return(age > TimeSpan.FromMinutes(3.0));
            }

            var message = (TimeEvent)JsonConvert.DeserializeObject(body, typeof(TimeEvent));

            if (MessageExpired(message))
            {
                Log.Warning($"Ignoring expired message. Time: {message.Time}");
                await markCompleted();

                return;
            }

            using (var scope = ScopeFactory.CreateScope())
            {
                var job = (ITimerJob)scope.ServiceProvider.GetRequiredService(JobType);
                var r   = await job.Handler(message);

                if (HandlerResult.IsAbort(r))
                {
                    await abort(r.Message);
                }
                if (HandlerResult.IsSuccess(r))
                {
                    await markCompleted();
                }
            }
        }
Exemplo n.º 13
0
        public async Task <string> RunAsUserAsync(string userName, string password)
        {
            using var scope = ScopeFactory.CreateScope();

            var userManager = scope.ServiceProvider.GetService <UserManager <ApplicationUser> >();

            var existingUser = await userManager.FindByNameAsync(userName);

            if (existingUser != null)
            {
                return(existingUser.Id);
            }

            var user = new ApplicationUser {
                UserName = userName, Email = userName
            };

            var result = await userManager.CreateAsync(user, password);

            if (result.Succeeded)
            {
                CurrentUserId = user.Id;

                return(CurrentUserId);
            }

            var errors = string.Join(Environment.NewLine, result.ToApplicationResult().Errors);

            throw new Exception($"Unable to create {userName}.{Environment.NewLine}{errors}");
        }
Exemplo n.º 14
0
        /// <summary> Indicates that the receiver wants to defer the processing for the message.</summary>
        ///
        /// <param name="lockToken">The lockToken of the <see cref="ServiceBusReceivedMessage"/> to defer.</param>
        /// <param name="propertiesToModify">The properties of the message to modify while deferring the message.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        ///
        /// <remarks>
        /// A lock token can be found in <see cref="ServiceBusReceivedMessage.LockToken"/>,
        /// only when <see cref="ReceiveMode"/> is set to <see cref="ReceiveMode.PeekLock"/>.
        /// In order to receive this message again in the future, you will need to save the
        /// <see cref="ServiceBusReceivedMessage.SequenceNumber"/>
        /// and receive it using <see cref="ReceiveDeferredMessageAsync(long, CancellationToken)"/>.
        /// Deferring messages does not impact message's expiration, meaning that deferred messages can still expire.
        /// This operation can only be performed on messages that were received by this receiver.
        /// </remarks>
        ///
        /// <returns>A task to be resolved on when the operation has completed.</returns>
        public virtual async Task DeferMessageAsync(
            string lockToken,
            IDictionary <string, object> propertiesToModify = null,
            CancellationToken cancellationToken             = default)
        {
            ThrowIfLockTokenIsEmpty(lockToken);
            Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusReceiver));
            ThrowIfNotPeekLockMode();
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
            Logger.DeferMessageStart(Identifier, 1, lockToken);
            using DiagnosticScope scope = ScopeFactory.CreateScope(
                      DiagnosticProperty.DeferActivityName,
                      lockToken: lockToken);
            scope.Start();

            try
            {
                await InnerReceiver.DeferAsync(
                    lockToken,
                    propertiesToModify,
                    cancellationToken).ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Logger.DeferMessageException(Identifier, exception.ToString());
                scope.Failed(exception);
                throw;
            }

            Logger.DeferMessageComplete(Identifier);
        }
Exemplo n.º 15
0
        internal async Task ProcessMessage(string label, string body, Func <Task> markCompleted, Func <string, Task> abort)
        {
            var typeFromLabel = Registry.GetMessageTypeByName(label);

            if (typeFromLabel != default)
            {
                var message = JsonConvert.DeserializeObject(body, typeFromLabel);

                using (var scope = ScopeFactory.CreateScope())
                {
                    var tasks = Registry
                                .GetHandlers(message.GetType(), scope)
                                .ToList()     // avoid deferred execution, we want all handlers to execute
                                .Select(h => CallHandler(h, message, abort))
                                .ToArray();
                    var results = await Task.WhenAll(tasks);

                    if (results.All(r => r))
                    {
                        await markCompleted();
                    }
                }
            }
            else
            {
                Log.Debug("No handler registered for the given {Label}. {@Body}", label, body);
                await markCompleted();
            }
        }
Exemplo n.º 16
0
        async Task daemon()
        {
            await ThreadingUtils.ContinueAtDedicatedThread();

            while (true)
            {
                try
                {
                    using var scope = ScopeFactory.CreateScope();
                    var db = scope.ServiceProvider.GetRequiredService <RunnerContext>();

                    var toUpdate = await db.RunResults
                                   .AsNoTracking()
                                   .IncludeGroup(API.Models.EntityGroups.ALL, db)
                                   .Where(r => !r.ResultBase.State.IsFinal && r.ResultBase.State.NextStateUpdate != null && r.ResultBase.State.NextStateUpdate.Value < DateTime.UtcNow)
                                   .ToArrayAsync();

                    foreach (var r in toUpdate)
                    {
                        Producer.FireUpdateTestResultState(new UpdateTestResultStateMessage(r.ResultBase.TestId, r.Id, r.ResultBase.SourceId, r.ResultBase.State));
                    }
                }
                catch (Exception ex)
                {
                    Debugger.Break();
                }

                await Task.Delay(10 * 1000);
            }
        }
Exemplo n.º 17
0
        private async Task Load()
        {
            using (var scope = ScopeFactory.CreateScope())
            {
                var db = scope.ServiceProvider.GetService <TandemBookingContext>();

                UnreconciledBookings = await db.Bookings
                                       .Where(b => b.Completed && !b.Canceled && b.PassengerFee > 0 && b.ReconciledDate == null)
                                       .Include(b => b.AssignedPilot)
                                       .Include(b => b.PaymentAccount)
                                       .Include(b => b.BookingPayments)
                                       .OrderBy(b => b.BookingDate)
                                       .AsNoTracking()
                                       .ToListAsync();

                UnreconciledPayments = await db.Payments
                                       .Where(p => p.UnreconciledAmount > 0)
                                       .Include(p => p.PaymentAccount)
                                       .OrderBy(p => p.PaymentDate)
                                       .AsNoTracking()
                                       .ToListAsync();

                PaymentAccounts = await db.PaymentAccounts
                                  .Where(p => p.Active)
                                  .OrderBy(p => p.Name)
                                  .ToListAsync();
            }
        }
Exemplo n.º 18
0
        async Task Consumer_TestAcquiredAsync(TestAcquiringResultMessage arg)
        {
            using var scope = ScopeFactory.CreateScope();
            using var db    = scope.ServiceProvider.GetRequiredService <TestsContext>();

            var test = new TestCase()
            {
                TestName        = arg.DefaultTestName,
                TestDescription = arg.DefaultTestDescription,
                CreationDate    = DateTime.UtcNow,
                Data            = new TestCaseData()
                {
                    Data          = arg.TestData,
                    Type          = arg.TestType,
                    Parameters    = arg.Parameters,
                    KeyParameters = arg.KeyParameters.Select(kvp => new KeyParameter(kvp.Key, kvp.Value)).ToList()
                },
                State = TestCaseState.RecordedButNotSaved,
            };
            await db.Cases.AddAsync(test);

            await db.SaveChangesAsync();

            MessageProducer.FireTestRecorded(new TestRecordedMessage(test.TestId, test.TestName, test.TestDescription));
        }
        private async Task <bool> HandleCurrentPassAsync(long currentPassHeight, CancellationToken cancellationToken)
        {
            bool processedAny = false;

            while (true)
            {
                long height = 0;
                using (var scope = ScopeFactory.CreateScope())
                {
                    var db = scope.ServiceProvider.GetRequiredService <PoolContext>();

                    using (var transaction = await db.Database.BeginTransactionAsync(cancellationToken))
                    {
                        var nextBlock = await db.BlockStates.Where(i => !i.SharesAveraged && i.Height <= currentPassHeight).OrderBy(i => i.Height).FirstOrDefaultAsync();

                        if (nextBlock == null)
                        {
                            return(processedAny);
                        }
                        height = nextBlock.Height;
                        await ProcessBlockAsync(nextBlock.Height, db, cancellationToken).ConfigureAwait(false);

                        processedAny             = true;
                        nextBlock.SharesAveraged = true;
                        await db.SaveChangesAsync(cancellationToken);

                        transaction.Commit();
                    }
                }
                await Messenger.PublishAsync("Block.State.Averaged", this, new BlockStateChangedMessage(height)).ConfigureAwait(false);
            }
        }
        protected override void DoStartAsync(object stoppingToken)
        {
            uart = new UART_Adapter(UARTSettings.COMPort);
            uart.Open();
            Logger.LogInformation($"UART is now listennig port {UARTSettings.COMPort}");
            OneWireSensor sensor = new DS18B20(uart);
            List <byte[]> ROMs   = sensor.GetConnectedROMs();

            Logger.LogInformation($"{ROMs.Count} connected sensor(s)");

            foreach (byte[] item in ROMs)
            {
                OneWireSensor physSensor = Utils.CreateSensor(item[0], uart, item);
                using (var scope = ScopeFactory.CreateScope())
                {
                    IUnitOfWork <Sensor> sensorsUnitOfWork = scope.ServiceProvider.GetRequiredService <IUnitOfWork <Sensor> >();
                    var dbSensor = sensorsUnitOfWork.GetRepository().Query().FirstOrDefault(sn => sn.ROM == physSensor.ROM);
                    if (dbSensor == null)
                    {
                        Sensors.Add(new UARTSensorDTO(physSensor)
                        {
                            SensorID = (Sensors.Count + 1) * -1, Name = "Not in DB", ROM = physSensor.ROM, DeviceName = physSensor.DeviceName(physSensor.FamilyCode)
                        });
                    }
                    else
                    {
                        Sensors.Add(new UARTSensorDTO(physSensor)
                        {
                            SensorID = dbSensor.snID, Name = dbSensor.Name, ROM = physSensor.ROM, DeviceName = physSensor.DeviceName(physSensor.FamilyCode)
                        });
                    }
                    Logger.LogInformation($"Added to list sensor with ROM: {physSensor.ROM}, Family Code = {physSensor.FamilyCode}");
                }
            }
        }
Exemplo n.º 21
0
        protected override async Task SpecificProcessAction(DtoSmsMessage msg)
        {
            using (var scope = ScopeFactory.CreateScope())
            {
                var provider = scope.ServiceProvider;

                var traceService = provider.GetService <ITraceService>();
                await traceService.WriteMessageAsync(
                    $"SMS_SENDER: sending sms for {msg.Phone}");

                var settingsService = provider.GetService <ISettingsService>();
                var url             = settingsService.GetSmsServiceUrl();

                var json = JsonConvert.SerializeObject(msg);

                var httpClient = new HttpClient();
                var response   = await httpClient.PostAsync($"{url}",
                                                            new StringContent(json, Encoding.UTF8, "application/json"));

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    throw new HttpRequestException($"{response.StatusCode}");
                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Fetches a list of active messages without changing the state of the receiver or the message source.
        /// </summary>
        /// <param name="sequenceNumber">The sequence number from where to peek the message.</param>
        /// <param name="maxMessages">The maximum number of messages that will be fetched.</param>
        /// <param name="cancellationToken">An optional <see cref="CancellationToken"/> instance to signal the request to cancel the operation.</param>
        /// <returns>An <see cref="IList{ServiceBusReceivedMessage}" /> of messages that were peeked.</returns>
        private async Task <IList <ServiceBusReceivedMessage> > PeekMessagesInternalAsync(
            long?sequenceNumber,
            int maxMessages,
            CancellationToken cancellationToken)
        {
            Argument.AssertNotClosed(IsDisposed, nameof(ServiceBusReceiver));
            cancellationToken.ThrowIfCancellationRequested <TaskCanceledException>();
            Logger.PeekMessageStart(Identifier, sequenceNumber, maxMessages);
            using DiagnosticScope scope = ScopeFactory.CreateScope(
                      DiagnosticProperty.PeekActivityName,
                      requestedMessageCount: maxMessages);
            scope.Start();

            IList <ServiceBusReceivedMessage> messages = new List <ServiceBusReceivedMessage>();

            try
            {
                messages = await InnerReceiver.PeekMessagesAsync(
                    sequenceNumber,
                    maxMessages,
                    cancellationToken)
                           .ConfigureAwait(false);
            }
            catch (Exception exception)
            {
                Logger.PeekMessageException(Identifier, exception.ToString());
                scope.Failed(exception);
                throw;
            }

            Logger.PeekMessageComplete(Identifier, messages.Count);
            scope.SetMessageData(messages);
            return(messages);
        }
Exemplo n.º 23
0
        private async Task ProcessSingleMessage(Message m)
        {
            try
            {
                SnsPayload snsPayload;
                try
                {
                    snsPayload = JsonConvert.DeserializeObject <SnsPayload>(m.Body);
                }
                catch (Exception e)
                {
                    Logger.LogError(e, $"{nameof(ProcessSingleMessage)} Failed to deserialize snsPayload with ID {m.MessageId}");
                    snsPayload = null;
                }

                if (snsPayload == null)
                {
                    // Either exception or null deserialization can occur with badly formed Json.
                    // Delete, so they don't just fill up the que
                    var deleteMessage  = new DeleteMessageRequest(_url, m.ReceiptHandle);
                    var deleteResponse = await _awSqsClient.DeleteMessageAsync(deleteMessage);

                    Logger.LogWarning($"{nameof(ProcessSingleMessage)} Failed to parse SQS Message. MessageID: {m.MessageId}, Body: {m.Body} Delete SQS Message Response Code: {deleteResponse.HttpStatusCode}");
                    return;
                }

                Logger.LogInformation($"{nameof(ProcessSingleMessage)} Processing SQS Message ID: {m.MessageId}.");
                // We need to create a scope, as a hosted service is a singleton, but some of the services are transient, we can't inject them.
                // Instead we create a scope for 'our' work
                using var serviceScope = ScopeFactory.CreateScope();
                var executor = RequestExecutorContainer.Build <TagFileSnsProcessExecutor>(
                    serviceScope.ServiceProvider.GetService <ILoggerFactory>(),
                    serviceScope.ServiceProvider.GetService <IConfigurationStore>(),
                    serviceScope.ServiceProvider.GetService <IDataCache>(),
                    serviceScope.ServiceProvider.GetService <ITRexTagFileProxy>(),
                    serviceScope.ServiceProvider.GetService <ITransferProxyFactory>(),
                    serviceScope.ServiceProvider.GetService <IWebRequest>());

                var result = await executor.ProcessAsync(snsPayload);

                // internalErrors are retry-able, so leave them on the que to be picked up again.
                if (result != null && result.Code != ContractExecutionStatesEnum.InternalProcessingError)
                {
                    // Mark as processed
                    var deleteMessage  = new DeleteMessageRequest(_url, m.ReceiptHandle);
                    var deleteResponse = await _awSqsClient.DeleteMessageAsync(deleteMessage);

                    Logger.LogInformation($"{nameof(ProcessSingleMessage)} Delete SQS Message Response Code: {deleteResponse.HttpStatusCode}");
                }
                else
                {
                    Logger.LogWarning($"{nameof(ProcessSingleMessage)} Tag file failed to process due to internal error, leave it on que to be re-processed: {m.MessageId}.");
                }
            }
            catch (Exception e)
            {
                Logger.LogError(e, $"{nameof(ProcessSingleMessage)} Failed to process message with ID {m.MessageId} - not deleted from the queue");
            }
        }
Exemplo n.º 24
0
        protected async Task ImportPaymentsIZettle()
        {
            using (var scope = ScopeFactory.CreateScope())
            {
                var db = scope.ServiceProvider.GetService <TandemBookingContext>();

                var purchases = await IZettleService.GetPayments(DateTime.Now.AddYears(-1), null);

                var payments = purchases.Purchases
                               .SelectMany(purchase => purchase.Payments
                                           .Select(payment => new
                {
                    Purchase = purchase,
                    Payment  = payment,
                })
                                           )
                               .ToList();

                var paymentAccounts = db.PaymentAccounts
                                      .Where(a => a.PaymentType == PaymentType.IZettle)
                                      .ToList();

                foreach (var x in payments)
                {
                    if (!db.Payments.Any(p => p.PaymentType == PaymentType.IZettle && p.ExternalRef == x.Payment.Uuid))
                    {
                        var paymentAccount = paymentAccounts.FirstOrDefault(a => a.PaymentType == PaymentType.IZettle && a.ExternalRef == x.Purchase.UserId.ToString());
                        if (paymentAccount == null)
                        {
                            paymentAccount = new PaymentAccount
                            {
                                Active      = true,
                                PaymentType = PaymentType.IZettle,
                                ExternalRef = x.Purchase.UserId.ToString(),
                                Name        = x.Purchase.UserDisplayName,
                            };
                            paymentAccounts.Add(paymentAccount);
                        }

                        var payment = new Payment
                        {
                            PaymentType        = PaymentType.IZettle,
                            ExternalRef        = x.Payment.Uuid,
                            Amount             = x.Payment.Amount / 100m,
                            UnreconciledAmount = x.Payment.Amount / 100m,
                            Fee            = 0m,
                            PaymentDate    = x.Purchase.Timestamp,
                            InsertDate     = DateTimeOffset.Now,
                            PaymentAccount = paymentAccount,
                        };
                        db.Add(payment);
                    }
                }

                await db.SaveChangesAsync();
            }

            await Load();
        }
Exemplo n.º 25
0
        public override async Task OnIntervalAsync()
        {
            using var scope = ScopeFactory.CreateScope();
            var db = scope.ServiceProvider.GetService <UsersDbContext>();

            db.RemoveRange(db.Users.Where(x => x.DeleteAt <= DateTime.Today));
            await db.SaveChangesAsync();
        }
        public async Task RemoveAsync <TEntity>(TEntity entity)
            where TEntity : BaseEntity
        {
            using var scope = ScopeFactory.CreateScope();

            var repository = scope.ServiceProvider.GetService <IRepository <TEntity> >();
            await repository.RemoveAsync(entity);
        }
Exemplo n.º 27
0
        private void EnsureDatabase()
        {
            using var scope = ScopeFactory.CreateScope();

            var context = scope.ServiceProvider.GetService <ApplicationDbContext>();

            context.Database.EnsureCreated();
        }
Exemplo n.º 28
0
        public static void EnsureDatabase()
        {
            using var scope = ScopeFactory.CreateScope();

            var context = scope.ServiceProvider.GetService <ApplicationDbContext>();

            context.Database.Migrate();
        }
Exemplo n.º 29
0
        public static async Task <Book> GetBookAsync(string title)
        {
            var scope   = ScopeFactory.CreateScope();
            var context = scope.ServiceProvider.GetService <AppDbContext>();

            return(await context.Books
                   .Include(b => b.Authors)
                   .FirstOrDefaultAsync(b => b.Title == title));
        }
Exemplo n.º 30
0
        public static async Task <Card> GetDefaultUserCardAsync()
        {
            var scope   = ScopeFactory.CreateScope();
            var context = scope.ServiceProvider.GetService <AppDbContext>();

            return(await context.Cards
                   .Include(c => c.Books)
                   .FirstAsync(c => c.Id == UserCardId));
        }