public static void AddComFr(this IServiceCollection services, IConfiguration configuration)
        {
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();
            services.TryAddTransient <IUserService, UserService>();

            services.AddTransient <IStorage, WebStorage>();

            services.ConfigureCache <ConcurrentDictionary <string, object> >();

            services.AddSingleton <IDatabaseConfiguring, EntityFrameWorkConfigure>();
            services.AddSingleton <IDbConnectionPool, SimpleDbConnectionPool>();

            services.AddScoped <IApplicationContextStateProvider, CurrentUserStateProvider>();
            services.AddScoped <IApplicationContextStateProvider, HostingEnvironmentStateProvider>();

            //池的配置:
            //MaximumRetained规定池的容量(常态最大保有数量)。
            //MaximumRetained为0时,相当于不使用DbConnection池,
            //但因为在Request期间Connection是保持打开的,所以对许多场合还是有性能改善的。
            services.AddSingleton(new ComFr.DbConnectionPool.Options()
            {
                MaximumRetained = 128
            });
            //提供在Request期间租、还DbConnection的支持
            services.AddScoped <IConnectionHolder, TransientConnectionHolder>();
            DatabaseOption databaseOption = configuration.GetSection("Database").Get <DatabaseOption>();

            services.AddSingleton(databaseOption);
            services.AddDataProtection();
        }
예제 #2
0
 public IdentityAccountContext(DbContextOptions <IdentityAccountContext> options, DatabaseOption databaseOption,
                               ILoggerFactory loggerFactor)
     : base(options)
 {
     DatabaseOption = databaseOption;
     _loggerFactory = loggerFactor;
 }
예제 #3
0
        public void Test3()
        {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "mdbx2");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (MdbxEnvironment env = new MdbxEnvironment())
            {
                EnvironmentFlag flags = EnvironmentFlag.NoTLS |
                                        EnvironmentFlag.NoMetaSync |
                                        EnvironmentFlag.Coalesce |
                                        EnvironmentFlag.LifoReclaim;
                env.SetMaxDatabases(20)
                .SetMaxReaders(128)
                .SetMapSize(10485760 * 10)
                .Open(path, flags, Convert.ToInt32("666", 8));


                DatabaseOption option = DatabaseOption.Create | DatabaseOption.IntegerKey;
                // add some values
                using (MdbxTransaction tran = env.BeginTransaction())
                {
                    MdbxDatabase db = tran.OpenDatabase("cursor_test3", option);

                    for (long i = 0; i < 1000000; i++)
                    {
                        db.Put(i, Guid.NewGuid().ToByteArray());
                    }

                    tran.Commit();
                }

                using (MdbxTransaction tran = env.BeginTransaction(TransactionOption.ReadOnly))
                {
                    MdbxDatabase db = tran.OpenDatabase("cursor_test3", option);
                    using (MdbxCursor cursor = db.OpenCursor())
                    {
                        long   key   = 0;
                        byte[] value = null;
                        cursor.Get(ref key, ref value, CursorOp.First);

                        long index = 0;
                        Assert.Equal(index, key);

                        key   = 0;
                        value = null;
                        while (cursor.Get(ref key, ref value, CursorOp.Next))
                        {
                            index++;
                            Assert.Equal(index, key);
                        }
                    }
                }

                env.Close();
            }
        }
예제 #4
0
 public BookContext(DbContextOptions options, DatabaseOption databaseOption, ILoggerFactory loggerFactory, IDomainEventDispatcher domainEventDispatcher) :
     base(options)
 {
     _databaseOption        = databaseOption;
     _loggerFactory         = loggerFactory;
     _domainEventDispatcher = domainEventDispatcher;
 }
예제 #5
0
 public static void ConfigDatabase(this IServiceCollection services, IConfiguration configuration)
 {
     #region 数据库配置
     services.AddSingleton <IDatabaseConfiguring, EntityFrameWorkConfigure>();
     services.AddSingleton <IDbConnectionPool, SimpleDbConnectionPool>();
     //池的配置:
     //MaximumRetained规定池的容量(常态最大保有数量)。
     //MaximumRetained为0时,相当于不使用DbConnection池,
     //但因为在Request期间Connection是保持打开的,所以对许多场合还是有性能改善的。
     services.AddSingleton(new DbConnectionPool.Options()
     {
         MaximumRetained = 128
     });
     //提供在Request期间租、还DbConnection的支持
     services.AddScoped <IConnectionHolder, TransientConnectionHolder>();
     services.AddDbContextOptions <CMSDbContext>();
     services.AddDbContext <CMSDbContext>();
     services.AddScoped <DbContextBase>((provider) => provider.GetService <CMSDbContext>());
     services.AddScoped <DbContext>((provider) => provider.GetService <CMSDbContext>());
     services.AddScoped <EasyDbContext>((provider) => provider.GetService <CMSDbContext>());
     DatabaseOption databaseOption = configuration.GetSection("Database").Get <DatabaseOption>();
     DataTableAttribute.IsLowerCaseTableNames = databaseOption.IsLowerCaseTableNames;
     services.AddSingleton(databaseOption);
     #endregion
 }
 public void Delete(DatabaseOption obj)
 {
     using (InsightEntities db = new InsightEntities())
     {
         db.DatabaseOptions.Attach(obj);
         db.DatabaseOptions.Remove(obj);
         db.SaveChanges();
     }
 }
 public void Update(DatabaseOption obj)
 {
     using (InsightEntities db = new InsightEntities())
     {
         db.DatabaseOptions.Attach(obj);
         db.Entry(obj).State = System.Data.Entity.EntityState.Modified;
         db.SaveChanges();
     }
 }
 public DatabaseOption Insert(DatabaseOption obj)
 {
     using (InsightEntities db = new InsightEntities())
     {
         db.DatabaseOptions.Add(obj);
         db.SaveChanges();
         return(obj);
     }
 }
