Example #1
0
        public HttpResponseMessage Cadastrar(CadastroModel cadastro)
        {
            if (cadastro == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound, $"mensagem: usuário vazio"));
            }

            try
            {
                AuthDAO authDAO = new AuthDAO();

                if (!authDAO.ExisteUsuario(cadastro.Usuario))
                {
                    Services.Hash hash = new Services.Hash();

                    string senhaMD5 = hash.GerarMD5($"{cadastro.Usuario}{cadastro.Senha}");

                    authDAO.Cadastrar(cadastro.Usuario, senhaMD5);

                    return(Request.CreateResponse(HttpStatusCode.OK, $"mensagem: usuário cadastrado"));
                }
            }
            catch (Exception)
            {
                return(Request.CreateResponse(HttpStatusCode.BadRequest, $"mensagem: Erro inesperado"));
            }

            return(Request.CreateResponse(HttpStatusCode.BadRequest, $"mensagem: usuário já existe"));
        }
Example #2
0
        public HttpResponseMessage Login(LoginModel login)
        {
            if (login == null)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            try
            {
                Services.Hash hash    = new Services.Hash();
                AuthDAO       authDAO = new AuthDAO();

                string senhaMD5 = hash.GerarMD5($"{login.Usuario}{login.Senha}");

                UsuarioModel usuario = authDAO.BuscarUsuario(login.Usuario, senhaMD5);

                if (usuario != null)
                {
                    usuario.Token = hash.GerarMD5($"{login.Usuario}{login.Senha}{DateTime.Now}");

                    authDAO.InserirToken(usuario.Usuario, usuario.Token);

                    return(Request.CreateResponse(HttpStatusCode.OK, new { userInfo = usuario }));
                }
            }
            catch (Exception)
            {
                return(Request.CreateResponse(HttpStatusCode.Unauthorized));
            }

            return(Request.CreateResponse(HttpStatusCode.Unauthorized));
        }
 /// <summary>
 /// Responsável por efetuar login na aplicação
 /// </summary>
 /// <param name="usuario">Login do usuário registrado na aplicação</param>
 /// <param name="senha">Senha do usuário registrado na aplicação</param>
 /// <returns></returns>
 public UsuarioAutenticado Login(string usuario, string senha)
 {
     using (var dao = new AuthDAO())
     {
         return(dao.Login(usuario, senha));
     }
 }
Example #4
0
        private void Button_Click_20(object sender, RoutedEventArgs e)
        {
            AuthDAO authDAO = new AuthDAO();
            var     result  = authDAO.GetByAuthLevel(Auther.AUTH_LEVEL_MANAGER);

            MessageBox.Show(JsonTools.Obj2JSONStrNew(result));
        }
 /// <summary>
 /// Responsável por inserir usuário na aplicação
 /// </summary>
 /// <param name="entidade">Entidade de usuário para registrar na aplicação</param>
 public void Registrar(Usuario entidade)
 {
     using (var dao = new AuthDAO())
     {
         dao.Registrar(entidade);
     }
 }
Example #6
0
        public void updateTest()
        {
            using (TransactionScope ts = new TransactionScope())//使整个代码块成为事务性代码

            {
                AuthDAO dao = new AuthDAO();
                Auther  a   = dao.Load(2);
                a.Auth_UserName = "******";
                dao.UpdateByPrimaryKey(a);
                //插入至上传表
                UploadManagementDAO uploadManagementDao1 = new UploadManagementDAO();
                uploadManagementDao1.Insert(new UploadManagement(a.Pk_Auth_Id, "bdl_auth", 1));

                Auther b = new Auther();
                b.Auth_UserName = "******";
                dao.Insert(b);
                //插入至上传表
                UploadManagementDAO uploadManagementDao = new UploadManagementDAO();
                uploadManagementDao.Insert(new UploadManagement(b.Pk_Auth_Id, "bdl_auth", 0));

                int p = 0;
                //int l = 8 / p;

                ts.Complete();
            }
        }
Example #7
0
        private void Button_Click_5(object sender, RoutedEventArgs e)
        {
            AuthDAO authDAO     = new AuthDAO();
            Auther  auther      = authDAO.Login("123", "123");
            string  pingJsonStr = JsonTools.Obj2JSONStrNew(auther);

            MessageBox.Show(pingJsonStr);
        }
