/// <summary> Refresh cache by key, TODO: temp</summary>
        public async Task RefreshCacheAsync(string cacheKey = null)
        {
            //using var scope = GeneralContext.CreateServiceScope();
            if (GeneralContext.ServiceScope != null)
            {
                try
                {
                    var cacheItems = this.GetCacheItems <ApiCacheItem>();
                    if (cacheKey != null)
                    {
                        cacheItems = cacheItems.Where(x => x.Key == cacheKey).ToDictionary(k => k.Key, v => v.Value);
                    }

                    CRPMContext dbContext = GeneralContext.ServiceScope.ServiceProvider.GetService <CRPMContext>();

                    var items = cacheItems.Where(x => x.Value?.Query.ToUpper().Contains("SELECT") ?? false);
                    foreach (var item in items)
                    {
                        using var conn = dbContext.Database.GetDbConnection();

                        if (conn.State.Equals(ConnectionState.Closed))
                        {
                            conn.Open();
                        }
                        using var command   = conn.CreateCommand();
                        command.CommandText = item.Value.Query;

                        //var result = command.ExecuteNonQuery();
                        //var result = dbContext.Database.ExecuteSqlRaw(item.Value.Query);

                        var result = dbContext.Set <User>()
                                     .FromSqlRaw <User>(item.Value.Query)
                                     .ToList();

                        var l = dbContext.User.Local;

                        var list = dbContext.GetTrackEntries <User>();

                        using var db = new NpgsqlConnection(conn.ConnectionString);
                        var result1 = db.Query <User>(item.Value.Query);

                        //using var cmd = new NpgsqlCommand(item.Value.Query, con);
                        //cmd.q

                        var cacheItem = new ApiCacheItem(result, true, true, item.ToString());
                        await _cache.SetAsync(item.Key, Util.ConvertObjectToByteArray(cacheItem));

                        //var encodedData = Encoding.UTF8.GetBytes(JsonSerializer.Serialize(data));
                        //await _cache.SetAsync(cacheKey, encodedData, new DistributedCacheEntryOptions());

                        _logger.LogInformation("{cacheKey} cache refreshed", item.Key);
                    }
                }
                catch (System.Exception ex)
                {
                    GeneralContext.Logger.Error(ex.GetApiMessageInfo());
                }
            }
        }
