Ejemplo n.º 1
0
 private DbConnection GetDbConnection(CustomerConfiguration cc)
 {
     if (cc.DbType == DatabaseType.Postgres)
     {
         return(new NpgsqlConnection(cc.ConnectionString));
     }
     return(new SqlConnection(cc.ConnectionString));
 }
Ejemplo n.º 2
0
        public Task <string> GetCachedHighloadApiAuthToken(CustomerConfiguration configuration)
        {
            var key    = configuration.Name;
            var result = _cacheProvider.GetOrAdd(key,
                                                 TimeSpan.FromSeconds(_cacheSettings.HighloadApiTokenCacheTimeoutSeconds),
                                                 () => GetHighloadApiAuthToken(configuration));

            return(result);
        }
        public void Install()
        {
            var migratorConfig = new CustomerConfiguration()
            {
                AutomaticMigrationsEnabled = true
            };
            var migrator = new DbMigrator(migratorConfig);

            migrator.Update();
        }
        public void Uninstall()
        {
            var migratorConfig = new CustomerConfiguration()
            {
                AutomaticMigrationDataLossAllowed = true
            };
            var migrator = new DbMigrator(migratorConfig);

            migrator.Configuration.AutomaticMigrationDataLossAllowed = true;
            migrator.Update(DbMigrator.InitialDatabase);
        }
Ejemplo n.º 5
0
        private bool IsDbConnected()
        {
            DBConnector.ConfigServiceUrl   = _intOptions.ConfigurationServiceUrl;
            DBConnector.ConfigServiceToken = _intOptions.ConfigurationServiceToken;
            var    customerCode     = ControllerContext.RouteData.Values["customerCode"];
            string connectionString = _options.FixedConnectionString;
            var    cc = new CustomerConfiguration()
            {
                ConnectionString = connectionString,
                DbType           = (_options.UsePostgres) ? DatabaseType.Postgres : DatabaseType.SqlServer
            };

            if (string.IsNullOrEmpty(connectionString) && customerCode != null)
            {
                try
                {
                    cc = DBConnector.GetCustomerConfiguration(customerCode.ToString()).Result;
                }
                catch (Exception ex)
                {
                    _logger.Error().Exception(ex).Message("Cannot receive configuration")
                    .Property("customerCode", customerCode)
                    .Write();

                    return(false);
                }
            }

            if (string.IsNullOrEmpty(cc.ConnectionString))
            {
                return(false);
            }

            using (var connection = GetDbConnection(cc))
            {
                try
                {
                    connection.Open();
                    return(true);
                }
                catch (DbException dbex)
                {
                    _logger.Error().Exception(dbex).Message("Cannot connect to database")
                    .Property("customerCode", customerCode)
                    .Write();

                    return(false);
                }
            }
        }
Ejemplo n.º 6
0
        public async Task <string> GetHighloadApiAuthToken(CustomerConfiguration configuration)
        {
            try
            {
                using (var connection = CreateConnection(configuration))
                {
                    var contentId = await GetContentId(connection);

                    return(await GetToken(connection, contentId));
                }
            }
            catch (Exception ex)
            {
                throw new GetHighloadApiTokenException("Error while getting highload api token", ex);
            }
        }