Example #8
0
        private void Button_Click_3(object sender, RoutedEventArgs e)
        {
            AuthDAO authDAO     = new AuthDAO();
            Auther  auther      = authDAO.GetByAuthLevel(Auther.AUTH_LEVEL_ADMIN);
            string  pingJsonStr = JsonTools.Obj2JSONStrNew(auther);

            MessageBox.Show(pingJsonStr);
        }
Example #9
0
        public void UpLoadAuth()
        {
            int pk_auth_id = new AuthDAO().getIdByMaxId();

            Console.WriteLine(pk_auth_id);

            /*
             * 多余的,不需要加
             * UploadManagement uploadManagement = new UploadManagement(pk_auth_id, "bdl_auth");
             * uploadManagementDAO.Insert(uploadManagement);*/
        }
Example #10
0
        //得到当前状态的心跳
        public HttpHeartBeat GetHeartBeatByCurrent()
        {
            HttpHeartBeat sendHeartBeat = null;

            //不属于未注册状态
            SetterDAO setterDAO = new SetterDAO();
            Setter    setter    = setterDAO.getSetter();

            if (setterDAO.ListAll().Count != 1)
            {
                //设置表没有唯一标识,直接返回
                return(null);
            }

            //需要加入解密逻辑
            string mac = "";

            //获得当前主机的mac地址
            mac = SystemInfo.GetMacAddress().Replace(":", "-");
            AuthDAO authDAO = new AuthDAO();
            var     result  = authDAO.GetByAuthLevel(Auther.AUTH_LEVEL_MANAGER);

            //注册用户设置mac与用户名
            //TODO设置mac地址不能从本地拿,必须实时获取


            sendHeartBeat = new HttpHeartBeat(result.Auth_UserName, mac);

            if (result.User_Status == Auther.USER_STATUS_FREEZE)
            {
                //是否为冻结状态的心跳,这里不能从数据库取,否则,云通知本地锁死,本地改状态后,会再次通知云锁死本机,陷入死循环
                sendHeartBeat.heartbeatType = 1;
                sendHeartBeat.authStatus    = 0;
            }
            else if (result.User_Status == Auther.USER_STATUS_FREE)

            {
                //是否完全离线
                sendHeartBeat.heartbeatType = 2;
                sendHeartBeat.authStatus    = 0;
            }
            else
            {
                //默认为正常心跳
                sendHeartBeat.heartbeatType = 0;
                sendHeartBeat.authStatus    = 0;
            }


            return(sendHeartBeat);
        }
Example #11
0
        public async Task <IActionResult> Index(string username, string password)
        {
            using (var authDAO = new AuthDAO())
            {
                var result = await authDAO.Read(username, password);

                if (result == null)
                {
                    return(Json(null));
                }
                var sessionId = await authDAO.CreateSession(result.Id);

                dynamic jsonObj = new ExpandoObject();

                jsonObj.sessionId  = sessionId;
                jsonObj.name       = result.Name;
                jsonObj.profileImg = result.ProfileImg;

                if (result.Employee != null)
                {
                    jsonObj.customer = null;
                    jsonObj.employee = new
                    {
                        address     = result.Employee.Address,
                        dateOfBirth = result.Employee.DateOfBirth,
                        homeTown    = result.Employee.HomeTown,
                        phoneNumber = result.Employee.PhoneNumber,
                        email       = result.Employee.Email,
                        type        = result.Employee.Type,
                        store       = result.Employee.Store
                    };
                }
                else
                {
                    jsonObj.customer = new
                    {
                        address     = result.Customer.Address,
                        phoneNumber = result.Customer.PhoneNumber,
                        email       = result.Customer.Email,
                        point       = result.Customer.Point.Value
                    };
                    jsonObj.employee = null;
                }

                return(Json(jsonObj));
            }
        }
        /// <summary>
        /// 获取当前心跳
        /// </summary>
        /// <returns></returns>
        public static HeartbeatRequest GetHeartBeatByCurrent()
        {
            HeartbeatRequest sendHeartBeat = new HeartbeatRequest();
            //不属于未注册状态
            SetterDAO setterDAO = new SetterDAO();
            Setter    setter    = setterDAO.getSetter();

            if (setterDAO.ListAll().Count != 1)
            {
                //设置表没有唯一标识,直接返回
                return(null);
            }
            AuthDAO authDAO = new AuthDAO();
            var     result  = authDAO.GetByAuthLevel(Auther.AUTH_LEVEL_MANAGER);

            if (result == null)
            {
                return(null);
            }
            //机器码mac地址从本地拿
            sendHeartBeat.UniqueId = setter.Set_Unique_Id;
            //setting表装换成json,赋值
            sendHeartBeat.SettingJSON = JsonTools.Obj2JSONStrNew <Setter>(setter);
            //项目名 医疗康复赋值
            sendHeartBeat.ProductName = "医疗康复";
            //使用期限
            sendHeartBeat.UseDeadTime = result.Auth_OfflineTime.ToString().Replace("/", "-");
            //地理位置
            //sendHeartBeat.Address = setter.Set_Organizationaddress;
            //冻结
            if (result.User_Status == Auther.USER_STATUS_FREEZE)
            {
                //是否为冻结状态的心跳,这里不能从数据库取,否则,云通知本地锁死,本地改状态后,会再次通知云锁死本机,陷入死循环
                //状态 正常0和锁定1
                sendHeartBeat.Status = 1.ToString();
            }
            //正常
            else if (result.User_Status == Auther.USER_STATUS_GENERAL)
            {
                //状态 正常0和锁定1
                //默认为正常心跳
                sendHeartBeat.Status = 0.ToString();
            }
            return(sendHeartBeat);
        }
