Esempio n. 1
0
        protected override Result <(Price[], Position[])> GetInputs()
        {
            var pricesResult = ResultEx.TryCatch(GetInputPrices);

            if (pricesResult is Failure <Price[]> getPricesFail)
            {
                return(new Failure <(Price[], Position[])>(getPricesFail.Reason));
            }

            var positionsResult = ResultEx.TryCatch(GetInputPositions);

            if (positionsResult is Failure <Position[]> getPostionsFail)
            {
                return(new Failure <(Price[], Position[])>(getPostionsFail.Reason));
            }

            // finally we succeeded
            if (pricesResult is Success <Price[]> pricesSuccess &&
                positionsResult is Success <Position[]> positionsSucces)
            {
                return(new Success <(Price[], Position[])>((pricesSuccess.Value, positionsSucces.Value)));
            }

            return(new Failure <(Price[], Position[])>("SequentalAppFlow.GetInputs - Fatal error."));
        }
Esempio n. 2
0
 /// <summary>
 /// 修改密码
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public ResultEx UpdatePassword(AccountModel.ModifyPwd model)
 {
     using (var dbScope = _dbScopeFactory.Create())
     {
         try
         {
             var db           = dbScope.DbContexts.Get <WebDbContext>();
             var accountModel = this.GetModel(CurrentUser.User.UserName);
             if (accountModel == null)
             {
                 return(ResultEx.Init(false, "未能找到用户信息!"));
             }
             if (accountModel.Password != new MD5Encrtpy().encode(model.OldPwd))
             {
                 return(ResultEx.Init(false, "原始密码错误!"));
             }
             accountModel.Password        = new MD5Encrtpy().encode(model.NewPwd);
             db.Entry(accountModel).State = EntityState.Modified;
             db.SaveChanges();
             return(ResultEx.Init());
         }
         catch (System.Exception ex)
         {
             return(ResultEx.Init(ex));
         }
     }
 }
Esempio n. 3
0
        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        public ResultEx Delete(List <int> ids)
        {
            using (TransactionScope ts = new TransactionScope())
            {
                try
                {
                    using (var dbScope = _dbScopeFactory.Create())
                    {
                        var db = dbScope.DbContexts.Get <WebDbContext>();

                        var query = from p in db.SysRoles
                                    where ids.Contains(p.Id)
                                    select p;

                        query.Delete();

                        //删除从表
                        db.SysRoleMenus.Where(p => ids.Contains(p.RoleId)).Delete();
                        db.SysRoleFunctions.Where(p => ids.Contains(p.RoleId)).Delete();

                        db.SaveChanges();
                        ts.Complete();
                        return(ResultEx.Init());
                    }
                }
                catch (Exception ex)
                {
                    ts.Dispose();
                    return(ResultEx.Init(ex));
                }
            }
        }
Esempio n. 4
0
 /// <summary>
 /// 修改密码
 /// </summary>
 /// <param name="model"></param>
 /// <returns></returns>
 public ResultEx UpdatePassword(int userId, AccountModel.ModifyPwd model)
 {
     using (var dbScope = _dbScopeFactory.Create())
     {
         try
         {
             var db           = dbScope.DbContexts.Get <WebDbContext>();
             var accountModel = db.SysAccounts.Where(x => x.Id == userId).SingleOrDefault();
             if (accountModel == null)
             {
                 return(ResultEx.Init(false, "未能找到用户信息!"));
             }
             if (accountModel.Password != new MD5Encrtpy().encode(model.OldPwd))
             {
                 return(ResultEx.Init(false, "原始密码错误!"));
             }
             db.SysAccounts.Where(x => x.Id == userId).Update(x => new SysAccount {
                 Password = new MD5Encrtpy().encode(model.NewPwd)
             });
             db.SaveChanges();
             return(ResultEx.Init());
         }
         catch (System.Exception ex)
         {
             return(ResultEx.Init(ex));
         }
     }
 }
