Beispiel #1
0
        /// <summary>
        /// 初始化提供者。
        /// </summary>
        private static void InitializeProviders()
        {
            //内置的提供者
#if !NETSTANDARD
            dicProviders.TryAdd("OleDb", OleDbProvider.Instance);
            dicProviders.TryAdd("Odbc", OdbcProvider.Instance);
#endif
            dicProviders.TryAdd("MsSql", MsSqlProvider.Instance);
            dicProviders.TryAdd("Oracle", OracleProvider.Instance);
            dicProviders.TryAdd("SQLite", SQLiteProvider.Instance);
            dicProviders.TryAdd("MySql", MySqlProvider.Instance);
            dicProviders.TryAdd("PostgreSql", PostgreSqlProvider.Instance);
            dicProviders.TryAdd("Firebird", FirebirdProvider.Instance);
            dicProviders.TryAdd("DB2", DB2Provider.Instance);

            //取配置,注册自定义提供者
            var section = ConfigurationUnity.GetSection <ProviderConfigurationSection>();
            if (section != null)
            {
                RegisterCustomProviders(section);
            }
        }
Beispiel #2
0
        /// <summary>
        /// 通过配置文件来配置 <see cref="BundleCollection"/>。
        /// </summary>
        /// <param name="containMin">是否允许包含 min 文件。</param>
        public static void Config(bool containMin = true)
        {
            if (containMin)
            {
                BundleTable.Bundles.IgnoreList.Clear();
                BundleTable.Bundles.IgnoreList.Ignore("*.intellisense.js");
                BundleTable.Bundles.IgnoreList.Ignore("*-vsdoc.js");
                BundleTable.Bundles.IgnoreList.Ignore("*.debug.js", OptimizationMode.WhenEnabled);
            }

            var section = ConfigurationUnity.GetSection <BundleGroupConfigurationSection>();

            if (section == null)
            {
                return;
            }

            BundleTable.EnableOptimizations = section.EnableOptimization;

            foreach (var setting in section.Settings)
            {
                var index = 0;
                foreach (var res in setting.Value.Resources)
                {
                    switch (res.Type)
                    {
                    case ResourceType.Script:
                        GetBundle("~/js/" + setting.Key + "/" + index).Include(res.Path);
                        break;

                    case ResourceType.Style:
                        GetBundle("~/css/" + setting.Key + "/" + index).Include(res.Path);
                        break;
                    }

                    index++;
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// 根据应用程序配置,创建日志管理器。
        /// </summary>
        /// <param name="configName">应用程序配置项的名称。</param>
        /// <returns><paramref name="configName"/>缺省时,如果应用程序未配置,则为 <see cref="DefaultLogger"/>,否则为配置项对应的 <see cref="ILogger"/> 实例。</returns>
        public static ILogger CreateLogger(string configName = null)
        {
            ILogger logger;
            LoggingConfigurationSetting setting = null;
            var section = ConfigurationUnity.GetSection <LoggingConfigurationSection>();

            if (section != null && section.Factory != null)
            {
                logger = section.Factory.CreateInstance(configName) as ILogger;
                if (logger != null)
                {
                    return(logger);
                }
            }

            if (string.IsNullOrEmpty(configName))
            {
                if (section == null || section.Default == null)
                {
                    return(DefaultLogger.Instance);
                }
                else
                {
                    setting = section.Default;
                }
            }
            else if (section != null)
            {
                setting = section.Settings[configName];
            }

            if (setting == null || setting.LogType == null)
            {
                return(null);
            }

            return(CreateBySetting(setting));
        }
        /// <summary>
        /// 尝试获取指定表达式的缓存。
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="context"></param>
        /// <param name="creator">当缓存不存在时,创建缓存数据的函数。</param>
        /// <returns></returns>
        Delegate IQueryCache.TryGetDelegate(Expression expression, QueryCacheContext context, Func <LambdaExpression> creator)
        {
            var section = ConfigurationUnity.GetSection <TranslatorConfigurationSection>();
            var option  = section == null ? TranslateOptions.Default : section.Options;

            var result = CacheableChecker.Check(expression);

            if (!result.Required ||
                (result.Enabled == null && (context.Enabled == false || (context.Enabled == null && !option.CacheParsing))) ||
                result.Enabled == false)
            {
                return(creator().Compile());
            }

            var generator = _serviceProvider.TryGetService <IQueryCacheKeyGenerator>(() => ExpressionKeyGenerator.Instance);
            var cacheKey  = _serviceProvider.GetCacheKey(generator.Generate(expression, "Trans"));

            Tracer.Debug($"QueryCache access to '{cacheKey}'");
            var cacheMgr = _serviceProvider.TryGetService <IMemoryCacheManager>(() => MemoryCacheManager.Instance);

            return(cacheMgr.TryGet(cacheKey, () =>
            {
                var lambdaExp = creator() as LambdaExpression;
                var segment = SegmentFinder.Find(expression);
                if (segment != null)
                {
                    //将表达式内的 Segment 替换成参数
                    var segParExp = Expression.Parameter(typeof(IDataSegment), "g");
                    var newExp = SegmentReplacer.Repalce(lambdaExp.Body, segParExp);
                    var parameters = new List <ParameterExpression>(lambdaExp.Parameters);
                    parameters.Insert(1, segParExp);
                    lambdaExp = Expression.Lambda(newExp, parameters.ToArray());
                }

                return lambdaExp.Compile();
            },
                                   () => new RelativeTime(GetExpire(result, option, context))));
        }
        /// <summary>
        /// 根据应用程序配置,创建任务调度管理器。
        /// </summary>
        /// <param name="serviceProvider">应用程序服务提供者实例。</param>
        /// <param name="configName">应用程序配置项的名称。</param>
        /// <returns><paramref name="configName"/>缺省时,如果应用程序未配置,则为 <see cref="DefaultTaskScheduler"/>,否则为配置项对应的 <see cref="ITaskScheduler"/> 实例。</returns>
        private static ITaskScheduler CreateScheduler(IServiceProvider serviceProvider, string configName = null)
        {
            ITaskScheduler            manager;
            IConfigurationSettingItem setting = null;
            var section = ConfigurationUnity.GetSection <TaskScheduleConfigurationSection>();

            if (section != null && section.Factory != null)
            {
                manager = ConfigurationUnity.Cached <ITaskScheduler>($"TaskScheduler_{configName ?? "default"}", serviceProvider,
                                                                     () => section.Factory.CreateInstance(serviceProvider, configName) as ITaskScheduler);

                if (manager != null)
                {
                    return(manager);
                }
            }

            if (string.IsNullOrEmpty(configName))
            {
                if (section == null || (setting = section.GetDefault()) == null)
                {
                    return(serviceProvider != null ?
                           new DefaultTaskScheduler(serviceProvider) : DefaultTaskScheduler.Instance);
                }
            }
            else if (section != null)
            {
                setting = section.GetSetting(configName);
            }

            if (setting == null)
            {
                return(null);
            }

            return(ConfigurationUnity.Cached <ITaskScheduler>($"TaskScheduler_{configName ?? "default"}", serviceProvider,
                                                              () => ConfigurationUnity.CreateInstance <TaskScheduleConfigurationSetting, ITaskScheduler>(serviceProvider, setting, s => s.SchedulerType, (s, t) => InitializeDefinitions(s, t))));
        }
Beispiel #6
0
        /// <summary>
        /// 使用引号标识符格式化表名称或列名称。
        /// </summary>
        /// <param name="syntax"></param>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string FormatByQuote(ISyntaxProvider syntax, string name)
        {
            if (syntax == null)
            {
                return(name);
            }

            var section = ConfigurationUnity.GetSection <GlobalConfigurationSection>();

            if ((section == null ||
                 (!section.Options.AttachQuote && name.IndexOf(' ') == -1) || name.Length == 0 || syntax.Quote == null || syntax.Quote.Length != 2))
            {
                return(name);
            }

            if (name.Length > 1 &&
                (name[0].ToString() == syntax.Quote[0] || name[name.Length - 1].ToString() == syntax.Quote[1]))
            {
                return(name);
            }

            return(string.Format("{0}{1}{2}", syntax.Quote[0], name, syntax.Quote[1]));
        }
Beispiel #7
0
        /// <summary>
        /// 尝试获取指定表达式的缓存。
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="func">当缓存不存在时,创建缓存数据的函数。</param>
        /// <returns></returns>
        internal static Expression <Func <IDatabase, object> > TryGet(Expression expression, Func <Expression <Func <IDatabase, object> > > func)
        {
            if (!CachaebleChecker.Check(expression))
            {
                return(func());
            }

            var section = ConfigurationUnity.GetSection <TranslatorConfigurationSection>();
            var option  = section == null ? TranslateOptions.Default : section.Options;

            if (!option.ParseCacheEnabled)
            {
                return(func());
            }

            ClearExpiredKeys();

            var lazy = new Lazy <CacheItem>(() => new CacheItem
            {
                Expression = func(),
                Expired    = DateTime.Now.AddSeconds(option.ParseCacheExpired)
            });

            var cacheKey = GetKey(expression);
            var result   = cache.GetOrAdd(cacheKey, k => lazy.Value);

            //在现有的表达式中查找 IDataSegment,去替换缓存中的 IDataSegment
            //原因是前端需要获得分页信息,如果不进行替换,将无法返回信息
            var segment = SegmentFinder.Find(expression);

            if (segment != null)
            {
                result.Expression = (Expression <Func <IDatabase, object> >)SegmentReplacer.Repalce(result.Expression, segment);
            }

            return(result.Expression);
        }
Beispiel #8
0
        /// <summary>
        /// 尝试获取指定表达式的缓存。
        /// </summary>
        /// <param name="expression"></param>
        /// <param name="func">当缓存不存在时,创建缓存数据的函数。</param>
        /// <returns></returns>
        internal static Delegate TryGetDelegate(Expression expression, Func <LambdaExpression> func)
        {
            if (!CachaebleChecker.Check(expression))
            {
                return(func().Compile());
            }

            var section = ConfigurationUnity.GetSection <TranslatorConfigurationSection>();
            var option  = section == null ? TranslateOptions.Default : section.Options;

            if (!option.ParseCacheEnabled)
            {
                return(func().Compile());
            }

            ClearExpiredKeys();

            var lazy = new Lazy <CacheItem>(() =>
            {
                //将表达式内的 Segment 替换成参数
                var segParExp = Expression.Parameter(typeof(IDataSegment), "g");
                var lambdaExp = func() as LambdaExpression;
                var newExp    = SegmentReplacer.Repalce(lambdaExp.Body, segParExp);
                lambdaExp     = Expression.Lambda(newExp, lambdaExp.Parameters[0], segParExp);

                return(new CacheItem
                {
                    Delegate = lambdaExp.Compile(),
                    Expired = DateTime.Now.AddSeconds(option.ParseCacheExpired)
                });
            });

            var cacheKey = GetKey(expression);
            var result   = cache.GetOrAdd(cacheKey, k => lazy.Value);

            return(result.Delegate);
        }
        /// <summary>
        /// 根据应用程序配置,创建文本序列化器。
        /// </summary>
        /// <param name="serviceProvider">应用程序服务提供者实例。</param>
        /// <param name="configName">应用程序配置项的名称。</param>
        /// <returns></returns>
        private static ISerializer CreateSerializer(IServiceProvider serviceProvider, string configName = null)
        {
            ISerializer serializer;
            IConfigurationSettingItem setting = null;
            var section = ConfigurationUnity.GetSection <SerializerConfigurationSection>();

            if (section != null && section.Factory != null)
            {
                serializer = ConfigurationUnity.Cached <ISerializer>($"Serializer_{configName}", serviceProvider,
                                                                     () => section.Factory.CreateInstance(serviceProvider, configName) as ISerializer);

                if (serializer != null)
                {
                    return(serializer);
                }
            }

            if (string.IsNullOrEmpty(configName))
            {
                if (section == null || (setting = section.GetDefault()) == null)
                {
                    return(null);
                }
            }
            else if (section != null)
            {
                setting = section.GetSetting(configName);
            }

            if (setting == null)
            {
                return(null);
            }

            return(ConfigurationUnity.Cached <ISerializer>($"Serializer_{configName}", serviceProvider,
                                                           () => ConfigurationUnity.CreateInstance <SerializerConfigurationSetting, ISerializer>(serviceProvider, setting, s => s.SerializerType)));
        }
Beispiel #10
0
        static ThemeManager()
        {
            var section = ConfigurationUnity.GetSection <ThemeConfigurationSection>();

            if (section != null)
            {
                if (section.TabControlRedererType != null)
                {
                    BaseRenderer = section.BaseRedererType.New <BaseRenderer>();
                }

                if (section.TreeListRedererType != null)
                {
                    TreeListRenderer = section.TreeListRedererType.New <TreeListRenderer>();
                }

                if (section.TabControlRedererType != null)
                {
                    //TabControlRenderer = section.TabControlRedererType.New<TabControlRenderer>();
                }
            }

            if (BaseRenderer == null)
            {
                BaseRenderer = new BaseRenderer();
            }

            if (TreeListRenderer == null)
            {
                TreeListRenderer = new TreeListRenderer();
            }

            //if (TabControlRenderer == null)
            {
                //TabControlRenderer = new TabControlRenderer();
            }
        }
        /// <summary>
        /// 根据应用程序配置,创建缓存管理器。
        /// </summary>
        /// <param name="serviceProvider">应用程序服务提供者实例。</param>
        /// <param name="configName">应用程序配置项的名称。</param>
        /// <returns><paramref name="configName"/>缺省时,如果应用程序未配置,则为 <see cref="MemoryCacheManager"/>,否则为配置项对应的 <see cref="ICacheManager"/> 实例。</returns>
        private static ICacheManager CreateManager(IServiceProvider serviceProvider, string configName = null)
        {
            ICacheManager             manager;
            IConfigurationSettingItem setting = null;
            var section = ConfigurationUnity.GetSection <CachingConfigurationSection>();

            if (section != null && section.Factory != null)
            {
                manager = ConfigurationUnity.Cached <ICacheManager>($"CacheManager_{configName}", serviceProvider,
                                                                    () => section.Factory.CreateInstance(serviceProvider, configName) as ICacheManager);
                if (manager != null)
                {
                    return(manager);
                }
            }

            if (string.IsNullOrEmpty(configName))
            {
                if (section == null || (setting = section.GetDefault()) == null)
                {
                    return(serviceProvider != null ?
                           new MemoryCacheManager(serviceProvider) : MemoryCacheManager.Instance);
                }
            }
            else if (section != null)
            {
                setting = section.GetSetting(configName);
            }

            if (setting == null)
            {
                return(null);
            }

            return(ConfigurationUnity.Cached <ICacheManager>($"CacheManager_{configName}", serviceProvider,
                                                             () => ConfigurationUnity.CreateInstance <CachingConfigurationSetting, ICacheManager>(serviceProvider, setting, s => s.CacheType)));
        }
        /// <summary>
        /// 根据应用程序配置,创建缓存管理器。
        /// </summary>
        /// <param name="configName">应用程序配置项的名称。</param>
        /// <returns><paramref name="configName"/>缺省时,如果应用程序未配置,则为 <see cref="MemoryCacheManager"/>,否则为配置项对应的 <see cref="ICacheManager"/> 实例。</returns>
        public static ICacheManager CreateManager(string configName = null)
        {
            ICacheManager manager;
            CachingConfigurationSetting setting = null;
            var section = ConfigurationUnity.GetSection <CachingConfigurationSection>();

            if (section != null && section.Factory != null)
            {
                manager = section.Factory.CreateInstance(configName) as ICacheManager;
                if (manager != null)
                {
                    return(manager);
                }
            }

            if (string.IsNullOrEmpty(configName))
            {
                if (section == null || section.Default == null)
                {
                    return(MemoryCacheManager.Instance);
                }

                setting = section.Default;
            }
            else if (section != null)
            {
                setting = section.Settings[configName];
            }

            if (setting == null || setting.CacheType == null)
            {
                return(null);
            }

            return(CreateBySetting(setting));
        }
Beispiel #13
0
        /// <summary>
        /// 根据应用程序配置,创建一个分布式锁。
        /// </summary>
        /// <param name="serviceProvider">应用程序服务提供者实例。</param>
        /// <param name="configName">应用程序配置项的名称。</param>
        /// <returns><paramref name="configName"/>为配置项对应的 <see cref="IDistributedLocker"/> 实例。</returns>
        private static IDistributedLocker CreateLocker(IServiceProvider serviceProvider, string configName = null)
        {
            IDistributedLocker        locker;
            IConfigurationSettingItem setting = null;
            var section = ConfigurationUnity.GetSection <LockerConfigurationSection>();

            if (section != null && section.Factory != null)
            {
                locker = ConfigurationUnity.Cached <IDistributedLocker>($"Locker_{configName}", serviceProvider,
                                                                        () => section.Factory.CreateInstance(serviceProvider, configName) as IDistributedLocker);
                if (locker != null)
                {
                    return(locker);
                }
            }

            if (string.IsNullOrEmpty(configName))
            {
                if (section == null || (setting = section.GetDefault()) == null)
                {
                    throw new NotSupportedException();
                }
            }
            else if (section != null)
            {
                setting = section.GetSetting(configName);
            }

            if (setting == null)
            {
                return(null);
            }

            return(ConfigurationUnity.Cached <IDistributedLocker>($"Locker_{configName}", serviceProvider,
                                                                  () => ConfigurationUnity.CreateInstance <LockerConfigurationSetting, IDistributedLocker>(serviceProvider, setting, s => s.LockerType)));
        }
Beispiel #14
0
        private TranslateOptions GetTranslateOptions()
        {
            var section = ConfigurationUnity.GetSection <TranslatorConfigurationSection>();

            return((section != null ? section.Options : Translators.TranslateOptions.Default).Clone());
        }
Beispiel #15
0
        private DefaultLogger()
        {
            var section = ConfigurationUnity.GetSection <LoggingConfigurationSection>();

            level = section == null ? LogLevel.Default : section.Level;
        }
        public void Test1()
        {
            var s = ConfigurationUnity.GetSection <Test1ConfigurationSection>();

            Console.WriteLine(s.Server);
        }
Beispiel #17
0
        /// <summary>
        /// 初始化 <see cref="CacheManager"/> 类的新实例。
        /// </summary>
        /// <param name="serviceProvider"></param>
        /// <param name="options"></param>
        public CacheManager(IServiceProvider serviceProvider, IOptionsMonitor <RedisCachingOptions> options)
            : base(serviceProvider)
        {
            RedisConfigurationSetting setting = null;
            var optValue = options.CurrentValue;

            if (!optValue.IsConfigured())
            {
                var section      = ConfigurationUnity.GetSection <CachingConfigurationSection>();
                var matchSetting = section.Settings.FirstOrDefault(s => s.Value.CacheType == typeof(CacheManager)).Value;
                if (matchSetting != null && section.GetSetting(matchSetting.Name) is ExtendConfigurationSetting extSetting)
                {
                    setting = (RedisConfigurationSetting)extSetting.Extend;
                }
                else
                {
                    throw new InvalidOperationException($"未发现与 {typeof(CacheManager).FullName} 相匹配的配置。");
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(optValue.ConfigName))
                {
                    var section = ConfigurationUnity.GetSection <CachingConfigurationSection>();
                    if (section != null && section.GetSetting(optValue.ConfigName) is ExtendConfigurationSetting extSetting)
                    {
                        setting = (RedisConfigurationSetting)extSetting.Extend;
                    }
                    else
                    {
                        throw new InvalidOperationException($"无效的配置节: {optValue.ConfigName}。");
                    }
                }
                else
                {
                    setting = new RedisConfigurationSetting
                    {
                        Password         = optValue.Password,
                        ConnectionString = optValue.ConnectionString,
                        DefaultDb        = optValue.DefaultDb,
                        DbRange          = optValue.DbRange,
                        KeyRule          = optValue.KeyRule,
                        ConnectTimeout   = optValue.ConnectTimeout,
                        LockTimeout      = optValue.LockTimeout,
                        SyncTimeout      = optValue.SyncTimeout,
                        WriteBuffer      = optValue.WriteBuffer,
                        PoolSize         = optValue.PoolSize,
                        SerializerType   = optValue.SerializerType,
                        Ssl             = optValue.Ssl,
                        Twemproxy       = optValue.Twemproxy,
                        SlidingTime     = optValue.SlidingTime,
                        IgnoreException = optValue.IgnoreException
                    };

                    RedisHelper.ParseHosts(setting, optValue.Hosts);
                }
            }

            if (setting != null)
            {
                (this as IConfigurationSettingHostService).Attach(setting);
            }
        }
        public void Test2()
        {
            var s = ConfigurationUnity.GetSection <Test2ConfigurationSection>();

            Console.WriteLine(s.Settings["a1"].Method);
        }
        private TranslateOptions GetTranslateOptions()
        {
            var section = ConfigurationUnity.GetSection <TranslatorConfigurationSection>();

            return(section?.Options ?? TranslateOptions.Default);
        }