示例#1
0
        /// <summary>
        /// 异步修改一条数据
        /// </summary>
        /// <param name="t">添加的实体</param>
        /// <param name="host">mongodb连接信息</param>
        /// <returns></returns>
        public static async Task <UpdateResult> UpdateAsync(MongodbHost host, T t, string id)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //修改条件
                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                //要修改的字段
                var list = new List <UpdateDefinition <T> >();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (item.Name.ToLower() == "id")
                    {
                        continue;
                    }
                    list.Add(Builders <T> .Update.Set(item.Name, item.GetValue(t)));
                }
                var updatefilter = Builders <T> .Update.Combine(list);

                return(await client.UpdateOneAsync(filter, updatefilter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#2
0
        /// <summary>
        /// 异步批量修改数据
        /// </summary>
        /// <param name="dic">要修改的字段</param>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">修改条件</param>
        /// <returns></returns>
        public static async Task <UpdateResult> UpdateManayAsync(MongodbHost host, Dictionary <string, string> dic, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                T t = new T();
                //要修改的字段
                var list = new List <UpdateDefinition <T> >();
                foreach (var item in t.GetType().GetProperties())
                {
                    if (!dic.ContainsKey(item.Name))
                    {
                        continue;
                    }
                    var value = dic[item.Name];
                    list.Add(Builders <T> .Update.Set(item.Name, value));
                }
                var updatefilter = Builders <T> .Update.Combine(list);

                return(await client.UpdateManyAsync(filter, updatefilter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#3
0
        /// <summary>
        /// 获取mongodb实例
        /// </summary>
        /// <param name="host">连接字符串,库,表</param>
        /// <returns></returns>
        public static IMongoCollection <T> MongodbInfoClient(MongodbHost host)
        {
            var client   = new MongoClient(host.Connection);
            var dataBase = client.GetDatabase(host.DataBase);

            return(dataBase.GetCollection <T>(string.IsNullOrEmpty(host.Table) ? typeof(T).Name : host.Table));
        }
        /// <summary>
        /// 获取mongodb实例
        /// </summary>
        public static IMongoCollection <T> MongodbInfoClient(MongodbHost host)
        {
            try
            {
                var hosts   = host.DBHost.Split(new char[] { '|' });
                var servers = new List <MongoServerAddress>();

                foreach (var h in hosts)
                {
                    servers.Add(new MongoServerAddress(h, int.Parse(host.DBPort)));
                }
                var mc = new MongoClient(new MongoClientSettings
                {
                    Servers     = servers,
                    Credentials = new List <MongoCredential> {
                        MongoCredential.CreateCredential("admin", host.DBUser, host.DBPwd)
                    },
                    SocketTimeout = TimeSpan.FromSeconds(double.Parse(host.DBTimeOut))
                });

                var Database = mc.GetDatabase(host.DBName);
                return(Database.GetCollection <T>(host.Table));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#5
0
        public IList <string> ListMongoDataBase(string datasourceCode)
        {
            DmeDataSource dmeDataSource = IsMongodbAndReturn(datasourceCode);
            MongodbHost   host          = JsonConvert.DeserializeObject <MongodbHost>(dmeDataSource.Connection);

            return(MongodbManager <object> .ListDataBases(host.ConnectionString));
        }
示例#6
0
        /// <summary>
        /// 异步根据id查询一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="id">objectid</param>
        /// <returns></returns>
        public static async Task <T> FindOneAsync(MongodbHost host, string id, string[] field = null)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    return(await client.Find(filter).FirstOrDefaultAsync());
                }

                //制定查询字段
                var fieldList = new List <ProjectionDefinition <T> >();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders <T> .Projection.Include(field[i].ToString()));
                }
                var projection = Builders <T> .Projection.Combine(fieldList);

                fieldList?.Clear();
                return(await client.Find(filter).Project <T>(projection).FirstOrDefaultAsync());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#7
0
 public UserService(IBookstoreDatabaseSettings settings)
 {
     mongodbHost = new MongodbHost()
     {
         Connection = settings.ConnectionString,
         DataBase   = settings.DatabaseName,
         Table      = "User"
     };
 }
示例#8
0
        public IList <string> ListMongoCollection(string datasourceCode)
        {
            DmeDataSource dmeDataSource = IsMongodbAndReturn(datasourceCode);
            MongodbHost   host          = JsonConvert.DeserializeObject <MongodbHost>(dmeDataSource.Connection);

            if (string.IsNullOrEmpty(host.DataBase))
            {
                throw new BusinessException((int)EnumSystemStatusCode.DME_FAIL, "mongodb的DataBase不能为空");
            }
            return(MongodbManager <object> .ListCollections(host.ConnectionString, host.DataBase));
        }
示例#9
0
        public static void UnitTest()
        {
            MongodbHost host = null;
            //1.批量修改,修改的条件
            var time = DateTime.Now;
            var list = new List <FilterDefinition <PhoneEntity> >
            {
                Builders <PhoneEntity> .Filter.Lt("AddTime", time.AddDays(5)),
                Builders <PhoneEntity> .Filter.Gt("AddTime", time)
            };
            var filter = Builders <PhoneEntity> .Filter.And(list);

            //2.要修改的字段内容
            var dic = new Dictionary <string, string>
            {
                { "UseAge", "168" },
                { "Name", "朝阳" }
            };
            //3.批量修改
            var kk = MongodbHelper <PhoneEntity> .UpdateManay(host, dic, filter);


            //根据条件查询集合
            time = DateTime.Now;
            list = new List <FilterDefinition <PhoneEntity> >
            {
                Builders <PhoneEntity> .Filter.Lt("AddTime", time.AddDays(20)),
                Builders <PhoneEntity> .Filter.Gt("AddTime", time)
            };
            filter = Builders <PhoneEntity> .Filter.And(list);

            //2.查询字段
            var field = new[] { "Name", "Price", "AddTime" };
            //3.排序字段
            var sort = Builders <PhoneEntity> .Sort.Descending("AddTime");

            var res = MongodbHelper <PhoneEntity> .FindList(host, filter, field, sort);


            //分页查询,查询条件
            time = DateTime.Now;
            list = new List <FilterDefinition <PhoneEntity> >
            {
                Builders <PhoneEntity> .Filter.Lt("AddTime", time.AddDays(400)),
                Builders <PhoneEntity> .Filter.Gt("AddTime", time)
            };
            filter = Builders <PhoneEntity> .Filter.And(list);

            //排序条件
            sort = Builders <PhoneEntity> .Sort.Descending("AddTime");

            res = MongodbHelper <PhoneEntity> .FindListByPage(host, filter, 2, 10, out long count, null, sort);
        }
示例#10
0
        /// <summary>
        /// 异步删除多条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">删除的条件</param>
        /// <returns></returns>
        public static async Task <DeleteResult> DeleteManyAsync(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(await client.DeleteManyAsync(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#11
0
        /// <summary>
        /// 异步根据条件获取总数
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">条件</param>
        /// <returns></returns>
        public static async Task <long> CountAsync(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(await client.CountAsync(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#12
0
        /// <summary>
        /// 删除一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">删除的条件</param>
        /// <returns></returns>
        public static DeleteResult DeleteMany(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(client.DeleteMany(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#13
0
        /// <summary>
        /// 根据条件获取总数
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">条件</param>
        /// <returns></returns>
        public static long Count(MongodbHost host, FilterDefinition <T> filter)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                return(client.Count(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#14
0
        //private readonly IMongoCollection<T> client;

        //public BaseService(IBookstoreDatabaseSettings settings)
        //{
        //    client = new MongodbClient<T>().MongodbInfoClient(
        //        new MongodbHost()
        //        {
        //            Connection = settings.ConnectionString,
        //            DataBase = settings.DatabaseName,
        //            Table = settings.BooksCollectionName
        //        }
        //    );

        //}
        #region +Add 添加一条数据
        /// <summary>
        /// 添加一条数据
        /// </summary>
        /// <param name="t">添加的实体</param>
        /// <param name="host">mongodb连接信息</param>
        /// <returns></returns>
        public int Add(MongodbHost host, T t)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                client.InsertOne(t);
                return(1);
            }
            catch
            {
                return(0);
            }
        }
示例#15
0
        /// <summary>
        /// 批量插入
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="t">实体集合</param>
        /// <returns></returns>
        public static int InsertMany(MongodbHost host, List <T> t)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                client.InsertMany(t);
                return(1);
            }
            catch (Exception ex)
            {
                return(0);
            }
        }
示例#16
0
        /// <summary>
        /// 删除一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="id">objectId</param>
        /// <returns></returns>
        public static DeleteResult Delete(MongodbHost host, string id)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                return(client.DeleteOne(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#17
0
        /// <summary>
        /// 异步添加一条数据
        /// </summary>
        /// <param name="t">添加的实体</param>
        /// <param name="host">mongodb连接信息</param>
        /// <returns></returns>
        public static async Task <bool> AddAsync(MongodbHost host, T t)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                await client.InsertOneAsync(t);

                return(true);
            }
            catch
            {
                return(false);
            }
        }
示例#18
0
        /// <summary>
        /// 异步批量插入
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="t">实体集合</param>
        /// <returns></returns>
        public static async Task <int> InsertManyAsync(MongodbHost host, List <T> t)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                await client.InsertManyAsync(t);

                return(1);
            }
            catch
            {
                return(0);
            }
        }
示例#19
0
        /// <summary>
        /// 异步删除一条数据
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="id">objectId</param>
        /// <returns></returns>
        public static async Task <DeleteResult> DeleteAsync(MongodbHost host, string id)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //修改条件
                FilterDefinition <T> filter = Builders <T> .Filter.Eq("_id", new ObjectId(id));

                return(await client.DeleteOneAsync(filter));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#20
0
        /// <summary>
        /// 查询集合
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">查询条件</param>
        /// <param name="field">Distinct字段</param>
        /// <returns></returns>
        public static List <string> Distinct(MongodbHost host, FilterDefinition <T> filter, string field = null)
        {
            try
            {
                FieldDefinition <T, string> fields = field;
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //制定查询字段
                //var fieldList = new List<ProjectionDefinition<T>>();
                //排序查询
                return(client.Distinct(fields, filter).ToList());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#21
0
        /// <summary>
        /// 分页查询集合
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">查询条件</param>
        /// <param name="pageIndex">当前页</param>
        /// <param name="pageSize">页容量</param>
        /// <param name="count">总条数</param>
        /// <param name="field">要查询的字段,不写时查询全部</param>
        /// <param name="sort">要排序的字段</param>
        /// <returns></returns>
        public static List <T> FindListByPage(MongodbHost host, FilterDefinition <T> filter, int pageIndex, int pageSize, out long count, string[] field = null, SortDefinition <T> sort = null)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                count = client.Count(filter);
                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        return(client.Find(filter).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
                    }
                    //进行排序
                    return(client.Find(filter).Sort(sort).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
                }

                //制定查询字段
                var fieldList = new List <ProjectionDefinition <T> >();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders <T> .Projection.Include(field[i].ToString()));
                }
                var projection = Builders <T> .Projection.Combine(fieldList);

                fieldList?.Clear();

                //不排序
                if (sort == null)
                {
                    return(client.Find(filter).Project <T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
                }

                //排序查询
                return(client.Find(filter).Sort(sort).Project <T>(projection).Skip((pageIndex - 1) * pageSize).Limit(pageSize).ToList());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#22
0
        public static List <T> Finds(MongodbHost host, FilterDefinition <T> filter, string field = null)
        {
            try
            {
                FieldDefinition <T, string> fields = field;
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //制定查询字段
                //var fieldList = new List<ProjectionDefinition<T>>();
                List <T> listFind = client.Find(filter).ToList();
                //var  infoList=listFind.AsQueryable();
                //Console.WriteLine(infoList.Count());
                return(listFind);
                //reutrn users;
                ////排序查询
                //return client.Find(filter).ToList();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#23
0
        /// <summary>
        /// 异步查询集合
        /// </summary>
        /// <param name="host">mongodb连接信息</param>
        /// <param name="filter">查询条件</param>
        /// <param name="field">要查询的字段,不写时查询全部</param>
        /// <param name="sort">要排序的字段</param>
        /// <returns></returns>
        public static async Task <List <T> > FindListAsync(MongodbHost host, FilterDefinition <T> filter, string[] field = null, SortDefinition <T> sort = null)
        {
            try
            {
                var client = MongodbClient <T> .MongodbInfoClient(host);

                //不指定查询字段
                if (field == null || field.Length == 0)
                {
                    if (sort == null)
                    {
                        return(await client.Find(filter).ToListAsync());
                    }
                    return(await client.Find(filter).Sort(sort).ToListAsync());
                }

                //制定查询字段
                var fieldList = new List <ProjectionDefinition <T> >();
                for (int i = 0; i < field.Length; i++)
                {
                    fieldList.Add(Builders <T> .Projection.Include(field[i].ToString()));
                }
                var projection = Builders <T> .Projection.Combine(fieldList);

                fieldList?.Clear();
                if (sort == null)
                {
                    return(await client.Find(filter).Project <T>(projection).ToListAsync());
                }
                //排序查询
                return(await client.Find(filter).Sort(sort).Project <T>(projection).ToListAsync());
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#24
0
 public DataSourceService(IRepository repository, MongodbHost host)
 {
     base.Repository = repository;
     this.mongoHost  = host;
 }
示例#25
0
        public Result Run()
        {
            IDictionary <string, Property> attributes = this.ruleStepMeta.ReadAttributes();
            string database   = Convert.ToString(attributes[nameof(this.ruleStepMeta.Database)].Value);
            string collection = Convert.ToString(attributes[nameof(this.ruleStepMeta.Collection)].Value);
            IList <MongoFieldDTO> mongoFields = (IList <MongoFieldDTO>)attributes[nameof(this.ruleStepMeta.MongoFields)].Value;

            if (0 == mongoFields?.Count)
            {
                return(new Result(EnumSystemStatusCode.DME_FAIL, "没有输出的字段信息,停止计算", null));
            }
            DmeDataSource dmeDataSource = (DmeDataSource)attributes[nameof(this.ruleStepMeta.Source)].Value;
            MongodbHost   mongodbHost   = JsonConvert.DeserializeObject <MongodbHost>(dmeDataSource.Connection);

            if (!string.IsNullOrEmpty(database))
            {
                mongodbHost.DataBase = database;
            }
            mongodbHost.Collection = collection;
            JObject json = new JObject
            {
                { new JProperty("TaskId", this.taskId) },
                { new JProperty("RuleStepId", this.step.Id) }
            };

            foreach (var item in mongoFields)
            {
                string fieldName = item.Name;
                if (0 == item.IsNeedPrecursor)
                {
                    LOG.Info($"当前[{item.Name}]为非前驱参数");
                    if (0 == item.IsUseName)
                    {
                        LOG.Info($"IsUseName为[{item.IsUseName}],将会使用NewName");
                        fieldName = item.NewName;
                    }
                    LOG.Info($"fieldName值为[{fieldName}]");
                    if (string.IsNullOrEmpty(fieldName))
                    {
                        LOG.Error("mongo输出字段名称为空,不能构建");
                        continue;
                    }
                    if (null == item.ConstantValue)
                    {
                        LOG.Error($"mongo输出字段[{fieldName}]的值不能为NULL");
                        continue;
                    }
                    json.Add(new JProperty(fieldName, item.ConstantValue));
                }
                else
                {
                    LOG.Info($"当前[{item.Name}]为前驱参数");
                    // 前驱参数
                    if (string.IsNullOrEmpty(item.Name) ||
                        !item.Name.ToString().Contains(":"))
                    {
                        throw new BusinessException((int)EnumSystemStatusCode.DME_ERROR, $"步骤[{step.SysCode}]的前驱参数[{item.Name}]无效");
                    }
                    string   preStepName      = item.Name.Split(":")[0];
                    string   preAttributeName = item.Name.Split(":")[1];
                    Property property         = base.GetStepAttributeValue(preStepName, preAttributeName);
                    if (null == property)
                    {
                        throw new BusinessException((int)EnumSystemStatusCode.DME_ERROR, $"步骤名[{preStepName}]的参数[{preAttributeName}]无效");
                    }
                    if (0 == item.IsUseName)
                    {
                        fieldName = item.NewName;
                    }
                    else
                    {
                        fieldName = preAttributeName;
                    }
                    if (string.IsNullOrEmpty(fieldName))
                    {
                        LOG.Error("mongo输出字段名称为空,不能构建");
                        continue;
                    }
                    if (null == property.Value)
                    {
                        LOG.Error($"mongo输出字段[{fieldName}]的值不能为NULL");
                        continue;
                    }
                    json.Add(new JProperty(fieldName, property.Value));
                }
            }
            // LOG.Info("JSON对象,方法ToJson:" + json.ToJson());
            // LOG.Info("JSON对象,方法ToString:" + json.ToString());
            // PS:不能使用json.ToJson()和json.ToBsonDocument构建一个BsonDocument,否则插入进去的实体对象不对;
            //      需要使用json.ToString()
            BsonDocument document = BsonDocument.Parse(json.ToString());

            MongodbHelper <BsonDocument> .Add(mongodbHost, document);

            return(new Result(EnumSystemStatusCode.DME_SUCCESS, $"模型[{step.ModelId}]的步骤[{step.SysCode}]运算完毕", null));
        }
示例#26
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddCors();
            services.AddMvc()
            .SetCompatibilityVersion(CompatibilityVersion.Version_2_1)
            .AddJsonOptions(options =>
            {
                options.SerializerSettings.MaxDepth = 2;
                options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
                // options.SerializerSettings.ContractResolver = new DefaultContractResolver();
                // options.SerializerSettings.DateFormatString = "yyyy-MM-dd";
            });

            // 分布式缓存
            services.AddDistributedMemoryCache();
            services.AddSession();

            services.AddDbContextPool <ZDDBContext>(option =>
            {
                option.UseSqlServer(Configuration.GetConnectionString("SqlServerConection"));
                // .UseQueryTrackingBehavior(QueryTrackingBehavior.NoTracking);
                option.UseLoggerFactory(_loggerFactory);
            });

            MongodbHost mongoDBConn = new MongodbHost();

            Configuration.GetSection("MongoDB").Bind(mongoDBConn);
            services.AddTransient <MongoDataBaseContext>(option =>
            {
                return(new MongoDataBaseContext(mongoDBConn));
            });

            RedisConfig redisConfig = new RedisConfig();

            Configuration.GetSection("RedisConfig").Bind(redisConfig);
            services.AddRedisClient(redisConfig);

            // 仓储注入都写在这里
            services.AddRepositoryService();
            _logger.LogInformation("Add Repo Services to service");
            // appsetting配置注入在这里
            services.AddConfigureService(Configuration);
            _logger.LogInformation("Add Configure Services to service");

            // Cookie验证
            // services.AddAuthentication(CookieAuthenticationDefaults.AuthenticationScheme).AddCookie(option =>
            // {
            //    option.LoginPath = "/api/account/login";
            // });

            // services.AddAuthorization(options =>
            // {
            //     options.AddPolicy(Permission.ArticleAudit, policy => policy.AddRequirements(new Authorization.PermissionAuthorizationRequirement(Permission.ArticleAudit)));
            //     options.AddPolicy("AdminOnly", policy => policy.RequireRole("admin"));                       //基于角色授权
            //     options.AddPolicy("ClaimAuthorization", policy => policy.RequireClaim("claimType", "value1", "value2")); //基于Claim授权
            // });

            // JWT验证
            JwtBearerConfig jwtBearerConfig = new JwtBearerConfig();

            Configuration.GetSection("JwtBearerConfig").Bind(jwtBearerConfig);
            services.AddAuthentication(option =>
            {
                option.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
                option.DefaultChallengeScheme    = JwtBearerDefaults.AuthenticationScheme;
            })
            .AddJwtBearer(option =>
            {
                // 自定义token获取方式
                // option.Events = new JwtBearerEvents()
                // {
                //     OnMessageReceived = context =>
                //     {
                //         context.Token= context.Request.Cookies["access_token"];
                //         return Task.CompletedTask;
                //     }
                // };
                option.SaveToken                 = true;
                option.RequireHttpsMetadata      = false;
                option.TokenValidationParameters = new TokenValidationParameters
                {
                    NameClaimType = JwtClaimTypes.Name,
                    // RoleClaimType = JwtClaimTypes.Role,
                    ValidIssuer              = jwtBearerConfig.Issuer,
                    ValidAudience            = jwtBearerConfig.Audience,
                    ValidateIssuer           = true,
                    ValidateAudience         = true,
                    ValidateIssuerSigningKey = true,
                    IssuerSigningKey         = new SymmetricSecurityKey(Encoding.ASCII.GetBytes(jwtBearerConfig.Secret))
                };
            });

            services.AIDIRegister();
            services.RedisDIRegister();

            Mapper.Initialize(cfg =>
            {
                cfg.AddProfile <AuditProfile>();
                cfg.AddProfile <SystemUserProfile>();
            });

            services.AddLogging(builder =>
            {
                builder.ClearProviders();
                builder.AddConfiguration(Configuration.GetSection("Logging"))
                .AddFilter("Microsoft", LogLevel.Warning)
                .AddConsole();
            });

            // In production, the React files will be served from this directory
            services.AddSpaStaticFiles(configuration =>
            {
                configuration.RootPath = "ClientApp/build";
            });

            // services.AddSingleton<Microsoft.AspNetCore.Authorization.IAuthorizationHandler, Authorization.PermissionHandler>();
        }
示例#27
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();
            // 设置数据源,读取appsettings.json配置文件
            GlobalSystemConfig.DBConnectionString = this.Configuration.GetConnectionString("DataSource");
            // 注册缓存对象
            services.AddMemoryCache();
            IConfigurationSection connectionStringsSection = this.Configuration.GetSection("ConnectionStrings");
            IConfigurationSection cacheProviderSection     = connectionStringsSection.GetSection("CacheProvider");

            if (cacheProviderSection != null)
            {
                try
                {
                    string type = cacheProviderSection.GetValue <string>("type");
                    if ("redis".Equals(type, StringComparison.OrdinalIgnoreCase))
                    {
                        // redis 分布式缓存
                        RedisCacheProvider provider = cacheProviderSection.GetSection("provider").Get <RedisCacheProvider>();
                        services.AddSingleton(typeof(ICacheService), new RedisCacheService(new RedisCacheOptions
                        {
                            Configuration = provider.HostName + ":" + provider.Port,
                            InstanceName  = provider.InstanceName
                        }, provider.DataBase));
                    }
                    else if ("redis.r.w".Equals(type, StringComparison.OrdinalIgnoreCase))
                    {
                        // redis读写分离
                        RedisRWConfigInfo provider     = cacheProviderSection.GetSection("provider").Get <RedisRWConfigInfo>();
                        RedisManager      redisManager = new RedisManager(provider);
                        services.AddSingleton(typeof(ICacheService), new RedisRWCacheService(redisManager.GetClient()));
                    }
                }
                catch (Exception ex)
                {
                    LOG.Error(ex, "redis连接失败,准备启用MemoryCache服务");
                    SetCacheService(services);
                }
            }
            else
            {
                SetCacheService(services);
            }
            // mongo
            IConfigurationSection mongoSection = this.Configuration.GetSection("ConnectionStrings").GetSection("Mongo");

            if (mongoSection != null)
            {
                try
                {
                    // 注册mongo连接信息
                    MongodbHost mongohost = mongoSection.Get <MongodbHost>();
                    services.AddSingleton(typeof(MongodbHost), mongohost);
                    // IMongoClient mongoClient = new MongoClient(mongohost.Connection);
                    IMongoClient mongoClient = MongodbManager <object> .GetMongodbClient(mongohost.ConnectionString);

                    services.AddSingleton(typeof(IMongoClient), mongoClient);
                    IMongoDatabase mongoDatabase = mongoClient.GetDatabase(mongohost.DataBase);
                    services.AddSingleton(typeof(IMongoDatabase), mongoDatabase);
                }
                catch (Exception ex)
                {
                    LOG.Error(ex, "mongo连接失败");
                }
            }
            // 注册知识库
            services.AddSingleton <IRepository, Repository>();
            // 注册版本服务
            services.AddSingleton <IVersionService, VersionService>();
            // 注册用户服务
            services.AddSingleton <IUserService, UserService>();
            // 注册模型服务
            services.AddSingleton <IModelService, ModelService> ();
            // 注册数据源服务
            services.AddSingleton <IDataSourceService, DataSourceService>();
            // 注册算法服务
            services.AddSingleton <IAlgorithmService, AlgorithmService>();
            // 注册业务日志服务
            services.AddSingleton <ILogService, LogService>();
            // 注册任务服务
            services.AddSingleton <ITaskService, TaskService>();
            // 设置全局
            IServiceProvider serviceProvider = services.BuildServiceProvider();

            ServiceFactory.CacheService  = serviceProvider.GetService <ICacheService>();
            ServiceFactory.MongoHost     = serviceProvider.GetService <MongodbHost>();
            ServiceFactory.MongoClient   = serviceProvider.GetService <IMongoClient>();
            ServiceFactory.MongoDatabase = serviceProvider.GetService <IMongoDatabase>();
            // 消息相关
            IConfigurationSection messageSection = connectionStringsSection.GetSection("Message");

            if (messageSection != null)
            {
                // 消息
                IConfigurationSection mqSection = messageSection.GetSection("MQ");
                if (mqSection != null)
                {
                    KafkaSetting kafkaSetting = mqSection.Get <KafkaSetting>();
                    if (kafkaSetting.Switch)
                    {
                        KafkaConsumer.CreateConsumer(kafkaSetting.Opinion.GroupId, kafkaSetting.Opinion.Servers, kafkaSetting.Opinion.Topics);
                        KafkaConsumer.Start();
                        KafkaProducer.CreateProducer(kafkaSetting.Opinion.Servers);
                    }
                }
                // websocket
                IConfigurationSection websocketSection = messageSection.GetSection("Websocket");
                if (websocketSection != null)
                {
                    WebsocketSetting websocketSetting = websocketSection.Get <WebsocketSetting>();
                    WebsocketFleckServer.CreateWebsocketServer(websocketSetting.NodeId, websocketSetting.Port, websocketSetting.Host);
                }
            }
            // scheduler,注入参数设置
            IConfigurationSection schedulerSection = this.Configuration.GetSection("Scheduler");

            if (schedulerSection != null)
            {
                if (schedulerSection.GetValue <Boolean>("switch"))
                {
                    IConfigurationSection propertiesSection = schedulerSection.GetSection("properties");
                    var values = propertiesSection.GetChildren()
                                 .Select(item => new KeyValuePair <string, string>(item.Key,
                                                                                   item.Value.Contains("$") ? Configuration.GetValue <string>(item.Value.Replace("${", "").Replace("}", "")) : item.Value))
                                 .ToDictionary(x => x.Key, x => x.Value);

                    DmeQuartzScheduler <TaskRunnerJob> .SetSchedulerProperties(DataUtil.ToNameValueCollection(values));

                    // 调取开启。如果不开启,则不会执行。
                    DmeQuartzScheduler <TaskRunnerJob> .Start().GetAwaiter();
                }
            }

            // DemoScheduler.RunProOracle().Wait();
            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info
                {
                    Version        = "v1",
                    Title          = "Dist Model Engine接口文档",
                    Description    = "RESTful API for DME",
                    TermsOfService = "None",
                    Contact        = new Contact {
                        Name = "weifj", Email = "*****@*****.**", Url = "https://github.com/leoterry-ulrica/dme"
                    }
                });
                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "Dist.Dme.WebApi.xml");
                c.IncludeXmlComments(xmlPath);
                //  c.OperationFilter<HttpHeaderOperation>(); // 添加httpHeader参数
            });

            // 配置日志服务
            services.AddLogging();
        }