Esempio n. 5
0
        public IHttpActionResult Login(string userName, string password)
        {
            var response = GetUserToken(userName, password);

            if (response.IsError)
            {
                return(Ok(ResultEx.Init(false, response.Error)));
            }
            var claims = new List <System.Security.Claims.Claim>();
            var model  = _AccountSvc.GetFullModel(userName);

            if (model != null)
            {
                claims.Add(new System.Security.Claims.Claim("UserName", model.UserName));
                claims.Add(new System.Security.Claims.Claim("UserType", model.UserType.ToString()));
                claims.Add(new System.Security.Claims.Claim("UserTypeName", model.UserTypeName));
            }
            var tockenModel = new TokenModel
            {
                AccessToken = response.AccessToken,
                ExpiresIn   = response.ExpiresIn,
                TokenType   = response.TokenType,
                Claims      = claims
            };

            return(Ok(ResultEx.Init(true, "", tockenModel)));
        }
Esempio n. 6
0
 /// <summary>
 /// 用户角色保存
 /// </summary>
 /// <param name="userId"></param>
 /// <param name="roleIds"></param>
 /// <returns></returns>
 public ResultEx SaveAccoutRole(int userId, List <int> roleIds)
 {
     using (TransactionScope ts = new TransactionScope())
     {
         using (var dbScope = _dbScopeFactory.Create())
         {
             try
             {
                 var db = dbScope.DbContexts.Get <WebDbContext>();
                 db.SysAccountRoles.Where(x => x.UserId == userId).Delete();
                 foreach (var roleId in roleIds)
                 {
                     db.SysAccountRoles.Add(new Models.SysAccountRole {
                         RoleId = roleId, UserId = userId
                     });
                 }
                 db.SaveChanges();
                 ts.Complete();
                 return(ResultEx.Init());
             }
             catch (System.Exception ex)
             {
                 ts.Dispose();
                 return(ResultEx.Init(ex));
             }
         }
     }
 }
Esempio n. 7
0
 public static Task <ResultEx <TResult> > ThenAsync <TValue, TResult>(this ResultEx <TValue> result, Func <TValue, Task <TResult> > func)
 {
     return(result.IsError
         ? Task.FromResult(ResultEx <TResult> .FromError(result.Error))
         : func(result.Value).ContinueWith(task => ResultEx <TResult> .FromValue(task.Result), CancellationToken.None,
                                           TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default));
 }
Esempio n. 8
0
 /// <summary>
 /// 删除
 /// </summary>
 /// <param name="ids">主键列表</param>
 /// <returns></returns>
 public ResultEx Delete(List <int> ids)
 {
     using (var dbScope = _dbScopeFactory.Create())
     {
         var db = dbScope.DbContexts.Get <WebDbContext>();
         db.SysAccounts.Where(p => ids.Contains(p.Id)).Delete();
         return(ResultEx.Init());
     }
 }
Esempio n. 9
0
 public static Task <ResultEx <T> > Where <T>(this Task <ResultEx <T> > resultTask, Func <T, bool> predicate,
                                              Func <T, string> errorMessageFunc, TaskScheduler scheduler = null)
 {
     return(resultTask.ContinueWith((task, f) =>
     {
         var result = task.Result;
         return result.IsError ? ResultEx <T> .FromError(result.Error) : result.Where((Func <T, bool>)f, errorMessageFunc);
     }, predicate, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, scheduler ?? TaskScheduler.Default));
 }
Esempio n. 10
0
 /// <summary>
 /// 修改头像
 /// </summary>
 /// <param name="id"></param>
 /// <param name="headPoint"></param>
 /// <returns></returns>
 public ResultEx UpdateHeadPoint(int id, string headPoint)
 {
     using (var dbScope = _dbScopeFactory.Create())
     {
         var db = dbScope.DbContexts.Get <WebDbContext>();
         db.SysAccounts.Where(x => x.Id == id).Update(x => new SysAccount {
             HeadPoint = headPoint
         });
         return(ResultEx.Init());
     }
 }
