Beispiel #1
0
        public void ConfigService(IServiceCollection services)
        {
            logger.Info($"AppId : {AppSetting.GetInstance().AppId}");
            logger.Info("Start XServiceHandler");
            var handlerList = AppSetting.GetInstance().ServiceHandler;

            if (handlerList == null || handlerList.Count == 0)
            {
                throw new FrameworkException(ErrorCode.InvalidXServiceHandler,
                                             $"ServiceHandler node is not configured, system can not process any dynamic request");
            }

            foreach (var typeName in handlerList)
            {
                logger.Info($"Initialize service handler : {typeName}");
                var instance = GetServiceHandler(typeName);
                // 初始化XService的各项服务
                instance.Init(services);

                var router = instance.Router.ToLower().Trim();

                if (handlers.ContainsKey(router))
                {
                    logger.Warn($"Service handler '{typeName}' is duplicate, {handlers[router].GetType().FullName} is loaded, "
                                + $"They have same router infomation : {router}, current service will not started");
                    continue;
                }

                services.AddSingleton(instance.GetType(), instance);
                handlers.Add(instance.Router.Trim().ToLower(), instance.GetType());
                logger.Info($"Service handler {instance.Name}({instance.GetType().FullName})" +
                            $" loaded successfully, router path : {router}");
            }
        }
 private void BeforeUILoad(object sender, EventArgs e)
 {
     AppContext.GetInstance().SetVal(typeof(CmdDispatcher), new CmdDispatcher());
     AppContext.GetInstance().SetVal(typeof(AppSetting), AppSetting.GetInstance());
     AppContext.GetInstance().SetVal(typeof(NoteSetting), AbstractSetting <NoteSetting> .CurSetting);
     AppContext.GetInstance().SetVal(typeof(SharpAcquirerFactory), new SharpAcquirerFactory());
 }
 public SqliteDatabaseContext()
 {
     connectionString = AppSetting.GetInstance().GetSqliteConnectionString();
     if (string.IsNullOrEmpty(connectionString))
     {
         throw new ArgumentException("数据库连接不能为空");
     }
 }
Beispiel #4
0
 public void ConnectionString()
 {
     try
     {
         string connectionString = AppSetting.GetInstance().GetSqliteConnectionString();
         Assert.IsTrue(!string.IsNullOrEmpty(connectionString), "连接字符串为空");
     }
     catch (Exception ex)
     {
         Assert.IsTrue(1 == 0, ex.Message);
     }
 }
        /// <summary>
        /// 组装Soa头部信息
        /// </summary>
        /// <returns></returns>
        private SoaRequestHeaderType BuildSoaHeader()
        {
            AppSetting setting = AppSetting.GetInstance();

            // 重新设定Header
            return(new SoaRequestHeaderType()
            {
                AppId = setting.AppId,
                Enviroment = setting.Enviroment?.EnvironmentName,
                TransactionId = Guid.NewGuid().ToString()
            });
        }
Beispiel #6
0
        private string GetConfigurationServerUri()
        {
            var enviroment = AppSetting.GetInstance().Enviroment;

            var name = "Development";

            if (enviroment != null && !string.IsNullOrEmpty(enviroment.EnvironmentName))
            {
                name = enviroment.EnvironmentName;
            }

            return($"http://{name.ToLower()}.configuration.colorstudio.com.cn");
        }
Beispiel #7
0
        /// <summary>
        /// 打开一个新的日志文件
        /// </summary>
        private static void OpenFile()
        {
            var logInfo = AppSetting.GetInstance().LocalLogInfo;

            // 创建目录
            var dir = Directory.CreateDirectory(logInfo.LogPath);

            // 如果日志前缀没有定义, 使用AppId作为前缀
            var prefix   = logInfo.Prefix ?? AppSetting.GetInstance().AppId;
            var filename = $"{prefix}.{DateTime.Now.ToString("yyyyMMdd.HHmmss.fff")}.log";

            writer = new StreamWriter(Path.Combine(dir.FullName, filename))
            {
                AutoFlush = true
            };
        }
        public SecurityTaskRepository Create(DatabaseContext dbContext)
        {
            string dbType = AppSetting.GetInstance().GetDatabaseType();

            if (dbType == "sqlite")
            {
                return(new SecurityTaskRepositorySqlite(dbContext));
            }
            else if (dbType == "mssql")
            {
                return(new SecurityTaskRepositoryMSSql(dbContext));
            }
            else
            {
                throw new ArgumentException("数据库暂时不支持");
            }
        }
        public SecurityDayQuotationRepository Create()
        {
            string dbType = AppSetting.GetInstance().GetDatabaseType();

            if (dbType == "sqlite")
            {
                return(new SecurityDayQuotationRepositorySqlite());
            }
            else if (dbType == "mssql")
            {
                return(new SecurityDayQuotationRepositoryMSSql());
            }
            else
            {
                throw new ArgumentException("数据库类型暂不支持");
            }
        }
