Ejemplo n.º 1
0
        public void Error_string_ConsoleFallback()
        {
            new WebLogger(null, _scopeFactory).LogError("error_message");

            var fakeConsole = _scopeFactory?.CreateScope().ServiceProvider.GetService <IConsole>() as FakeConsoleWrapper;

            Assert.AreEqual("error_message", fakeConsole.WrittenLines.LastOrDefault());
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Trace = 0, Debug = 1, Information = 2, Warning = 3, Error = 4, Critical = 5, and None = 6.
        /// @see https://docs.microsoft.com/en-us/aspnet/core/fundamentals/logging/?view=aspnetcore-6.0
        /// </summary>
        /// <param name="logger">ILoggerFactory</param>
        /// <param name="scopeFactory">optional scopeFactory</param>
        public WebLogger(ILoggerFactory logger = null, IServiceScopeFactory scopeFactory = null)
        {
            _logger = logger?.CreateLogger("app");
            var scopeProvider = scopeFactory?.CreateScope().ServiceProvider;

            if (scopeProvider != null)
            {
                _console = scopeProvider.GetService <IConsole>();
            }
        }
Ejemplo n.º 3
0
        private bool disposedValue = false; // To detect redundant calls

        #endregion Fields

        #region Constructors

        public RequestServicesContainer(
            HttpContext context,
            IServiceScopeFactory scopeFactory,
            IServiceProvider appServiceProvider)
        {
            if (scopeFactory == null)
            {
                throw new ArgumentNullException(nameof(scopeFactory));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            Context = context;
            PriorAppServices = context.ApplicationServices;
            PriorRequestServices = context.RequestServices;

            // Begin the scope
            Scope = scopeFactory.CreateScope();

            Context.ApplicationServices = appServiceProvider;
            Context.RequestServices = Scope.ServiceProvider;
        }
 public static async Task MigrateDbAsync(this IServiceScopeFactory scopeFactory, CancellationToken cancellationToken)
 {
     using var scope = scopeFactory.CreateScope();
     var   dbContext = scope.ServiceProvider.GetService <MarketplaceDbContext>();
     await dbContext !.Database.MigrateAsync(cancellationToken: cancellationToken);
 }
Ejemplo n.º 5
0
 public void StartScope()
 {
     ServiceProvider = ServiceScopeFactory.CreateScope().ServiceProvider;
     GetService <DietContext>().Database.EnsureCreated();
 }
Ejemplo n.º 6
0
        public async Task Run(CancellationToken cancellationToken)
        {
            using (var scope = _scopeFactory.CreateScope())
            {
                var dbContext     = scope.ServiceProvider.GetService <BIDatabaseContext>();
                var lastRunConfig = await dbContext.RuntimeConfigs.FindAsync("OrderProcessingLastRun");

                var lastRunDate = _initialConfig.InitialReferenceDate;
                if (lastRunConfig != null)
                {
                    lastRunDate = lastRunConfig.DateConfig;
                }
                else
                {
                    lastRunConfig = new RuntimeConfig
                    {
                        RuntimeConfigId = "OrderProcessingLastRun", DateConfig = _initialConfig.InitialReferenceDate
                    };
                    _logger.LogInformation("Starting from default start date {StartDate}",
                                           _initialConfig.InitialReferenceDate);
                    dbContext.RuntimeConfigs.Add(lastRunConfig);
                }

                // subtract 10 minute jitter
                var from = lastRunDate.Subtract(TimeSpan.FromMinutes(10));
                var to   = from.Add(_initialConfig.MaximumTimeSpan);
                _logger.LogInformation("Searching orders from {From} to {To}", from, to);
                var orders =
                    await _searchClient.SearchOrdersBetween(from, to);

                List <SFCCTools.Jobs.Order> orderEntities = new List <Order>();

                await foreach (var searchHit in orders)
                {
                    var order = searchHit.Data;
                    try
                    {
                        orderEntities.Add(new Order()
                        {
                            OrderId      = order.OrderNo,
                            CustomerNo   = order.CustomerInfo.CustomerNo,
                            Status       = order.Status,
                            CreationDate = order.CreationDate,

                            ProductTotal  = order.ProductTotal,
                            TaxTotal      = order.TaxTotal,
                            OrderTotal    = order.OrderTotal,
                            ShippingTotal = order.ShippingTotal,

                            ShippingMethod = order.Shipments.Count > 0 ? order.Shipments[0].ShippingMethod.Id : null,

                            BillingCountryCode  = order.BillingAddress.CountryCode,
                            BillingStateCode    = order.BillingAddress.StateCode,
                            ShippingCountryCode = order.Shipments.Count > 0
                                ? order.Shipments[0].ShippingAddress.CountryCode
                                : null,
                            ShippingStateCode = order.Shipments.Count > 0
                                ? order.Shipments[0].ShippingAddress.StateCode
                                : null,

                            Products = order.ProductItems.Select <ProductItem, ProductLineItem>((pi, i) =>
                            {
                                return(new ProductLineItem()
                                {
                                    Index = i,
                                    OrderId = order.OrderNo,
                                    ProductId = pi.ProductId
                                });
                            }).ToList(),

                            PaymentMethods = order.PaymentInstruments.Select <PaymentInstrument, PaymentMethod>(
                                (pi, i) =>
                            {
                                return(new PaymentMethod()
                                {
                                    Index = i,
                                    OrderId = order.OrderNo,
                                    Method = pi.PaymentMethodId
                                });
                            }).ToList(),
                        });
                    }
                    catch (System.ArgumentNullException e)
                    {
                        _logger.LogError(e, "Invalid order {OrderNo} received, skipping", order.OrderNo);
                    }
                }

                _logger.LogInformation("Saving {NumOrders} orders to database", orderEntities.Count);
                foreach (var orderEntity in orderEntities)
                {
                    var found = await dbContext.Orders.FindAsync(orderEntity.OrderId);

                    if (found == null)
                    {
                        dbContext.Orders.Add(orderEntity);
                    }
                }

                await dbContext.SaveChangesAsync(cancellationToken);

                var mostRecentOrder = await dbContext.Orders.OrderByDescending(o => o.CreationDate).FirstOrDefaultAsync(cancellationToken: cancellationToken);

                if (mostRecentOrder != null && mostRecentOrder.CreationDate <= to)
                {
                    lastRunConfig.DateConfig = mostRecentOrder.CreationDate;
                }
                else
                {
                    lastRunConfig.DateConfig = to;
                }

                await dbContext.SaveChangesAsync(cancellationToken);
            }
        }
Ejemplo n.º 7
0
 public KafkaMessageConsumerFactory(IServiceScopeFactory serviceScopeFactory)
 {
     ServiceScope = serviceScopeFactory.CreateScope();
 }
Ejemplo n.º 8
0
        public async Task HandleApplicationMessageReceivedAsync(MqttApplicationMessageReceivedEventArgs args)
        {
            var message = Encoding.ASCII.GetString(args.ApplicationMessage.Payload);

            _logger.LogInformation("Received message {0}", message);

            if (args.ApplicationMessage.Topic.Contains("r"))
            {
                return;
            }

            using var scope = _serviceFactory.CreateScope();
            var dbContext     = scope.ServiceProvider.GetRequiredService <SmartLockDbContext>();
            var macAddress    = GetMacAddress(args.ApplicationMessage.Topic);
            var result        = dbContext.Devices.SingleOrDefault(device => device.MacAddress == macAddress);
            var responseTopic = args.ApplicationMessage.Topic + "/r00";

            if (result is null)
            {
                _logger.LogInformation("Device not registered");
                await _client.PublishAsync(responseTopic, "2,f");

                return;
            }

            var(messageType, thumbprint) = ReadRequest(message);

            if (messageType == MessageType.Auth)
            {
                var registered = dbContext.Entry(result)
                                 .Collection(result => result.Registries)
                                 .Query()
                                 .Any(registry => registry.Thumbprint == thumbprint);
                var regResult = registered ? "t" : "f";
                var response  = $"2,{regResult}";
                await _client.PublishAsync(responseTopic, response);

                return;
            }
            else if (messageType == MessageType.Register)
            {
                var registered = dbContext.TagRegistries.FirstOrDefault(registry => registry.Thumbprint == thumbprint);
                if (registered is null || registered.OwnerDevice.DeviceId != result.DeviceId)
                {
                    dbContext.TagRegistries.Add(new Shared.Models.TagRegistry()
                    {
                        OwnerDevice = result,
                        IsActive    = true,
                        Thumbprint  = thumbprint
                    });
                }
                else
                {
                    _logger.LogInformation("Already registered");
                }
                await dbContext.SaveChangesAsync();

                await _client.PublishAsync(responseTopic, "2,t");

                return;
            }
Ejemplo n.º 9
0
        protected async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            try
            {
                while (!stoppingToken.IsCancellationRequested)
                {
                    using (var scope = _serviceScopeFactory.CreateScope())
                    {
                        // get name of job
                        string JobType = Utilities.GetFullTypeName(GetType().AssemblyQualifiedName);

                        // load jobs and find current job
                        IJobRepository Jobs = scope.ServiceProvider.GetRequiredService <IJobRepository>();
                        Job            Job  = Jobs.GetJobs().Where(item => item.JobType == JobType).FirstOrDefault();
                        if (Job != null && Job.IsEnabled && !Job.IsExecuting)
                        {
                            // set next execution date
                            if (Job.NextExecution == null)
                            {
                                if (Job.StartDate != null)
                                {
                                    Job.NextExecution = Job.StartDate;
                                }
                                else
                                {
                                    Job.NextExecution = DateTime.Now;
                                }
                            }

                            // determine if the job should be run
                            if (Job.NextExecution <= DateTime.Now && (Job.EndDate == null || Job.EndDate >= DateTime.Now))
                            {
                                IJobLogRepository JobLogs = scope.ServiceProvider.GetRequiredService <IJobLogRepository>();

                                // create a job log entry
                                JobLog log = new JobLog();
                                log.JobId      = Job.JobId;
                                log.StartDate  = DateTime.Now;
                                log.FinishDate = null;
                                log.Succeeded  = false;
                                log.Notes      = "";
                                log            = JobLogs.AddJobLog(log);

                                // update the job to indicate it is running
                                Job.IsExecuting = true;
                                Jobs.UpdateJob(Job);

                                // execute the job
                                try
                                {
                                    log.Notes     = ExecuteJob(scope.ServiceProvider);
                                    log.Succeeded = true;
                                }
                                catch (Exception ex)
                                {
                                    log.Notes     = ex.Message;
                                    log.Succeeded = false;
                                }

                                // update the job log
                                log.FinishDate = DateTime.Now;
                                JobLogs.UpdateJobLog(log);

                                // update the job
                                Job.NextExecution = CalculateNextExecution(Job.NextExecution.Value, Job.Frequency, Job.Interval);
                                Job.IsExecuting   = false;
                                Jobs.UpdateJob(Job);

                                // trim the job log
                                List <JobLog> logs = JobLogs.GetJobLogs().Where(item => item.JobId == Job.JobId)
                                                     .OrderByDescending(item => item.JobLogId).ToList();
                                for (int i = logs.Count; i > Job.RetentionHistory; i--)
                                {
                                    JobLogs.DeleteJobLog(logs[i - 1].JobLogId);
                                }
                            }
                        }
                    }

                    // wait 1 minute
                    await Task.Delay(TimeSpan.FromMinutes(1), stoppingToken);
                }
            }
            catch
            {
                // can occur during the initial installation as there is no DBContext
            }
        }
Ejemplo n.º 10
0
 public void Initialize()
 {
     using var serviceScope = _scopeFactory.CreateScope();
     using var context      = serviceScope.ServiceProvider.GetService <ApplicationDbContext>();
     context.Database.Migrate();
 }
            public async Task OnAuthorizationCodeReceived(AuthorizationCodeReceivedContext context)
            {
                // Use MSAL to swap the code for an access token
                // Extract the code from the response notification
                var code = context.ProtocolMessage.Code;

                //var Identity = context.Principal.Identity as ClaimsIdentity;
                //Identity.RemoveClaim(Identity.FindFirst("Name"));


                string signedInUserID = context.Principal.FindFirst(ClaimTypes.NameIdentifier).Value;
                IConfidentialClientApplication cca = ConfidentialClientApplicationBuilder.Create(AzureAdB2COptions.ClientId)
                                                     .WithB2CAuthority(AzureAdB2COptions.Authority)
                                                     .WithRedirectUri(AzureAdB2COptions.RedirectUri)
                                                     .WithClientSecret(AzureAdB2COptions.ClientSecret)
                                                     .Build();

                new MSALStaticCache(signedInUserID, context.HttpContext).EnablePersistence(cca.UserTokenCache);

                if (context.Principal != null)
                {
                    using (var scope = _scopeFactory.CreateScope())
                    {
                        var db = scope.ServiceProvider.GetRequiredService <DataContext>();

                        string email = context.Principal.Identities.First().Claims.Where(x => x.Type == "emails").First().Value;

                        var user = db.User.Include(x => x.Role).Where(x => x.EmailAdress == email).FirstOrDefault();

                        if (user == null)
                        {
                            string firstName = context.Principal.Identities.First().Claims.Where(x => x.Type == ClaimTypes.GivenName).First().Value;
                            string lastName  = context.Principal.Identities.First().Claims.Where(x => x.Type == ClaimTypes.Surname).First().Value;

                            db.User.Add(new User()
                            {
                                EmailAdress = email, RoleId = 3, FirstName = firstName, LastName = lastName, PhoneNumber = "111111111"
                            });
                            db.SaveChanges();

                            user = db.User.Include(x => x.Role).Where(x => x.EmailAdress == email).FirstOrDefault();
                        }

                        var Identity = context.Principal.Identity as ClaimsIdentity;
                        if (Identity.FindFirst("Name") != null)
                        {
                            Identity.RemoveClaim(Identity.FindFirst("Name"));
                        }
                        context.Principal.Identities.First().AddClaim(new Claim(ClaimTypes.Role, user.Role.Name));
                        context.Principal.Identities.First().AddClaim(new Claim(context.Principal.Identities.First().NameClaimType, user.FirstName + " " + user.LastName));
                    }

                    var p = context.Principal.Identities.First();
                }

                try
                {
                    AuthenticationResult result = await cca.AcquireTokenByAuthorizationCode(AzureAdB2COptions.ApiScopes.Split(' '), code)
                                                  .ExecuteAsync();

                    context.HandleCodeRedemption(result.AccessToken, result.IdToken);
                }
                catch
                {
                    //TODO: Handle
                    throw;
                }
            }
Ejemplo n.º 12
0
 public FtpScheduleTask(IServiceScopeFactory serviceScopeFactory, IOptions <AppSettingFtp> ftpSettings) : base(serviceScopeFactory)
 {
     FtpConfiguration = ftpSettings;
     _db = serviceScopeFactory.CreateScope().ServiceProvider.GetRequiredService <MovieDatabaseContext>();
 }
Ejemplo n.º 13
0
        public async Task <IActionResult> Put(
            [FromServices] IConfiguration Config,
            [FromServices] IServiceScopeFactory scopeFactory,
            [FromServices] StateMachineAwaiter awaiter,
            [FromServices] ManagementServiceClient MgmtSvc,
            [FromServices] IHubContext <OnlineJudgeHub> hub,
            CancellationToken token)
        {
            var request = JsonConvert.DeserializeObject <JudgeRequest>(RequestBody);
            var problem = await DB.Problems
                          .Include(x => x.TestCases)
                          .SingleOrDefaultAsync(x => x.Id == request.problemId, token);

            if (problem == null)
            {
                return(Result(400, "The problem does not exist."));
            }

            if (!problem.IsVisible && string.IsNullOrWhiteSpace(request.contestId) && !await HasPermissionToProblemAsync(problem.Id, token))
            {
                return(Result(403, "You have no permission to the problem."));
            }

            if (!Constants.SupportedLanguages.Contains(request.language))
            {
                return(Result(400, "The language has not been supported."));
            }

            // TODO: Check contest permission

            if (!Constants.SupportedLanguages.Contains(request.language) && !Constants.UnsupportedLanguages.Contains(request.language) && problem.Source == ProblemSource.Local)
            {
                return(Result(400, "The programming language which you selected was not supported"));
            }

            if (request.isSelfTest && request.data.Count() == 0)
            {
                return(Result(400, "The self testing data has not been found"));
            }

            if (problem.Source != ProblemSource.Local && request.isSelfTest)
            {
                return(Result(400, "You could not use self data to test with a remote problem."));
            }

            #region Local Judge
            if (problem.Source == ProblemSource.Local)
            {
                var blobs = new ConcurrentDictionary <int, BlobInfo[]>();
                blobs.TryAdd(-1, new[] { new BlobInfo
                                         {
                                             Id   = await MgmtSvc.PutBlobAsync("Main" + Constants.GetSourceExtension(request.language), Encoding.UTF8.GetBytes(request.code)),
                                             Name = "Main" + Constants.GetSourceExtension(request.language),
                                             Tag  = "Problem=" + problem.Id
                                         } });
                blobs.TryAdd(-2, new[] { new BlobInfo
                                         {
                                             Id = await MgmtSvc.PutBlobAsync("limit.json", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(new
                        {
                            UserTime     = problem.TimeLimitationPerCaseInMs,
                            PhysicalTime = problem.TimeLimitationPerCaseInMs * 4,
                            Memory       = problem.MemoryLimitationPerCaseInByte
                        }))),
                                             Name = "limit.json",
                                             Tag  = "Problem=" + problem.Id
                                         } });
                if (!problem.ValidatorBlobId.HasValue)
                {
                    blobs.TryAdd(-3, new[]
                    {
                        new BlobInfo
                        {
                            Id   = Guid.Parse(Config["JoyOI:StandardValidatorBlobId"]),
                            Name = "Validator" + Constants.GetBinaryExtension(problem.ValidatorLanguage)
                        }
                    });
                }
                else
                {
                    // TODO: Special Judge
                }

                if (request.isSelfTest)
                {
                    Parallel.For(0, request.data.Count(), i =>
                    {
                        // Uploading custom data
                        var inputId  = MgmtSvc.PutBlobAsync($"input_{ i }.txt", Encoding.UTF8.GetBytes(request.data.ElementAt(i).input), token).Result;
                        var outputId = MgmtSvc.PutBlobAsync($"output_{ i }.txt", Encoding.UTF8.GetBytes(request.data.ElementAt(i).output), token).Result;
                        blobs.TryAdd(i, new[] {
                            new BlobInfo {
                                Id = inputId, Name = $"input_{ i }.txt", Tag = i.ToString()
                            },
                            new BlobInfo {
                                Id = outputId, Name = $"output_{ i }.txt", Tag = i.ToString()
                            }
                        });
                    });
                }
                else
                {
                    // TODO: Test case type
                    var testCases = await DB.TestCases
                                    .Where(x => x.ProblemId == problem.Id && (x.Type == TestCaseType.Small || x.Type == TestCaseType.Large))
                                    .ToListAsync(token);

                    if (testCases.Count == 0)
                    {
                        return(Result(400, "No test case found."));
                    }

                    for (var i = 0; i < testCases.Count; i++)
                    {
                        blobs.TryAdd(i, new[] {
                            new BlobInfo {
                                Id = testCases[i].InputBlobId, Name = $"input_{ i }.txt", Tag = i.ToString()
                            },
                            new BlobInfo {
                                Id = testCases[i].OutputBlobId, Name = $"output_{ i }.txt", Tag = i.ToString()
                            }
                        });
                    }
                }

                var stateMachineId = await MgmtSvc.PutStateMachineInstanceAsync("JudgeStateMachine", Config["ManagementService:CallBack"], blobs.SelectMany(x => x.Value), await CalculatePriorityAsync(), token);

                var substatuses = blobs
                                  .Where(x => x.Key >= 0)
                                  .Select(x => new SubJudgeStatus
                {
                    SubId        = x.Key,
                    Result       = JudgeResult.Pending,
                    InputBlobId  = x.Value.Single(y => y.Name.StartsWith("input_")).Id,
                    OutputBlobId = x.Value.Single(y => y.Name.StartsWith("output_")).Id,
                })
                                  .ToList();

                var status = new JudgeStatus
                {
                    Code                   = request.code,
                    Language               = request.language,
                    Result                 = JudgeResult.Pending,
                    CreatedTime            = DateTime.Now,
                    ContestId              = request.contestId,
                    SubStatuses            = substatuses,
                    ProblemId              = problem.Id,
                    UserId                 = User.Current.Id,
                    IsSelfTest             = request.isSelfTest,
                    RelatedStateMachineIds = new List <JudgeStatusStateMachine>
                    {
                        new JudgeStatusStateMachine
                        {
                            StateMachine = new StateMachine
                            {
                                CreatedTime = DateTime.Now,
                                Name        = "JudgeStateMachine",
                                Id          = stateMachineId
                            },
                            StateMachineId = stateMachineId
                        }
                    },
                };

                DB.JudgeStatuses.Add(status);
                await DB.SaveChangesAsync(token);

                hub.Clients.All.InvokeAsync("ItemUpdated", "judge", status.Id);

                // For debugging
                if (Config["ManagementService:Mode"] == "Polling")
                {
                    Task.Factory.StartNew(async() =>
                    {
                        using (var scope = scopeFactory.CreateScope())
                            using (var db = scope.ServiceProvider.GetService <OnlineJudgeContext>())
                            {
                                try
                                {
                                    await awaiter.GetStateMachineResultAsync(stateMachineId);
                                    var handler = scope.ServiceProvider.GetService <JudgeStateMachineHandler>();
                                    await handler.HandleJudgeResultAsync(stateMachineId, default(CancellationToken));
                                }
                                catch (Exception ex)
                                {
                                    Console.Error.WriteLine(ex);
                                }
                            }
                    });
                }
                return(Result(status.Id));
            }
            #endregion
            #region Bzoj, LeetCode, CodeVS
            else if (problem.Source == ProblemSource.Bzoj || problem.Source == ProblemSource.LeetCode || problem.Source == ProblemSource.CodeVS)
            {
                var metadata = new
                {
                    Source    = problem.Source.ToString(),
                    Language  = request.language,
                    Code      = request.code,
                    ProblemId = problem.Id.Replace(problem.Source.ToString().ToLower() + "-", "")
                };

                var metadataBlob = new BlobInfo
                {
                    Id   = await MgmtSvc.PutBlobAsync("metadata.json", Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(metadata)), token),
                    Name = "metadata.json",
                    Tag  = "Problem=" + problem.Id
                };

                var stateMachineId = await MgmtSvc.PutStateMachineInstanceAsync("VirtualJudgeStateMachine", Config["ManagementService:Callback"], new[] { metadataBlob }, await CalculatePriorityAsync(), token);

                var status = new JudgeStatus
                {
                    Code                   = request.code,
                    Language               = request.language,
                    ProblemId              = problem.Id,
                    IsSelfTest             = false,
                    UserId                 = User.Current.Id,
                    Result                 = JudgeResult.Pending,
                    RelatedStateMachineIds = new List <JudgeStatusStateMachine>
                    {
                        new JudgeStatusStateMachine {
                            StateMachine = new StateMachine
                            {
                                CreatedTime = DateTime.Now,
                                Name        = "JudgeStateMachine",
                                Id          = stateMachineId
                            },
                            StateMachineId = stateMachineId
                        }
                    }
                };

                DB.JudgeStatuses.Add(status);
                await DB.SaveChangesAsync(token);

                // For debugging
                if (Config["ManagementService:Mode"] == "Polling")
                {
                    Task.Factory.StartNew(async() =>
                    {
                        using (var scope = scopeFactory.CreateScope())
                        {
                            try
                            {
                                await awaiter.GetStateMachineResultAsync(stateMachineId);
                                var handler = scope.ServiceProvider.GetService <JudgeStateMachineHandler>();
                                await handler.HandleJudgeResultAsync(stateMachineId, default(CancellationToken));
                            }
                            catch (Exception ex)
                            {
                                Console.Error.WriteLine(ex);
                            }
                        }
                    });
                }

                hub.Clients.All.InvokeAsync("ItemUpdated", "judge", status.Id);

                return(Result(status.Id));
            }
            #endregion
            #region Others
            else
            {
                throw new NotSupportedException(problem.Source.ToString() + " has not been supported yet.");
            }
            #endregion
        }