Esempio n. 11
0
 public static Task <ResultEx <TResult> > ThenAsync <TValue, TResult>(this Task <ResultEx <TValue> > resultTask,
                                                                      Func <TValue, Task <ResultEx <TResult> > > func, TaskScheduler scheduler = null)
 {
     return(resultTask.ContinueWith((task, f) =>
     {
         return task.Result.IsError
                 ? Task.FromResult(ResultEx <TResult> .FromError(task.Result.Error))
                 : ((Func <TValue, Task <ResultEx <TResult> > >)f)(task.Result.Value)
         .ContinueWith(t => t.Result, TaskContinuationOptions.ExecuteSynchronously);
     }, func,
                                    CancellationToken.None, TaskContinuationOptions.DenyChildAttach,
                                    scheduler ?? TaskScheduler.Default).Unwrap());
 }
Esempio n. 12
0
        /// <summary>
        /// 修改菜单
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        public ResultEx Edit(SysMenu menu)
        {
            var result = new ResultEx();

            using (var dbScope = _dbScopeFactory.Create())
            {
                var db = dbScope.DbContexts.Get <WebDbContext>();
                db.Entry(menu).State = System.Data.Entity.EntityState.Modified;
                db.SaveChanges();
                result.msg = "修改成功";
                return(result);
            }
        }
Esempio n. 13
0
 /// <summary>
 /// 保存
 /// </summary>
 /// <param name="model"></param>
 /// <param name="menuIDs"></param>
 /// <param name="funcIDs"></param>
 /// <returns></returns>
 public ResultEx Save(SysRole model, List <int> menuIDs, List <int> funcIDs)
 {
     using (TransactionScope ts = new TransactionScope())
     {
         try
         {
             using (var dbScope = _dbScopeFactory.Create())
             {
                 var db = dbScope.DbContexts.Get <WebDbContext>();
                 if (model.Id == 0)
                 {
                     db.SysRoles.Add(model);
                 }
                 else
                 {
                     db.Entry(model).State = System.Data.Entity.EntityState.Modified;
                 }
                 db.SaveChanges();
                 if (menuIDs != null)
                 {
                     db.SysRoleMenus.Where(p => p.RoleId == model.Id).Delete();
                     foreach (var item in menuIDs)
                     {
                         db.SysRoleMenus.Add(new SysRoleMenu {
                             MenuId = item, RoleId = model.Id
                         });
                     }
                 }
                 if (funcIDs != null)
                 {
                     db.SysRoleFunctions.Where(p => p.RoleId == model.Id).Delete();
                     foreach (var item in funcIDs)
                     {
                         db.SysRoleFunctions.Add(new SysRoleFunction {
                             FunctionId = item, RoleId = model.Id
                         });
                     }
                 }
                 db.SaveChanges();
                 ts.Complete();
                 return(ResultEx.Init());
             }
         }
         catch (Exception ex)
         {
             ts.Dispose();
             return(ResultEx.Init(ex));
         }
     }
 }
Esempio n. 14
0
        /// <summary>
        /// 添加菜单
        /// </summary>
        /// <param name="menu"></param>
        /// <returns></returns>
        public ResultEx Add(SysMenu menu)
        {
            var result = new ResultEx();

            using (var dbScope = _dbScopeFactory.Create())
            {
                var db    = dbScope.DbContexts.Get <WebDbContext>();
                var model = db.SysMenus.Add(menu);
                db.SaveChanges();
                result.data = model;
                result.msg  = "添加成功";
                return(result);
            }
        }
