Exemplo n.º 1
0
        public static async Task SeedAsync(MyContext myContext)
        {
            try
            {
                //codefirst创建数据库 ,如果是第二次执行,注释掉即可
                myContext.CreateTableByEntity(false,

                                              //typeof(Module),
                                              //typeof(ModulePermission),
                                              //typeof(OperateLog),
                                              //typeof(PasswordLib),
                                              //typeof(Permission),
                                              //typeof(Role),
                                              //typeof(RoleModulePermission),
                                              //typeof(sysUserInfo),
                                              //typeof(UserRole),
                                              //typeof(Topic),
                                              //typeof(TopicDetail),
                                              ////以下是业务表
                                              //typeof(CustomInfo),
                                              //typeof(ExtraProjectInfo),
                                              //typeof(ExtraOtherProject),
                                              //typeof(Dictionary),
                                              //typeof(PartyAdvisoryInfo),
                                              //typeof(PartyBookInfo),
                                              //typeof(PartyDemands),
                                              typeof(GraduationStatistics)
                                              //typeof(ExcelMapToModel)
                                              );
                //下面就是种子数据
                #region CustomInfo
                if (!await myContext.Db.Queryable <CustomInfo>().AnyAsync())
                {
                    myContext.GetEntityDB <CustomInfo>().Insert(
                        new CustomInfo
                    {
                        Name          = "管理员",
                        PhoneNumber   = "158888888",
                        Birthday      = "11岁",
                        AdvisoryTime  = DateTime.Now,
                        ScheduledDate = DateTime.Now,
                        CreatedBy     = "wangchao",
                        UpdatedBy     = "wangchao",
                        CreateTime    = DateTime.Now,
                        UpdateTime    = DateTime.Now,
                    });
                    Console.WriteLine("Done seeding database.");
                    Console.WriteLine();
                }
                #endregion
                #region Module
                if (!await myContext.Db.Queryable <Module>().AnyAsync())
                {
                    myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module"))));
                    Console.WriteLine("Table:Module created success!");
                }
                else
                {
                    Console.WriteLine("Table:Module already exists...");
                }
                #endregion


                #region Permission
                if (!await myContext.Db.Queryable <Permission>().AnyAsync())
                {
                    myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission"))));
                    Console.WriteLine("Table:Permission created success!");
                }
                else
                {
                    Console.WriteLine("Table:Permission already exists...");
                }
                #endregion


                #region Role
                if (!await myContext.Db.Queryable <Role>().AnyAsync())
                {
                    myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))));
                    Console.WriteLine("Table:Role created success!");
                }
                else
                {
                    Console.WriteLine("Table:Role already exists...");
                }
                #endregion


                #region RoleModulePermission
                if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync())
                {
                    myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission"))));
                    Console.WriteLine("Table:RoleModulePermission created success!");
                }
                else
                {
                    Console.WriteLine("Table:RoleModulePermission already exists...");
                }
                #endregion


                #region Topic
                if (!await myContext.Db.Queryable <Topic>().AnyAsync())
                {
                    myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic"))));
                    Console.WriteLine("Table:Topic created success!");
                }
                else
                {
                    Console.WriteLine("Table:Topic already exists...");
                }
                #endregion


                #region TopicDetail
                if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync())
                {
                    myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail"))));
                    Console.WriteLine("Table:TopicDetail created success!");
                }
                else
                {
                    Console.WriteLine("Table:TopicDetail already exists...");
                }
                #endregion


                #region UserRole
                if (!await myContext.Db.Queryable <UserRole>().AnyAsync())
                {
                    myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))));
                    Console.WriteLine("Table:UserRole created success!");
                }
                else
                {
                    Console.WriteLine("Table:UserRole already exists...");
                }
                #endregion


                #region sysUserInfo
                if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync())
                {
                    myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))));
                    Console.WriteLine("Table:sysUserInfo created success!");
                }
                else
                {
                    Console.WriteLine("Table:sysUserInfo already exists...");
                }
                #endregion


                Console.WriteLine("Done seeding database.");
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                throw new Exception("初始化种子数据失败" + ex.Message);
            }
        }
Exemplo n.º 2
0
        public static void EnsureSeedData(IServiceProvider serviceProvider)
        {
            //1.dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
            //2.dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
            //3.dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o Data
            //4.dotnet run /seed
            Console.WriteLine("Seeding database...");

            using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                {
                    var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                    context.Database.Migrate();
                    EnsureSeedData(context);
                }

                {
                    var context = scope.ServiceProvider.GetService <ApplicationDbContext>();
                    context.Database.Migrate();

                    var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();

                    var BlogCore_Users     = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")));
                    var BlogCore_Roles     = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")));
                    var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")));

                    foreach (var item in BlogCore_Users)
                    {
                        if (item == null || item.uLoginName == null)
                        {
                            continue;
                        }
                        var userItem = userMgr.FindByNameAsync(item.uLoginName).Result;
                        var rid      = BlogCore_UserRoles.FirstOrDefault(d => d.UserId == item.uID)?.RoleId;
                        var rName    = BlogCore_Roles.FirstOrDefault(d => d.Id == rid)?.Name;

                        if (userItem == null)
                        {
                            if (rid > 0 && !string.IsNullOrEmpty(rName))
                            {
                                userItem = new ApplicationUser
                                {
                                    UserName   = item.uLoginName,
                                    LoginName  = item.uRealName,
                                    sex        = item.sex,
                                    age        = item.age,
                                    birth      = item.birth,
                                    addr       = item.addr,
                                    tdIsDelete = item.tdIsDelete
                                };

                                //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result;

                                // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了
                                var result = userMgr.CreateAsync(userItem, "BlogIdp123$InitPwd").Result;
                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }

                                result = userMgr.AddClaimsAsync(userItem, new Claim[] {
                                    new Claim(JwtClaimTypes.Name, item.uRealName),
                                    new Claim(JwtClaimTypes.Email, $"{item.uLoginName}@email.com"),
                                    new Claim(JwtClaimTypes.Role, rName)
                                }).Result;

                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }
                                Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表
                            }
                            else
                            {
                                Console.WriteLine($"{item?.uLoginName} doesn't have a corresponding role.");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"{userItem?.UserName} already exists");
                        }
                    }
                }
            }

            Console.WriteLine("Done seeding database.");
            Console.WriteLine();
        }