Example #13
0
        /// <summary>
        /// 根据web传来的心跳信息,做操作
        /// </summary>
        /// <param name="httpHeartBeat"></param>
        public void SolveHeartbeat(HttpHeartBeat httpHeartBeat)
        {
            AuthDAO authDAO = new AuthDAO();
            Auther  auther  = authDAO.GetByAuthLevel(Auther.AUTH_LEVEL_MANAGER);

            if (httpHeartBeat.authStatus == 0)
            {
                //0权限操作位  不作处理,属于正常心跳
                //解锁
                auther.User_Status = Auther.USER_STATUS_GENERAL;
            }
            else if (httpHeartBeat.authStatus == 1)
            {
                //锁定
                auther.User_Status = Auther.USER_STATUS_FREEZE;
            }
            else if (httpHeartBeat.authStatus == 2)
            {
                //解锁
                auther.User_Status = Auther.USER_STATUS_GENERAL;
            }
            else if (httpHeartBeat.authStatus == 3)
            {
                //永久离线至9999年
                auther.User_Status      = Auther.USER_STATUS_FREE;
                auther.Auth_OfflineTime = Auther.Auth_OFFLINETIMEFREE;
            }
            else if (httpHeartBeat.authStatus == 4)
            {
                //删除用户,做冻结处理
                auther.User_Status = Auther.USER_STATUS_FREEZE;
            }

            authDAO.UpdateByPrimaryKey(auther);
            //插入至上传表
            UploadManagementDAO uploadManagementDao = new UploadManagementDAO();

            uploadManagementDao.Insert(new UploadManagement(auther.Pk_Auth_Id, "bdl_auth", 1));
        }
Example #14
0
        //按钮:高级设置
        private void AdvancedSettings(object sender, RoutedEventArgs e)
        {
            //Window window = (Window)this.Parent;
            //window.Content = new AdvancedSettingPassWord();

            /*AdvancedSettingPassWord advancedSettingPassWord = new AdvancedSettingPassWord
             * {
             *  Owner = Window.GetWindow(this),
             *  ShowActivated = true,
             *  ShowInTaskbar = false,
             *  WindowStartupLocation = WindowStartupLocation.CenterScreen
             * };
             * advancedSettingPassWord.ShowDialog();
             * if (advancedSettingPassWord.IsTrue == 1)
             * {
             *  Window window = (Window)this.Parent;
             *  window.Content = new AdvancedSettings();
             * }*/
            AuthDAO authDAO = new AuthDAO();
            Auther  auther  = new Auther();

            try
            {
                auther = authDAO.Login(UserConstant.USERNAME, UserConstant.PASSWORD);
                if (auther.Auth_Level == 0x00)
                {
                    Window window = (Window)this.Parent;
                    window.Content = new AdvancedSettings();
                }
                else
                {
                    MessageBoxX.Info(LanguageUtils.ConvertLanguage("当前用户没有权限,请与管理员取得联系", "The current user does not have permission. Please contact the administrator"));
                }
            }
            catch (Exception ee)
            {
                MessageBoxX.Info(LanguageUtils.ConvertLanguage("请先登陆", "Log in first, please"));
            }
        }