Esempio n. 15
0
        /// <summary>
        /// 批量删除菜单
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public ResultEx Deletes(List <int> ids)
        {
            using (var ts = new TransactionScope())
            {
                using (var dbScope = _dbScopeFactory.Create())
                {
                    try
                    {
                        var db   = dbScope.DbContexts.Get <WebDbContext>();
                        var list = db.SysMenus.ToList();

                        Func <int, List <int> > func = null;
                        func = new Func <int, List <int> >(p =>
                        {
                            var result    = new List <int>();
                            var childList = list.Where(x => x.ParentId == p).ToList();
                            if (childList.Count > 0)
                            {
                                result.AddRange(childList.Select(x => x.Id).ToList());
                            }
                            foreach (var item in childList)
                            {
                                result.AddRange(func(item.Id));
                            }
                            return(result);
                        });
                        foreach (var id in ids)
                        {
                            var childIds = func(id);
                            if (childIds.Count > 0)
                            {
                                db.SysMenus.Where(x => childIds.Contains(x.Id)).Delete();
                            }
                            db.SysMenus.Where(x => x.Id == id).Delete();
                            db.SysMenuFunctions.Where(x => x.MenuId == id).Delete();
                        }
                        db.SaveChanges();
                        ts.Complete();
                        return(ResultEx.Init());
                    }
                    catch (Exception ex)
                    {
                        ts.Dispose();
                        return(ResultEx.Init(ex));
                    }
                }
            }
        }
Esempio n. 16
0
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            //检验登录
            ResultEx res       = new ResultEx();
            var      SSO_Token = filterContext.HttpContext.Session["SSO_Token"];
            //获取returnurl
            string strHost   = filterContext.HttpContext.Request.Url.Host;
            string strPort   = filterContext.HttpContext.Request.Url.Port.ToString();
            string url       = string.Format("http://{0}:{1}{2}", strHost, strPort, filterContext.HttpContext.Request.RawUrl);
            string returnurl = Regex.Replace(url, @"(\?|&)cert=.*", "", RegexOptions.IgnoreCase);

            if (SSO_Token != null)//验证token获取用户信息
            {
                res = IdentityByToken(SSO_Token.ToString());
                if (!res.Flag)
                {
                    //跳转到登录
                    filterContext.HttpContext.Session.Abandon();//清除session
                    filterContext.Result = new RedirectResult(CommonConstants.SSO_URL + "/Home/Login?returnurl=" + returnurl);
                }
            }
            else if (!string.IsNullOrEmpty(filterContext.HttpContext.Request.QueryString["cert"]))//验证一次性cert
            {
                res = IdentityByCert(filterContext.HttpContext.Request.QueryString["cert"]);
                if (res.Flag)
                {
                    string token = res.Data.ToString();
                    //更新session
                    filterContext.HttpContext.Session["SSO_Token"] = token;
                    //验证token
                    res = IdentityByToken(token);
                }
                if (!res.Flag)
                {
                    //跳转到登录
                    filterContext.HttpContext.Session.Abandon();//清除session
                    filterContext.Result = new RedirectResult(CommonConstants.SSO_URL + "/Home/Login?returnurl=" + returnurl);
                }
            }
            else
            {
                //跳转到登录
                filterContext.Result = new RedirectResult(CommonConstants.SSO_URL + "/Home/Login?returnurl=" + returnurl);
            }


            base.OnActionExecuting(filterContext);
        }
Esempio n. 17
0
 /// <summary>
 /// 保存
 /// </summary>
 /// <param name="model">model</param>
 /// <returns></returns>
 public ResultEx Save(SysAccount model)
 {
     using (var dbScope = _dbScopeFactory.Create())
     {
         var db = dbScope.DbContexts.Get <WebDbContext>();
         if (model.Id == 0)
         {
             db.SysAccounts.Add(model);
         }
         else
         {
             db.Entry(model).State = System.Data.Entity.EntityState.Modified;
         }
         return(ResultEx.Init(db.SaveChanges() > 0));
     }
 }
Esempio n. 18
0
 /// <summary>
 /// 重置密码
 /// </summary>
 /// <param name="ids"></param>
 /// <param name="password"></param>
 /// <returns></returns>
 public ResultEx ResetPassWord(List <int> ids, string password)
 {
     using (var dbScope = _dbScopeFactory.Create())
     {
         try
         {
             var db = dbScope.DbContexts.Get <WebDbContext>();
             db.SysAccounts.Where(x => ids.Contains(x.Id)).Update(x => new SysAccount {
                 Password = password
             });
             return(ResultEx.Init());
         }
         catch (System.Exception ex)
         {
             return(ResultEx.Init(ex));
         }
     }
 }