예제 #9
0
        public SimpleDbConnectionPool(Options options, DatabaseOption databaseOption)
        {
            DatabaseOption = databaseOption;
            int maximumRetained = Math.Max(options.MaximumRetained, 0);

            if (maximumRetained > 0)
            {
                _pooledObjectPolicy = new PooledObjectPolicy(maximumRetained, CreateDbConnection);
                ConnectionPool      = new DefaultObjectPool <DbConnection>(_pooledObjectPolicy, maximumRetained);
            }
        }
예제 #10
0
파일: Dbi.cs 프로젝트: wangjia184/mdbx.NET
        internal static uint Open(IntPtr txn, string name, DatabaseOption options)
        {
            uint dbi;
            int  err = _openDelegate(txn, name, (int)options, out dbi);

            if (err != 0)
            {
                throw new MdbxException("mdbx_dbi_open", err);
            }
            return(dbi);
        }
예제 #11
0
 public DbUpdaterService(DatabaseOption databaseOption,
                         IOptions <DBVersionOption> dbVersionOption,
                         IWebClient webClient,
                         IDBContextProvider dbContextProvider,
                         ILogger <DbUpdaterService> logger)
 {
     _dbVersionOption   = dbVersionOption;
     _webClient         = webClient;
     _scriptFileName    = $"{databaseOption.DbType}.sql";//MsSql.sql, MySql.sql, Sqlite.sql
     _logger            = logger;
     _dbContextProvider = dbContextProvider;
 }
예제 #12
0
        public List <DatabaseOption> GetDatabaseOptions()
        {
            var     databaseList = new List <DatabaseOption>();
            DataSet ds           = new DataSet();
            string  query        = Resources.DatabaseOptions;

            try
            {
                ds = (DataSet)ExecuteQuery(query);
                foreach (DataTable t in ds.Tables)
                {
                    foreach (DataRow r in t.Rows)
                    {
                        DatabaseOption DO = new DatabaseOption();
                        DO.Name           = (String)r["name"];
                        DO.Compatibility  = Convert.ToInt16(r["compatibility_level"]);
                        DO.StateDesc      = (String)r["state_desc"];
                        DO.UserAccessDesc = (String)r["user_access_desc"];
                        DO.RecoveryModel  = (String)r["recovery_model_desc"];
                        // DO.Collation = (String)r["collation_name"];
                        DO.Collation       = r["collation_name"] == DBNull.Value ? null : (String)r?["collation_name"];
                        DO.PageVerify      = (String)r["page_verify_option_desc"];
                        DO.ReadOnly        = Convert.ToBoolean(r["is_read_only"]);
                        DO.AutoClose       = Convert.ToBoolean(r["is_auto_close_on"]);
                        DO.AutoShrink      = Convert.ToBoolean(r["is_auto_shrink_on"]);
                        DO.AutoCreateStats = Convert.ToBoolean(r["is_auto_create_stats_on"]);
                        DO.AutoUpdateStats = Convert.ToBoolean(r["is_auto_update_stats_on"]);
                        DO.FullText        = Convert.ToBoolean(r["is_fulltext_enabled"]);
                        DO.DbChaining      = Convert.ToBoolean(r["is_db_chaining_on"]);
                        DO.Trustworthy     = Convert.ToBoolean(r["is_trustworthy_on"]);
                        DO.Owner           = (String)r["Owner"];

                        databaseList.Add(DO);
                    }
                }
            }
            catch (Exception ex)
            {
                throw;
                //Console.WriteLine("Exception catched: " + ex.Message);
                //DO2.Success = false;
            }

            return(databaseList);
        }
 public static void Update(DatabaseOption obj)
 {
     repository.Update(obj);
 }
예제 #14
0
 public DbUpdaterService(DatabaseOption databaseOption, IWebHostEnvironment hostingEnvironment)
 {
     _databaseOption     = databaseOption;
     _hostingEnvironment = hostingEnvironment;
 }