Beispiel #10
0
        public DatabaseContext CreateDatabaseContext()
        {
            string databaseType = AppSetting.GetInstance().GetDatabaseType();

            if (databaseType == "mssql")
            {
                return(new SqlDatabaseContext());
            }
            else if (databaseType == "sqlite")
            {
                return(new SqliteDatabaseContext());
            }
            else
            {
                throw new ArgumentException("配置文件中数据库类型不支持");
            }
        }
        /// <summary>
        /// 判断类型是否符合Soa服务规范,包括
        /// 1. 不能是抽象类
        /// 2. 实现了ISoaService接口
        /// 3. 定义了SoaService属性
        /// </summary>
        /// <param name="type"></param>
        /// <returns></returns>
        private bool IsSoaTypeValid(Type type)
        {
            // 必须是引用类型,不能为抽象类
            if (!type.IsClass || type.IsAbstract)
            {
                return(false);
            }

            if (!Array.Exists(type.GetInterfaces(), p => p.IsGenericType && p.GetGenericTypeDefinition() == typeof(ISoaService <,>)))
            {
                // 必须实现SoaServiceAttribute属性,而且不能继承与父类
                if (!type.IsDefined(typeof(SoaAttribute), false))
                {
                    return(false);
                }
            }

            // 获取SoaService特性定义
            SoaAttribute[] attrs = (SoaAttribute[])type.GetCustomAttributes(typeof(SoaAttribute), false);

            if (attrs == null || attrs.Length == 0)
            {
                return(false);
            }

            // 获取第一个SoaServiceAttribute
            var attr = attrs[0];

            // 必须定义Service和Operation
            if (string.IsNullOrWhiteSpace(attr.Service) || string.IsNullOrWhiteSpace(attr.Operation))
            {
                logger.Warn($"Found soa service class : {type.FullName}, but either service({attr.Service}) " +
                            $"or operation({attr.Operation}) attribute is not defined.");
                return(false);
            }

            if (!AppSetting.GetInstance().SoaServiceListener.Exists
                    (p => p.StartsWith(attr.Service + SOA_LISTENER_SEPERATOR, StringComparison.InvariantCultureIgnoreCase)))
            {
                logger.Debug($"Found soa service : {attr.Service}, but this service listener is not registered.");
                return(false);
            }

            return(true);
        }
Beispiel #12
0
        /// <summary>
        /// 保存日志的范围
        /// </summary>
        /// <param name="currentSize"></param>
        /// <param name="entity"></param>
        /// <param name="prefix"></param>
        /// <returns></returns>
        private static void LogScopes(LogEntity entity, string prefix)
        {
            if (entity.LogTags != null && entity.LogTags.Count > 0)
            {
                foreach (var item in entity.LogTags)
                {
                    if (AppSetting.GetInstance().LocalLogInfo.IgnoreScopes.Contains(item.Key))
                    {
                        continue;
                    }
                    sb.Append($"[{item.Key}={item.Value}],");
                }
                ;
            }

            sb.Append($"[category={entity.CategoryName}]");

            Log(sb.ToString());
        }
Beispiel #13
0
        private void RegisterAssembly(ContainerBuilder builder)
        {
            var assemblies = AppSetting.GetInstance().AutofacAssemblies;

            if (assemblies == null || assemblies.Count == 0)
            {
                return;
            }

            foreach (var assemblyName in assemblies)
            {
                builder.RegisterAssemblyTypes(Assembly.Load(assemblyName))
                .Where(p => p.FullName.StartsWith("XFramework"))
                .PublicOnly()
                .AsSelf()
                .AsImplementedInterfaces()
                .SingleInstance()
                .PropertiesAutowired();
            }
        }