Ejemplo n.º 14
0
        public BirdBotService(IServiceScopeFactory scopeFactory)
        {
            var scope = scopeFactory.CreateScope();

            _birdBotMain = scope.ServiceProvider.GetRequiredService <BirdBotMain>();
        }
        public static void SeedData(this IServiceScopeFactory scopeFactory)
        {
            using (var serviceScope = scopeFactory.CreateScope())
            {
                var context = serviceScope.ServiceProvider.GetService <DatabaseContext>();
                if (!context.Roles.Any())
                {
                    var roles = new List <Role>
                    {
                        new Role
                        {
                            Name        = "User",
                            AccessLevel = 100
                        }
                    };
                    context.AddRange(roles);
                    context.SaveChanges();
                }

                if (!context.Languages.Any())
                {
                    var languages = new List <Language>
                    {
                        new Language {
                            Name = "Polski", Code = "pl-PL"
                        },
                        new Language {
                            Name = "Angielski", Code = "en-US"
                        },
                        new Language {
                            Name = "Niemiecki", Code = "de-DE"
                        },
                        new Language {
                            Name = "Francuski", Code = "fd-FR"
                        },
                        new Language {
                            Name = "Włoski", Code = "it-IT"
                        },
                        new Language {
                            Name = "Szwedzki", Code = "sv-SE"
                        },
                        new Language {
                            Name = "Czeski", Code = "cs-CZ"
                        },
                        new Language {
                            Name = "Rosyjski", Code = "ru-RU"
                        },
                        new Language {
                            Name = "Hiszpański", Code = "es-ES"
                        }
                    };
                    context.AddRange(languages);
                    context.SaveChanges();
                }

                if (!context.Games.Any())
                {
                    var languages = new List <Game>
                    {
                        new Game {
                            Name = "Fiszki"
                        },
                        new Game {
                            Name = "Test"
                        },
                        new Game {
                            Name = "Memo"
                        },
                        new Game {
                            Name = "Wisielec"
                        }
                    };
                    context.AddRange(languages);
                    context.SaveChanges();
                }
            }
        }