예제 #15
0
        public void Test1()
        {
            string path = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "mdbx");

            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            using (MdbxEnvironment env = new MdbxEnvironment())
            {
                env.SetMaxDatabases(10) /* allow us to use a different db for testing */
                .Open(path, EnvironmentFlag.NoTLS, Convert.ToInt32("666", 8));

                DatabaseOption option = DatabaseOption.Create /* needed to create a new db if not exists */
                                        | DatabaseOption.IntegerKey /* opitimized for fixed key */;

                // mdbx_put
                using (MdbxTransaction tran = env.BeginTransaction())
                {
                    MdbxDatabase db = tran.OpenDatabase("basic_op_test", option);
                    db.Put(10L, "ten");
                    db.Put(1000L, "thousand");
                    db.Put(1000000000L, "billion");
                    db.Put(1000000L, "million");
                    db.Put(100L, "hundred");
                    db.Put(1L, "one");
                    tran.Commit();
                }


                // mdbx_get
                using (MdbxTransaction tran = env.BeginTransaction(TransactionOption.ReadOnly))
                {
                    MdbxDatabase db = tran.OpenDatabase("basic_op_test", option);

                    string text = db.Get <long, string>(1000000L);
                    Assert.NotNull(text);
                    Assert.Equal("million", text);
                }

                // mdbx_del
                using (MdbxTransaction tran = env.BeginTransaction())
                {
                    MdbxDatabase db      = tran.OpenDatabase("basic_op_test", option);
                    bool         deleted = db.Del(100L);
                    Assert.True(deleted);
                    deleted = db.Del(100L);
                    Assert.False(deleted);
                    tran.Commit();
                }


                // mdbx_get
                using (MdbxTransaction tran = env.BeginTransaction(TransactionOption.ReadOnly))
                {
                    MdbxDatabase db = tran.OpenDatabase("basic_op_test", option);

                    string text = db.Get <long, string>(100L);
                    Assert.Null(text);
                }

                env.Close();
            }
        }
예제 #16
0
        public static void UseHbCrm(this IServiceCollection services, IHostingEnvironment env, IConfiguration config)
        {
            services.AddEasyCaching(option => option.UseInMemory("hbcrm_memory_cache"));
            services.AddScoped <ICacheManager, MemoryCacheManager>();//封装一层,缓存用的是EasyCaching
            //services.AddScoped<IDbContext, HbCrmContext>();

            services.AddScoped(typeof(IRepository <>), typeof(EfRepository <>));

            HbCrmConfiguration hbCrmConfiguration = config.GetSection("HbCrmConfiguration").Get <HbCrmConfiguration>();

            services.TryAddSingleton <HbCrmConfiguration>(hbCrmConfiguration);

            services.AddDbContext <HbCrmContext>((provider, option) =>
            {
                //option.UseLazyLoadingProxies();
                DatabaseOption databaseOption = provider.GetRequiredService <HbCrmConfiguration>().DatabaseOption;
                switch (databaseOption.DbType)
                {
                case DbTypes.MsSql:
                    option.UseSqlServer(databaseOption.ConnectionString);
                    break;

                case DbTypes.MySql:
                    option.UseMySql(databaseOption.ConnectionString);
                    break;

                default:
                    throw new NotSupportedException("The database type " + databaseOption.DbType + " no support!");
                }
            });

            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddScoped <IMenuService, MenuService>();
            services.AddScoped <IRoleService, RoleService>();
            services.AddScoped <IAdminService, AdminService>();
            services.AddScoped <IWorkContext, WorkContext>();
            services.AddScoped <IAuthenticationService, CookieAuthenticationService>();
            services.AddScoped <IPermissionService, PermissionService>();

            services.AddAuthentication(HbCrmAuthenticationDefaults.AdminAuthenticationScheme)
            .AddCookie(HbCrmAuthenticationDefaults.AdminAuthenticationScheme, option =>
            {
                option.LoginPath        = HbCrmAuthenticationDefaults.LoginPath;
                option.AccessDeniedPath = HbCrmAuthenticationDefaults.AccessDeniedPath;
                option.Cookie.Name      = HbCrmAuthenticationDefaults.AdminAuthenticationScheme;
            })
            .AddCookie(HbCrmAuthenticationDefaults.CustomerAuthenticationScheme, option =>
            {
                option.LoginPath = HbCrmAuthenticationDefaults.SigninPath;
            });

            services.AddAuthorization(options =>
                                      PermissionKeys.AllPermissions.ForEach(keys =>
                                                                            options.AddPolicy(keys.Name, policy => policy.Requirements.Add(new AdminAuthorizationRequirement {
                Policy = keys.Name
            }))
                                                                            ));

            services.AddSingleton <IAuthorizationHandler, AdminAuthorizationHandler>();

            var mvcBuilder = services.AddMvc();

            mvcBuilder.AddFluentValidation(option =>
            {
                //https://docs.microsoft.com/zh-cn/aspnet/core/mvc/advanced/app-parts?view=aspnetcore-2.2
                var assemblies = mvcBuilder.PartManager.ApplicationParts
                                 .OfType <AssemblyPart>()
                                 .Where(part => part.Name.StartsWith("HbCrm", StringComparison.InvariantCultureIgnoreCase))
                                 .Select(part => part.Assembly);
                option.RegisterValidatorsFromAssemblies(assemblies);                 //从程序集中加载继承AbstractValidator<T> 的 public类,且是非 abstract的
                option.RunDefaultMvcValidationAfterFluentValidationExecutes = false; //去掉默认验证,只运行FluentValidation验证
                option.ImplicitlyValidateChildProperties = true;                     //支持子属性是类的验证
            });
            ValidatorOptions.CascadeMode = CascadeMode.StopOnFirstFailure;           //开启全局设置,第一个验证失败立即停止验证

            services.AddAutoMapper(typeof(Builder));
        }
 public EntityFrameWorkConfigure(DatabaseOption dataBaseOption, ILoggerFactory loggerFactory)
 {
     _dataBaseOption = dataBaseOption;
     _loggerFactory  = loggerFactory;
 }