Beispiel #14
0
        /// <summary>
        /// 将XFramework架构添加到服务中,便于引入Ioc
        /// </summary>
        /// <param name="services"></param>
        /// <returns></returns>
        public static IServiceCollection AddXServiceHandler
            (this IServiceCollection services, IConfiguration configuration, IHostingEnvironment environment)
        {
            var setting = AppSetting.GetInstance();

            // 初始化配置文件
            configuration.Bind(setting);
            setting.Enviroment = environment;

            try
            {
                // 初始化
                ServiceHandlerProvider.GetInstance().ConfigService(services);
            }
            catch (Exception e)
            {
                logger.Error(e, "Service handler start up failure");
                // 销毁LogProvider,确保日志记录完整
                LogProvider.GetInstance().Dispose();
                throw e;
            }

            return(services);
        }
Beispiel #15
0
        public static IDalClient GetClient(string dbName)
        {
            if (string.IsNullOrWhiteSpace(dbName))
            {
                throw new DalException(ErrorCode.InitDalClientFailed,
                                       "Database name is empty");
            }

            // 每一个数据库逻辑名称,对应一个Dal的实例
            var logicName = dbName.Trim().ToLower();

            return(clients.GetOrAdd(logicName, p =>
            {
                var setting = AppSetting.GetInstance();
                if (setting.DatabaseSets == null || setting.DatabaseSets.Count == 0)
                {
                    throw new DalException(ErrorCode.InitDalClientFailed,
                                           "Initialize dal client failed, could not find databasesets in appsettings.json");
                }

                var set = setting.DatabaseSets.Find(x => logicName.Equals(x.Name, StringComparison.InvariantCultureIgnoreCase)) ??
                          throw new DalException(ErrorCode.InitDalClientFailed,
                                                 $"Initialize dal client failed, invalid database name : {dbName}");

                logger.Info($"Create dal client, logic name : {set.Name}, database type : {set.DatabaseType}");

                if (dalClients.ContainsKey(set.DatabaseType) == false)
                {
                    logger.Error($"Unsupported database type : {set.DatabaseType} of {set.Name}");
                    throw new DalException(ErrorCode.UnsupportedDatabaseType,
                                           $"Initialize dal client failed, invalid database name : {dbName}");
                }

                return (IDalClient)Activator.CreateInstance(dalClients[set.DatabaseType], set);
            }));
        }
        public void ConfigService(IServiceCollection services)
        {
            var soaServices = AppSetting.GetInstance().SoaServiceListener;

            if (soaServices == null || soaServices.Count == 0)
            {
                logger.Warn("None of soa service listener was registered in appsetting.json file, " +
                            "please check 'SoaServiceListener' node");
                return;
            }

            foreach (var service in soaServices)
            {
                if (string.IsNullOrEmpty(service))
                {
                    throw new FrameworkException(ErrorCode.InvalidSoaListener,
                                                 "Soa service listener is empty, please check appsetting.json file");
                }

                var value = service.Split(SOA_LISTENER_SEPERATOR);
                if (value.Length != SOA_LISTENER_DEF_LEN)
                {
                    throw new FrameworkException(ErrorCode.InvalidSoaListener,
                                                 "Invalid soa service listener, the correct format is [listener],[Assembly]");
                }

                // SoaServiceListener 正确的注册格式为 : [serviceId], [AssemblyName]
                var serviceId    = value[0].Trim().ToLower();
                var assemblyName = value[1].Trim();

                var assembly = Assembly.Load(assemblyName);
                if (assembly == null)
                {
                    throw new FrameworkException(ErrorCode.InvalidSoaListener,
                                                 $"Invalid soa service listener, unable to load assembly {value[1].Trim()}");
                }

                foreach (var type in assembly.GetExportedTypes())
                {
                    var entity = GetSoaServiceEntity(type);

                    if (entity == null)
                    {
                        continue;
                    }

                    // 配置中的ServiceId信息和实际代码中的信息不一致, 则忽略当前的Soa实现.
                    if (!serviceId.Equals(entity.Service, StringComparison.InvariantCultureIgnoreCase))
                    {
                        logger.Warn($"Service Id is not matched, found other soa service " +
                                    $"{entity.Service}.{entity.Operation} defined in assembly {assemblyName}." +
                                    $"Current service Id is : {serviceId}, This service will be ignored");
                        continue;
                    }

                    // 保存Soa服务的信息
                    SaveSoaService(entity, services);
                }

                // Soa self regisition
                RegisterService(serviceId, AppSetting.GetInstance().InstanceId);
            }
        }
 private string GetConfigurationServerUri()
 {
     return($"http://{AppSetting.GetInstance().Enviroment.EnvironmentName.ToLower()}.configuration.colorstudio.com.cn");
 }