Esempio n. 19
0
 /// <summary>
 /// 批量更新状态
 /// </summary>
 /// <param name="ids"></param>
 /// <param name="flag"></param>
 /// <returns></returns>
 public ResultEx Enabled(List <int> ids, bool flag)
 {
     using (var dbScope = _dbScopeFactory.Create())
     {
         try
         {
             var db = dbScope.DbContexts.Get <WebDbContext>();
             db.SysAccounts.Where(x => ids.Contains(x.Id)).Update(x => new SysAccount {
                 IsEnabled = !flag
             });
             return(ResultEx.Init());
         }
         catch (System.Exception ex)
         {
             return(ResultEx.Init(ex));
         }
     }
 }
        public static Task <ResultEx <TResult> > ThenTryAsync <TValue, TResult>(this Result <TValue> result,
                                                                                Func <TValue, Task <Result <TResult> > > func)
        {
            if (result.IsError)
            {
                return(Task.FromResult(ResultEx <TResult> .FromError(new ResultErrorException(result.Error))));
            }

            try
            {
                return(func(result.Value).ContinueWith(task => task.Result.ToResultEx(),
                                                       TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously));
            }
            catch (Exception e)
            {
                return(Task.FromResult(ResultEx <TResult> .FromError(e)));
            }
        }
Esempio n. 21
0
        public void UpdatePasswordOldPwdNotRight()
        {
            var model = new AccountModel.ModifyPwd {
                ConfirmPwd = "123456", NewPwd = "123456", OldPwd = "888888", UserID = 1
            };
            var accountService = new Mock <IAccountSvc>();

            accountService
            .Setup(c => c.UpdatePassword(model))
            .Returns(ResultEx.Init());
            // Target object
            var presenter = new AccountPresenter(accountService.Object);
            // Act
            var result = presenter.UpdatePassword(model);

            // Assert
            Assert.NotNull(result);
            Assert.True(result.flag);
            Assert.Empty(result.msg);
        }
Esempio n. 22
0
        public ResultEx ConnectTest(InstallSqlServerModel sqlServerModel)
        {
            var result = CheckSqlServerParameter(sqlServerModel);

            if (result.Flag)
            {
                string connectionString;
                if (sqlServerModel.ConnectionString != null)
                {
                    sqlServerModel.ConnectionString = sqlServerModel.ConnectionString.Trim();
                }
                if (sqlServerModel.ConnectionType == ConnectionType.String)
                {
                    connectionString = sqlServerModel.ConnectionString;
                }
                else
                {
                    connectionString = CreateConnectionString(
                        sqlServerModel.AuthenticationType == AuthenticationType.Windows,
                        sqlServerModel.ServerName, sqlServerModel.DatabaseName, sqlServerModel.Username,
                        sqlServerModel.Password);
                }
                try
                {
                    //通过连接数据库方式确定
                    using (var conn = new SqlConnection(connectionString))
                    {
                        conn.Open();
                        conn.Close();
                    }
                    return(ResultEx.Init(true));
                }
                catch (Exception ex)
                {
                    return(ResultEx.Init(false, ex.Message));
                }
            }

            return(result);
        }
        public static Task <ResultEx <TResult> > ThenTryAsync <TValue, TResult>(this Result <TValue> result, Func <TValue, Task <TResult> > func)
        {
            if (result.IsError)
            {
                return(Task.FromResult(ResultEx <TResult> .FromError(new ResultErrorException(result.Error))));
            }

            try
            {
                return(func(result.Value)
                       .ContinueWith(task => task.IsFaulted
                            ? ResultEx <TResult> .FromError(task.Exception.TryFlattenAggregateException())
                            : ResultEx <TResult> .FromValue(
                                         task.Result), CancellationToken.None,
                                     TaskContinuationOptions.DenyChildAttach | TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default));
            }
            catch (Exception e)
            {
                var exception = (e as AggregateException)?.GetBaseException() ?? e;
                return(Task.FromResult(ResultEx <TResult> .FromError(exception)));
            }
        }