예제 #18
0
 /// <summary>
 /// Open a table in the environment.
 ///
 /// A table handle denotes the name and parameters of a table, independently
 /// of whether such a table exists. The table handle may be discarded by
 /// calling mdbx_dbi_close(). The old table handle is returned if the table
 /// was already open. The handle may only be closed once.
 ///
 /// The table handle will be private to the current transaction until
 /// the transaction is successfully committed. If the transaction is
 /// aborted the handle will be closed automatically.
 /// After a successful commit the handle will reside in the shared
 /// environment, and may be used by other transactions.
 ///
 /// This function must not be called from multiple concurrent
 /// transactions in the same process. A transaction that uses
 /// this function must finish (either commit or abort) before
 /// any other transaction in the process may use this function.
 /// </summary>
 /// <param name="name"></param>
 /// <param name="option"></param>
 /// <returns></returns>
 public MdbxDatabase OpenDatabase(string name = null, DatabaseOption option = DatabaseOption.Unspecific)
 {
     return(new MdbxDatabase(_env, this, Dbi.Open(_txnPtr, name, option)));
 }
예제 #19
0
 public override void Visit(DatabaseOption node) { this.action(node); }
예제 #20
0
        public static void UseZKEACMS(this IServiceCollection services, IConfiguration configuration)
        {
            //添加session
            services.AddDistributedMemoryCache();
            services.AddSession(opt =>
            {
                opt.IdleTimeout = TimeSpan.FromMinutes(20);
                //opt.Cookie.Expiration = TimeSpan.FromMinutes(30);
                //opt.Cookie.MaxAge
                opt.Cookie.HttpOnly    = true;
                opt.Cookie.IsEssential = true;
            });

            IMvcBuilder mvcBuilder = services.AddControllersWithViews(option =>
            {
                option.ModelBinderProviders.Insert(0, new WidgetTypeModelBinderProvider());
                option.ModelMetadataDetailsProviders.Add(new DataAnnotationsMetadataProvider());
            })
                                     .AddRazorOptions(opt =>
            {
                opt.ViewLocationExpanders.Clear();
                opt.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
            })
                                     .AddControllersAsServices()
                                     .AddDataAnnotationsLocalization(option => option.DataAnnotationLocalizerProvider = (t, factory) =>
            {
                if (t.IsClass)
                {
                    return(new LocalizeString(t));
                }
                else
                {
                    return(null);
                }
            })
                                     .SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.AddRazorPages();
            services.AddHealthChecks();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddRouting(option => option.LowercaseUrls = true);

            services.TryAddScoped <IApplicationContextAccessor, ApplicationContextAccessor>();
            services.TryAddScoped <IApplicationContext, CMSApplicationContext>();
            services.TryAddSingleton <IRouteProvider, RouteProvider>();

            services.AddTransient <IRouteDataProvider, PaginationRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, PostIdRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, CategoryRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, HtmlRouteDataProvider>();

            services.TryAddSingleton <IAdminMenuProvider, AdminMenuProvider>();
            services.TryAddScoped <IWidgetActivator, DefaultWidgetActivator>();
            services.TryAddTransient <ICarouselItemService, CarouselItemService>();
            services.TryAddTransient <ICarouselService, CarouselService>();
            services.TryAddTransient <INavigationService, NavigationService>();
            services.TryAddTransient <Site.ISiteInformationService, Site.SiteInformationService>();

            services.TryAddTransient <IDashboardProviderService, DashboardProviderService>();
            services.AddTransient <IDashboardPartDriveService, DashboardWelcomePartService>();
            services.AddTransient <IDashboardPartDriveService, DashboardEventLogPartService>();

            services.TryAddTransient <IDataArchivedService, DataArchivedService>();
            services.TryAddTransient <IExtendFieldService, ExtendFieldService>();
            services.TryAddTransient <INotifyService, NotifyService>();
            services.AddTransient <IUserCenterLinksProvider, UserCenterLinksProvider>();
            services.AddTransient <IUserCenterLinkService, UserCenterLinkService>();
            services.TryAddScoped <ILayoutService, LayoutService>();
            services.TryAddScoped <ILayoutHtmlService, LayoutHtmlService>();
            services.TryAddTransient <IMediaService, MediaService>();
            services.TryAddScoped <IPageService, PageService>();
            services.TryAddScoped <IApplicationSettingService, ApplicationSettingService>();
            services.TryAddScoped <IThemeService, ThemeService>();
            services.TryAddTransient <IWidgetTemplateService, WidgetTemplateService>();
            services.TryAddScoped <IWidgetBasePartService, WidgetBasePartService>();
            services.TryAddScoped <IZoneService, ZoneService>();
            services.TryAddScoped <IHostOptionProvider, HostOptionProvider>();
            services.TryAddTransient <Rule.IRuleService, Rule.RuleService>();

            services.AddScoped <IOnModelCreating, EntityFrameWorkModelCreating>();

            services.AddTransient <Easy.Notification.ISmtpProvider, SmtpProvider>();
            services.AddTransient <IPackageInstaller, ThemePackageInstaller>();
            services.AddTransient <IPackageInstaller, WidgetPackageInstaller>();
            services.AddTransient <IPackageInstaller, FilePackageInstaller>();
            services.AddTransient <IPackageInstaller, DataDictionaryPackageInstaller>();
            services.AddTransient <IPackageInstallerProvider, PackageInstallerProvider>();
            services.AddTransient <IEventViewerService, EventViewerService>();
            services.AddTransient <IDBContextProvider, DefaultDBContextProvider>();
            services.AddScoped <IEventManager, EventManager>();

            services.AddTransient <IStorage, WebStorage>();
            services.AddTransient <ICurrencyService, CurrencyService>();

            services.ConfigureStateProvider <StateProvider.OuterChainPictureStateProvider>();
            services.ConfigureStateProvider <StateProvider.EnableResponsiveDesignStateProvider>();
            services.ConfigureStateProvider <Site.SiteInformationStateProvider>();
            services.ConfigureStateProvider <CurrencyStateProvider>();

            services.ConfigureCache <IEnumerable <WidgetBase> >();
            services.ConfigureCache <IEnumerable <ZoneEntity> >();
            services.ConfigureCache <IEnumerable <LayoutHtml> >();
            services.ConfigureCache <IEnumerable <ThemeEntity> >();
            services.ConfigureCache <List <TemplateFile> >();
            services.ConfigureCache <ConcurrentDictionary <string, object> >();
            services.ConfigureCache <string>();

            services.ConfigureMetaData <AdminSignViewModel, AdminSignViewModelMetaData>();
            services.ConfigureMetaData <SignInViewModel, SignInViewModelMetaData>();
            services.ConfigureMetaData <CustomerSignInViewModel, CustomerSignInViewModelMetaData>();
            services.ConfigureMetaData <ArticleEntity, ArticleEntityMeta>();
            services.ConfigureMetaData <ArticleGallery, ArticleGalleryMetaData>();
            services.ConfigureMetaData <ArticleGalleryItem, ArticleGalleryItemMetaData>();
            services.ConfigureMetaData <ArticleItem, ArticleGalleryProductMetaData>();
            services.ConfigureMetaData <ArticleType, ArtycleTypeMetaData>();
            services.ConfigureMetaData <BreadcrumbWidget, BreadcrumbWidgetMetaData>();
            services.ConfigureMetaData <CarouselEntity, CarouselEntityMetaData>();
            services.ConfigureMetaData <CarouselWidget, CarouselWidgetMetaData>();
            services.ConfigureMetaData <CarouselItemEntity, CarouselItemEntityMeta>();
            services.ConfigureMetaData <HtmlWidget, HtmlWidgetMetaData>();
            services.ConfigureMetaData <ImageWidget, ImageWidgetMedaData>();
            services.ConfigureMetaData <NavigationEntity, NavigationEntityMeta>();
            services.ConfigureMetaData <NavigationWidget, NavigationWidgetMetaData>();
            services.ConfigureMetaData <ScriptWidget, ScriptWidgetMetaData>();
            services.ConfigureMetaData <StyleSheetWidget, StyleSheetWidgetMetaData>();
            services.ConfigureMetaData <VideoWidget, VideoWidgetMetaData>();
            services.ConfigureMetaData <DataArchived.DataArchived, DataArchivedMetaData>();
            services.ConfigureMetaData <ExtendFieldEntity, ExtendFieldEntityMetaData>();
            services.ConfigureMetaData <LayoutEntity, LayoutEntityMetaData>();
            services.ConfigureMetaData <MediaEntity, MediaEntityMetaData>();
            services.ConfigureMetaData <PageEntity, PageMetaData>();
            services.ConfigureMetaData <PageAsset, PageAssetMetaData>();
            services.ConfigureMetaData <ProductEntity, ProductMetaData>();
            services.ConfigureMetaData <ProductCategory, ProductCategoryMetaData>();
            services.ConfigureMetaData <ProductImage, ProductImageMetaData>();
            services.ConfigureMetaData <ProductGallery, ProductGalleryMetaData>();
            services.ConfigureMetaData <ProductGalleryItem, ProductGalleryItemMetaData>();
            services.ConfigureMetaData <ProductItem, ProductGalleryProductMetaData>();
            services.ConfigureMetaData <ApplicationSetting, ApplicationSettingMedaData>();
            services.ConfigureMetaData <ThemeEntity, ThemeEntityMetaData>();
            services.ConfigureMetaData <ZoneEntity, ZoneEntityMetaData>();
            services.ConfigureMetaData <Rule.Rule, Rule.RuleMetaData>();
            services.ConfigureMetaData <Rule.RuleItem, Rule.RuleItemMetaData>();
            services.ConfigureMetaData <Robots, RobotsMetaData>();
            services.ConfigureMetaData <TemplateFile, TemplateFileMetaData>();
            services.ConfigureMetaData <TabWidget, TabWidgetMetaData>();
            services.ConfigureMetaData <TabItem, TabItemMetaData>();
            services.ConfigureMetaData <HeadWidget, HeaderWidgetMetaData>();
            services.ConfigureMetaData <ForgottenViewModel, ForgottenViewModelMetaData>();
            services.ConfigureMetaData <ResetViewModel, ResetViewModelMetaData>();

            services.ConfigureMetaData <CurrencyEntry, CurrencyEntryMetaData>();
            services.ConfigureMetaData <CurrencyOption, CurrencyOptionMetaData>();

            services.RegistEvent <RemoveCacheOnPagePublishedEventHandler>(Events.OnPagePublished);
            services.RegistEvent <RemoveOldVersionOnPagePublishedEventHandler>(Events.OnPagePublished);
            services.RegistEvent <RemoveCacheOnPageDeletedEventHandler>(Events.OnPageDeleted);
            services.RegistEvent <WidgetChangedTriggerPageEventHandler>(Events.OnWidgetAdded, Events.OnWidgetUpdated, Events.OnWidgetDeleted, Events.OnWidgetBasePartUpdated);

            services.AddScoped <IImageCaptchaService, ImageCaptchaService>();
            services.AddScoped <IImageGenerator, DefaultImageGenerator>();
            services.AddScoped <ICaptchaCodeStorageProvider, SessionCaptchaCodeStorageProvider>();

            services.AddScoped <ITemplateService, TemplateService>();

            services.Configure <NavigationWidget>(option =>
            {
                option.DataSourceLinkTitle = "Navigation";
                option.DataSourceLink      = "~/admin/Navigation";
            });

            services.Configure <CarouselWidget>(option =>
            {
                option.DataSourceLinkTitle = "Carousel";
                option.DataSourceLink      = "~/admin/Carousel";
            });
            #region 数据库配置
            services.AddSingleton <IDatabaseConfiguring, EntityFrameWorkConfigure>();
            services.AddSingleton <IDbConnectionPool, SimpleDbConnectionPool>();
            //池的配置:
            //MaximumRetained规定池的容量(常态最大保有数量)。
            //MaximumRetained为0时,相当于不使用DbConnection池,
            //但因为在Request期间Connection是保持打开的,所以对许多场合还是有性能改善的。
            services.AddSingleton(new DbConnectionPool.Options()
            {
                MaximumRetained = 128
            });
            //提供在Request期间租、还DbConnection的支持
            services.AddScoped <IConnectionHolder, TransientConnectionHolder>();
            services.AddDbContextOptions <CMSDbContext>();
            services.AddDbContext <CMSDbContext>();
            services.AddScoped <EasyDbContext>((provider) => provider.GetService <CMSDbContext>());
            DatabaseOption databaseOption = configuration.GetSection("Database").Get <DatabaseOption>();
            DataTableAttribute.IsLowerCaseTableNames = databaseOption.IsLowerCaseTableNames;
            services.AddSingleton(databaseOption);
            #endregion
            services.Configure <HostOption>(configuration.GetSection("Host"));

            services.UseEasyFrameWork(configuration);
            foreach (IPluginStartup item in services.LoadAvailablePlugins())
            {
                item.Setup(new object[] { services, mvcBuilder });
            }

            foreach (KeyValuePair <string, Type> item in WidgetBase.KnownWidgetService)
            {
                services.TryAddTransient(item.Value);
            }
            foreach (KeyValuePair <string, Type> item in WidgetBase.KnownWidgetModel)
            {
                services.TryAddTransient(item.Value);
            }

            services.Configure <AuthorizationOptions>(options =>
            {
                PermissionKeys.Configure(options);
                KnownRequirements.Configure(options);
            });

            services.AddAuthentication(DefaultAuthorizeAttribute.DefaultAuthenticationScheme)
            .AddCookie(DefaultAuthorizeAttribute.DefaultAuthenticationScheme, o =>
            {
                o.LoginPath        = new PathString("/account/login");
                o.AccessDeniedPath = new PathString("/error/forbidden");
            })
            .AddCookie(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, option =>
            {
                option.LoginPath        = new PathString("/account/signin");
                option.AccessDeniedPath = new PathString("/error/forbidden");
            })
            .AddJwtBearer(JwtBearerDefaults.AuthenticationScheme, options =>
            {
                options.TokenValidationParameters = new TokenValidationParameters()
                {
                    ValidateIssuer           = true,
                    ValidIssuer              = JwtBearerDefaults.Issuer,
                    ValidateAudience         = true,
                    ValidAudience            = JwtBearerDefaults.Audience,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.UTF8.GetBytes(JwtBearerDefaults.IssuerSigningKey))
                };
            });
        }