Exemplo n.º 3
0
        public async Task <MessageModel <PayReturnResultModel> > Pay(PayNeedModel payModel)
        {
            _logger.LogInformation("支付开始");
            MessageModel <PayReturnResultModel> messageModel = new MessageModel <PayReturnResultModel>();

            messageModel.response = new PayReturnResultModel();
            string url        = string.Empty;
            string param      = string.Empty;
            string returnData = string.Empty;

            try
            {
                _logger.LogInformation($"原始GET参数->{_httpContextAccessor.HttpContext.Request.QueryString}");
                //被扫支付
                string host = "https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00_BEPAY?";
                ////商户信息
                //string merInfo = "MERCHANTID=105910100190000&POSID=000000000&BRANCHID=610000000";
                ////获取柜台完整公钥
                //string pubKey = "30819d300d06092a864886f70d010101050003818b0030818702818100a32fb2d51dda418f65ca456431bd2f4173e41a82bb75c2338a6f649f8e9216204838d42e2a028c79cee19144a72b5b46fe6a498367bf4143f959e4f73c9c4f499f68831f8663d6b946ae9fa31c74c9332bebf3cba1a98481533a37ffad944823bd46c305ec560648f1b6bcc64d54d32e213926b26cd10d342f2c61ff5ac2d78b020111";
                ////加密原串
                //string param = merInfo + "&MERFLAG=1&TERMNO1=&TERMNO2=&ORDERID=937857156" +
                //        "&QRCODE=134737690209713400&AMOUNT=0.01&TXCODE=PAY100&PROINFO=&REMARK1=&REMARK2=&SMERID=&SMERNAME=&SMERTYPEID=" +
                //        "&SMERTYPE=&TRADECODE=&TRADENAME=&SMEPROTYPE=&PRONAME=";

                Dictionary <string, string> dic = new Dictionary <string, string>();

                //支付信息
                dic.Add("MERCHANTID", StaticPayInfo.MERCHANTID); // => self::MERCHANTID, // 商户号
                dic.Add("POSID", StaticPayInfo.POSID);           // => self::POSID, // 柜台号
                dic.Add("BRANCHID", StaticPayInfo.BRANCHID);     // => self::BRANCHID, // 分行号
                dic.Add("TXCODE", "PAY100");                     // => 'PAY100', // 交易码
                dic.Add("MERFLAG", "1");                         // => '', // 商户类型 1线上 2线下
                dic.Add("ORDERID", payModel.ORDERID);            //payModel.ORDERID);// => '', // 订单号
                dic.Add("QRCODE", payModel.QRCODE);              // => '', // 码信息(一维码、二维码)
                dic.Add("AMOUNT", payModel.AMOUNT);              // => '0.01', // 订单金额,单位:元
                dic.Add("PROINFO", payModel.PROINFO);            // => '', // 商品名称
                dic.Add("REMARK1", payModel.REMARK1);            // => '', // 备注 1
                dic.Add("REMARK2", payModel.REMARK2);            // => '', // 备注 2

                //dic.Add("TERMNO1", "");// => '', // 终端编号 1
                //dic.Add("TERMNO2", "");// => '', // 终端编号 2
                //dic.Add("GROUPMCH", "");// => '', // 集团商户信息
                //dic.Add("FZINFO1", "");// => '', // 分账信息一
                //dic.Add("FZINFO2", "");// => '', // 分账信息二
                //dic.Add("SUB_APPID", "");// => '', // 子商户公众账号 ID
                //dic.Add("RETURN_FIELD", "");// => '', // 返回信息位图
                //dic.Add("USERPARAM", "");// => '', // 实名支付
                //dic.Add("detail", "");// => '', // 商品详情
                //dic.Add("goods_tag", "");// => '', // 订单优惠标记

                //商户信息
                Dictionary <string, string> dicInfo = new Dictionary <string, string>();
                dicInfo.Add("MERCHANTID", StaticPayInfo.MERCHANTID); // => self::MERCHANTID, // 商户号
                dicInfo.Add("POSID", StaticPayInfo.POSID);           // => self::POSID, // 柜台号
                dicInfo.Add("BRANCHID", StaticPayInfo.BRANCHID);     // => self::BRANCHID, // 分行号
                var Info = StringHelper.GetPars(dicInfo);


                //获取拼接请求串
                param = StringHelper.GetPars(dic);

                //加密
                var paramEncryption = new CCBPayUtil().makeCCBParam(param, StaticPayInfo.pubKey);
                //拼接请求串
                url = host + Info + "&ccbParam=" + paramEncryption;
                //请求
                _logger.LogInformation($"请求地址->{url}");
                _logger.LogInformation($"请求参数->{param}");
                PayResultModel payResult;
                try
                {
                    returnData = await GetNetData.PostAsync(url);

                    //转换数据
                    try
                    {
                        payResult = JsonHelper.ParseFormByJson <PayResultModel>(returnData);
                    }
                    catch
                    {
                        payResult = new PayResultModel {
                            RESULT = "N", ERRMSG = "参数错误", ORDERID = payModel.ORDERID, AMOUNT = payModel.AMOUNT
                        };
                        returnData = StringHelper.GetCusLine(returnData, 15);
                    }
                    _logger.LogInformation($"响应数据->{returnData}");
                }
                catch (Exception ex)
                {
                    _logger.LogInformation($"异常信息:{ex.Message}");
                    _logger.LogInformation($"异常堆栈:{ex.StackTrace}");
                    messageModel = await  PayCheck(payModel, 1);

                    return(messageModel);
                }
                switch (payResult.RESULT)
                {
                case "Y":
                    Dictionary <string, string> dicCheckPars = new Dictionary <string, string>();
                    dicCheckPars.Add("RESULT", payResult.RESULT);
                    dicCheckPars.Add("ORDERID", payResult.ORDERID);
                    dicCheckPars.Add("AMOUNT", payResult.AMOUNT);
                    dicCheckPars.Add("WAITTIME", payResult.WAITTIME);
                    dicCheckPars.Add("TRACEID", payResult.TRACEID);
                    string strCheckPars = StringHelper.GetPars(dicCheckPars);
                    if (NotifyCheck(strCheckPars, payResult.SIGN, StaticPayInfo.pubKey))
                    {
                        messageModel.success = true;
                        messageModel.msg     = "支付成功";
                    }
                    else
                    {
                        messageModel.success = false;
                        messageModel.msg     = "签名失败";
                    }
                    break;

                case "N":
                    messageModel.success = false;
                    messageModel.msg     = "支付失败";
                    break;

                case "U":
                case "Q":
                    int waittime = payResult.WAITTIME.ObjToInt();
                    if (waittime <= 0)
                    {
                        waittime = 5;                   //如果需要等待默认等待5秒后再次查询
                    }
                    Thread.Sleep(waittime * 1000);
                    //轮询查询
                    messageModel = await PayCheck(payModel, 1);

                    break;

                default:
                    messageModel.success = false;
                    messageModel.msg     = "支付失败";
                    break;
                }
                messageModel.response.ORDERID    = payResult.ORDERID;
                messageModel.response.ERRCODE    = payResult.ERRCODE;
                messageModel.response.ERRMSG     = payResult.ERRMSG;
                messageModel.response.TRACEID    = payResult.TRACEID;
                messageModel.response.AMOUNT     = payResult.AMOUNT;
                messageModel.response.QRCODETYPE = payResult.QRCODETYPE;
            }
            catch (Exception ex)
            {
                messageModel.success         = false;
                messageModel.msg             = "服务错误";
                messageModel.response.ERRMSG = ex.Message;
                _logger.LogInformation($"异常信息:{ex.Message}");
                _logger.LogInformation($"异常堆栈:{ex.StackTrace}");
            }
            finally
            {
                _logger.LogInformation($"返回数据->{JsonHelper.GetJSON<MessageModel<PayReturnResultModel>>(messageModel)}");
                _logger.LogInformation("支付结束");
            }
            return(messageModel);
        }