Ejemplo n.º 16
0
 public async Task SendAsync <TCommand>(TCommand command) where TCommand : class, ICommand
 {
     using var scope = _scopeFactory.CreateScope();
     var handler = scope.ServiceProvider.GetService <ICommandHandler <TCommand> >();
     await handler.HandleAsync(command);
 }
Ejemplo n.º 17
0
        public async Task <IEnumerable <Recipe> > GetRecipes(RecipesQuery query)
        {
            using (var scope = _serviceScopeFactory.CreateScope())
            {
                using (var context = scope.ServiceProvider.GetRequiredService <ApplicationDbContext>())
                {
                    var includableQueryable = context.Recipes
                                              .Include(recipe => recipe.RecipeActionGroups)
                                              .ThenInclude(group => group.RecipeActions)
                                              .ThenInclude(action => action.ExternalService)
                                              .Include(recipe => recipe.RecipeActions)
                                              .ThenInclude(action => action.ExternalService)
                                              .Include(recipe => recipe.RecipeActions)
                                              .ThenInclude(action => action.RecipeInvocations)
                                              .Include(recipe => recipe.RecipeTrigger)
                                              .ThenInclude(trigger => trigger.ExternalService);

                    if (query.IncludeRecipeInvocations)
                    {
                        includableQueryable.Include(recipe => recipe.RecipeInvocations);
                    }

                    var queryable = includableQueryable.AsQueryable();

                    if (query.Enabled.HasValue)
                    {
                        queryable = queryable.Where(x => x.Enabled == query.Enabled.Value);
                    }

                    if (!string.IsNullOrEmpty(query.TriggerId))
                    {
                        queryable = queryable.Where(x => x.RecipeTrigger.TriggerId == query.TriggerId);
                    }

                    if (!string.IsNullOrEmpty(query.UserId))
                    {
                        queryable = queryable.Where(x => x.UserId == query.UserId);
                    }

                    if (!string.IsNullOrEmpty(query.RecipeId))
                    {
                        queryable = queryable.Where(x => x.Id == query.RecipeId);
                    }

                    return(await queryable.ToListAsync());
                }
            }
        }