Ejemplo n.º 7
0
        private static DbConnection CreateConnection(CustomerConfiguration configuration)
        {
            switch (configuration.DbType)
            {
            case QP.ConfigurationService.Models.DatabaseType.SqlServer:
                var connectionString = configuration.ConnectionString.Replace("Provider=SQLOLEDB;", "");
                var sqlConnection    = new SqlConnection(connectionString);
                sqlConnection.Open();
                return(sqlConnection);

            case QP.ConfigurationService.Models.DatabaseType.Postgres:
                var npgsqlConnection = new NpgsqlConnection(configuration.ConnectionString);
                npgsqlConnection.Open();
                return(npgsqlConnection);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Ejemplo n.º 8
0
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.HasDefaultSchema("efcore");

            CategoryConfiguration.Configure(modelBuilder.Entity <Category>());
            ShipperConfiguration.Configure(modelBuilder.Entity <Shipper>());
            RegionConfiguration.Configure(modelBuilder.Entity <Region>());
            SupplierConfiguration.Configure(modelBuilder.Entity <Supplier>());
            EmployeeConfiguration.Configure(modelBuilder.Entity <Employee>());
            CustomerDemographicsConfiguration.Configure(modelBuilder.Entity <CustomerDemoGraphic>());
            CustomerConfiguration.Configure(modelBuilder.Entity <Customer>());
            OrderConfiguration.Configure(modelBuilder.Entity <Order>());
            ProductConfiguration.Configure(modelBuilder.Entity <Product>());
            TerritoryConfiguration.Configure(modelBuilder.Entity <Territories>());
            EmployeeTerritoryConfiguration.Configure(modelBuilder.Entity <EmployeeTerritories>());
            CustomerCustomerDemographConfiguration.Configure(modelBuilder.Entity <CustomerCustomerDemograph>());
            OrderDetailConfiguration.Configure(modelBuilder.Entity <OrderDetail>());

            base.OnModelCreating(modelBuilder);
        }
Ejemplo n.º 9
0
        private CustomerConfigurationsFile getConfiguration()
        {
            var ci         = new CultureInfo("nl-NL");
            var configItem = new CustomerConfiguration
            {
                CustomerName        = CCustomerName,
                MaintenanceSchedule = new[]
                {
                    new TimeFrame
                    {
                        GroupName = CGroupName,
                        DayOfWeek = (int)DateTime.UtcNow.DayOfWeek,
                        WeekCount = (int)Math.Ceiling((decimal)DateTime.UtcNow.Day / 7),
                        StartTime = DateTime.UtcNow.AddHours(-1).ToString(ci),
                        EndTime   = DateTime.UtcNow.AddHours(1).ToString(ci)
                    }
                },
                ServerUpdateConfiguration = new ServerConfiguration
                {
                    ExcludedServers = new[]
                    {
                        "ExcludedServer1", "ExcludedServer2"
                    },
                    Servers = new[]
                    {
                        new ServerConfigurationItem
                        {
                            Name = CServerName,
                            ExcludedUpdateKbArticles = new[] { "2267602", "2290967" }
                        }
                    }
                }
            };

            var config = new CustomerConfigurationsFile();

            config.Add(configItem);

            return(config);
        }
Ejemplo n.º 10
0
        private void readCentralConfiguration()
        {
            mRetryCount++;

            string xmlData = null;

            Logger.Debug("Reading central configuration.");

            try
            {
                xmlData = WebHttpClient.GetResponse(LocalConfig.ConfigurationFileUrl);
            }
            catch (Exception ex)
            {
                Logger.Error("Failed to read central configuration " + LocalConfig.ConfigurationFileUrl, ex);
                WindowsTaskHandler.WriteEventLog(Constants.CEventLogId, EventLogEntryType.Warning, Constants.CEventLogFailedToRetrieveCentralConfiguration);
            }

            if (!string.IsNullOrEmpty(xmlData))
            {
                mRetryCount = 0;
                var serializer = new Serialization <CustomerConfigurationsFile>();
                mCentralConfiguration = serializer.GetObjectFromXml(xmlData).FirstOrDefault(cc => cc.CustomerName.Equals(mCustomerName, StringComparison.InvariantCultureIgnoreCase));
            }
            else
            {
                if (mRetryCount == LocalConfig.ReadConfigFileRetryCount)
                {
                    mCentralConfiguration = null;
                    mRetryCount           = 0;
                }

                if (mCentralConfiguration == null)
                {
                    throw new Exception("Could not read central configuration file.");
                }
            }
        }
Ejemplo n.º 11
0
        protected override void OnModelCreating(ModelBuilder builder)
        {
            CustomerConfiguration.Configure(builder);
            OrderConfiguration.Configure(builder);

            base.OnModelCreating(builder);

            var entityTypes = builder.Model
                              .GetEntityTypes()
                              .ToList();

            // Set global query filter for not deleted entities only

            // Disable cascade delete
            var foreignKeys = entityTypes
                              .SelectMany(e => e.GetForeignKeys()
                                          .Where(f => f.DeleteBehavior == DeleteBehavior.Cascade));

            foreach (var foreignKey in foreignKeys)
            {
                foreignKey.DeleteBehavior = DeleteBehavior.Restrict;
            }
        }
Ejemplo n.º 12
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            services.AddSwaggerGen(o =>
            {
                o.SwaggerDoc(SWAGGER_VERSION, new OpenApiInfo
                {
                    Title   = SWAGGER_TITLE,
                    Version = SWAGGER_VERSION
                });
                var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);
                o.IncludeXmlComments(xmlPath);
            });
            services.AddMemoryCache();
            services.AddSingleton <ICacheProvider, VersionedCacheCoreProvider>();
            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddScoped(sp =>
            {
                var uow = sp.GetService <IUnitOfWork>();
                return(new DBConnector(uow.Connection));
            });
            services.AddScoped <IAuthenticationService, AuthenticationService>();

            services.AddScoped <IUnitOfWork, UnitOfWork>(sp =>
            {
                var httpContextAccessor = sp.GetService <IHttpContextAccessor>();
                if (!httpContextAccessor.HttpContext.Request.Headers.TryGetValue("Customer-Code", out var customerCode))
                {
                    throw new Exception("Customer-Code header must be provided.");
                }

                var config = Configuration.GetSection("ConfigurationService").Get <ConfigurationServiceConfig>();
                if (!String.IsNullOrEmpty(config.Url) && !String.IsNullOrEmpty(config.Token))
                {
                    DBConnector.ConfigServiceUrl   = config.Url;
                    DBConnector.ConfigServiceToken = config.Token;
                }
                CustomerConfiguration dbConfig = DBConnector.GetCustomerConfiguration(customerCode.ToString()).Result;
                return(new UnitOfWork(dbConfig.ConnectionString, dbConfig.DbType.ToString()));
            });
            services.AddScoped <IMetaInfoRepository, MetaInfoRepository>();
            services.AddScoped <INetNameQueryAnalyzer, NetNameQueryAnalyzer>();
            services.AddScoped <IItemDefinitionRepository, ItemDefinitionRepository>();
            services.AddScoped <IAbTestRepository, AbTestRepository>();

            var qpUrlResolverCacheSettings = new QpSiteStructureCacheSettings
            {
                QpSchemeCachePeriod = new TimeSpan(0, 1, 0)
            };

            services.AddSingleton(typeof(QpSiteStructureCacheSettings), qpUrlResolverCacheSettings);
            services.AddScoped <IQpUrlResolver, QpUrlResolver>();
            services.AddAuthentication(options =>
            {
                options.DefaultAuthenticateScheme = QpAuthDefaults.AuthenticationScheme;
                options.DefaultChallengeScheme    = QpAuthDefaults.AuthenticationScheme;
            }).AddQpAuth(authOptions =>
            {
                authOptions.Settings = Configuration.GetSection("QpAuthSettings").Get <QpAuthSettings>();
            });

            services.AddAuthorization(options =>
            {
                options.DefaultPolicy = new AuthorizationPolicy(
                    new List <IAuthorizationRequirement>
                {
                    new QpUserRequirement()
                },
                    new[] { QpAuthDefaults.AuthenticationScheme });
            });

            services.AddCacheTagServices(options =>
                                         options.InvalidateByMiddleware(
                                             @"^(?!\/api\/).+$")); //инвалидировать только если запрос начинается с /api/

            services.AddHealthChecks();

            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder.AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  );
            });
        }