Exemplo n.º 4
0
        internal static void EnsureSeedData(IServiceProvider serviceProvider)
        {
            //1.dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
            //2.dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
            //3.dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o Data
            //4.dotnet run /seed
            Console.WriteLine("Seeding database...");

            using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                {
                    var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                    context.Database.Migrate();
                    EnsureSeedData(context);
                }

                {
                    var context = scope.ServiceProvider.GetService <AppIdentityDbContext>();
                    context.Database.Migrate();
                    var userMgr            = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                    var roleMgr            = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >();
                    var BlogCore_Users     = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")));
                    var BlogCore_Roles     = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")));
                    var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")));

                    // 迁移【用户】信息
                    foreach (var item in BlogCore_Users)
                    {
                        if (item == null || item.uLoginName == null)
                        {
                            continue;
                        }
                        var userItem  = userMgr.FindByNameAsync(item.uLoginName).Result;
                        var userRoles = BlogCore_UserRoles.Where(d => d.UserId == item.uID).ToList();
                        //var rName = BlogCore_Roles.FirstOrDefault(d => d.Id == rid)?.Name;

                        if (userItem == null)
                        {
                            if (userRoles.Count > 0)
                            {
                                var applicationUserRole = new List <ApplicationUserRole>();
                                foreach (var userRoleItemS in userRoles)
                                {
                                    applicationUserRole.Add(new ApplicationUserRole()
                                    {
                                    });
                                }

                                userItem = new ApplicationUser
                                {
                                    UserName   = item.uLoginName,
                                    LoginName  = item.uRealName,
                                    sex        = item.sex,
                                    age        = item.age,
                                    birth      = item.birth,
                                    addr       = item.addr,
                                    tdIsDelete = item.tdIsDelete,
                                    RealName   = item.uRealName,
                                };

                                //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result;

                                // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了
                                var result = userMgr.CreateAsync(userItem, "BlogIdp123$InitPwd").Result;
                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }


                                result = userMgr.AddClaimsAsync(userItem, new Claim[] {
                                    //new Claim(JwtClaimTypes.Name, item.uRealName),
                                    new Claim(JwtClaimTypes.Email, $"{item.uLoginName}@email.com"),
                                    //new Claim(JwtClaimTypes.Role, rName)
                                }).Result;

                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }
                                Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表
                            }
                            else
                            {
                                Console.WriteLine($"{item?.uLoginName} doesn't have a corresponding role.");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"{userItem?.UserName} already exists");
                        }
                    }

                    // 迁移【角色】信息,Role信息统一在这里处理,Blog.Core 只负责读,不负责写
                    foreach (var item in BlogCore_Roles)
                    {
                        if (item == null || item.Name == null)
                        {
                            continue;
                        }

                        var roleModel = roleMgr.FindByNameAsync(item.Name).Result;

                        if (roleModel == null)
                        {
                            roleModel = new ApplicationRole
                            {
                                Name           = item.Name,
                                Description    = item.Description,
                                IsDeleted      = (bool)(item.IsDeleted),
                                CreateBy       = item.CreateBy,
                                CreateId       = item.CreateId,
                                CreateTime     = item.CreateTime,
                                ModifyBy       = item.ModifyBy,
                                ModifyId       = item.ModifyId,
                                ModifyTime     = item.ModifyTime,
                                Enabled        = item.Enabled,
                                OrderSort      = item.OrderSort,
                                NormalizedName = item.Name,
                            };

                            var result = roleMgr.CreateAsync(roleModel).Result;
                            if (!result.Succeeded)
                            {
                                throw new Exception(result.Errors.First().Description);
                            }
                        }
                        else
                        {
                            Console.WriteLine($"{roleModel?.Name} already exists");
                        }
                    }
                }
            }

            Console.WriteLine("Done seeding database.");
            Console.WriteLine();
        }
Exemplo n.º 5
0
        /// <summary>
        /// 异步添加种子数据
        /// </summary>
        /// <param name="myContext"></param>
        /// <returns></returns>
        public static async Task SeedAsync(MyContext myContext)
        {
            try
            {
                // 如果生成过了,第二次,就不用再执行一遍了,注释掉该方法即可

                #region 自动创建数据库暂停服务
                // 自动创建数据库,注意版本是 sugar 5.x 版本的

                // 注意:这里还是有些问题,比如使用mysql的话,如果通过这个方法创建空数据库,字符串不是utf8的,所以还是手动创建空的数据库吧,然后设置数据库为utf-8,我再和作者讨论一下。
                // 但是使用SqlServer 和 Sqlite 好像没有这个问题。
                //myContext.Db.DbMaintenance.CreateDatabase();
                #endregion


                // 创建表
                myContext.CreateTableByEntity(false,
                                              typeof(Advertisement),
                                              typeof(BlogArticle),
                                              typeof(Guestbook),
                                              typeof(Module),
                                              typeof(ModulePermission),
                                              typeof(OperateLog),
                                              typeof(PasswordLib),
                                              typeof(Permission),
                                              typeof(Role),
                                              typeof(RoleModulePermission),
                                              typeof(sysUserInfo),
                                              typeof(Topic),
                                              typeof(TopicDetail),
                                              typeof(UserRole));

                // 后期单独处理某些表
                //myContext.Db.CodeFirst.InitTables(typeof(sysUserInfo));
                //myContext.Db.CodeFirst.InitTables(typeof(Permission));
                //myContext.Db.CodeFirst.InitTables(typeof(Advertisement));

                Console.WriteLine("Database:WMBlog created success!");
                Console.WriteLine();

                if (Appsettings.app(new string[] { "AppSettings", "SeedDBDataEnabled" }).ObjToBool())
                {
                    Console.WriteLine("Seeding database...");

                    #region BlogArticle
                    if (!await myContext.Db.Queryable <BlogArticle>().AnyAsync())
                    {
                        var strJson = GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle"));
                        myContext.GetEntityDB <BlogArticle>().InsertRange(JsonHelper.ParseFormByJson <List <BlogArticle> >(GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle"))));
                        Console.WriteLine("Table:BlogArticle created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:BlogArticle already exists...");
                    }
                    #endregion


                    #region Module
                    if (!await myContext.Db.Queryable <Module>().AnyAsync())
                    {
                        myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module"))));
                        Console.WriteLine("Table:Module created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:Module already exists...");
                    }
                    #endregion


                    #region Permission
                    if (!await myContext.Db.Queryable <Permission>().AnyAsync())
                    {
                        myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission"))));
                        Console.WriteLine("Table:Permission created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:Permission already exists...");
                    }
                    #endregion


                    #region Role
                    if (!await myContext.Db.Queryable <Role>().AnyAsync())
                    {
                        myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))));
                        Console.WriteLine("Table:Role created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:Role already exists...");
                    }
                    #endregion


                    #region RoleModulePermission
                    if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync())
                    {
                        myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission"))));
                        Console.WriteLine("Table:RoleModulePermission created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:RoleModulePermission already exists...");
                    }
                    #endregion


                    #region Topic
                    if (!await myContext.Db.Queryable <Topic>().AnyAsync())
                    {
                        myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic"))));
                        Console.WriteLine("Table:Topic created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:Topic already exists...");
                    }
                    #endregion


                    #region TopicDetail
                    if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync())
                    {
                        myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail"))));
                        Console.WriteLine("Table:TopicDetail created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:TopicDetail already exists...");
                    }
                    #endregion


                    #region UserRole
                    if (!await myContext.Db.Queryable <UserRole>().AnyAsync())
                    {
                        myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))));
                        Console.WriteLine("Table:UserRole created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:UserRole already exists...");
                    }
                    #endregion


                    #region sysUserInfo
                    if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync())
                    {
                        myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))));
                        Console.WriteLine("Table:sysUserInfo created success!");
                    }
                    else
                    {
                        Console.WriteLine("Table:sysUserInfo already exists...");
                    }
                    #endregion

                    Console.WriteLine("Done seeding database.");
                }

                Console.WriteLine();
            }
            catch (Exception ex)
            {
                throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message);
            }
        }