Ejemplo n.º 18
0
 public IServiceScope CreateScope()
 {
     return(_serviceScopeFactory.CreateScope());
 }
Ejemplo n.º 19
0
 public VehicleRemover(IServiceScopeFactory factory)
 {
     this.RepoVehicle = factory.CreateScope().ServiceProvider.GetRequiredService <IRepositoryVehicle>();
 }
        private static void SeedUsersInDataBase(IServiceScopeFactory servicesScopeFactory)
        {
            using (var scope = servicesScopeFactory.CreateScope())
            {
                var context = scope.ServiceProvider.GetService <ApplicationDbContext>();
                context.Database.Migrate();

                var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                var alice   = userMgr.FindByNameAsync("alice").Result;
                if (alice == null)
                {
                    alice = new ApplicationUser
                    {
                        UserName       = "******",
                        Email          = "*****@*****.**",
                        EmailConfirmed = true,
                    };
                    IdentityResult result = userMgr.CreateAsync(alice, "Pass123$").Result;
                    if (!result.Succeeded)
                    {
                        throw new Exception(result.Errors.First().Description);
                    }
                    result = userMgr.AddClaimsAsync(alice, new Claim[]
                    {
                        new Claim(JwtClaimTypes.Name, "Alice Smith"),
                        new Claim(JwtClaimTypes.GivenName, "Alice"),
                        new Claim(JwtClaimTypes.FamilyName, "Smith"),
                        new Claim(JwtClaimTypes.WebSite, "http://alice.com"),
                        new Claim("CanViewProducts", "true"),
                        new Claim("CanViewLocations", "true"),
                    }).Result;
                    if (!result.Succeeded)
                    {
                        throw new Exception(result.Errors.First().Description);
                    }

                    Log.Debug("alice created");
                }
                else
                {
                    Log.Debug("alice already exists");
                }

                var bob = userMgr.FindByNameAsync("bob").Result;
                if (bob == null)
                {
                    bob = new ApplicationUser
                    {
                        UserName       = "******",
                        Email          = "*****@*****.**",
                        EmailConfirmed = true
                    };
                    var result = userMgr.CreateAsync(bob, "Pass123$").Result;
                    if (!result.Succeeded)
                    {
                        throw new Exception(result.Errors.First().Description);
                    }

                    result = userMgr.AddClaimsAsync(bob, new Claim[]
                    {
                        new Claim(JwtClaimTypes.Name, "Bob Smith"),
                        new Claim(JwtClaimTypes.GivenName, "Bob"),
                        new Claim(JwtClaimTypes.FamilyName, "Smith"),
                        new Claim(JwtClaimTypes.WebSite, "http://bob.com"),
                        new Claim("location", "somewhere")
                    }).Result;
                    if (!result.Succeeded)
                    {
                        throw new Exception(result.Errors.First().Description);
                    }

                    Log.Debug("bob created");
                }
                else
                {
                    Log.Debug("bob already exists");
                }
            }
        }