Example #15
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="uploadManagement">传入上传管理者实体</param>
        /// <returns>返回可以用来上传的辅助对象</returns>
        public ServiceResult GetServiceResult(UploadManagement uploadManagement)
        {
            //service返回结果对象
            ServiceResult serviceResult = new ServiceResult();
            //提前载入唯一Setter
            SetterDAO setterDAO = new SetterDAO();
            Setter    setter    = setterDAO.getSetter();
            //需要加入解密逻辑 TODO
            string mac = "";

            //try
            //{
            //    byte[] deBytes = AesUtil.Decrypt(Encoding.GetEncoding("GBK").GetBytes(setter.Set_Unique_Id),
            //        ProtocolConstant.USB_DOG_PASSWORD);
            //    mac = Encoding.GetEncoding("GBK").GetString(deBytes);
            //}
            //catch (Exception ex)
            //{
            //    mac = setter.Set_Unique_Id.Replace(":", "");
            //}
            byte[] a = ProtocolUtil.StringToBcd(setter.Set_Unique_Id);
            byte[] b = AesUtil.Decrypt(a, ProtocolConstant.USB_DOG_PASSWORD);
            mac = Encoding.GetEncoding("GBK").GetString(b).Replace(":", "-");

            ///if识别出表,设置发送路径,select出实体,转化至DTO,json打成string,返回
            //识别是否是权限用户添加
            if (uploadManagement.UM_DataTable == "bdl_auth")
            {
                AuthDAO authDAO = new AuthDAO();
                Auther  auther  = authDAO.Load(uploadManagement.UM_DataId);
                if (auther == null)
                {
                    return(null);
                }
                AutherDTO autherDTO = new AutherDTO(setter, auther, mac);


                //serviceResult.URL = "clientController/addClient.action";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <AutherDTO>(autherDTO);
            }
            //bdl_customdata表
            else if (uploadManagement.UM_DataTable == "bdl_customdata")
            {
                CustomDataDAO customDataDAO = new CustomDataDAO();
                CustomData    customData    = customDataDAO.Load(uploadManagement.UM_DataId);
                if (customData == null)
                {
                    return(null);
                }
                CustomDataDTO customDataDTO = new CustomDataDTO(customData, mac);
                serviceResult.Data = JsonTools.Obj2JSONStrNew <CustomDataDTO>(customDataDTO);
            }
            //bdl_datacode表
            else if (uploadManagement.UM_DataTable == "bdl_datacode")
            {
                DataCodeDAO dataCodedao = new DataCodeDAO();
                DataCode    dataCode    = dataCodedao.Load(uploadManagement.UM_DataId);

                if (dataCode == null)
                {
                    return(null);
                }
                DataCodeDTO dataCodeDTO = new DataCodeDTO(dataCode, mac);
                serviceResult.Data = JsonTools.Obj2JSONStrNew <DataCodeDTO>(dataCodeDTO);
            }
            //bdl_deviceset表
            else if (uploadManagement.UM_DataTable == "bdl_deviceset")
            {
                DeviceSetDAO deviceSetDAO = new DeviceSetDAO();
                DeviceSet    deviceSet    = deviceSetDAO.Load(uploadManagement.UM_DataId);
                if (deviceSet == null)
                {
                    return(null);
                }
                DeviceSetDTO deviceSetDTO = new DeviceSetDTO(deviceSet, mac);

                serviceResult.Data = JsonTools.Obj2JSONStrNew <DeviceSetDTO>(deviceSetDTO);
            }
            //bdl_devicesort表
            else if (uploadManagement.UM_DataTable == "bdl_devicesort")
            {
                DeviceSortDAO deviceSortDAO = new DeviceSortDAO();
                DeviceSort    deviceSort    = deviceSortDAO.Load(uploadManagement.UM_DataId);
                if (deviceSort == null)
                {
                    return(null);
                }
                DeviceSortDTO deviceSortDTO = new DeviceSortDTO(deviceSort, mac);


                serviceResult.Data = JsonTools.Obj2JSONStrNew <DeviceSortDTO>(deviceSortDTO);
            }
            //bdl_onlinedevice表
            else if (uploadManagement.UM_DataTable == "bdl_onlinedevice")
            {
                OnlineDeviceDAO onlineDeviceDAO = new OnlineDeviceDAO();
                OnlineDevice    onlineDevice    = onlineDeviceDAO.Load(uploadManagement.UM_DataId);

                if (onlineDevice == null)
                {
                    return(null);
                }
                OnlineDeviceDTO onlineDeviceDTO = new OnlineDeviceDTO(onlineDevice, mac);

                serviceResult.Data = JsonTools.Obj2JSONStrNew <OnlineDeviceDTO>(onlineDeviceDTO);
            }
            //bdl_set表
            else if (uploadManagement.UM_DataTable == "bdl_set")
            {
                SetterDAO setterDAO1 = new SetterDAO();
                Setter    setter1    = setterDAO1.Load(uploadManagement.UM_DataId);

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

                SetterDTO setterDTO = new SetterDTO(setter1, mac);

                serviceResult.Data = JsonTools.Obj2JSONStrNew <SetterDTO>(setterDTO);
            }
            //病人表
            else if (uploadManagement.UM_DataTable == "bdl_user")
            {
                UserDAO userDAO = new UserDAO();
                User    user    = userDAO.Load(uploadManagement.UM_DataId);
                if (user == null)
                {
                    return(null);
                }


                UserDTO userDTO = new UserDTO(user, mac);
                //serviceResult.URL = "bigData/bodyStrongUser";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <UserDTO>(userDTO);
            }

            //症状表
            else if (uploadManagement.UM_DataTable == "bdl_symptominfo")
            {
                SymptomInfoDao symptomInfoDao = new SymptomInfoDao();
                var            result         = symptomInfoDao.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                SymptomInfoDTO symptomInfoDTO = new SymptomInfoDTO(result, mac);
                //serviceResult.URL = "bigData/symptomInfo";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <SymptomInfoDTO>(symptomInfoDTO);
            }

            //训练处方总表
            else if (uploadManagement.UM_DataTable == "bdl_traininfo")
            {
                TrainInfoDAO trainInfoDAO = new TrainInfoDAO();
                var          result       = trainInfoDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                TrainInfoDTO trainInfoDTO = new TrainInfoDTO(result, mac);
                //serviceResult.URL = "bigData/trainInfo";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <TrainInfoDTO>(trainInfoDTO);
            }

            //总表中的一条数据对某台设备的具体处方
            else if (uploadManagement.UM_DataTable == "bdl_deviceprescription")
            {
                DevicePrescriptionDAO devicePrescriptionDAO = new DevicePrescriptionDAO();
                var result = devicePrescriptionDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                DevicePrescriptionDTO devicePrescriptionDTO = new DevicePrescriptionDTO(result, mac);
                //serviceResult.URL = "bigData/devicePrescription";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <DevicePrescriptionDTO>(devicePrescriptionDTO);
            }
            //具体处方的具体反馈
            else if (uploadManagement.UM_DataTable == "bdl_prescriptionresult")
            {
                PrescriptionResultDAO prescriptionResultDAO = new PrescriptionResultDAO();
                var result = prescriptionResultDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }


                PrescriptionResultDTO prescriptionResultDTO = new PrescriptionResultDTO(result, mac);
                //serviceResult.URL = "bigData/prescriptionResult";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <PrescriptionResultDTO>(prescriptionResultDTO);
            }
            else if (uploadManagement.UM_DataTable == "bdl_physicalpower")
            {
                PhysicalPowerDAO physicalPowerDAO = new PhysicalPowerDAO();
                var result = physicalPowerDAO.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }

                PhysicalPowerDTO physicalPowerDTO = new PhysicalPowerDTO(result, mac);
                //serviceResult.URL = "bigData/physicalPower";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <PhysicalPowerDTO>(physicalPowerDTO);
            }
            else if (uploadManagement.UM_DataTable == "bdl_error")
            {
                ErrorDao errorDao = new ErrorDao();
                var      result   = errorDao.Load(uploadManagement.UM_DataId);
                if (result == null)
                {
                    return(null);
                }

                ErrorDTO errorDTO = new ErrorDTO(result, mac);
                //serviceResult.URL = "bigData/physicalPower";
                serviceResult.Data = JsonTools.Obj2JSONStrNew <ErrorDTO>(errorDTO);
            }

            return(serviceResult);
        }