Exemplo n.º 6
0
        public async Task <MessageModel <PayReturnResultModel> > PayCheck(PayNeedModel payModel, int times)
        {
            _logger.LogInformation("轮序开始");
            MessageModel <PayReturnResultModel> messageModel = new MessageModel <PayReturnResultModel>();

            messageModel.response = new PayReturnResultModel();
            string url        = string.Empty;
            string param      = string.Empty;
            string returnData = string.Empty;

            try
            {
                string host = "https://ibsbjstar.ccb.com.cn/CCBIS/B2CMainPlat_00_BEPAY?";

                Dictionary <string, string> dic = new Dictionary <string, string>();

                dic.Add("MERCHANTID", StaticPayInfo.MERCHANTID); // => self::MERCHANTID, // 商户号
                dic.Add("POSID", StaticPayInfo.POSID);           // => self::POSID, // 柜台号
                dic.Add("BRANCHID", StaticPayInfo.BRANCHID);     // => self::BRANCHID, // 分行号
                dic.Add("TXCODE", "PAY101");                     // => 'PAY100', // 交易码
                dic.Add("QRYTIME", times.ToString());            // => '', // 查询此时(每次加1)
                dic.Add("MERFLAG", "1");                         // => '', // 商户类型
                dic.Add("ORDERID", payModel.ORDERID);            // => '', // 订单号
                dic.Add("QRCODE", payModel.QRCODE);              // => '', // 码信息(一维码、二维码)


                //dic.Add("GROUPMCH", "");// => '', // 集团商户信息
                //dic.Add("QRCODETYPE", "");// => '', // 支付类型1:龙支付 2:微信 3:支付宝 4:银联
                //dic.Add("TERMNO1", "");// => '', // 终端编号 1
                //dic.Add("TERMNO2", "");// => '', // 终端编号 2
                //dic.Add("AMOUNT", "");// => '0.01', // 订单金额,单位:元
                //dic.Add("PROINFO", "");// => '', // 商品名称
                //dic.Add("REMARK1", "");// => '', // 备注 1
                //dic.Add("REMARK2", "");// => '', // 备注 2
                //dic.Add("FZINFO1", "");// => '', // 分账信息一
                //dic.Add("FZINFO2", "");// => '', // 分账信息二
                //dic.Add("SUB_APPID", "");// => '', // 子商户公众账号 ID
                //dic.Add("RETURN_FIELD", "");// => '', // 返回信息位图
                //dic.Add("USERPARAM", "");// => '', // 实名支付
                //dic.Add("detail", "");// => '', // 商品详情
                //dic.Add("goods_tag", "");// => '', // 订单优惠标记

                //商户信息
                Dictionary <string, string> dicInfo = new Dictionary <string, string>();
                dicInfo.Add("MERCHANTID", StaticPayInfo.MERCHANTID); // => self::MERCHANTID, // 商户号
                dicInfo.Add("POSID", StaticPayInfo.POSID);           // => self::POSID, // 柜台号
                dicInfo.Add("BRANCHID", StaticPayInfo.BRANCHID);     // => self::BRANCHID, // 分行号
                var Info = StringHelper.GetPars(dicInfo);

                //var newDic = dic.OrderBy(t => t.Key).ToDictionary(o => o.Key, p => p.Value);
                //参数信息
                param = StringHelper.GetPars(dic);
                //加密
                var paramEncryption = new CCBPayUtil().makeCCBParam(param, StaticPayInfo.pubKey);
                //拼接请求串
                url = host + Info + "&ccbParam=" + paramEncryption;
                //请求
                _logger.LogInformation($"请求地址->{url}");
                _logger.LogInformation($"请求参数->{param}");
                //转换数据
                PayResultModel payResult;
                try
                {
                    returnData = await GetNetData.PostAsync(url);

                    _logger.LogInformation($"响应数据->{returnData}");
                }
                catch (Exception ex)
                {
                    _logger.LogInformation($"异常信息:{ex.Message}");
                    _logger.LogInformation($"异常堆栈:{ex.StackTrace}");
                    return(await PayCheck(payModel, ++times));
                }


                try
                {
                    payResult = JsonHelper.ParseFormByJson <PayResultModel>(returnData);
                }
                catch
                {
                    payResult = new PayResultModel {
                        RESULT = "N", ERRMSG = "参数错误", ORDERID = payModel.ORDERID, AMOUNT = payModel.AMOUNT
                    };
                }

                switch (payResult.RESULT)
                {
                case "Y":
                    Dictionary <string, string> dicCheckPars = new Dictionary <string, string>();
                    dicCheckPars.Add("RESULT", payResult.RESULT);
                    dicCheckPars.Add("ORDERID", payResult.ORDERID);
                    dicCheckPars.Add("AMOUNT", payResult.AMOUNT);
                    dicCheckPars.Add("WAITTIME", payResult.WAITTIME);
                    string strCheckPars = StringHelper.GetPars(dicCheckPars);
                    if (NotifyCheck(strCheckPars, payResult.SIGN, StaticPayInfo.pubKey))
                    {
                        messageModel.success = true;
                        messageModel.msg     = "支付成功";
                    }
                    else
                    {
                        messageModel.success = false;
                        messageModel.msg     = "签名失败";
                    }
                    break;

                case "N":
                    messageModel.success = false;
                    messageModel.msg     = "支付失败";
                    break;

                case "U":
                case "Q":
                    int waittime = payResult.WAITTIME.ObjToInt();
                    if (waittime <= 0)
                    {
                        waittime = 5;                   //如果需要等待默认等待5秒后再次查询
                    }
                    Thread.Sleep(waittime * 1000);
                    //改成轮询查询
                    messageModel = await PayCheck(payModel, ++times);

                    break;

                default:
                    messageModel.success = false;
                    messageModel.msg     = "支付失败";
                    break;
                }
                messageModel.response.ORDERID    = payResult.ORDERID;
                messageModel.response.ERRCODE    = payResult.ERRCODE;
                messageModel.response.ERRMSG     = payResult.ERRMSG;
                messageModel.response.TRACEID    = payResult.TRACEID;
                messageModel.response.AMOUNT     = payResult.AMOUNT;
                messageModel.response.QRCODETYPE = payResult.QRCODETYPE;
            }
            catch (Exception ex)
            {
                messageModel.success         = false;
                messageModel.msg             = "服务错误";
                messageModel.response.ERRMSG = ex.Message;
                _logger.LogInformation($"异常信息:{ex.Message}");
                _logger.LogInformation($"异常堆栈:{ex.StackTrace}");
            }
            finally
            {
                _logger.LogInformation($"返回数据->{JsonHelper.GetJSON<MessageModel<PayReturnResultModel>>(messageModel)}");
                _logger.LogInformation("轮序结束");
            }
            return(messageModel);
        }