Ejemplo n.º 21
0
        private (IServiceScope Scope, VirtualNetworkDbContext DbContext) GetScopeDbContext()
        {
            var scope = _scopeFactory.CreateScope();

            return(scope, scope.ServiceProvider.GetRequiredService <VirtualNetworkDbContext>());
        }
Ejemplo n.º 22
0
        }                                                                   //Дописать

        #endregion

        #region Cities
        public async Task <string> GetRusCityNameAsync(string engName)
        {
            using var scope = scopeFactory.CreateScope();
            var db       = scope.ServiceProvider.GetRequiredService <ICityRepo>();
            var cityPair = await db.GetCityByEngName(engName);

            if (cityPair is null)
            {
                return(engName);
            }
            return(cityPair.RusName);
        }
 private void RunService()
 {
     using var scope   = _serviceScopeFactory.CreateScope();
     using var service = scope.ServiceProvider.GetRequiredService <WorkerService>();
     service.Run();
 }
        private void DoWork(object state)
        {
            _logger.LogInformation("Timed Background Service is working.");

            using (var scope = scopeFactory.CreateScope())
            {
                var dbContext = scope.ServiceProvider.GetRequiredService <FlightContext>();
                //var city =  dbContext.Cities.Where(c => c.Name == "aaa").FirstOrDefault();
                //if(city != null)
                //{
                //    dbContext.Cities.Remove(city);
                //    dbContext.SaveChanges();
                //}
                using (var transaction = new TransactionScope())
                {
                    try
                    {
                        //get the suspended bookings(not finished) over 60 seconds, and reverse them
                        //获取寿命大于一分钟的临时订单,然后进行取消
                        foreach (var b in dbContext.BookingTransactions.Where(b => b.BookingDateTime.AddMinutes(1) < DateTime.Now).Where(b => b.Suspended == true).GroupBy(x => new { x.Flight_ScheduleID, x.CabinType })
                                 .Select(group => new {
                            Flight_ScheduleID = group.Key.Flight_ScheduleID,
                            CabinType = group.Key.CabinType,
                            Count = group.Count()
                        })
                                 )
                        {
                            switch (b.CabinType.ToString())
                            {
                            case "Economy":
                                dbContext.Flight_Schedules.Where(f => f.Flight_ScheduleID == b.Flight_ScheduleID).ToList().ForEach(f => f.Economy = f.Economy + b.Count);
                                //remove multiple records in database
                                //同时删除多个记录
                                foreach (var bt in dbContext.BookingTransactions.Where(x => x.Flight_ScheduleID == b.Flight_ScheduleID))
                                {
                                    dbContext.BookingTransactions.Remove(bt);
                                }
                                break;

                            case "Business":
                                dbContext.Flight_Schedules.Where(f => f.Flight_ScheduleID == b.Flight_ScheduleID).ToList().ForEach(f => f.Business = f.Business + b.Count);
                                foreach (var bt in dbContext.BookingTransactions.Where(x => x.Flight_ScheduleID == b.Flight_ScheduleID))
                                {
                                    dbContext.BookingTransactions.Remove(bt);
                                }
                                break;

                            case "PremEconomy":
                                dbContext.Flight_Schedules.Where(f => f.Flight_ScheduleID == b.Flight_ScheduleID).ToList().ForEach(f => f.PremEconomy = f.PremEconomy + b.Count);
                                foreach (var bt in dbContext.BookingTransactions.Where(x => x.Flight_ScheduleID == b.Flight_ScheduleID))
                                {
                                    dbContext.BookingTransactions.Remove(bt);
                                }
                                break;

                            case "First":
                                dbContext.Flight_Schedules.Where(f => f.Flight_ScheduleID == b.Flight_ScheduleID).ToList().ForEach(f => f.First = f.First + b.Count);
                                foreach (var bt in dbContext.BookingTransactions.Where(x => x.Flight_ScheduleID == b.Flight_ScheduleID))
                                {
                                    dbContext.BookingTransactions.Remove(bt);
                                }
                                break;
                            }
                        }
                        //SaveChanges要在transaction.Complete()之前或者using (var transaction = new TransactionScope())之外
                        dbContext.SaveChanges();
                        transaction.Complete();
                    }
                    catch (Exception ex)
                    {
                    }
                }
            }
        }