Esempio n. 24
0
 /// <summary>
 /// 保存功能
 /// </summary>
 /// <param name="menuId"></param>
 /// <param name="List"></param>
 /// <returns></returns>
 public ResultEx Save(int menuId, List <SysMenuFunction> List)
 {
     using (TransactionScope ts = new TransactionScope())
     {
         try
         {
             using (var dbScope = _dbScopeFactory.Create())
             {
                 var db           = dbScope.DbContexts.Get <WebDbContext>();
                 var notDeleteIds = List.Where(p => p.Id != 0).Select(p => p.Id).ToList();
                 if (notDeleteIds.Count > 0)
                 {
                     db.SysMenuFunctions.Where(p => !notDeleteIds.Contains(p.Id) && p.MenuId == menuId).Delete();
                 }
                 foreach (var item in List)
                 {
                     item.MenuId = menuId;
                     if (item.Id != 0)
                     {
                         db.Entry(item).State = System.Data.Entity.EntityState.Modified;
                     }
                     else
                     {
                         db.SysMenuFunctions.Add(item);
                     }
                 }
                 var rs = db.SaveChanges();
             }
             ts.Complete();
             return(ResultEx.Init());
         }
         catch (Exception ex)
         {
             ts.Dispose();
             return(ResultEx.Init(ex));
         }
     }
 }
        public static Task <ResultEx <TResult> > ThenTryAsync <TValue, TResult>(this Task <Result <TValue> > resultTask,
                                                                                Func <TValue, Task <TResult> > func, TaskScheduler scheduler = null)
        {
            return(resultTask.ContinueWith((task, f) =>
            {
                var result = task.Result;
                if (result.IsError)
                {
                    return Task.FromResult(ResultEx <TResult> .FromError(new ResultErrorException(result.Error)));
                }

                try
                {
                    return ((Func <TValue, Task <TResult> >)f)(task.Result.Value)
                    .ContinueWith(t => ResultEx.FromValue(t.Result), TaskContinuationOptions.ExecuteSynchronously);
                }
                catch (Exception e)
                {
                    return Task.FromResult(ResultEx <TResult> .FromError(e));
                }
            }, func, CancellationToken.None, TaskContinuationOptions.DenyChildAttach,
                                           scheduler ?? TaskScheduler.Default).Unwrap());
        }
Esempio n. 26
0
        protected override Result <(Price[], Position[])> GetInputs()
        {
            var pricesAsync    = ResultEx.TryCatchAsync(GetInputPrices);
            var positionsAsync = ResultEx.TryCatchAsync(GetInputPositions);

            var(pricesResult, positionsResult) = TaskEx.WhenAll(pricesAsync, positionsAsync).Result;
            switch (pricesResult)
            {
            case Success <Price[]> successPrice when positionsResult is Success <Position[]> positionsSuccess:
                return(new Success <(Price[], Position[])>((successPrice.Value, positionsSuccess.Value)));

            // :( it's all about failures
            case Failure <Price[]> priceFailure when positionsResult is Failure <Position[]> positionFailure:
                return(new Failure <(Price[], Position[])>(priceFailure.Reason + " " + positionFailure.Reason));

            case Failure <Price[]> failure:
                return(new Failure <(Price[], Position[])>(failure.Reason));

            case Success <Price[]> _ when positionsResult is Failure <Position[]> failure:
                return(new Failure <(Price[], Position[])>(failure.Reason));
            }

            return(new Failure <(Price[], Position[])>("ParallelAppFlow.GetInputs - Fatal error."));
        }