Example #16
0
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public string Login(string username, string password)
        {
            string  loginResult = "success";
            AuthDAO authDAO     = new AuthDAO();

            //先验证admin
            Auther auther = authDAO.Login(username, password);

            //超管监测权限
            if (auther != null && auther.Auth_Level == Auther.AUTH_LEVEL_ADMIN)
            {
                loginResult = "check_U";
                return(loginResult);
            }
            Auther autherCN = authDAO.GetByName(username);

            //密码错误
            if (autherCN == null)
            {
                loginResult = "没有该用户";
                return(loginResult);
            }

            //没有该用户
            if (autherCN != null && auther == null)
            {
                loginResult = "密码错误!";
                return(loginResult);
            }
            //普通用户测试是否超时登录
            if (auther.Auth_OfflineTime < DateTime.Now)
            {
                loginResult = "您的使用时间已经用尽,请联系宝德龙管理员";
                return(loginResult);
            }


            //登录mac与激活mac不对应
            SetterDAO setterDAO = new SetterDAO();
            Setter    setter    = setterDAO.getSetter();

            string mac = "";

            try {
                byte[] debytes = AesUtil.Decrypt(Encoding.GetEncoding("GBK").GetBytes(setter.Set_Unique_Id), ProtocolConstant.USB_DOG_PASSWORD);

                mac = Encoding.GetEncoding("GBK").GetString(debytes);
                //byte[] a = ProtocolUtil.StringToBcd(setter.Set_Unique_Id);
                //byte[] b = AesUtil.Decrypt(a, ProtocolConstant.USB_DOG_PASSWORD);
                //mac = Encoding.GetEncoding("GBK").GetString(b);
            }
            catch (Exception ex)
            {
                //解密出现问题,经常会报错,目前是直接返回的登陆成功的信息。
                logger.Error("解密异常:" + ex.Message);
                //Console.WriteLine("解密异常:" + ex.Message);
                //loginResult = "解密异常.";
                //return loginResult;
            }
            //如果解密后的setter中的mac不包含现在获得的mac
            if (mac.IndexOf(SystemInfo.GetMacAddress().Replace(":", "-")) == -1)
            {
                //Console.WriteLine("DB:"+ mac);
                //Console.WriteLine("current:" + SystemInfo.GetMacAddress().Replace(":","-"));

                //loginResult = "登录异常";
                //return loginResult;
                logger.Error("机器码匹配异常," + DateTime.Now.ToString());
            }
            if (autherCN.User_Status == Auther.USER_STATUS_FREEZE)
            {
                loginResult = "用户已被冻结";
                return(loginResult);
            }
            return(loginResult);
        }
 public AuthController(UserManager <ApplicationUser> userManager, JwtFactory jwtFactory, IEmailSender emailSender)
 {
     authDAO = new AuthDAO(userManager, jwtFactory, emailSender);
 }