Ejemplo n.º 25
0
 public static void Scoped <TService>(Action <TService> action)
 {
     using var scope = ScopeFactory.CreateScope();
     action(scope.ServiceProvider.GetService <TService>());
 }
Ejemplo n.º 26
0
 public InteriorLatestWorker(IServiceScopeFactory factory, ILogger <InteriorLatestWorker> logger)
 {
     _logger                    = logger;
     _sensorService             = factory.CreateScope().ServiceProvider.GetRequiredService <ISensorService>();
     _temperatureReadingService = factory.CreateScope().ServiceProvider.GetRequiredService <ITemperatureReadingService>();
 }
Ejemplo n.º 27
0
        public void DoWork(object state)
        {
            _logger.LogInformation("Timed Background Service is working.");

            using (var scope = _scopeFactory.CreateScope())
            {
                var databaseContext = scope.ServiceProvider.GetRequiredService <DatabaseContext>();

                SensorHistoryRepository sensorHistoryRepository = new SensorHistoryRepository(databaseContext);
                SensorRepository        sensorRepository        = new SensorRepository(databaseContext);

                var temperatureSensors = databaseContext.Sensors.OfType <TemperatureSensor>().ToList();
                var humiditySensors    = databaseContext.Sensors.OfType <HumiditySensor>().ToList();
                var smokeSensors       = databaseContext.Sensors.OfType <SmokeSensor>().ToList();
                var motionSensors      = databaseContext.Sensors.OfType <MotionSensor>().ToList();

                double       currentTemperature = 0;
                double       currentHumidity    = 0;
                double       currentSmoke       = 0;
                double       currentMotion      = 0;
                const double MAX_NUMBER         = 1.5;
                const double MIN_NUMBER         = 0.5;

                foreach (var sensor in temperatureSensors)
                {
                    currentTemperature = random.NextDouble() * ((double)sensor.MaxValue * MAX_NUMBER - (double)sensor.MinValue * MIN_NUMBER) + (double)sensor.MinValue * MIN_NUMBER;
                    _logger.LogInformation("currentTemperature = " + currentTemperature);

                    if (currentTemperature > sensor.MaxValue || currentTemperature < sensor.MinValue)
                    {
                        sensor.IsOn        = true;
                        sensor.Temperature = currentTemperature;
                    }

                    else
                    {
                        sensor.IsOn        = false;
                        sensor.Temperature = currentTemperature;
                    }

                    _logger.LogInformation("IsOn = " + sensor.IsOn);

                    sensorHistoryRepository.AddTemperatureSensorHistory(sensor);
                    sensorRepository.UpdateTemperatureSensor(sensor);
                }

                foreach (var sensor in humiditySensors)
                {
                    currentHumidity = random.NextDouble() * ((double)sensor.MaxValue * MAX_NUMBER - (double)sensor.MinValue * MIN_NUMBER) + (double)sensor.MinValue * MIN_NUMBER;
                    _logger.LogInformation("currentHumidity = " + currentHumidity);

                    if (currentHumidity > sensor.MaxValue || currentHumidity < sensor.MinValue)
                    {
                        sensor.IsOn     = true;
                        sensor.Humidity = currentHumidity;
                    }

                    else
                    {
                        sensor.IsOn     = false;
                        sensor.Humidity = currentHumidity;
                    }

                    _logger.LogInformation("IsOn = " + sensor.IsOn);

                    sensorHistoryRepository.AddHumiditySensorHistory(sensor);
                    sensorRepository.UpdateHumiditySensor(sensor);
                }

                foreach (var sensor in smokeSensors)
                {
                    currentSmoke = random.NextDouble() * ((double)sensor.MaxValue * MAX_NUMBER - (double)sensor.MinValue * MIN_NUMBER) + (double)sensor.MinValue * MIN_NUMBER;
                    _logger.LogInformation("currentSmoke = " + currentSmoke);

                    if (currentSmoke > sensor.MaxValue || currentSmoke < sensor.MinValue)
                    {
                        sensor.IsOn  = true;
                        sensor.Smoke = currentSmoke;
                    }

                    else
                    {
                        sensor.IsOn  = false;
                        sensor.Smoke = currentSmoke;
                    }

                    _logger.LogInformation("IsOn = " + sensor.IsOn);

                    sensorHistoryRepository.AddSmokeSensorHistory(sensor);
                    sensorRepository.UpdateSmokeSensor(sensor);
                }

                foreach (var sensor in motionSensors)
                {
                    currentMotion = random.NextDouble();
                    _logger.LogInformation("currentMotion = " + currentMotion);

                    if (currentMotion > 0.5)
                    {
                        sensor.IsOn   = true;
                        sensor.IsMove = true;
                    }

                    else
                    {
                        sensor.IsOn   = false;
                        sensor.IsMove = false;
                    }

                    _logger.LogInformation("IsOn = " + sensor.IsOn);

                    sensorHistoryRepository.AddMotionSensorHistory(sensor);
                    sensorRepository.UpdateMotionSensor(sensor);
                }
            }
        }