Beispiel #2
0
        /// <summary> define web test context </summary>
        public TestWebHost()
        {
            WebHostBuilder = new WebHostBuilder()
                             .Configure(appBuilder =>
            {
                GeneralContext.HttpContext.RequestServices = appBuilder.ApplicationServices;
            })
                             .ConfigureAppConfiguration((hostingContext, config) =>
            {
                var env             = hostingContext.HostingEnvironment;
                env.EnvironmentName = "Test";

                config.SetBasePath(env.ContentRootPath)
                .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
                .AddEnvironmentVariables(prefix: "CRPM_")
                .AddEnvironmentVariables()
                .Build();
            })
                             .ConfigureServices((context, services) =>
            {
                var loggerConfig = new LoggerConfiguration()
                                   .ReadFrom.Configuration(context.Configuration);

                // appConfig
                var configSection = context.Configuration.GetSection("AppConfig");
                var appConfig     = configSection?.Get <AppConfig>();
                services.AddSingleton <IAppConfig>(appConfig);

                // authOptions
                var authConfigSection = context.Configuration.GetSection("AuthOptions");
                var authOptions       = authConfigSection?.Get <AuthOptions>();
                services.AddSingleton <IAuthOptions>(authOptions);

                // logger
                Log.Logger = loggerConfig.CreateLogger();
                Log.Information($"{Assembly.GetEntryAssembly().GetName().Name} API started");
                services.AddSingleton(Log.Logger);

                // contexts
                var mockContext = new Mock <HttpContext>(MockBehavior.Strict);
                mockContext.SetupGet(hc => hc.User.Identity.Name).Returns("4cast");
                services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
                services.AddSingleton <IActionContextAccessor, ActionContextAccessor>();

                //var mockIActionContextAccessor = new Mock<IActionContextAccessor>();
                //mockIActionContextAccessor.SetupGet(x => x.ActionContext)
                //.Returns(new ActionContext());
                //services.AddSingleton<IActionContextAccessor>(mockIActionContextAccessor.Object);
                //services.AddSingleton<IActionContextAccessor>(mockIActionContextAccessor.Object);

                // referenced assemblies
                var referencedAssembliesNames = Assembly.GetExecutingAssembly().GetReferencedAssemblies()
                                                .Select(x => x.Name)
                                                .Where(x => x.ToUpper().Contains("CRPM"))
                                                .ToList();

                referencedAssembliesNames.Add(Assembly.GetExecutingAssembly().GetName().Name);
                var referencedAssemblies = AppDomain.CurrentDomain.GetAssemblies()
                                           .Where(x => referencedAssembliesNames.Contains(x.GetName().Name))
                                           .ToList();
                Util.CreateGuid();     //need for include reference to Crmp.Utilities

                services
                .AddMvc(options =>
                {
                    options.Filters.Add(typeof(ApiExceptionFilter));
                    options.Filters.Add(typeof(ApiValidationFilter));
                })
                .SetCompatibilityVersion(CompatibilityVersion.Version_3_0)
                .AddFluentValidation(config =>
                {
                    config.RegisterValidatorsFromAssemblies(referencedAssemblies);
                    config.RunDefaultMvcValidationAfterFluentValidationExecutes = false;
                });

                // AutoMapper
                services.AddAutoMapper(referencedAssemblies);

                services.AddScoped <OrganizationService>();
                services.AddScoped <ActivityService>();
                services.AddScoped <ReportService>();
                services.AddScoped <ActivityTemplateService>();
                services.AddScoped <FormService>();
                services.AddScoped <FormTemplateService>();
                services.AddScoped <GeneralService>();
                services.AddScoped <ModelService>();
                services.AddScoped <UserService>();

                services.AddScoped(provider =>
                {
                    var connectionString       = context.Configuration["ConnectionStrings:CRPMDatabase"];
                    var builder                = new DbContextOptionsBuilder <CRPMContext>();
                    var migrationsAssemblyName = typeof(TestWebHost).Assembly.GetName().Name;
                    builder.UseNpgsql(connectionString, x => x.MigrationsAssembly(migrationsAssemblyName));
                    builder.UseLoggerFactory(CRPMContext.CRPMLoggerFactory);
                    var dbContext = new CRPMContext(builder.Options);
                    return(dbContext);
                });

                var mockUrlHelper = new Mock <IUrlHelper>(MockBehavior.Strict);
                Expression <Func <IUrlHelper, string> > urlSetup = url =>
                                                                   url.Action(It.Is <UrlActionContext>(uac => uac.Action == "Get"));
                mockUrlHelper.Setup(urlSetup).Returns("mock/testing");

                //GeneralContext.SetServiceProvider(services.BuildServiceProvider());
                GeneralContext.HttpContext = new DefaultHttpContext()
                {
                    RequestServices = services.BuildServiceProvider()
                };
                var mockHttpContextAccessor = new Mock <IHttpContextAccessor>();
                mockHttpContextAccessor.SetupGet(x => x.HttpContext).Returns(GeneralContext.HttpContext);

                var requestMethod   = GeneralContext.HttpContext?.Request?.Method;
                requestMethod       = string.IsNullOrEmpty(requestMethod) ? "GET" : requestMethod;
                var mockBaseService = new Mock <IBaseService>();
                Expression <Func <IBaseService, HttpMethod> > CurrentHttpMethodAction = x =>
                                                                                        It.Is <HttpMethod>(y => y.Method == "");
                mockBaseService.Setup(x => x.CurrentHttpMethod).Returns(new HttpMethod("GET"));
            })
                             .ConfigureLogging((context, logging) =>
            {
                logging.AddSerilog(logging.Services
                                   .BuildServiceProvider()
                                   .GetRequiredService <ILogger>(),
                                   dispose: true);
            })
                             .UseSerilog()
                             .UseStartup <Startup>();

            testServer = new TestServer(WebHostBuilder);
        }