Exemplo n.º 7
0
        public static void EnsureSeedData(IServiceProvider serviceProvider)
        {
            /*
             * 本项目同时支持Mysql和Sqlserver,我一直使用的是Mysql,所以Mysql的迁移文件已经配置号,在Data文件夹下,
             * 直接执行update-database xxxx,那三步即可。如果你使用sqlserver,可以先从迁移开始,下边有步骤
             *
             * 当然你也可以都删掉,自己重新做迁移。
             * 迁移完成后,执行dotnet run /seed
             *  1、PM> add-migration InitialIdentityServerPersistedGrantDbMigrationMysql -c PersistedGrantDbContext -o Data/MigrationsMySql/IdentityServer/PersistedGrantDb
             *  Build started...
             *  Build succeeded.
             *  To undo this action, use Remove-Migration.
             *  2、PM> update-database -c PersistedGrantDbContext
             *  Build started...
             *  Build succeeded.
             *  Applying migration '20200509165052_InitialIdentityServerPersistedGrantDbMigrationMysql'.
             *  Done.
             *  3、PM> add-migration InitialIdentityServerConfigurationDbMigrationMysql -c ConfigurationDbContext -o Data/MigrationsMySql/IdentityServer/ConfigurationDb
             *  Build started...
             *  Build succeeded.
             *  To undo this action, use Remove-Migration.
             *  4、PM> update-database -c ConfigurationDbContext
             *  Build started...
             *  Build succeeded.
             *  Applying migration '20200509165153_InitialIdentityServerConfigurationDbMigrationMysql'.
             *  Done.
             *  5、PM> add-migration AppDbMigration -c ApplicationDbContext -o Data/MigrationsMySql
             *  Build started...
             *  Build succeeded.
             *  To undo this action, use Remove-Migration.
             *  6、PM> update-database -c ApplicationDbContext
             *  Build started...
             *  Build succeeded.
             *  Applying migration '20200509165505_AppDbMigration'.
             *  Done.
             *
             */

            Console.WriteLine("Seeding database...");

            using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();
                {
                    var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                    context.Database.Migrate();
                    EnsureSeedData(context);
                }

                {
                    var context = scope.ServiceProvider.GetService <ApplicationDbContext>();
                    context.Database.Migrate();

                    var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                    var roleMgr = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >();

                    var BlogCore_Users     = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")));
                    var BlogCore_Roles     = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")));
                    var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")));

                    foreach (var user in BlogCore_Users)
                    {
                        if (user == null || user.uLoginName == null)
                        {
                            continue;
                        }
                        var userItem = userMgr.FindByNameAsync(user.uLoginName).Result;
                        var rid      = BlogCore_UserRoles.FirstOrDefault(d => d.UserId == user.uID)?.RoleId;
                        var rName    = BlogCore_Roles.Where(d => d.Id == rid).Select(d => d.Id).ToList();
                        var roleName = BlogCore_Roles.FirstOrDefault(d => d.Id == rid)?.Name;

                        if (userItem == null)
                        {
                            if (rid > 0 && rName.Count > 0)
                            {
                                userItem = new ApplicationUser
                                {
                                    UserName       = user.uLoginName,
                                    LoginName      = user.uRealName,
                                    sex            = user.sex,
                                    age            = user.age,
                                    birth          = user.birth,
                                    addr           = user.addr,
                                    tdIsDelete     = user.tdIsDelete,
                                    Email          = user.uLoginName + "@email.com",
                                    EmailConfirmed = true,
                                    RealName       = user.uRealName,
                                };

                                //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result;

                                // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了,可以先登录,然后修改密码
                                var result = userMgr.CreateAsync(userItem, "BlogIdp123$InitPwd").Result;
                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }

                                var claims = new List <Claim> {
                                    new Claim(JwtClaimTypes.Name, user.uRealName),
                                    new Claim(JwtClaimTypes.Email, $"{user.uLoginName}@email.com"),
                                    new Claim("rolename", roleName),
                                };

                                claims.AddRange(rName.Select(s => new Claim(JwtClaimTypes.Role, s.ToString())));


                                result = userMgr.AddClaimsAsync(userItem, claims).Result;


                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }
                                Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表
                            }
                            else
                            {
                                Console.WriteLine($"{user?.uLoginName} doesn't have a corresponding role.");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"{userItem?.UserName} already exists");
                        }
                    }

                    foreach (var role in BlogCore_Roles)
                    {
                        if (role == null || role.Name == null)
                        {
                            continue;
                        }
                        var roleItem = roleMgr.FindByNameAsync(role.Name).Result;

                        if (roleItem != null)
                        {
                            role.Name = role.Name + Guid.NewGuid().ToString("N");
                        }

                        roleItem = new ApplicationRole
                        {
                            CreateBy    = role.CreateBy,
                            Description = role.Description,
                            IsDeleted   = role.IsDeleted != null ? (bool)role.IsDeleted : true,
                            CreateId    = role.CreateId,
                            CreateTime  = role.CreateTime,
                            Enabled     = role.Enabled,
                            Name        = role.Name,
                            OrderSort   = role.OrderSort,
                        };

                        var result = roleMgr.CreateAsync(roleItem).Result;
                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }
                        Console.WriteLine($"{roleItem?.Name} created");//AspNetUserClaims 表
                    }
                }
            }

            Console.WriteLine("Done seeding database.");
            Console.WriteLine();
        }