Ejemplo n.º 28
0
 public MongoMigrationStartupFilter(IServiceScopeFactory serviceScopeFactory, ILoggerFactory loggerFactory)
 {
     _migration = serviceScopeFactory.CreateScope().ServiceProvider.GetService <IMongoMigration>();
     _logger    = loggerFactory.CreateLogger <MongoMigrationStartupFilter>();
 }
Ejemplo n.º 29
0
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            while (!stoppingToken.IsCancellationRequested)
            {
                if (_update)
                {
                    bool aggregatePoll = _aggregatePolling;
                    bool serverPoll    = _serverPolling;
                    if (aggregatePoll || serverPoll)
                    {
                        using (var scope = _scopeFactory.CreateScope()) {
                            Metrics        m;
                            MonitoringJson monitor;
                            var            dbContext = scope.ServiceProvider.GetRequiredService <ServersContext>();

                            if (aggregatePoll)
                            {
                                bool    firstMetric = true;
                                Metrics total       = new Metrics();
                                foreach (Server s in dbContext.Servers)
                                {
                                    _activeServers.TryAdd(s.Name, s);

                                    try {
                                        monitor = RequestMetrics(s);
                                    }
                                    catch (Exception) {
                                        continue;
                                    }

                                    m           = new Metrics();
                                    m.ServerId  = s.ServerId;
                                    m.Timestamp = DateTime.UtcNow;
                                    m.Date      = DateHelper.DateToInt(m.Timestamp);
                                    m.Time      = DateHelper.TimeToInt(m.Timestamp);
                                    m.DayOfWeek = (int)m.Timestamp.DayOfWeek;
                                    monitor.CopyTo(ref m);

                                    if (firstMetric == true)
                                    {
                                        firstMetric = false;
                                        total       = m;
                                    }
                                    else
                                    {
                                        total.Add(ref m);
                                    }

                                    if (serverPoll)
                                    {
                                        if (_serverNamesToClientIds[s.Name].Count > 0)
                                        {
                                            await _hubContext.Clients.Group(s.Name).SendAsync("ReceiveMessage", $"{JsonConvert.SerializeObject(monitor)}");
                                        }
                                    }
                                }

                                await _hubContext.Clients.Group(PollHub.GROUP_MAIN).SendAsync("ReceiveMessage", $"{JsonConvert.SerializeObject(total)}");
                            }
                            else
                            {
                                foreach (string serverName in _serverNamesToClientIds.Keys)
                                {
                                    if (_serverNamesToClientIds[serverName].Count > 0)
                                    {
                                        var server = dbContext.Servers.FirstOrDefault(s => s.Name == serverName);
                                        _activeServers.TryAdd(serverName, server);

                                        try {
                                            monitor = RequestMetrics(server);
                                        }
                                        catch (Exception) {
                                            continue;
                                        }

                                        await _hubContext.Clients.Group(serverName).SendAsync("ReceiveMessage", $"{JsonConvert.SerializeObject(monitor)}");
                                    }
                                }
                            }
                        }
                    }

                    _update = false;
                }
            }
        }
 public async Task SendAsync <T>(T command) where T : class, ICommand
 {
     using var scope = _serviceFactory.CreateScope();
     var handler = scope.ServiceProvider.GetRequiredService <ICommandHandler <T> >();
     await handler.HandleAsync(command);
 }
Ejemplo n.º 31
0
 private TService CreateServiceScope <TService>(IServiceScopeFactory serviceScopeFactory)
 {
     return(serviceScopeFactory.CreateScope().ServiceProvider.GetRequiredService <TService>());
 }