예제 #21
0
 public BaseController(IOptions <DatabaseOption> databaseOption)
 {
     DatabaseOption = databaseOption.Value;
 }
 public static DatabaseOption Insert(DatabaseOption obj)
 {
     return(repository.Insert(obj));
 }
예제 #23
0
 public CurrentDbContext(DatabaseOption dataBaseOption)
 {
     _dataBaseOption = dataBaseOption;
 }
 public static void Delete(DatabaseOption obj)
 {
     repository.Delete(obj);
 }
예제 #25
0
        public static void UseZKEACMS(this IServiceCollection services, IConfiguration configuration)
        {
            //添加session
            services.AddDistributedMemoryCache();
            services.AddSession(opt =>
            {
                opt.IdleTimeout = TimeSpan.FromMinutes(20);
                //opt.Cookie.Expiration = TimeSpan.FromMinutes(30);
                //opt.Cookie.MaxAge
                opt.Cookie.HttpOnly    = true;
                opt.Cookie.IsEssential = true;
            });

            IMvcBuilder mvcBuilder = services.AddControllersWithViews(option =>
            {
                option.ModelBinderProviders.Insert(0, new WidgetTypeModelBinderProvider());
                option.ModelMetadataDetailsProviders.Add(new DataAnnotationsMetadataProvider());
            })
                                     .AddRazorOptions(opt =>
            {
                opt.ViewLocationExpanders.Clear();
                opt.ViewLocationExpanders.Add(new ThemeViewLocationExpander());
            })
                                     .AddControllersAsServices()
                                     .AddNewtonsoftJson(options =>
            {
                options.SerializerSettings.DateFormatString = "yyyy/MM/dd H:mm";
            })
                                     .SetCompatibilityVersion(CompatibilityVersion.Latest);

            services.AddRazorPages();
            services.AddHealthChecks();
            services.TryAddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            services.AddRouting(option => option.LowercaseUrls = true);

            services.TryAddScoped <IApplicationContextAccessor, ApplicationContextAccessor>();
            services.TryAddScoped <IApplicationContext, CMSApplicationContext>();
            services.TryAddSingleton <IRouteProvider, RouteProvider>();

            services.AddTransient <IRouteDataProvider, PaginationRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, PostIdRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, CategoryRouteDataProvider>();
            services.AddTransient <IRouteDataProvider, HtmlRouteDataProvider>();

            services.TryAddSingleton <IAdminMenuProvider, AdminMenuProvider>();
            services.TryAddScoped <IWidgetActivator, DefaultWidgetActivator>();
            services.TryAddTransient <ICarouselItemService, CarouselItemService>();
            services.TryAddTransient <ICarouselService, CarouselService>();
            services.TryAddTransient <INavigationService, NavigationService>();

            services.TryAddTransient <IDashboardProviderService, DashboardProviderService>();
            services.AddTransient <IDashboardPartDriveService, DashboardWelcomePartService>();
            services.AddTransient <IDashboardPartDriveService, DashboardEventLogPartService>();

            services.TryAddTransient <IDataArchivedService, DataArchivedService>();
            services.TryAddTransient <IExtendFieldService, ExtendFieldService>();
            services.TryAddTransient <INotifyService, NotifyService>();
            services.AddTransient <IUserCenterLinksProvider, UserCenterLinksProvider>();
            services.AddTransient <IUserCenterLinkService, UserCenterLinkService>();
            services.TryAddScoped <ILayoutService, LayoutService>();
            services.TryAddScoped <ILayoutHtmlService, LayoutHtmlService>();
            services.TryAddTransient <IMediaService, MediaService>();
            services.TryAddScoped <IPageService, PageService>();
            services.TryAddScoped <IApplicationSettingService, ApplicationSettingService>();
            services.TryAddScoped <IThemeService, ThemeService>();
            services.TryAddTransient <IWidgetTemplateService, WidgetTemplateService>();
            services.TryAddScoped <IWidgetBasePartService, WidgetBasePartService>();
            services.TryAddScoped <IZoneService, ZoneService>();
            services.TryAddTransient <Rule.IRuleService, Rule.RuleService>();

            services.AddScoped <IOnModelCreating, EntityFrameWorkModelCreating>();

            services.AddTransient <Easy.Notification.ISmtpProvider, SmtpProvider>();
            services.AddTransient <IPackageInstaller, ThemePackageInstaller>();
            services.AddTransient <IPackageInstaller, WidgetPackageInstaller>();
            services.AddTransient <IPackageInstaller, FilePackageInstaller>();
            services.AddTransient <IPackageInstaller, DataDictionaryPackageInstaller>();
            services.AddTransient <IPackageInstallerProvider, PackageInstallerProvider>();
            services.AddTransient <IEventViewerService, EventViewerService>();

            services.AddTransient <IStorage, WebStorage>();

            services.ConfigureStateProvider <StateProvider.OuterChainPictureStateProvider>();

            services.ConfigureCache <IEnumerable <WidgetBase> >();
            services.ConfigureCache <IEnumerable <ZoneEntity> >();
            services.ConfigureCache <IEnumerable <LayoutHtml> >();
            services.ConfigureCache <IEnumerable <ThemeEntity> >();
            services.ConfigureCache <List <TemplateFile> >();
            services.ConfigureCache <ConcurrentDictionary <string, object> >();
            services.ConfigureCache <string>();

            services.ConfigureMetaData <ArticleEntity, ArticleEntityMeta>();
            services.ConfigureMetaData <ArticleType, ArtycleTypeMetaData>();
            services.ConfigureMetaData <BreadcrumbWidget, BreadcrumbWidgetMetaData>();
            services.ConfigureMetaData <CarouselEntity, CarouselEntityMetaData>();
            services.ConfigureMetaData <CarouselWidget, CarouselWidgetMetaData>();
            services.ConfigureMetaData <CarouselItemEntity, CarouselItemEntityMeta>();
            services.ConfigureMetaData <HtmlWidget, HtmlWidgetMetaData>();
            services.ConfigureMetaData <ImageWidget, ImageWidgetMedaData>();
            services.ConfigureMetaData <NavigationEntity, NavigationEntityMeta>();
            services.ConfigureMetaData <NavigationWidget, NavigationWidgetMetaData>();
            services.ConfigureMetaData <ScriptWidget, ScriptWidgetMetaData>();
            services.ConfigureMetaData <StyleSheetWidget, StyleSheetWidgetMetaData>();
            services.ConfigureMetaData <VideoWidget, VideoWidgetMetaData>();
            services.ConfigureMetaData <DataArchived.DataArchived, DataArchivedMetaData>();
            services.ConfigureMetaData <ExtendFieldEntity, ExtendFieldEntityMetaData>();
            services.ConfigureMetaData <LayoutEntity, LayoutEntityMetaData>();
            services.ConfigureMetaData <MediaEntity, MediaEntityMetaData>();
            services.ConfigureMetaData <PageEntity, PageMetaData>();
            services.ConfigureMetaData <PageAsset, PageAssetMetaData>();
            services.ConfigureMetaData <ProductEntity, ProductMetaData>();
            services.ConfigureMetaData <ProductCategory, ProductCategoryMetaData>();
            services.ConfigureMetaData <ProductImage, ProductImageMetaData>();
            services.ConfigureMetaData <ApplicationSetting, ApplicationSettingMedaData>();
            services.ConfigureMetaData <ThemeEntity, ThemeEntityMetaData>();
            services.ConfigureMetaData <ZoneEntity, ZoneEntityMetaData>();
            services.ConfigureMetaData <Rule.Rule, Rule.RuleMetaData>();
            services.ConfigureMetaData <Rule.RuleItem, Rule.RuleItemMetaData>();
            services.ConfigureMetaData <SmtpSetting, SmtpSettingMetaData>();
            services.ConfigureMetaData <Robots, RobotsMetaData>();
            services.ConfigureMetaData <TemplateFile, TemplateFileMetaData>();

            services.AddScoped <IValidateService, DefaultValidateService>();

            services.AddScoped <ITemplateService, TemplateService>();

            services.Configure <NavigationWidget>(option =>
            {
                option.DataSourceLinkTitle = "导航";
                option.DataSourceLink      = "~/admin/Navigation";
            });

            services.Configure <CarouselWidget>(option =>
            {
                option.DataSourceLinkTitle = "焦点图";
                option.DataSourceLink      = "~/admin/Carousel";
            });
            #region 数据库配置
            services.AddSingleton <IDatabaseConfiguring, EntityFrameWorkConfigure>();
            services.AddSingleton <IDbConnectionPool, SimpleDbConnectionPool>();
            //池的配置:
            //MaximumRetained规定池的容量(常态最大保有数量)。
            //MaximumRetained为0时,相当于不使用DbConnection池,
            //但因为在Request期间Connection是保持打开的,所以对许多场合还是有性能改善的。
            services.AddSingleton(new DbConnectionPool.Options()
            {
                MaximumRetained = 128
            });
            //提供在Request期间租、还DbConnection的支持
            services.AddScoped <IConnectionHolder, TransientConnectionHolder>();
            services.AddDbContextOptions <CMSDbContext>();
            services.AddDbContext <CMSDbContext>();
            services.AddScoped <EasyDbContext>((provider) => provider.GetService <CMSDbContext>());
            DatabaseOption databaseOption = configuration.GetSection("Database").Get <DatabaseOption>();
            //DataTableAttribute.IsLowerCaseTableNames = databaseOption.DbType == DbTypes.MySql;
            services.AddSingleton(databaseOption);
            #endregion

            services.UseEasyFrameWork(configuration);
            foreach (IPluginStartup item in services.LoadAvailablePlugins())
            {
                item.Setup(new object[] { services, mvcBuilder });
            }

            foreach (KeyValuePair <string, Type> item in WidgetBase.KnownWidgetService)
            {
                services.TryAddTransient(item.Value);
            }
            foreach (KeyValuePair <string, Type> item in WidgetBase.KnownWidgetModel)
            {
                services.TryAddTransient(item.Value);
            }

            services.Configure <AuthorizationOptions>(options =>
            {
                PermissionKeys.Configure(options);
                KnownRequirements.Configure(options);
            });

            services.AddAuthentication(DefaultAuthorizeAttribute.DefaultAuthenticationScheme)
            .AddCookie(DefaultAuthorizeAttribute.DefaultAuthenticationScheme, o =>
            {
                o.LoginPath        = new PathString("/account/login");
                o.AccessDeniedPath = new PathString("/error/forbidden");
            })
            .AddCookie(CustomerAuthorizeAttribute.CustomerAuthenticationScheme, option =>
            {
                option.LoginPath        = new PathString("/account/signin");
                option.AccessDeniedPath = new PathString("/error/forbidden");
            });
        }
 public override void ExplicitVisit(DatabaseOption fragment)
 {
     _fragments.Add(fragment);
 }