Exemplo n.º 8
0
        /// <summary>
        /// 异步添加种子数据
        /// </summary>
        /// <param name="myContext"></param>
        /// <returns></returns>
        public static async Task SeedAsync(MyContext myContext)
        {
            try
            {
                // 如果生成过了,第二次,就不用再执行一遍了,注释掉该方法即可

                // 自动创建数据库,注意版本是 sugar 5.x 版本的
                myContext.Db.DbMaintenance.CreateDatabase();
                // 创建表
                myContext.CreateTableByEntity(false,
                                              typeof(Advertisement),
                                              typeof(BlogArticle),
                                              typeof(Guestbook),
                                              typeof(Module),
                                              typeof(ModulePermission),
                                              typeof(OperateLog),
                                              typeof(PasswordLib),
                                              typeof(Permission),
                                              typeof(Role),
                                              typeof(RoleModulePermission),
                                              typeof(sysUserInfo),
                                              typeof(Topic),
                                              typeof(TopicDetail),
                                              typeof(UserRole));

                // 后期单独处理某些表
                //myContext.Db.CodeFirst.InitTables(typeof(sysUserInfo));
                //myContext.Db.CodeFirst.InitTables(typeof(Permission));
                //myContext.Db.CodeFirst.InitTables(typeof(Advertisement));

                Console.WriteLine("Database:WMBlog created success!");
                Console.WriteLine();

                Console.WriteLine("Seeding database...");

                #region BlogArticle
                if (!await myContext.Db.Queryable <BlogArticle>().AnyAsync())
                {
                    myContext.GetEntityDB <BlogArticle>().InsertRange(JsonHelper.ParseFormByJson <List <BlogArticle> >(GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle"))));
                    Console.WriteLine("Table:BlogArticle created success!");
                }
                else
                {
                    Console.WriteLine("Table:BlogArticle already exists...");
                }
                #endregion


                #region Module
                if (!await myContext.Db.Queryable <Module>().AnyAsync())
                {
                    myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module"))));
                    Console.WriteLine("Table:Module created success!");
                }
                else
                {
                    Console.WriteLine("Table:Module already exists...");
                }
                #endregion


                #region Permission
                if (!await myContext.Db.Queryable <Permission>().AnyAsync())
                {
                    myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission"))));
                    Console.WriteLine("Table:Permission created success!");
                }
                else
                {
                    Console.WriteLine("Table:Permission already exists...");
                }
                #endregion


                #region Role
                if (!await myContext.Db.Queryable <Role>().AnyAsync())
                {
                    myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))));
                    Console.WriteLine("Table:Role created success!");
                }
                else
                {
                    Console.WriteLine("Table:Role already exists...");
                }
                #endregion


                #region RoleModulePermission
                if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync())
                {
                    myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission"))));
                    Console.WriteLine("Table:RoleModulePermission created success!");
                }
                else
                {
                    Console.WriteLine("Table:RoleModulePermission already exists...");
                }
                #endregion


                #region Topic
                if (!await myContext.Db.Queryable <Topic>().AnyAsync())
                {
                    myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic"))));
                    Console.WriteLine("Table:Topic created success!");
                }
                else
                {
                    Console.WriteLine("Table:Topic already exists...");
                }
                #endregion


                #region TopicDetail
                if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync())
                {
                    myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail"))));
                    Console.WriteLine("Table:TopicDetail created success!");
                }
                else
                {
                    Console.WriteLine("Table:TopicDetail already exists...");
                }
                #endregion


                #region UserRole
                if (!await myContext.Db.Queryable <UserRole>().AnyAsync())
                {
                    myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))));
                    Console.WriteLine("Table:UserRole created success!");
                }
                else
                {
                    Console.WriteLine("Table:UserRole already exists...");
                }
                #endregion


                #region sysUserInfo
                if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync())
                {
                    myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))));
                    Console.WriteLine("Table:sysUserInfo created success!");
                }
                else
                {
                    Console.WriteLine("Table:sysUserInfo already exists...");
                }
                #endregion


                Console.WriteLine("Done seeding database.");
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message);
            }
        }
Exemplo n.º 9
0
        public static async Task SeedAsync(MyContext myContext)
        {
            try
            {
                // myContext.Db.DbMaintenance.CreateDatabase();

                myContext.CreateTableByEntity(false,
                                              typeof(RoleInfo),
                                              typeof(UserInfo),
                                              typeof(UserRole),
                                              typeof(ShopInfo)
                                              );

                // myContext.Db.CodeFirst.InitTables(typeof(UserRole));

                Console.WriteLine("dataBase:shop created success!");
                Console.WriteLine("");

                Console.WriteLine("seed dataBase...");

                if (!await myContext.Db.Queryable <UserInfo>().AnyAsync())
                {
                    myContext.GetEntityDB <UserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <UserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserInfo"))));
                    Console.WriteLine("Table:UserInfo created success!");
                }
                else
                {
                    Console.WriteLine("Table:UserInfo already exists...");
                }

                if (!await myContext.Db.Queryable <RoleInfo>().AnyAsync())
                {
                    myContext.GetEntityDB <RoleInfo>().InsertRange(JsonHelper.ParseFormByJson <List <RoleInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleInfo"))));
                    Console.WriteLine("Table:RoleInfo created success!");
                }
                else
                {
                    Console.WriteLine("Table:RoleInfo already exists...");
                }


                if (!await myContext.Db.Queryable <UserRole>().AnyAsync())
                {
                    myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))));
                    Console.WriteLine("Table:UserRole created success!");
                }
                else
                {
                    Console.WriteLine("Table:UserRole already exists...");
                }



                if (!await myContext.Db.Queryable <ShopInfo>().AnyAsync())
                {
                    myContext.GetEntityDB <ShopInfo>().InsertRange(JsonHelper.ParseFormByJson <List <ShopInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "ShopInfo"))));
                    Console.WriteLine("Table:ShopInfo created success!");
                }
                else
                {
                    Console.WriteLine("Table:ShopInfo already exists...");
                }

                Console.WriteLine("Done seeding database.");
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message);
            }
        }