Esempio n. 27
0
        public async Task <ResultEx> InitDataBase(InstallSqlServerModel sqlServerModel)
        {
            var result = CheckSqlServerParameter(sqlServerModel);

            if (result.Flag)
            {
                _dataBaseName = result.Data.ToString();
                string connectionString;
                if (!string.IsNullOrEmpty(sqlServerModel.ConnectionString))
                {
                    sqlServerModel.ConnectionString = sqlServerModel.ConnectionString.Trim();
                }
                if (sqlServerModel.ConnectionType == ConnectionType.String)
                {
                    connectionString = sqlServerModel.ConnectionString;
                }
                else
                {
                    connectionString = CreateConnectionString(
                        sqlServerModel.AuthenticationType == AuthenticationType.Windows,
                        sqlServerModel.ServerName, sqlServerModel.DatabaseName, sqlServerModel.Username,
                        sqlServerModel.Password);
                }

                //创建新的DBContext对象只是数据库创建操作
                var builder = new DbContextOptionsBuilder();
                builder.UseSqlServer(connectionString);
                var dbContext       = new Kj1012Context(builder.Options);
                var dataBase        = dbContext.Database;
                var databaseCreator = dataBase.GetService <IRelationalDatabaseCreator>();
                sqlServerModel.ConnectionString = connectionString;
                var isCreateDatabase = false;
                if (sqlServerModel.AlwaysCreate)
                {
                    if (databaseCreator.Exists())
                    {
                        await databaseCreator.DeleteAsync();
                    }
                    await CreateDataBase(databaseCreator, dataBase);

                    isCreateDatabase = true;
                }
                else if (sqlServerModel.NotExistCreate)
                {
                    if (!databaseCreator.Exists())
                    {
                        await CreateDataBase(databaseCreator, dataBase);

                        isCreateDatabase = true;
                    }
                }
                else
                {
                    if (!databaseCreator.Exists())
                    {
                        return(ResultEx.Init(false, "数据库名称不存在,请核对"));
                    }
                }
                var version = GetSqlServerVersion(sqlServerModel.ConnectionString);
                if (version < 10)
                {
                    return(ResultEx.Init(false, "创建数据表失败,Sql Server 数据库版本至少需要Sql Server 2008及以上"));
                }
                if (version > 0)
                {
                    //SQL Server2016 及以上执行2016脚本
                    if (version >= 13 && isCreateDatabase)
                    {
                        //执行2016脚本
                        ExecuteSqlScriptFromFile(dataBase, $"{SqlServerScriptPath}\\SqlServer_2016.sql");
                    }
                    //保存数据库配置信息
                    _appSettingService.SaveDataSetting(new DataSettings
                    {
                        DataProvider     = DataProviderType.SqlServer,
                        Version          = version,
                        ConnectionString = AesHelper.AesEncrypt(sqlServerModel.ConnectionString, ConstDefine.DataSettingAesKey)
                    });
                }
                else
                {
                    return(ResultEx.Init(false, "创建数据表失败,未知SQL SERVER数据库版本"));
                }
            }

            return(result);
        }