Example #18
0
        /// <summary>
        /// 应用启动的时候生命周期
        /// </summary>
        /// <param name="ex"></param>
        protected override void OnStartup(StartupEventArgs ex)
        {
            //全局异常处理机制,UI异常
            Current.DispatcherUnhandledException += App_OnDispatcherUnhandledException;
            //全局异常处理机制,线程异常
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            //加载语言
            LanguageUtils.SetLanguage();

            //启动netty,用于与设备端通信
            Thread th = new Thread(() =>
            {
                try
                {
                    logger.Info("线程启动成功");
                    NettyLuncher.getInstance().Start().Wait();
                }
                catch (AggregateException ee)
                {
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        MessageBoxX.Info(LanguageUtils.GetCurrentLanuageStrByKey("App.PortOccupy"));
                        System.Environment.Exit(0);
                    }));
                }
            });

            th.Start();


            //启动远程更新
            Thread updateTh = new Thread(() =>
            {
                try
                {
                    Thread.Sleep(1000 * 8);
                    Dictionary <string, string> param = new Dictionary <string, string>();

                    param.Add("version", CommUtil.GetCurrentVersion());
                    var result = HttpSender.GET(HttpSender.URL_UPDATE, param);
                    if (string.IsNullOrEmpty(result))
                    {
                        return;
                    }
                    var info = JsonTools.DeserializeJsonToObject <VersionInfo>(result);
                    if (info == null || info.update == false)
                    {
                        return;
                    }

                    info.language = LanguageUtils.IsChainese() ? 1 : 0;
                    App.Current.Dispatcher.Invoke(new Action(() =>
                    {
                        Boolean dr = MessageBoxX.Question(LanguageUtils.GetCurrentLanuageStrByKey("App.UpdateInfo"));
                        if (dr == true)
                        {
                            Process.Start("AutoUpdater.exe", info.GetProcessString());
                            Environment.Exit(0);
                        }
                    }));
                }
                catch (Exception exc)
                {
                    Console.WriteLine(exc.ToString());
                    return;
                }
            });

            updateTh.Start();



            //大数据线程

            Thread bdth = new Thread(() =>
            {
                try
                {
                    SetterDAO setterDao = new SetterDAO();
                    AuthDAO authDAO     = new AuthDAO();
                    while (true)
                    {
                        if (setterDao.ListAll().Count != 1)
                        {
                            //不激活不开启
                            Thread.Sleep(1000 * 15);
                            continue;
                        }
                        if (authDAO.ListAll().Count == 1)
                        {
                            //Console.WriteLine("-----------------boom shakalaka--------------");
                            //只有admin,不创建用户,不开启,睡个15s
                            Thread.Sleep(1000 * 15);
                            continue;
                        }
                        try
                        {
                            BigDataOfficer bigDataOfficer = new BigDataOfficer();
                            bigDataOfficer.Run();
                            //int heartBeatRate = (int)CommUtil.GetBigDataRate();
                            Thread.Sleep(1000 * 60);
                            //Console.WriteLine("-----------------boom");
                        }
                        catch (Exception e)
                        {
                            logger.Error("大数据线程失败:" + e.StackTrace);
                            Console.WriteLine("大数据线程失败:" + e.Message);
                        }
                    }
                }
                catch (Exception exct)
                {
                    Console.WriteLine(exct.ToString());
                }
            });

            bdth.Start();

            //心跳线程
            Thread hbth = new Thread(() =>
            {
                ProtoBufSocket socket = null;
                try
                {
                    socket = new ProtoBufSocket();
                    socket.Connect();
                }
                catch (Exception exception)
                {
                    Console.WriteLine("连接失败:" + exception.StackTrace);
                    TcpHeartBeatUtils.WriteLogFile("连接失败:" + exception.StackTrace);
                }

                while (true)
                {
                    try
                    {
                        BodyStrongMessage bodyStrongMessage = new BodyStrongMessage
                        {
                            MessageType = BodyStrongMessage.Types.MessageType.Heaerbeatreq,
                            //可能为null
                            HeartbeatRequest = TcpHeartBeatUtils.GetHeartBeatByCurrent()
                        };

                        socket.SendMessage(bodyStrongMessage);
                        Console.WriteLine("发送msg!!");
                        //Thread.Sleep(5000);
                    }
                    catch (Exception eee)
                    {
                        Console.WriteLine("发送msg失败" + eee.StackTrace);
                        TcpHeartBeatUtils.WriteLogFile("发送msg失败" + eee.StackTrace);
                    }
                    finally
                    {
                        Thread.Sleep(5000);
                    }
                }
            });

            hbth.Start();

            base.OnStartup(ex);
        }
Example #19
0
 public AuthBM()
 {
     dao    = new AuthDAO();
     output = new OutPutApi();
 }
Example #20
0
        private void Button_Click_7(object sender, RoutedEventArgs e)
        {
            var a = new AuthDAO().GetByAuthLevel(2);

            view.Pages.MessageBoxX.Info(a.User_Status.ToString());
        }