Exemplo n.º 10
0
        public static void EnsureSeedData(IServiceProvider serviceProvider)
        {
            //1.dotnet ef migrations add InitialIdentityServerPersistedGrantDbMigration -c PersistedGrantDbContext -o Data/Migrations/IdentityServer/PersistedGrantDb
            //2.dotnet ef migrations add InitialIdentityServerConfigurationDbMigration -c ConfigurationDbContext -o Data/Migrations/IdentityServer/ConfigurationDb
            //3.dotnet ef migrations add AppDbMigration -c ApplicationDbContext -o Data
            //4.dotnet run /seed
            Console.WriteLine("Seeding database...");

            using (var scope = serviceProvider.GetRequiredService <IServiceScopeFactory>().CreateScope())
            {
                scope.ServiceProvider.GetRequiredService <PersistedGrantDbContext>().Database.Migrate();

                {
                    var context = scope.ServiceProvider.GetRequiredService <ConfigurationDbContext>();
                    context.Database.Migrate();
                    EnsureSeedData(context);
                }

                {
                    var context = scope.ServiceProvider.GetService <ApplicationDbContext>();
                    context.Database.Migrate();

                    var userMgr = scope.ServiceProvider.GetRequiredService <UserManager <ApplicationUser> >();
                    var roleMgr = scope.ServiceProvider.GetRequiredService <RoleManager <ApplicationRole> >();

                    var BlogCore_Users     = JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo")));
                    var BlogCore_Roles     = JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role")));
                    var BlogCore_UserRoles = JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole")));

                    foreach (var user in BlogCore_Users)
                    {
                        if (user == null || user.uLoginName == null)
                        {
                            continue;
                        }
                        var userItem = userMgr.FindByNameAsync(user.uLoginName).Result;
                        var rid      = BlogCore_UserRoles.FirstOrDefault(d => d.UserId == user.uID)?.RoleId;
                        var rName    = BlogCore_Roles.Where(d => d.Id == rid).Select(d => d.Id).ToList();

                        if (userItem == null)
                        {
                            if (rid > 0 && rName.Count > 0)
                            {
                                userItem = new ApplicationUser
                                {
                                    UserName   = user.uLoginName,
                                    LoginName  = user.uRealName,
                                    sex        = user.sex,
                                    age        = user.age,
                                    birth      = user.birth,
                                    addr       = user.addr,
                                    tdIsDelete = user.tdIsDelete
                                };

                                //var result = userMgr.CreateAsync(userItem, "BlogIdp123$" + item.uLoginPWD).Result;

                                // 因为导入的密码是 MD5密文,所以这里统一都用初始密码了
                                var pwdInit = "BlogIdp123$InitPwd";
                                //if (userItem.UserName== "blogadmin")
                                //{
                                //    pwdInit = "#InitPwd";
                                //}
                                var result = userMgr.CreateAsync(userItem, pwdInit).Result;
                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }

                                var claims = new List <Claim> {
                                    new Claim(JwtClaimTypes.Name, user.uRealName),
                                    new Claim(JwtClaimTypes.Email, $"{user.uLoginName}@email.com"),
                                };

                                claims.AddRange(rName.Select(s => new Claim(JwtClaimTypes.Role, s.ToString())));


                                result = userMgr.AddClaimsAsync(userItem, claims).Result;


                                if (!result.Succeeded)
                                {
                                    throw new Exception(result.Errors.First().Description);
                                }
                                Console.WriteLine($"{userItem?.UserName} created");//AspNetUserClaims 表
                            }
                            else
                            {
                                Console.WriteLine($"{user?.uLoginName} doesn't have a corresponding role.");
                            }
                        }
                        else
                        {
                            Console.WriteLine($"{userItem?.UserName} already exists");
                        }
                    }

                    foreach (var role in BlogCore_Roles)
                    {
                        if (role == null || role.Name == null)
                        {
                            continue;
                        }
                        var roleItem = roleMgr.FindByNameAsync(role.Name).Result;

                        if (roleItem != null)
                        {
                            role.Name = role.Name + Guid.NewGuid().ToString("N");
                        }

                        roleItem = new ApplicationRole
                        {
                            CreateBy    = role.CreateBy,
                            Description = role.Description,
                            IsDeleted   = role.IsDeleted != null ? (bool)role.IsDeleted : true,
                            CreateId    = role.CreateId,
                            CreateTime  = role.CreateTime,
                            Enabled     = role.Enabled,
                            Name        = role.Name,
                            OrderSort   = role.OrderSort,
                        };

                        var result = roleMgr.CreateAsync(roleItem).Result;
                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }

                        if (!result.Succeeded)
                        {
                            throw new Exception(result.Errors.First().Description);
                        }
                        Console.WriteLine($"{roleItem?.Name} created");//AspNetUserClaims 表
                    }
                }
            }

            Console.WriteLine("Done seeding database.");
            Console.WriteLine();
        }
Exemplo n.º 11
0
        /// <summary>
        /// 异步添加种子数据
        /// </summary>
        /// <param name="myContext"></param>
        /// <returns></returns>
        public static async Task SeedAsync(MyContext myContext)
        {
            try
            {
                // 创建数据库
                myContext.Db.DbMaintenance.CreateDatabase();

                // 创建表
                myContext.CreateTableByEntity(false,
                                              typeof(Module),
                                              typeof(Permission),
                                              typeof(Role),
                                              typeof(RoleModulePermission),
                                              typeof(SysAdmin),
                                              typeof(CCT),
                                              typeof(Clazz),
                                              typeof(Course),
                                              typeof(Exam),
                                              typeof(ExamDetail),
                                              typeof(ExamDetailScore),
                                              typeof(ExScore),
                                              typeof(Grade),
                                              typeof(Students),
                                              typeof(Teacher),
                                              typeof(UserRole));


                Console.WriteLine("Database:WMBlog created success!");
                Console.WriteLine();

                Console.WriteLine("Seeding database...");



                #region Module
                if (!await myContext.Db.Queryable <Module>().AnyAsync())
                {
                    myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module"))));
                    Console.WriteLine("Table:Module created success!");
                }
                else
                {
                    Console.WriteLine("Table:Module already exists...");
                }
                #endregion


                #region Permission
                if (!await myContext.Db.Queryable <Permission>().AnyAsync())
                {
                    myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission"))));
                    Console.WriteLine("Table:Permission created success!");
                }
                else
                {
                    Console.WriteLine("Table:Permission already exists...");
                }
                #endregion


                #region Role
                if (!await myContext.Db.Queryable <Role>().AnyAsync())
                {
                    myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))));
                    Console.WriteLine("Table:Role created success!");
                }
                else
                {
                    Console.WriteLine("Table:Role already exists...");
                }
                #endregion


                #region RoleModulePermission
                if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync())
                {
                    myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission"))));
                    Console.WriteLine("Table:RoleModulePermission created success!");
                }
                else
                {
                    Console.WriteLine("Table:RoleModulePermission already exists...");
                }
                #endregion


                #region UserRole
                if (!await myContext.Db.Queryable <UserRole>().AnyAsync())
                {
                    myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))));
                    Console.WriteLine("Table:UserRole created success!");
                }
                else
                {
                    Console.WriteLine("Table:UserRole already exists...");
                }
                #endregion

                #region SysAdmin
                if (!await myContext.Db.Queryable <SysAdmin>().AnyAsync())
                {
                    myContext.GetEntityDB <SysAdmin>().InsertRange(JsonHelper.ParseFormByJson <List <SysAdmin> >(GetNetData.Get(string.Format(GitJsonFileFormat, "SysAdmin"))));
                    Console.WriteLine("Table:SysAdmin created success!");
                }
                else
                {
                    Console.WriteLine("Table:SysAdmin already exists...");
                }
                #endregion
                Console.WriteLine("Done seeding database.");
                Console.WriteLine();
            }
            catch (Exception ex)
            {
                throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message);
            }
        }