Ejemplo n.º 13
0
        private void CustomerEntityConfiguraion(ModelBuilder modelBuilder)
        {
            var config = new CustomerConfiguration();

            config.CustomerEntityConfiguration(modelBuilder);
        }
Ejemplo n.º 14
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <EnvironmentConfiguration>(Configuration);
            var config = Configuration.Get <EnvironmentConfiguration>();

            services
            .AddMvc(opt => { opt.Filters.Add(typeof(QpAutorizationFilter)); })
            .AddNewtonsoftJson(o =>
            {
                o.SerializerSettings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore;
            });

            services.AddSwaggerGen(o =>
            {
                o.SwaggerDoc(SWAGGER_VERSION, new OpenApiInfo()
                {
                    Title   = SWAGGER_TITLE,
                    Version = SWAGGER_VERSION
                });
                var xmlFile = $"{System.Reflection.Assembly.GetExecutingAssembly().GetName().Name}.xml";
                var xmlPath = System.IO.Path.Combine(AppContext.BaseDirectory, xmlFile);
                o.IncludeXmlComments(xmlPath);
            });

            services.AddAutoMapper();

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.AddScoped <QpHelper>();
            services.AddScoped <QPSecurityChecker>();
            services.AddScoped <IWebAppQpHelper, WebAppQpHelper>();

            services.AddScoped <INetNameQueryAnalyzer, NetNameQueryAnalyzer>();
            services.AddScoped <IUnitOfWork, UnitOfWork>(sp => {
                if (config.UseFake)
                {
                    return(new UnitOfWork(Configuration.GetConnectionString("QpConnection"),
                                          config.DatabaseType));
                }
                var qpHelper = sp.GetService <IWebAppQpHelper>();
                DBConnector.ConfigServiceUrl   = config.ConfigurationServiceUrl;
                DBConnector.ConfigServiceToken = config.ConfigurationServiceToken;
                CustomerConfiguration dbConfig = DBConnector.GetCustomerConfiguration(qpHelper.CustomerCode).Result;
                return(new UnitOfWork(dbConfig.ConnectionString, dbConfig.DbType.ToString()));
            });

            services.AddScoped <IAbstractItemRepository, AbstractItemRepository>();
            services.AddScoped <IItemDefinitionRepository, ItemDefinitionRepository>();
            services.AddScoped <IMetaInfoRepository, MetaInfoRepository>();

            services.AddScoped <ISiteMapProvider, SiteMapProvider>();
            services.AddScoped <IWidgetProvider, WidgetProvider>();
            services.AddScoped <IDictionaryProvider, DictionaryProvider>();
            services.AddScoped <IQpDataProvider, QpDataProvider>();
            services.AddScoped <ISettingsProvider, SettingsProvider>();
            services.AddScoped <IItemExtensionProvider, ItemExtensionProvider>();

            services.AddScoped <IQpDbConnector, QpDbConnector>(sp =>
            {
                var uow = sp.GetService <IUnitOfWork>();
                return(new QpDbConnector(uow.Connection));
            });
            services.AddScoped <IQpMetadataManager, QpMetadataManager>();
            services.AddScoped <IQpContentManager, QpContentManager>();

            services.AddScoped <ISiteMapService, SiteMapService>();
            services.AddScoped <ISiteMapModifyService, SiteMapModifyService>();
            services.AddScoped <IItemDifinitionService, ItemDifinitionService>();
            services.AddScoped <IRegionService, RegionService>();
            services.AddScoped <ICultureService, CultureService>();
            services.AddScoped <IContentService, ContentService>();
            services.AddScoped <ICustomActionService, CustomActionService>();

            services.AddDistributedMemoryCache();

            services.Configure <CookiePolicyOptions>(options =>
            {
                options.Secure = CookieSecurePolicy.SameAsRequest;
                options.MinimumSameSitePolicy = config.UseSameSiteNone ? SameSiteMode.None : SameSiteMode.Lax;
            });

            services.AddSession(options =>
            {
                // Set a short timeout for easy testing.
                options.IdleTimeout         = TimeSpan.FromMinutes(20);
                options.Cookie.SameSite     = config.UseSameSiteNone ? SameSiteMode.None : SameSiteMode.Lax;
                options.Cookie.SecurePolicy = CookieSecurePolicy.SameAsRequest;
                options.Cookie.IsEssential  = true;
            });

            services.AddAuthorization();

            services.AddLocalization(x => x.ResourcesPath = "Resources");


            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "wwwroot/dist";
            });
        }