Esempio n. 28
0
        public async Task <ResultEx> SaveEntityAsync(Device entity)
        {
            //分站程序编号和序号保持一致
            if (entity.DeviceType == DeviceTypeEnum.Substation)
            {
                if (entity.DeviceNum < 1 || entity.DeviceNum > 64)
                {
                    return(ResultEx.Init(false, "分站编号只能为1~64"));
                }
                entity.SerialNum = entity.DeviceNum;
            }
            if (!(entity.DeviceType == DeviceTypeEnum.BaseStation || entity.DeviceType == DeviceTypeEnum.BeaconCard))
            {
                entity.SubstationId = null;
            }
            else
            {
                if (entity.DeviceNum < 1 || entity.DeviceNum > 65535)
                {
                    return(ResultEx.Init(false, "基站编号只能为1~65535"));
                }
                if (entity.SerialNum.GetValueOrDefault(0) > 64 || entity.SerialNum.GetValueOrDefault(0) < 1)
                {
                    return(ResultEx.Init(false, "设备序号只能为1~64的数字"));
                }
            }

            if (entity.Id == Guid.Empty)
            {
                // 查看相同设备类型下的编号是否已经使用
                var existEntity = await BaseRepository.TableNoTracking.FirstOrDefaultAsync(r =>
                                                                                           r.DeviceType == entity.DeviceType && r.DeviceNum == entity.DeviceNum);

                if (existEntity != null)
                {
                    return(ResultEx.Init(false, "该设备类型指定的编号已经存在,请使用其它编号"));
                }
                //查看基站和定位器序号是否已经使用
                if (entity.DeviceType == DeviceTypeEnum.BaseStation || entity.DeviceType == DeviceTypeEnum.BeaconCard)
                {
                    //基站和定位器编号不能重复
                    existEntity = await BaseRepository.TableNoTracking.FirstOrDefaultAsync(r =>
                                                                                           (r.DeviceType == DeviceTypeEnum.BaseStation || r.DeviceType == DeviceTypeEnum.BeaconCard) && r.DeviceNum == entity.DeviceNum);

                    if (existEntity != null)
                    {
                        return(ResultEx.Init(false, "编号在基站或者定位器中已使用,请换其他编号"));
                    }

                    //判断相同类型设备同一分站下序号是否重复
                    existEntity = await BaseRepository.TableNoTracking.FirstOrDefaultAsync(r =>
                                                                                           r.DeviceType == entity.DeviceType && r.SubstationId == entity.SubstationId && r.SerialNum == entity.SerialNum);

                    if (existEntity != null)
                    {
                        return(ResultEx.Init(false, "设备序号已经使用,请换其它序号"));
                    }
                }
                //基站和分站新增时状态处理为未知
                if (entity.DeviceType == DeviceTypeEnum.BaseStation || entity.DeviceType == DeviceTypeEnum.Substation)
                {
                    entity.DeviceState = -1;
                }
                entity.SysStartTime = DateTime.Now;
                entity.SysEndTime   = DateTime.MaxValue;
                //新增
                await BaseRepository.InsertAsync(entity);

                var result = await _unitOfWork.SaveChangesAsync();

                if (result <= 0)
                {
                    return(ResultEx.Init(false, "保存失败"));
                }

                await _cacheProvider.RemoveAsync($"devices:{entity.DeviceNum}");

                //新增时同步将数据推送到mqtt,下发到下位机,编辑时不下发
                //因为保存进来的数据没有设备所属分站信息,所有这里需要从数据库重新查询一次
                if (entity.SubstationId != null && entity.SubstationId != Guid.Empty)
                {
                    entity.Substation = await BaseRepository.GetByKeys(entity.SubstationId);
                }
#pragma warning disable 4014
                _devicePublish.AddPublishAsync(entity);
#pragma warning restore 4014
            }
            else
            {
                //修改时候讲分站对象赋值空,否则,修改时候会循环多次修改相关数据
                entity.Substation = null;
                var newDevice = BaseRepository.Table.Update(entity);
                //设备状态和设备状态监测时间是不能修改的
                newDevice.Property(r => r.DeviceState).IsModified   = false;
                newDevice.Property(r => r.LastCheckTime).IsModified = false;
                newDevice.Property(r => r.CreateDate).IsModified    = false;
                newDevice.Property(r => r.SysStartTime).IsModified  = false;
                newDevice.Property(r => r.SysEndTime).IsModified    = false;
                int result = await _unitOfWork.SaveChangesAsync();

                if (result <= 0)
                {
                    return(ResultEx.Init(false, "保存失败"));
                }
            }
            return(ResultEx.Init());
        }
Esempio n. 29
0
 public static ResultHasNoValueException From <TValue>(ResultEx <TValue> _) =>
 new ResultHasNoValueException(string.Format(MESSAGE, typeof(Result <TValue>).Name));
Esempio n. 30
0
 public static ResultInInvalidStateException From <TValue>(ResultEx <TValue> result) =>
 new ResultInInvalidStateException(string.Format(MESSAGE, typeof(Result <TValue>).Name));