Exemplo n.º 12
0
        /// <summary>
        /// 异步添加种子数据
        /// </summary>
        /// <param name="myContext"></param>
        /// <returns></returns>
        public static async Task SeedAsync(MyContext myContext)
        {
            try
            {
                // 注意!一定要先手动创建一个【空的数据库】
                // 如果生成过了,第二次,就不用再执行一遍了,注释掉该方法即可
                myContext.CreateTableByEntity(false,
                                              typeof(Advertisement),
                                              typeof(BlogArticle),
                                              typeof(Guestbook),
                                              typeof(Module),
                                              typeof(ModulePermission),
                                              typeof(OperateLog),
                                              typeof(PasswordLib),
                                              typeof(Permission),
                                              typeof(Role),
                                              typeof(RoleModulePermission),
                                              typeof(sysUserInfo),
                                              typeof(Topic),
                                              typeof(TopicDetail),
                                              typeof(UserRole));

                // 后期单独处理某些表
                //myContext.Db.CodeFirst.InitTables(typeof(sysUserInfo));
                //myContext.Db.CodeFirst.InitTables(typeof(Permission));
                //myContext.Db.CodeFirst.InitTables(typeof(Advertisement));



                #region BlogArticle
                if (!await myContext.Db.Queryable <BlogArticle>().AnyAsync())
                {
                    myContext.GetEntityDB <BlogArticle>().InsertRange(JsonHelper.ParseFormByJson <List <BlogArticle> >(GetNetData.Get(string.Format(GitJsonFileFormat, "BlogArticle"))));
                }
                #endregion


                #region Module
                if (!await myContext.Db.Queryable <Module>().AnyAsync())
                {
                    myContext.GetEntityDB <Module>().InsertRange(JsonHelper.ParseFormByJson <List <Module> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Module"))));
                }
                #endregion


                #region Permission
                if (!await myContext.Db.Queryable <Permission>().AnyAsync())
                {
                    myContext.GetEntityDB <Permission>().InsertRange(JsonHelper.ParseFormByJson <List <Permission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Permission"))));
                }
                #endregion


                #region Role
                if (!await myContext.Db.Queryable <Role>().AnyAsync())
                {
                    myContext.GetEntityDB <Role>().InsertRange(JsonHelper.ParseFormByJson <List <Role> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Role"))));
                }
                #endregion


                #region RoleModulePermission
                if (!await myContext.Db.Queryable <RoleModulePermission>().AnyAsync())
                {
                    myContext.GetEntityDB <RoleModulePermission>().InsertRange(JsonHelper.ParseFormByJson <List <RoleModulePermission> >(GetNetData.Get(string.Format(GitJsonFileFormat, "RoleModulePermission"))));
                }
                #endregion


                #region Topic
                if (!await myContext.Db.Queryable <Topic>().AnyAsync())
                {
                    myContext.GetEntityDB <Topic>().InsertRange(JsonHelper.ParseFormByJson <List <Topic> >(GetNetData.Get(string.Format(GitJsonFileFormat, "Topic"))));
                }
                #endregion


                #region TopicDetail
                if (!await myContext.Db.Queryable <TopicDetail>().AnyAsync())
                {
                    myContext.GetEntityDB <TopicDetail>().InsertRange(JsonHelper.ParseFormByJson <List <TopicDetail> >(GetNetData.Get(string.Format(GitJsonFileFormat, "TopicDetail"))));
                }
                #endregion


                #region UserRole
                if (!await myContext.Db.Queryable <UserRole>().AnyAsync())
                {
                    myContext.GetEntityDB <UserRole>().InsertRange(JsonHelper.ParseFormByJson <List <UserRole> >(GetNetData.Get(string.Format(GitJsonFileFormat, "UserRole"))));
                }
                #endregion


                #region sysUserInfo
                if (!await myContext.Db.Queryable <sysUserInfo>().AnyAsync())
                {
                    myContext.GetEntityDB <sysUserInfo>().InsertRange(JsonHelper.ParseFormByJson <List <sysUserInfo> >(GetNetData.Get(string.Format(GitJsonFileFormat, "sysUserInfo"))));
                }
                #endregion
            }
            catch (Exception ex)
            {
                throw new Exception("1、注意要先创建空的数据库\n2、" + ex.Message);
            }
        }
Exemplo n.º 13
0
        public async Task <JsonResult <LoginUserDTO> > ShopMallLogin([FromBody] LoginParameterModel obj)
        {
            var model = new JsonResult <LoginUserDTO>
            {
                ret     = 0,
                Success = true
            };

            #region 参数检验
            if (string.IsNullOrWhiteSpace(obj.LoginName) || string.IsNullOrWhiteSpace(obj.Password))
            {
                model.ret    = 1;
                model.Result = "参数有误!";
                return(model);
            }
            #endregion
            var user = await _userServices.GetSysUserByLoginNameAsync(obj.LoginName.Trim());

            if (user == null)
            {
                model.ret    = 1;
                model.Result = "不存在该用户!";
                return(model);
            }

            try
            {
                #region 请求IdentityServer4,校验用户名密码
                IDictionary <string, string> parameters = new Dictionary <string, string>();
                parameters.Add("username", obj.LoginName.Trim());
                parameters.Add("password", obj.Password.Trim());
                parameters.Add("grant_type", "password");
                parameters.Add("client_id", "client2");
                parameters.Add("client_secret", "secret");
                var loginMsg = GetNetData.DoPost("http://shopmall.identityserver.com/connect/token", parameters, "UTF-8");
                #endregion
                if (loginMsg.IndexOf("error_description") > -1)
                {
                    var error = JsonHelper.ParseFormByJson <ErrorViewModel>(loginMsg);
                    model.ret    = 1;
                    model.Result = error.error_description;
                }
                else
                {
                    var          result       = JsonHelper.ParseFormByJson <ResultViewModel>(loginMsg);
                    LoginUserDTO loginUserDTO = new LoginUserDTO()
                    {
                        headPortrait = string.IsNullOrEmpty(user.headPortrait) ? "默认头像" : user.headPortrait,
                        mobile       = user.Mobile,
                        nickname     = user.nickName,
                        token        = $"{result.TokenType} {result.Token}",
                        uid          = user.uid
                    };
                    await _User_LogServices.LoginSuccessServiceAsync(user.uid, 1, $"{user.loginName}登录系统", obj.Source);

                    model.Result  = "登录成功!";
                    model.Content = loginUserDTO;
                }
            }
            catch (Exception e)
            {
                model.ret    = 3;
                model.Result = "e:" + e;
            }
            return(model);
        }