Exemplo n.º 1
0
        private void AlteraUsuario(string id)
        {
            // CHama validação dos dados
            validaDados();

            // Gera objeto para encritar a senha
            var objEncryptar = new EncryptHelper();

            // Encrypto a senha
            var senha = objEncryptar.Encrypt(tbAltSenha.Text);

            // Defino usuario
            var usuario = tbAltUsuario.Text;

            // Defino email
            var email = tbAltEmail.Text;

            // Defino nome
            var nome = tbAltNome.Text;

            // Defino admin
            var admin = cbAdmin.IsChecked.Value;

            // Defino ativo
            var ativo = cbAtivo.IsChecked.Value;

            // Gera novo objeto de conexao ao banco de dados
            var dataBase = new DatabaseHelper("aniversariantes");

            // Gero nova lista com dados de campos e valores
            var lista = new Dictionary<string, string>();

            // Adiciona campos na lista com os respectivos valores
            lista.Add("c_usuario", usuario);
            lista.Add("c_senha", senha);
            lista.Add("b_ativo", ativo.ToString());
            lista.Add("b_admin", admin.ToString());
            lista.Add("c_nome", nome);
            lista.Add("c_email", email);

            // Verifica se consegue dar update no usuario
            if (dataBase.Update("dados.usuarios", lista, "id = " + id)) {
                MessageBox.Show("Usuario alterado com sucesso");
            }
            else {
                MessageBox.Show("Ocorreu um erro ao tentar atualizar o usuário");
            }

            Close();
        }
Exemplo n.º 2
0
        /// <summary>
        /// 修改或者添加一条数据
        /// </summary>
        /// <param name="model">实体参数</param>
        /// <returns>大于0,操作成功,反之失败</returns>
        public int OperateModel(Base_UserInfo model)
        {
            if (!string.IsNullOrEmpty(model.Id) && model.Id.Length == 36)
            {
                //编辑
                var existModel = this.LoadEntities(u => u.Id == model.Id).FirstOrDefault();
                existModel.UserName   = model.UserName;
                existModel.UserPwd    = EncryptHelper.EncryptPwd(model.UserPwd);
                existModel.Phone      = model.Phone;
                existModel.OrderBy    = model.OrderBy;
                existModel.Addrs      = model.Addrs;
                existModel.BirthDay   = model.BirthDay;
                existModel.Bz         = model.Bz;
                existModel.DeptId     = model.DeptId;
                existModel.ModifyTime = DateTime.Now;
                existModel.Modified   = model.Modified;
                existModel.Email      = model.Email;
                #region 修改用户角色关系
                var existUserRoles = DbSession.Base_UserRoleInfoRepository.LoadEntities(ur => ur.UserId == existModel.Id);
                //1. 删除现有用户角色关系
                foreach (var item in existUserRoles)
                {
                    DbSession.Base_UserRoleInfoRepository.DeleteEntity(item);
                }
                //2. 添加 新的用户角色关系
                if (model.RoleIds != null)
                {
                    foreach (var roleId in model.RoleIds)
                    {
                        Base_UserRoleInfo userRoleModel = new Base_UserRoleInfo();
                        userRoleModel.Id     = Guid.NewGuid().ToString();
                        userRoleModel.RoleId = roleId;
                        userRoleModel.UserId = existModel.Id;
                        DbSession.Base_UserRoleInfoRepository.AddEntity(userRoleModel);
                    }
                }

                #endregion
            }
            else if (string.IsNullOrEmpty(model.Id))
            {
                //添加
                var addModel = new Base_UserInfo();
                addModel.Id         = Guid.NewGuid().ToString();
                addModel.UserName   = model.UserName;
                addModel.UserPwd    = EncryptHelper.EncryptPwd(model.UserPwd);
                addModel.Phone      = model.Phone;
                addModel.OrderBy    = model.OrderBy;
                addModel.Addrs      = model.Addrs;
                addModel.BirthDay   = model.BirthDay;
                addModel.Bz         = model.Bz;
                addModel.DelFlag    = 0;
                addModel.Creator    = model.Creator;
                addModel.CreateTime = DateTime.Now;
                addModel.DeptId     = model.DeptId;
                addModel.Email      = model.Email;
                DbSession.Base_UserInfoRepository.AddEntity(addModel);
                #region 添加用户角色关系
                //1. 添加 新的用户角色关系
                if (model.RoleIds != null)
                {
                    foreach (var roleId in model.RoleIds)
                    {
                        Base_UserRoleInfo userRoleModel = new Base_UserRoleInfo();
                        userRoleModel.Id     = Guid.NewGuid().ToString();
                        userRoleModel.RoleId = roleId;
                        userRoleModel.UserId = addModel.Id;
                        DbSession.Base_UserRoleInfoRepository.AddEntity(userRoleModel);
                    }
                }

                #endregion
            }


            return(DbSession.SaveChange());
        }
Exemplo n.º 3
0
    public UserModule(IRootPathProvider pathProvider)
    {
        User me = null; //add the user  as a property to the model :)

        Before += ctx =>
        {
            if (ctx.Request.Cookies.ContainsKey("flex"))
            {
                var myId = ctx.Request.Cookies["flex"];
                var id_u = new EncryptHelper(AppConfig.Provider,
                                                    Xmlconfig.get(
                                                      "cryptokey",
                                                      pathProvider.GetRootPath()).Value).decrypt(myId);

                if (!string.IsNullOrEmpty(id_u))
                {
                    me = UsersRepository.getById(Convert.ToInt32(id_u));
                    if (me != null)
                    {
                        return null; //it means you can carry on!!!!
                    }

                }
            }

            var res = new Response();
            res.StatusCode = HttpStatusCode.Forbidden;
            return res;
        };

        Get["/users"] = _ =>
        {
            var model = new
            {
                title = "Son Quattro CMS",
                users = UsersRepository.getOrderedByName(),
                me = me
            };

            if (!me.IsAdmin) //check if I am an admin
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.Forbidden;
                return res;
            }
            else
                return View["users", model];
        };

        Get[@"/users/{id:int}"] = parameters =>
        {
            //*important
            int id = parameters.id; //I'm forcing the right conversion
            var puser = UsersRepository.getById(id);

            if (puser == null) //the user does not exists
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.NotFound;
                return res;
            }

            var model = new
            {
                title = "Son Quattro CMS",
                user = puser,
                me = me
            };

            if ((me.Id != id) && !me.IsAdmin) //check if I am not an admin and I'm changing someone's else profile
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.Forbidden;
                return res;
            }

            return View["single_user", model];
        };

        Post["/users/{id:int}"] = parameters =>
        {
            //*important
            int id = parameters.id;

            dynamic model = null;
            //check first if I'm a simple editor, not an Admin and I want to change someone's else profile
            if ((me.Id != id) && !me.IsAdmin)
            {
                var res = new Response();
                res.StatusCode = HttpStatusCode.Forbidden;
                return res;
            }

            var us = new User
            {
                Id = id,
                UserName = Request.Form.username,
                Password = Request.Form.password,
                SimpleRoles = Request.Form.hr
            };

            if ((me.Id == id) && me.IsAdmin && !us.SimpleRoles.Contains("0"))
            {
                model = new
                {
                    title = "Son Quattro CMS",
                    user = us,
                    me = me,
                    success = false,
                    messages = new List<string> { "You can't quit being an admin!" }
                };
            }
            else
            {
                var rip_password = Request.Form.repeate_password;

                //first of all validate data
                if ((us.Password != rip_password) && (!string.IsNullOrEmpty(us.Password)))
                {
                    model = new
                    {
                        title = "Son Quattro CMS",
                        user = us,
                        me = me,
                        success = false,
                        messages = new List<string> { "Please, the passwords must match" }
                    };
                }
                else
                {
                    //first of all validate data
                    if (string.IsNullOrEmpty(us.UserName) || (string.IsNullOrEmpty(us.SimpleRoles) && me.IsAdmin))
                    {
                        model = new
                        {
                            title = "Son Quattro CMS",
                            user = us,
                            me = me,
                            success = false,
                            messages = new List<string> { "Please, provide username and at least one role." }
                        };
                    }
                    else
                    {
                        var isChangePassword = false;
                        //Am I trying to change the password?
                        if (!string.IsNullOrEmpty(us.Password))
                        {

                            us.Password = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey",
                                                                                  pathProvider.GetRootPath()).Value).encrypt(us.Password); //real_password

                            isChangePassword = true;
                        }

                        if (me.IsAdmin) //only an admin can change the roles
                        {
                            us = UsersRepository.insertIfAdmin(us, isChangePassword);
                        }
                        else
                        {
                            us = UsersRepository.insert(us, isChangePassword);
                        }

                        if (us != null)
                        {
                            model = new
                            {
                                title = "Son Quattro CMS",
                                user = us,
                                me = me,
                                success = true,
                                messages = new List<string> { "User modified succesfully" }
                            };
                        }
                        else
                        {
                            model = new
                            {
                                title = "Son Quattro CMS",
                                user = us,
                                me = me,
                                success = false,
                                messages = new List<string> { "Sorry, we couldn't find the user specified!" }
                            };
                        }
                    }
                }
            }

            return View["single_user", model];
        };
    }
Exemplo n.º 4
0
 /// <summary>
 /// 获取该值的MD5
 /// </summary>
 /// <param name="str"></param>
 /// <returns></returns>
 public static string Md5(this string str)
 {
     return(str.IsNullOrEmpty() ? str : EncryptHelper.Hash(str, EncryptHelper.HashFormat.MD532));
 }
Exemplo n.º 5
0
        /// <summary>
        /// AES加密
        /// </summary>
        /// <param name="text"></param>
        /// <returns></returns>
        public string EncryptAES(string text)
        {
            var encryptStr = EncryptHelper.EncryptAES(text);

            return(encryptStr);
        }
Exemplo n.º 6
0
        /// <summary>
        /// 删除Sqlite中的数据
        /// </summary>
        /// <param name="filter"></param>
        /// <returns></returns>
        public async Task <int> DeleteFromSqliteKeyValueTable(Object filter)
        {
            string key = EncryptHelper.GetMD5(JsonConvert.SerializeObject(filter));

            return(await SqliteHelper.Current.db.DeleteAsync <KeyValueTable>(key));
        }
Exemplo n.º 7
0
    public ItemModule(IRootPathProvider pathProvider)
    {
        User me = null; //add the user  as a property to the model :)

        Before += ctx =>
        {
            if (ctx.Request.Cookies.ContainsKey("flex"))
            {
                var myId = ctx.Request.Cookies["flex"];
                var id_user = new EncryptHelper(AppConfig.Provider,
                                                    Xmlconfig.get(
                                                      "cryptokey",
                                                      pathProvider.GetRootPath()).Value).decrypt(myId);

                if (!string.IsNullOrEmpty(id_user))
                {
                    me = UsersRepository.getById(Convert.ToInt32(id_user));
                    return null; //it means you can carry on!!!!
                }
            }

            var res = new Response();
            res.StatusCode = HttpStatusCode.Forbidden;
            return res;
        };

        Get["/items"] = _ =>
        {
            var model = new
            {
                title = "Son Quattro CMS",
                items = ItemsRepository.Items,
                me = me
            };
            return View["items", model];
        };

        Get[@"/items/(?<order>[0-3])"] = parameters =>
        {
            //*important
            byte order = parameters.order; //I'm forcing the right conversion
            var model = new
            {
                title = "Son Quattro CMS",
                item = ItemsRepository.getByOrder(order),
                me = me
            };
            return View["single_item", model];
        };

        Post["/items/(?<order>[0-3])"] = parameters =>
        {
            byte order = parameters.order;
            Item it = null;

            //check if you're only changing other then the pix
            if (Request.Form.title != null)
            {
                it = new Item
                {
                    Order = parameters.order,
                    Title = Request.Form["title"],
                    Description = Request.Form["description"],
                    Image = Request.Form["image"]
                };
            }
            else
            {
                int x1 = Request.Form.x1;
                int y1 = Request.Form.y1;
                int x2 = Request.Form.x2;
                int y2 = Request.Form.y2;
                int w = Request.Form.w;
                int h = Request.Form.h;

                string image_file = Guid.NewGuid() + ".png";
                string image_file_raw = Request.Form.b64_img;
                var image_b64 = image_file_raw.Replace("data:image/jpeg;base64,", "").Replace("data:image/png;base64,", "").Replace("data:image/gif;base64,", "");
                var rimg = ImageHelper.b64ToImage(image_b64);
                var ratio = Convert.ToDecimal(rimg.Width) / Convert.ToDecimal(528);
                var rect = ImageHelper.ratioRectangle(new Rectangle(x1, y1, w, h), ratio);
                var n_img = ImageHelper.cropImage(rimg, rect);

                //at the end resize 840x540
                var r_img = ImageHelper.resize(n_img, 840);
                r_img.Save(pathProvider.GetRootPath() + @"images\" + image_file);

                it = ItemsRepository.getByOrder(order);
                it.Image = image_file;
            }

            dynamic model = null;
            var result = ItemsRepository.insert(order, it);

            if (result != null)
            {
                model = new
                {
                    title = "Son Quattro CMS",
                    item = result,
                    success = true,
                    messages = new List<string> { "The item has been successfull modified" },
                    me = me
                };
            }
            else
            {
                model = new
                {
                    title = "Son Quattro Items CRUD",
                    item = it, //I'm going to return back the one given
                    success = false,
                    messages = new List<string> { "The item could not be modified" },
                    me = me
                };
            }
            return View["single_item", model];
        };
    }
Exemplo n.º 8
0
        public void EncryptNullTest()
        {
            var input = "";

            Assert.Throws <ArgumentNullException>(() => EncryptHelper.Hash(input));
        }
Exemplo n.º 9
0
 public string GetDecrypt(string encryptedString, string key)
 {
     return(EncryptHelper.Decrypt(encryptedString, key));
 }
Exemplo n.º 10
0
 public string GetEncrypt(string pwd, string key)
 {
     return(EncryptHelper.Encrypt(pwd, key));
 }
Exemplo n.º 11
0
        /// <summary>
        /// 发送图片
        /// </summary>
        /// <param name="image">The image.</param>
        /// <param name="shareData">The share data.</param>
        /// <param name="wins">The wins.</param>
        private void SendImage(Image image, List <weChatShareTextModel> shareData, List <WindowInfo> wins, bool isImageText, bool sendVideo = false, bool isJoinImage = false)
        {
            string path = System.Environment.CurrentDirectory + "\\temp\\joinimage";

            if (!isJoinImage)
            {
                if (image == null)
                {
                    return;
                }
                if (!sendVideo)
                {
                    Clipboard.SetImage(image);
                }
            }
            else
            {
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
            }
            //粘贴图片
            foreach (var item in shareData)
            {
                try
                {
                    if (isJoinImage)
                    {
                        try
                        {
                            string fileName = EncryptHelper.MD5(item.taskid.ToString() + item.field3);

                            if (File.Exists(string.Format("{0}\\{1}.jpg", path, fileName)))
                            {
                                using (Stream stream = new FileStream(string.Format("{0}\\{1}.jpg", path, fileName), FileMode.Open))
                                {
                                    image = Image.FromStream(stream);
                                }
                                Clipboard.SetImage(image);
                            }
                            else
                            {
                                log.Info(string.Format("商品图片不存在,群[{0}]未发送", item.title));
                                continue;
                            }
                        }
                        catch (Exception)
                        {
                            //通知
                            SendNotify(item.title);
                            continue;
                        }
                    }



                    if (!isStartTask || MyUserInfo.currentUserId == 0)
                    {
                        break;
                    }

                    //如果当前微信已经发送,则结束本循环
                    if (imageResult.Contains(item.title))
                    {
                        continue;
                    }

                    wins = WinApi.GetAllDesktopWindows();
                    if (wins == null || wins.Count() == 0)
                    {
                        continue;
                    }

                    bool b = wins.Exists(win => { return(win.szWindowName == item.title); });
                    if (b)
                    {
                        var win = wins.Find(w => { return(w.szWindowName == item.title); });
                        if (sendVideo && win.winType == 1)
                        {
                        }
                        else
                        {
                            //复制粘贴发送
                            WinApi.SendData(win.hWnd, win.winType == 1);


                            SleepImage(0.5m);
                            if (!sendVideo && !imageResult.Contains(item.title))
                            {
                                imageResult.Add(item.title);
                            }
                        }

                        if (!isImageText)
                        {
                            //更新修改状态
                            UpdateShareTextStatus(item.id);
                        }
                    }
                    else
                    {
                        //通知
                        SendNotify(item.title);
                    }
                }
                catch (Exception ex)
                {
                    //通知
                    SendNotify(item.title);

                    if (!sendVideo && !imageResult.Contains(item.title))
                    {
                        imageResult.Add(item.title);
                    }

                    AddErrorLog(item, 0);

                    if (!isImageText)
                    {
                        //更新修改状态
                        UpdateShareTextStatus(item.id);
                    }
                    log.Error(ex);
                }
            }
            Clipboard.Clear();
        }
Exemplo n.º 12
0
    public LoginModule(IRootPathProvider pathProvider)
    {
        Before += ctx =>
        {
            if (ctx.Request.Cookies.ContainsKey("flex"))
            {
                var myId = ctx.Request.Cookies["flex"];
                var id_user = new EncryptHelper(AppConfig.Provider,
                                                    Xmlconfig.get(
                                                      "cryptokey",
                                                      pathProvider.GetRootPath()).Value).decrypt(myId);

                if (!string.IsNullOrEmpty(id_user))
                {
                    return Response.AsRedirect("/slides"); //redirects to items
                }
            }

            return null; //it means you can carry on!!!!
        };

        Get["/login"] = _ =>
        {
            var model = new
            {
                title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework"
            };

            return View["login", model];
        };

        Post["/login"] = _ =>
        {
            dynamic model = null;

            var us = new User
            {
                UserName = Request.Form.username,
                Password = Request.Form.password,
            };

            //first of all validate data

            if (string.IsNullOrEmpty(us.UserName) || string.IsNullOrEmpty(us.Password))
            {
                model = new
                {
                    title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework",
                    user = us,
                    success = false,
                    messages = new List<string> { "Please, provide username and password" }
                };
            }
            else
            {
                us.Password = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey",
                                                                     pathProvider.GetRootPath()).Value).encrypt(us.Password); //real_password

                var ut_res = UsersRepository.authenticate(us);

                if (ut_res != null)
                {
                    var myEncryptedId = new EncryptHelper(AppConfig.Provider, Xmlconfig.get("cryptokey",
                                                     pathProvider.GetRootPath()).Value).encrypt(ut_res.Id.ToString() ); //encrypt 4 cookie

                    //create cookie, http only with encrypted id user and add it to the current response
                    var mc = new NancyCookie("flex", myEncryptedId, true);

                    var res = Response.AsRedirect("/slides");
                    res.WithCookie(mc);
                    return res;
                }
                else
                {
                    model = new
                    {
                        title = "Mobile Day 2014 - Reveal.js - The HTML Presentation Framework",
                        user = us,
                        success = false,
                        messages = new List<string> { "Wrong username or password" }
                    };
                }
            }

            return View["login", model];
        };
    }
Exemplo n.º 13
0
        /// <summary>
        /// Realiza todos los procesos internos de ordenamiento de la información y solicitud de ejecución de sentencias en ambas
        /// bases de datos para que la sincronización se lleve a cabo.
        /// </summary>
        /// <param name="pathFile">Ruta del archivo donde se intentará leer los logs</param>
        /// <returns></returns>
        private bool ProcesoSincronizacion(String pathFile)
        {
            EncryptHelper encripter = new EncryptHelper();

            List<String> listaSentencias = new List<String>();
            List<Query> listaQuerys = new List<Query>();

            try
            {
                // Lee todas las filas del archivo log
                using (StreamReader sr = new StreamReader(pathFile))
                {
                    String linea;
                    while ((linea = sr.ReadLine()) != null)
                    {
                        listaSentencias.Add(encripter.Decrypt(linea));
                    }
                }

                // Arma la lista de querys que se deben (o no) ejecutar
                foreach (String registro in listaSentencias)
                {
                    Query query = new Query();

                    String[] palabras = registro.Split('|');

                    query.Pendiente = palabras[0] ?? String.Empty;
                    query.Hora = palabras[1] ?? String.Empty;
                    query.TargetDatabase = palabras[2] ?? String.Empty;
                    query.TipoQuery = palabras[3] ?? String.Empty;
                    query.QueryString = palabras[4] ?? String.Empty;
                    query.QueryAlterno = palabras[5] ?? String.Empty;
                    query.DpiOriginal = palabras[6] ?? String.Empty;
                    query.DpiModificado = palabras[7] ?? String.Empty;

                    listaQuerys.Add(query);
                }

                // Ordena la lista de querys por la hora en la que fueron ejecutados
                listaQuerys.OrderBy(q => q.Hora);

                foreach (Query query in listaQuerys)
                {
                    if (query.Pendiente == String.Empty)
                    {
                        switch (query.TipoQuery)
                        {
                            case "I":
                                // Verifica si el registro existe o no en ambas bases de datos
                                if (conexionMySQL.ConsultarRegistro(query.DpiOriginal))
                                {
                                    // Si el usuario existe, ejecuta la consulta especifica
                                    conexionMySQL.EjecutarQuery(query.QueryString);
                                }
                                else
                                {
                                    // De lo contrario, ejecutará la consulta alternativa
                                    conexionMySQL.EjecutarQuery(query.QueryAlterno);
                                }

                                if (conexionPgSQL.ConsultarRegistro(query.DpiOriginal))
                                {
                                    // Si el usuario existe, ejecuta la consulta especifica
                                    conexionPgSQL.EjecutarQuery(query.QueryString);
                                }
                                else
                                {
                                    // De lo contrario, ejecutará la consulta alternativa
                                    conexionPgSQL.EjecutarQuery(query.QueryAlterno);
                                }
                                break;
                            case "M":
                                // Si el DPI nuevo y el anterior no cambian, solo se actualiza o inserta el registro en ambas bases
                                if (query.DpiOriginal == query.DpiModificado)
                                {
                                    // Verifica si el registro existe o no en ambas bases de datos
                                    if (conexionMySQL.ConsultarRegistro(query.DpiOriginal))
                                    {
                                        // Si el usuario existe, hace un Update
                                        conexionMySQL.EjecutarQuery(query.QueryString);
                                    }
                                    else
                                    {
                                        // De lo contrario, hace un Insert
                                        conexionMySQL.EjecutarQuery(query.QueryAlterno);
                                    }

                                    if (conexionPgSQL.ConsultarRegistro(query.DpiOriginal))
                                    {
                                        // Si el usuario existe, hace un Update
                                        conexionPgSQL.EjecutarQuery(query.QueryString);
                                    }
                                    else
                                    {
                                        // De lo contrario, hace un Insert
                                        conexionPgSQL.EjecutarQuery(query.QueryAlterno);
                                    }
                                }
                                // Si no
                                else
                                {
                                    // Si el DPI original existe en la base de datos
                                    if (conexionMySQL.ConsultarRegistro(query.DpiOriginal))
                                    {
                                        // Si el DPI nuevo existe en la base de datos
                                        if (conexionMySQL.ConsultarRegistro(query.DpiModificado))
                                        {
                                            // Elimina el registro del DPI viejo
                                            conexionMySQL.EjecutarQuery(String.Format("DELETE FROM contacto WHERE dpi='{0}'", query.DpiOriginal));

                                            // Hace un update al registro del DPI nuevo
                                            String newQuery = String.Format(query.QueryString.Substring(0, query.QueryString.IndexOf("WHERE")) + "WHERE dpi='{0}'", query.DpiModificado);
                                            conexionMySQL.EjecutarQuery(newQuery);
                                        }
                                        // si no, solo se hace el update normal
                                        else
                                        {
                                            conexionMySQL.EjecutarQuery(query.QueryString);
                                        }
                                    }
                                    // de lo contrario, Inserta (o hace un Update) del registro con el nuevo DPI
                                    else
                                    {
                                        // Si el nuevo DPI existe, se hace un Update
                                        if (conexionMySQL.ConsultarRegistro(query.DpiModificado))
                                        {
                                            String newQuery = String.Format(query.QueryString.Substring(0, query.QueryString.IndexOf("WHERE")) + "WHERE dpi='{0}'", query.DpiModificado);
                                            conexionMySQL.EjecutarQuery(newQuery);
                                        }
                                        // de lo contrario, solo se inserta el nuevo registro
                                        else
                                        {
                                            // De lo contrario, hace un Insert
                                            conexionMySQL.EjecutarQuery(query.QueryAlterno);
                                        }
                                    }

                                    if (conexionPgSQL.ConsultarRegistro(query.DpiOriginal))
                                    {
                                        // Si el DPI nuevo existe en la base de datos
                                        if (conexionPgSQL.ConsultarRegistro(query.DpiModificado))
                                        {
                                            // Elimina el registro del DPI viejo
                                            conexionPgSQL.EjecutarQuery(String.Format("DELETE FROM contacto WHERE dpi='{0}'", query.DpiOriginal));

                                            // Hace un update al registro del DPI nuevo
                                            String newQuery = String.Format(query.QueryString.Substring(0, query.QueryString.IndexOf("WHERE")) + "WHERE dpi='{0}'", query.DpiModificado);
                                            conexionPgSQL.EjecutarQuery(newQuery);
                                        }
                                        // si no, solo se hace el update normal
                                        else
                                        {
                                            conexionPgSQL.EjecutarQuery(query.QueryString);
                                        }
                                    }
                                    // de lo contrario, Inserta (o hace un Update) del registro con el nuevo DPI
                                    else
                                    {
                                        // Si el nuevo DPI existe, se hace un Update
                                        if (conexionPgSQL.ConsultarRegistro(query.DpiModificado))
                                        {
                                            String newQuery = String.Format(query.QueryString.Substring(0, query.QueryString.IndexOf("WHERE")) + "WHERE dpi='{0}'", query.DpiModificado);
                                            conexionPgSQL.EjecutarQuery(newQuery);
                                        }
                                        // de lo contrario, solo se inserta el nuevo registro
                                        else
                                        {
                                            // De lo contrario, hace un Insert
                                            conexionPgSQL.EjecutarQuery(query.QueryAlterno);
                                        }
                                    }
                                }
                                break;
                            case "D":
                                // Verifica si el registro existe o no en ambas bases de datos
                                if (conexionMySQL.ConsultarRegistro(query.DpiOriginal))
                                {
                                    // Si el usuario existe, ejecuta la consulta especifica
                                    conexionMySQL.EjecutarQuery(query.QueryString);
                                }

                                if (conexionPgSQL.ConsultarRegistro(query.DpiOriginal))
                                {
                                    // Si el usuario existe, ejecuta la consulta especifica
                                    conexionPgSQL.EjecutarQuery(query.QueryString);
                                }
                                break;
                        }
                    }
                }

                // Inserta los logs dentro del archivo de los archivos de texto de respaldo
                using (StreamWriter swLog = new StreamWriter(HttpContext.Current.Server.MapPath(LOG_PATH + FILE_LOG_NAME), false))
                {
                    foreach (Query query in listaQuerys)
                    {
                        swLog.WriteLine(encripter.Encrypt(String.Format("x|{0}|{1}|{2}|{3}|{4}|{5}|{6}", query.Hora, query.TargetDatabase, query.TipoQuery, query.QueryString, query.QueryAlterno, query.DpiOriginal, query.DpiModificado)));
                    }
                }

                using (StreamWriter swBackup = new StreamWriter(HttpContext.Current.Server.MapPath(LOG_BACKUP_PATH + FILE_LOG_NAME), false))
                {
                    foreach (Query query in listaQuerys)
                    {
                        swBackup.WriteLine(encripter.Encrypt(String.Format("x|{0}|{1}|{2}|{3}|{4}|{5}|{6}", query.Hora, query.TargetDatabase, query.TipoQuery, query.QueryString, query.QueryAlterno, query.DpiOriginal, query.DpiModificado)));
                    }
                }

                using (StreamWriter swPrincipal = new StreamWriter(HttpContext.Current.Server.MapPath(FILE_LOG_NAME), false))
                {
                    foreach (Query query in listaQuerys)
                    {
                        swPrincipal.WriteLine(encripter.Encrypt(String.Format("x|{0}|{1}|{2}|{3}|{4}|{5}|{6}", query.Hora, query.TargetDatabase, query.TipoQuery, query.QueryString, query.QueryAlterno, query.DpiOriginal, query.DpiModificado)));
                    }
                }

            }
            catch (Exception e)
            {
                return false;
            }

            return true;
        }
Exemplo n.º 14
0
        /// <summary>
        /// Guarda en archivos .txt los logs de las consultas realizadas en cualquiera de las dos bases de datos.
        /// </summary>
        /// <param name="query">Sentencia a ejecutar en la base de datos</param>
        /// <param name="targetDatabase">Base de datos en la cual se debe ejecutar el query</param>
        /// <param name="tipoQuery">Indica si el query fue un Select, Update o Delete</param>
        /// <param name="timeStamp">Hora exacta en la que se finalizó la consulta</param>
        /// <param name="queryAlterno">Query alterno que se debe ejecutar si el registro existe o no</param>
        /// <returns></returns>
        public bool GuardarSentenciaEnArchivo(String query, String targetDatabase, String tipoQuery, String timeStamp, String queryAlterno, String dpiOriginal, String dpiModificado)
        {
            EncryptHelper encripter = new EncryptHelper();

            // Si el directorio no existe, lo crea
            if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(LOG_PATH)))
            {
                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(LOG_PATH));
            }

            if (!System.IO.Directory.Exists(HttpContext.Current.Server.MapPath(LOG_BACKUP_PATH)))
            {
                System.IO.Directory.CreateDirectory(HttpContext.Current.Server.MapPath(LOG_BACKUP_PATH));
            }

            // Inserta los logs dentro del archivo de los archivos de texto de respaldo
            using (StreamWriter swLog = File.AppendText(HttpContext.Current.Server.MapPath(LOG_PATH + FILE_LOG_NAME)))
            {
                swLog.WriteLine(encripter.Encrypt(String.Format("|{0}|{1}|{2}|{3}|{4}|{5}|{6}", timeStamp, targetDatabase, tipoQuery, query, queryAlterno, dpiOriginal, dpiModificado)));
            }

            using (StreamWriter swBackup = File.AppendText(HttpContext.Current.Server.MapPath(LOG_BACKUP_PATH + FILE_LOG_NAME)))
            {
                swBackup.WriteLine(encripter.Encrypt(String.Format("|{0}|{1}|{2}|{3}|{4}|{5}|{6}", timeStamp, targetDatabase, tipoQuery, query, queryAlterno, dpiOriginal, dpiModificado)));
            }

            using (StreamWriter swPrincipal = File.AppendText(HttpContext.Current.Server.MapPath(FILE_LOG_NAME)))
            {
                swPrincipal.WriteLine(encripter.Encrypt(String.Format("|{0}|{1}|{2}|{3}|{4}|{5}|{6}", timeStamp, targetDatabase, tipoQuery, query, queryAlterno, dpiOriginal, dpiModificado)));
            }

            return true;
        }
Exemplo n.º 15
0
        /// <summary>
        /// 保存微信openid
        /// </summary>
        /// <param name="customerId">商户Id</param>
        /// <param name="openId"></param>
        public void SetOpenId(int customerId, string openId)
        {
            CookieHelper.SetCookieValByCurrentDomain(this.GetOpenIdDataKey(customerId), 1, EncryptHelper.Encrypt(openId, ENCRYPTKEY));

            //双保险,session也存储
            HttpContext.Current.Session[this.GetOpenIdDataKey(customerId)] = openId;
        }
        public ValidationAppResult CadastrarNovoAluno(NovoAlunoViewModel novoAlunoViewModel)
        {
            BeginTransaction();

            var usuario = new Usuario(novoAlunoViewModel.Email, novoAlunoViewModel.Senha, EncryptHelper.Encrypt(novoAlunoViewModel.Senha), TipoUsuario.Aluno);
            var aluno   = new Aluno(novoAlunoViewModel.Nome, CaracteresHelper.SomenteNumeros(novoAlunoViewModel.CPF), novoAlunoViewModel.DataNascimento, novoAlunoViewModel.Ativo, usuario);

            aluno.AdicionarHistorico(new AlunoHistorico(aluno, SituacaoAluno.Cadastrado));

            var resultadoValidacao = DomainToApplicationResult(_alunoService.AdicionarNovoAluno(aluno));

            if (resultadoValidacao.IsValid)
            {
                Commit();
            }

            return(resultadoValidacao);
        }
Exemplo n.º 17
0
        /// <summary>
        /// 获取随机字符串
        /// </summary>
        /// <returns></returns>
        public static string GetNoncestr()
        {
            var random = new Random();

            return(EncryptHelper.GetMD5(random.Next(1000).ToString(), "GBK"));
        }
Exemplo n.º 18
0
        public dynamic Save(string parameters)
        {
            string encyptKey = ConfigurationManager.AppSettings["EncyptKey"];

            if (string.IsNullOrEmpty(encyptKey))
            {
                throw new Exception("EncyptKey not found in App.config");
            }

            var dataJson  = EncryptHelper.Base64Decode(parameters);
            var jSettings = new JsonSerializerSettings
            {
                Formatting           = Formatting.Indented,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };

            jSettings.Converters.Add(new DefaultWrongFormatDeserialize());
            var viewModel = JsonConvert.DeserializeObject <RequestAssessmentPcsVo>(dataJson, jSettings);

            TrackingCompleteInformation(viewModel);

            var listDisclodureError      = new List <MessageErrorVo>();
            var IsDisclosureFormComplete = true;
            var listError = new List <MessageErrorVo>();

            if (viewModel.IsSaveAll == true)
            {
                var checkDisclosureForm = CheckInValidDisclosureForm(viewModel.DisclosureFormVo);
                if (checkDisclosureForm.Count > 0)
                {
                    if (viewModel.MessageErrorTotal == null)
                    {
                        viewModel.MessageErrorTotal = new List <MessageErrorVo>();
                        viewModel.MessageErrorTotal.AddRange(checkDisclosureForm);
                    }
                    else
                    {
                        viewModel.MessageErrorTotal.AddRange(checkDisclosureForm);
                    }
                    listDisclodureError      = checkDisclosureForm;
                    IsDisclosureFormComplete = false;
                }
                var checkMid = CheckMidDisclosureFormAndPcstForm(viewModel);
                if (checkMid.Count > 0)
                {
                    if (viewModel.MessageErrorTotal == null)
                    {
                        viewModel.MessageErrorTotal = new List <MessageErrorVo>();
                        viewModel.MessageErrorTotal.AddRange(checkMid);
                    }
                    else
                    {
                        viewModel.MessageErrorTotal.AddRange(checkMid);
                    }
                }

                if (viewModel.MessageErrorTotal != null && viewModel.MessageErrorTotal.Count > 0)
                {
                    var index = 0;
                    foreach (var item in viewModel.MessageErrorTotal)
                    {
                        index++;
                        item.Index = index;
                    }
                    //var result = new ObjectReturnVo();
                    //result.Error = viewModel.MessageErrorTotal;
                    //result.Id = viewModel.AssessmentPcsId;
                    //return result;
                    listError = viewModel.MessageErrorTotal;
                }
            }

            var assessmentData = new AssessmentDataVo
            {
                Sections = viewModel.Sections,
                AssessmentSectionQuestions = viewModel.AssessmentSectionQuestions,
            };
            //GetContentHtml(viewModel, assessmentData);

            var encryptAssessmentData =
                EncryptHelper.Encrypt(JsonConvert.SerializeObject(assessmentData), encyptKey);

            //parse string to DateTime
            if (viewModel.DisclosureFormVo.Member != null)
            {
                viewModel.DisclosureFormVo.Member.Dob =
                    CaculatorHelper.TryParseDatTimeFromStr(viewModel.DisclosureFormVo.Member.DobStr);//.GetValueOrDefault();
                if (viewModel.DisclosureFormVo.Member.Signature == "_blank")
                {
                    viewModel.DisclosureFormVo.Member.Signature = null;
                }
            }
            viewModel.DisclosureFormVo.DateSigned =
                CaculatorHelper.TryParseDatTimeFromStr(viewModel.DisclosureFormVo.DateSignedStr);       //.GetValueOrDefault();
            viewModel.DisclosureFormVo.TheFollowingDate =
                CaculatorHelper.TryParseDatTimeFromStr(viewModel.DisclosureFormVo.TheFollowingDateStr); //.GetValueOrDefault();
            if (viewModel.DisclosureFormVo.Guardian != null && viewModel.DisclosureFormVo.Guardian.Signature == "_blank")
            {
                viewModel.DisclosureFormVo.Guardian.Signature = null;
            }
            if (viewModel.DisclosureFormVo.IsHasProviderAgency)
            {
                //set MPI == id
                if (viewModel.DisclosureFormVo.Providers != null && viewModel.DisclosureFormVo.Providers.Count > 0)
                {
                    foreach (var dt in viewModel.DisclosureFormVo.Providers)
                    {
                        if (dt.Id != null && dt.Id.GetValueOrDefault() > 0)
                        {
                            dt.Mpi = dt.Id.ToString();
                        }
                    }
                }
            }
            else
            {
                viewModel.DisclosureFormVo.Providers = new List <ProviderDisclosureFormViewModel>();
            }
            var encryptDisclosureFormData =
                EncryptHelper.Encrypt(JsonConvert.SerializeObject(viewModel.DisclosureFormVo), encyptKey);

            var encryptMid = EncryptHelper.Encrypt(JsonConvert.SerializeObject(GetMid(viewModel)), encyptKey);

            var extensionVm = new ExtensionAssessment
            {
                DisclosureFormIsComplete = IsDisclosureFormComplete,
                ErrorDisclosureForm      = listDisclodureError
            };

            var extensionStr = JsonConvert.SerializeObject(extensionVm);

            using (var context = new AssessmentContext())
            {
                //Update
                if (viewModel.AssessmentPcsId > 0)
                {
                    var assessment = context.Assessments.FirstOrDefault(o => o.Id == viewModel.AssessmentPcsId);
                    if (assessment != null)
                    {
                        assessment.FileName           = viewModel.AssessmentName;
                        assessment.ModifiedOn         = DateTime.Now;
                        assessment.AssessmentData     = encryptAssessmentData;
                        assessment.DisclosureFormData = encryptDisclosureFormData;
                        assessment.Mid       = encryptMid;
                        assessment.Extension = extensionStr;

                        context.Entry(assessment).State = EntityState.Modified;
                        context.SaveChanges();

                        var result = new ObjectReturnVo();
                        result.Id    = assessment.Id;
                        result.Error = listError.Count > 0 ? listError : null;
                        return(result);
                    }
                    else
                    {
                        var result = new ObjectReturnVo();
                        result.Error = new List <MessageErrorVo>
                        {
                            new MessageErrorVo
                            {
                                MessageError = "This record was delete."
                            }
                        };
                        result.Id = 0;

                        return(result);
                    }
                }
                //Add
                else
                {
                    var entity = new Assessment
                    {
                        FileName           = viewModel.AssessmentName,
                        FilePath           = "",
                        CreatedOn          = DateTime.Now,
                        ModifiedOn         = DateTime.Now,
                        AssessmentData     = encryptAssessmentData,
                        DisclosureFormData = encryptDisclosureFormData,
                        Mid       = encryptMid,
                        Extension = extensionStr
                    };
                    context.Entry(entity).State = EntityState.Added;
                    context.SaveChanges();

                    var result = new ObjectReturnVo();
                    result.Id    = entity.Id;
                    result.Error = listError;
                    return(result);
                }
            }
        }
Exemplo n.º 19
0
        private void IncluiUsuario()
        {
            // CHama validação dos dados
            validaDados();

            // Gera objeto para encritar a senha
            var objEncryptar = new EncryptHelper();

            // Encrypto a senha
            var senha = objEncryptar.Encrypt(tbAltSenha.Text);

            // Defino usuario
            var usuario = tbAltUsuario.Text;

            // Defino email
            var email = tbAltEmail.Text;

            // Defino nome
            var nome = tbAltNome.Text;

            // Defino admin
            var admin = cbAdmin.IsChecked.Value;

            // Defino ativo
            var ativo = cbAtivo.IsChecked.Value;

            // Gera novo objeto de conexao ao banco de dados
            var dataBase = new DatabaseHelper("aniversariantes");

            // Gero nova lista com dados de campos e valores
            var lista = new Dictionary<string, string>();

            // Adiciona campos na lista com os respectivos valores
            lista.Add("c_usuario", usuario);
            lista.Add("c_senha", senha);
            lista.Add("b_ativo", ativo.ToString());
            lista.Add("b_admin", admin.ToString());
            lista.Add("c_nome", nome);
            lista.Add("c_email", email);

            // Chama método que insere os usuarios na tabela passando os parametros
            if (dataBase.Insert("dados.usuarios", lista)) {
                MessageBox.Show("Usuario adicionado com sucesso");
            }
            else {
                MessageBox.Show("Ocorreu um erro ao tentar cadastrar o usuário.");
            }

            Close();
        }
Exemplo n.º 20
0
        public dynamic Verify(string parameters)
        {
            string encyptKey = ConfigurationManager.AppSettings["EncyptKey"];

            if (string.IsNullOrEmpty(encyptKey))
            {
                throw new Exception("EncyptKey not found in App.config");
            }

            var dataJson  = EncryptHelper.Base64Decode(parameters);
            var jSettings = new JsonSerializerSettings
            {
                Formatting           = Formatting.Indented,
                DateTimeZoneHandling = DateTimeZoneHandling.Utc
            };

            jSettings.Converters.Add(new DefaultWrongFormatDeserialize());
            var viewModel = JsonConvert.DeserializeObject <RequestAssessmentPcsVo>(dataJson, jSettings);

            //if tabSelected == 1 , Disclose form
            if (viewModel.TabSelected == 1)
            {
                var checkDisclosureForm = CheckInValidDisclosureForm(viewModel.DisclosureFormVo);
                if (checkDisclosureForm.Count > 0)
                {
                    var result = new ObjectReturnVo();
                    result.Error = checkDisclosureForm;
                    result.Id    = viewModel.AssessmentPcsId;
                    return(result);
                }
            }
            //if tabSelected == 2 , PCST form
            else
            {
                TrackingCompleteInformation(viewModel);
                if (viewModel.CurrentSectionId == null)
                {
                    var checkMid = CheckMidDisclosureFormAndPcstForm(viewModel);
                    if (checkMid.Count > 0)
                    {
                        if (viewModel.MessageErrorTotal == null)
                        {
                            viewModel.MessageErrorTotal = new List <MessageErrorVo>();
                            viewModel.MessageErrorTotal.AddRange(checkMid);
                        }
                        else
                        {
                            viewModel.MessageErrorTotal.AddRange(checkMid);
                        }
                    }
                    var checkErrorExpedited = CheckErrorExpedited(viewModel);
                    if (checkErrorExpedited.Count > 0)
                    {
                        viewModel.MessageErrorTotal.AddRange(checkErrorExpedited);
                    }
                }


                if (viewModel.MessageErrorTotal != null && viewModel.MessageErrorTotal.Count > 0)
                {
                    var index = 0;
                    foreach (var item in viewModel.MessageErrorTotal)
                    {
                        index++;
                        item.Index = index;
                    }
                    var result = new ObjectReturnVo();
                    result.Error = viewModel.MessageErrorTotal;
                    result.Id    = viewModel.AssessmentPcsId;
                    return(result);
                }
            }

            var result1 = new ObjectReturnVo();

            result1.Id = viewModel.AssessmentPcsId;
            return(result1);
        }
Exemplo n.º 21
0
        /// <summary>
        /// 用于登陆加密
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        public static string GetCode(string str, string key)
        {
            string code = EncryptHelper.GetMd5(str, key);

            return(code);
        }
Exemplo n.º 22
0
        public BaseModel ResetMobile(string token, string password, string mobileNum, string smsCode)
        {
            try
            {
                #region 非数据库端验证token
                BaseModel cv_Token = ClientValidateToken(token);
                if (cv_Token.Code != 0)
                {
                    return(cv_Token);
                }
                #endregion

                #region 非数据库端验证mobileNum
                BaseModel cv_MobileNum = ClientValidateMobileNum(mobileNum);
                if (cv_MobileNum.Code != 0)
                {
                    return(cv_MobileNum);
                }
                #endregion

                #region 非数据库端验证smsCode
                BaseModel cv_SMSCode = ClientValidateSMSCode(smsCode);
                if (cv_SMSCode.Code != 0)
                {
                    return(cv_SMSCode);
                }
                #endregion

                #region 非数据库端验证password
                BaseModel cv_Password = ClientValidatePassword(password);
                if (cv_Password.Code != 0)
                {
                    return(cv_Password);
                }
                #endregion

                UserModel TokenModel = userDAL.GetByToken(token);
                #region 数据库端验证token
                BaseModel sv_Token = ServerValidateToken(TokenModel);
                if (sv_Token.Code != 0)
                {
                    return(sv_Token);
                }
                #endregion

                DateTime dt  = DateTime.Now;
                DateTime dt2 = dt.AddMinutes(0 - ConfigHelper.SMSTime);

                #region 数据库端验证smsCode
                BaseModel sv_SMSCode = ServerValidateSMSCode(smsCode, mobileNum, dt2);
                if (sv_SMSCode.Code != 0)
                {
                    return(sv_SMSCode);
                }
                #endregion

                UserModel userModel = userDAL.GetByMobile(mobileNum);
                #region 数据库端验证mobileNum
                BaseModel sv_MobileNum = ServerValidateMobileNum(userModel);
                if (sv_MobileNum.Code != 0)
                {
                    return(sv_MobileNum);
                }
                #endregion

                #region 更新用户手机号

                if (TokenModel.Password != EncryptHelper.MD5Encrypt(password + ConfigHelper.Salt))
                {
                    return(new BaseModel()
                    {
                        Code = (int)CodeEnum.密码错误, Msg = string.Format(CodeMsgDAL.GetByCode((int)CodeEnum.密码错误))
                    });
                }
                TokenModel.MobileNum = mobileNum;

                if (userDAL.Update(TokenModel))
                {
                    return(new BaseModel()
                    {
                        Code = (int)CodeEnum.成功, Msg = string.Format(CodeMsgDAL.GetByCode((int)CodeEnum.成功))
                    });
                }
                else
                {
                    return(new BaseModel()
                    {
                        Code = (int)CodeEnum.失败, Msg = string.Format(CodeMsgDAL.GetByCode((int)CodeEnum.失败))
                    });
                }
                #endregion
            }
            catch (Exception ex)
            {
                LogHelper.Error(ex);
                return(new BaseModel()
                {
                    Code = (int)CodeEnum.系统异常, Msg = CodeMsgDAL.GetByCode((int)CodeEnum.系统异常)
                });
            }
        }
Exemplo n.º 23
0
        /// <summary>
        /// 注册用户
        /// </summary>
        /// <param name="telephone"></param>
        /// <param name="vcode"></param>
        /// <param name="password"></param>
        /// <param name="salerSource">销售源头:门店:Store 业务员:Saler</param>
        /// <returns></returns>
        public JsonResult RegisterNew(string telephone, string vcode, string SourceType, string salesCode)
        {
            telephone  = Request["telephone"];
            vcode      = Request["vcode"];
            SourceType = Request["SourceType"];
            salesCode  = Request["Scode"];
            string         password  = "******";
            ApiUserEntity  viewE     = new ApiUserEntity();
            CustomerEntity chkENtity = CustomerService.GetCustomerByTelephone(telephone);

            if (chkENtity == null)
            {
                //判断验证码是否正确、是否已经过期了
                VerificationCodeEntity VCode = BaseDataService.CheckVerificationCode(telephone, vcode);
                if (string.IsNullOrEmpty(VCode.Mobile))
                {
                    CustomerEntity entity = CustomerService.Register(telephone, EncryptHelper.MD5Encrypt(password), vcode, 4);
                    if (entity != null)
                    {
                        #region 注册成功与业务员建立关系


                        List <SalerRelationEntity> listSaler = SalerService.GetSalerCustomerByTelephone(telephone);
                        if (listSaler != null && listSaler.Count > 0)
                        {
                        }
                        else
                        {
                            //绑定和业务员之间的关系
                            SalerRelationEntity sr = new SalerRelationEntity();
                            sr.SalerCode = salesCode;
                            //sr.SalerID = sid;
                            sr.CustomerID   = entity.CustomerID;
                            sr.CustomerCode = entity.CustomerCode;
                            sr.SalerSource  = SourceType;
                            SalerService.CreateRelation(sr);

                            #endregion

                            viewE.code           = "200";
                            viewE.codeinfo       = "注册成功!";
                            viewE.customerEntity = entity;
                        }

                        #region 给客户发送短信
                        SendSMSService.SendRegisterMess(telephone, password);
                        #endregion
                    }
                    else
                    {
                        viewE.code     = "201";
                        viewE.codeinfo = "注册失败!";
                    }
                }
                else
                {
                    viewE.code     = "202";
                    viewE.codeinfo = "验证码已经过期!";
                }
            }
            else
            {
                viewE.code     = "203";
                viewE.codeinfo = "手机号已经注册!";
            }
            return(Json("ok"));
        }
Exemplo n.º 24
0
        /// <summary>
        /// Send an email using gmail
        /// </summary>
        /// <param name="Email"></param>
        /// <returns></returns>
        public static bool SendMail(Email Email)
        {
            bool result = false;

            try
            {
                Email       SavedEmail  = Email;
                MailAddress fromAddress = new MailAddress(Email.FromEmail, MailName);


                MailAddress toAddress    = new MailAddress(Email.ToEmail, "To " + Email.ToEmail);
                string      fromPassword = EncryptHelper.DecryptString(PasswordMailAdress);

                if (String.IsNullOrWhiteSpace(Email.EndMailTemplate))
                {
                    Email.EndMailTemplate = "_EndMail_" + CommonsConst.Languages.ToString(Email.LanguageId);
                }

                if (!String.IsNullOrWhiteSpace(Email.EMailTemplate) && !String.IsNullOrWhiteSpace(Email.ToEmail))
                {
                    string TemplateName = Email.EMailTemplate;
                    Email.Subject = "#WebsiteTitle# - " + Email.Subject;

                    var smtp = new SmtpClient
                    {
                        Host                  = "smtp.gmail.com",
                        Port                  = 587,
                        EnableSsl             = true,
                        DeliveryMethod        = SmtpDeliveryMethod.Network,
                        UseDefaultCredentials = false,
                        Credentials           = new NetworkCredential(fromAddress.Address, fromPassword)
                    };
                    smtp.SendCompleted += new SendCompletedEventHandler(SendCompletedCallback);



                    string PathHeaderOnServer   = Email.BasePathFile + "\\_HeaderMail.html";
                    string PathFooterOnServer   = Email.BasePathFile + "\\_FooterMail.html";
                    string PathEndMailOnServer  = Email.BasePathFile + "\\" + Email.EndMailTemplate + ".html";
                    string PathTemplateOnServer = Email.BasePathFile + "\\" + TemplateName + ".html";
                    string headerTemplate       = new StreamReader(PathHeaderOnServer).ReadToEnd();
                    string bodyTemplate         = new StreamReader(PathTemplateOnServer).ReadToEnd();
                    string footerTemplate       = new StreamReader(PathFooterOnServer).ReadToEnd();
                    string endMailTemplate      = new StreamReader(PathEndMailOnServer).ReadToEnd();
                    bodyTemplate = headerTemplate + bodyTemplate + endMailTemplate + footerTemplate;
                    //    bodyTemplate=  new StreamReader(Email.BasePathFile + "/_Test.html").ReadToEnd();
                    foreach (var content in Email.EmailContent)
                    {
                        string key   = content.Item1;
                        string value = content.Item2;

                        if (key.Contains("_watcher"))
                        {
                            value = AddEmailWatcher(value, Email.AuditGuidId);
                        }
                        bodyTemplate  = bodyTemplate.Replace(key, value);
                        Email.Subject = Email.Subject.Replace(key, value);
                    }
                    List <Tuple <string, string> > GenericEmailContent = GetGenericEmailContent();
                    foreach (var content in GenericEmailContent)
                    {
                        bodyTemplate  = bodyTemplate.Replace(content.Item1, content.Item2);
                        Email.Subject = Email.Subject.Replace(content.Item1, content.Item2);
                    }



                    var message = new MailMessage(fromAddress, toAddress)
                    {
                        Subject    = Email.Subject,
                        Body       = bodyTemplate,
                        IsBodyHtml = true
                    };

                    if (Email.AttachmentsMails != null)
                    {
                        foreach (System.Net.Mail.Attachment file in Email.AttachmentsMails)
                        {
                            if (file != null)
                            {
                                try
                                {
                                    message.Attachments.Add(file);
                                }
                                catch (Exception e)
                                {
                                    Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "file = " + file + " and UserMail = " + Email.ToEmail + " and subject = " + Email.Subject);
                                }
                            }
                        }
                    }
                    if (Email.CCList != null)
                    {
                        foreach (string CC in Email.CCList)
                        {
                            message.CC.Add(CC);
                        }
                    }
                    smtp.SendAsync(message, SavedEmail);
                    result = true;
                }
            }
            catch (Exception e)
            {
                result = false;
                Commons.Logger.GenerateError(e, System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "UserMail = " + Email.ToEmail + " and subject = " + Email.Subject + " and EMailTypeId = " + Email.EMailTypeId);
            }
            return(result);
        }
Exemplo n.º 25
0
        /// <summary>
        /// 创建md5摘要,规则是:按参数名称a-z排序,遇到空值的参数不参加签名
        /// <para>key和value通常用于填充最后一组参数</para>
        /// </summary>
        /// <param name="key">参数名</param>
        /// <param name="value">参数值</param>
        /// <param name="workPaySignType">企业支付签名(workwx_sign)类型,默认为 None</param>
        /// <returns></returns>
        public virtual string CreateMd5Sign(string key, string value, WorkPaySignType workPaySignType = WorkPaySignType.None)
        {
            StringBuilder sb = new StringBuilder();

            ArrayList akeys = new ArrayList(Parameters.Keys);

            akeys.Sort(ASCIISort.Create());

            foreach (string k in akeys)
            {
                string v = (string)Parameters[k];
                if (null != v && "".CompareTo(v) != 0 &&
                    "sign".CompareTo(k) != 0
                    //&& "sign_type".CompareTo(k) != 0
                    && "key".CompareTo(k) != 0)
                {
                    //过滤企业支付特殊情况
                    if (workPaySignType == WorkPaySignType.WorkSendRedPackage)
                    {
                        //企业支付微信红包,仅保留以下字段
                        if ("act_name".CompareTo(k) != 0 ||
                            "mch_billno".CompareTo(k) != 0 ||
                            "mch_id".CompareTo(k) != 0 ||
                            "nonce_str".CompareTo(k) != 0 ||
                            "re_openid".CompareTo(k) != 0 ||
                            "total_amount".CompareTo(k) != 0 ||
                            "wxappid".CompareTo(k) != 0
                            )
                        {
                            continue;
                        }
                    }
                    else if (workPaySignType == WorkPaySignType.WorkPayApi)
                    {
                        //企业支付微信红包,仅保留以下字段
                        if ("amount".CompareTo(k) != 0 ||
                            "appid".CompareTo(k) != 0 ||
                            "desc".CompareTo(k) != 0 ||
                            "mch_id".CompareTo(k) != 0 ||
                            "nonce_str".CompareTo(k) != 0 ||
                            "openid".CompareTo(k) != 0 ||
                            "partner_trade_no".CompareTo(k) != 0 ||
                            "ww_msg_type".CompareTo(k) != 0
                            )
                        {
                            continue;
                        }
                    }
                    sb.Append(k + "=" + v + "&");
                }
            }

            sb.Append(key + "=" + value);

            //string sign = EncryptHelper.GetMD5(sb.ToString(), GetCharset()).ToUpper();

            //编码强制使用UTF8:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_1
            string sign = EncryptHelper.GetMD5(sb.ToString(), "UTF-8").ToUpper();

            return(sign);
        }
Exemplo n.º 26
0
 /// <summary>
 /// 登录
 /// </summary>
 /// <param name="user">包含用户名,密码</param>
 /// <returns>成功返回对象,失败返回null</returns>
 public UserInfo Login(UserInfo user)
 {
     user.UserPwd = EncryptHelper.Get32MD5(user.UserPwd);
     user.UserPwd = EncryptHelper.Get32MD5(user.UserPwd);
     return(_userInfoDal.Login(user));
 }
Exemplo n.º 27
0
    protected void btnChangePassword_Click(object sender, EventArgs e)
    {
        string name  = Session["firstname"].ToString() + Session["lastname"].ToString();
        string cpass = Helper.CreateSHAHash(txtCPassword.Text);

        con.Open();
        SqlCommand com = new SqlCommand();

        com.Connection = con;
        if (cpass == cpassword.ToString())
        {
            if (txtNPassword.Text == txtReEnterNP.Text)
            {
                com.CommandText = "UPDATE Users SET Password=@Password WHERE UserID=@UserID";
                com.Parameters.AddWithValue("@Password", Helper.CreateSHAHash(txtNPassword.Text));
                com.Parameters.AddWithValue("@UserID", Session["userid"].ToString());
                com.ExecuteNonQuery();
                con.Close();
                aud.AuditLog(EncryptHelper.Encrypt("Change Password", Helper.GetSalt()), int.Parse(Session["empid"].ToString()), EncryptHelper.Encrypt("Updated: " + name + "'s" + " Password", Helper.GetSalt()));
                validatealert.Visible  = false;
                validatealert2.Visible = false;
            }
            else
            {
                validatealert.Visible  = false;
                validatealert2.Visible = true;
            }
        }
        else
        {
            validatealert.Visible  = true;
            validatealert2.Visible = false;
        }
    }
    protected void Page_Load(object sender, EventArgs e)
    {
        if (Request.QueryString["OTRID"] != null)
        {
            int  OTRID      = 0;
            bool validOTRID = int.TryParse(Request.QueryString["OTRID"].ToString(), out OTRID);

            if (validOTRID)
            {
                if (!IsPostBack)
                {
                    string name = Session["firstname"].ToString() + " " + Session["lastname"].ToString();
                    aud.AuditLog(EncryptHelper.Encrypt("Rejected OT", Helper.GetSalt()), int.Parse(Session["empid"].ToString()), EncryptHelper.Encrypt(name + "Rejected OT for OTRID " + Request.QueryString["OTRID"].ToString(), Helper.GetSalt()));
                    Reject(OTRID);
                }
            }
            else
            {
                Response.Redirect("getOvertimeApplication.aspx");
            }
        }
        if (Session["userid"] != null)
        {
            if (Session["position"].ToString() == "Department Head")
            {
            }
            else
            {
                Response.Redirect("../Login.aspx");
            }
        }
        else
        {
            Response.Redirect("../Login.aspx");
        }
    }
Exemplo n.º 29
0
        public ActionResult _Form(int?Id
                                  , string MaNhanVien
                                  , string HoVaTen
                                  , string TenDangNhap
                                  , string MatKhau
                                  , string Email
                                  , string DienThoai
                                  , string CMT
                                  , string ChucVuId
                                  , string VanPhongId
                                  , string NgaySinh
                                  , string DiaChi
                                  , double?HanMuc
                                  , string AnhDaiDien
                                  , bool TrangThai
                                  , string[] thumbnails
                                  )
        {
            var session = (UserLogin)Session[CommonConstants.USER_SESSION];
            NguoiDungService _nguoidung = new NguoiDungService();

            Models.NguoiDung nguoidung = _nguoidung.FindByKeys(Id);
            nguoidung.MaNhanVien  = MaNhanVien;
            nguoidung.HoVaTen     = HoVaTen;
            nguoidung.TenDangNhap = TenDangNhap;
            nguoidung.MatKhau     = EncryptHelper.EncryptMD5(MatKhau);;
            nguoidung.Email       = Email;
            nguoidung.AnhDaiDien  = AnhDaiDien;
            nguoidung.NguoiTao    = session.Name;
            nguoidung.SoCMT       = CMT;
            nguoidung.GioiHan     = HanMuc;
            if (!string.IsNullOrEmpty(NgaySinh))
            {
                nguoidung.NgaySinh = ConvertEx.ToDate(NgaySinh);
            }
            nguoidung.DiaChi    = DiaChi;
            nguoidung.DienThoai = DienThoai;
            if (!string.IsNullOrEmpty(ChucVuId))
            {
                nguoidung.ChucVuId = Convert.ToInt32(ChucVuId);
            }
            if (!string.IsNullOrEmpty(VanPhongId))
            {
                nguoidung.VanPhongId = Convert.ToInt32(VanPhongId);
            }
            nguoidung.TrangThai = TrangThai;

            nguoidung.DaXoa = false;
            if (Id.HasValue)
            {
                if (thumbnails != null && thumbnails.Length > 0)
                {
                    nguoidung.AnhDaiDien = string.Join(";", thumbnails);
                }
                nguoidung.GioiHan  = HanMuc;
                nguoidung.NguoiSua = session.Name;
                nguoidung.NgaySua  = DateTime.Now;
                _nguoidung.Update(nguoidung);
                setAlert("Thông tin người dùng đã được cập nhập", "success");
            }
            else
            {
                if (thumbnails != null && thumbnails.Length > 0)
                {
                    nguoidung.AnhDaiDien = string.Join(";", thumbnails);
                }
                nguoidung.GioiHan = 500000;
                nguoidung.NgayTao = DateTime.Now;
                _nguoidung.Insert(nguoidung);
                setAlert("Thêm người dùng thành công", "success");
            }
            return(RedirectToAction("Index"));
        }
Exemplo n.º 30
0
        public async Task <IActionResult> Register([FromBody] AccountRegisterRequestInfo info, CancellationToken token)
        {
            // 检测注册信息合法性
            ValidateAccount(info);

            try
            {
                // 检测帐号名是否可以被注册
                var oldAccountEntity = await this.Database.Accounts.GetSingleAsync(
                    a => a.AccountName == info.AccountName,
                    //|| a.Email == info.Email
                    //|| a.Phone == info.Phone,
                    token);

                if (oldAccountEntity != null)
                {
                    throw new UCenterException(UCenterErrorCode.AccountNameAlreadyExist);
                }

                // 检查Device是否绑定了游客号
                AccountEntity accountEntity = null;
                if (info != null &&
                    !string.IsNullOrEmpty(info.AppId) &&
                    info.Device != null &&
                    !string.IsNullOrEmpty(info.Device.Id))
                {
                    string guestDeviceId     = $"{info.AppId}_{info.Device.Id}";
                    var    guestDeviceEntity = await this.Database.GuestDevices.GetSingleAsync(guestDeviceId, token);

                    if (guestDeviceEntity != null)
                    {
                        accountEntity = await this.Database.Accounts.GetSingleAsync(guestDeviceEntity.AccountId, token);
                    }
                }

                bool guestConvert = true;
                if (accountEntity == null)
                {
                    guestConvert = false;

                    // 没有绑定游客号,正常注册
                    accountEntity = new AccountEntity
                    {
                        Id = Guid.NewGuid().ToString(),
                    };
                }

                accountEntity.AccountName   = info.AccountName;
                accountEntity.AccountType   = AccountType.NormalAccount;
                accountEntity.AccountStatus = AccountStatus.Active;
                accountEntity.Name          = info.Name;
                accountEntity.Identity      = info.Identity;
                accountEntity.Password      = EncryptHelper.ComputeHash(info.Password);
                accountEntity.SuperPassword = EncryptHelper.ComputeHash(info.SuperPassword);
                accountEntity.Phone         = info.Phone;
                accountEntity.Email         = info.Email;
                accountEntity.Gender        = info.Gender;

                //var placeholders = new[]
                //    {
                //        this.GenerateKeyPlaceholder(accountEntity.AccountName, KeyType.Name, accountEntity.Id, accountEntity.AccountName),
                //        this.GenerateKeyPlaceholder(accountEntity.Phone, KeyType.Phone, accountEntity.Id, accountEntity.AccountName),
                //        this.GenerateKeyPlaceholder(accountEntity.Email, KeyType.Email, accountEntity.Id, accountEntity.AccountName)
                //    };

                //foreach (var placeholder in placeholders)
                //{
                //    if (!string.IsNullOrEmpty(placeholder.Name))
                //    {
                //        await this.Database.KeyPlaceholders.InsertAsync(placeholder, token);
                //        removeTempsIfError.Add(placeholder);
                //    }
                //}

                if (guestConvert)
                {
                    // 绑定了游客号,游客号转正
                    await this.Database.Accounts.UpsertAsync(accountEntity, token);

                    try
                    {
                        await this.Database.GuestDevices.DeleteAsync(
                            d => d.AppId == info.AppId && d.AccountId == accountEntity.Id,
                            token);
                    }
                    catch (Exception ex)
                    {
                        CustomTrace.TraceError(ex, "Error to remove guest device");
                    }

                    await this.TraceAccountEvent(accountEntity, "GuestConvert", token : token);
                }
                else
                {
                    // 没有绑定游客号,正常注册

                    // Remove this from UCenter for performance concern
                    // If user does not have default profile icon, app client should use local default one
                    // accountEntity.ProfileImage = await this.storageContext.CopyBlobAsync(
                    //    accountEntity.Gender == Gender.Female ? this.settings.DefaultProfileImageForFemaleBlobName : this.settings.DefaultProfileImageForMaleBlobName,
                    //    this.settings.ProfileImageForBlobNameTemplate.FormatInvariant(accountEntity.Id),
                    //    token);

                    // accountEntity.ProfileThumbnail = await this.storageContext.CopyBlobAsync(
                    //    accountEntity.Gender == Gender.Female
                    //        ? this.settings.DefaultProfileThumbnailForFemaleBlobName
                    //        : this.settings.DefaultProfileThumbnailForMaleBlobName,
                    //    this.settings.ProfileThumbnailForBlobNameTemplate.FormatInvariant(accountEntity.Id),
                    //    token);

                    await this.Database.Accounts.InsertAsync(accountEntity, token);

                    await TraceAccountEvent(accountEntity, "Register", info.Device, token : token);
                }

                if (info.Device != null)
                {
                    await LogDeviceInfo(info.Device, token);
                }

                return(this.CreateSuccessResult(this.ToResponse <AccountRegisterResponse>(accountEntity)));
            }
            catch (Exception ex)
            {
                CustomTrace.TraceError(ex, "Account.Register Exception:AccoundName={info.AccountName}");
                throw;
            }
        }
Exemplo n.º 31
0
 /// <summary>
 /// 64位加密方式
 /// </summary>
 /// <param name="password"></param>
 /// <returns></returns>
 private string Base64Generate(string encryptStr)
 {
     return(EncryptHelper.Encode(encryptStr + "|" + "ee7018a6AA5b53e50"));
 }
 private string GetEncryptedValue()
 {
     return(_value > 0 ? EncryptHelper.Encrypt(_value) : "");
 }
Exemplo n.º 33
0
        /// <summary>
        /// 获取微信授权用户信息
        /// </summary>
        /// <param name="customerId">商户Id</param>
        /// <returns></returns>
        public WeixinOAuthUserInfoModel GetUserInfo(int customerId)
        {
            string keyUserinfo       = this.GetUserinfoDataKey(customerId);
            string encryptedUserInfo = CookieHelper.GetCookieVal(keyUserinfo);

            if (string.IsNullOrEmpty(encryptedUserInfo))
            {
                //尝试从session中读取
                if (HttpContext.Current.Session[keyUserinfo] != null)
                {
                    WeixinOAuthUserInfoModel seModel = HttpContext.Current.Session[keyUserinfo] as WeixinOAuthUserInfoModel;
                    return(seModel);
                }
                return(null);
            }
            try
            {
                WeixinOAuthUserInfoModel model = JsonConvert.DeserializeObject <WeixinOAuthUserInfoModel>(EncryptHelper.Decrypt(encryptedUserInfo, ENCRYPTKEY));
                return(model);
            }
            catch (Exception ex)
            {
                LogHelper.Write(string.Format("WeixinOAuthUserDataProvider->GetUserInfo发生异常:{0}", ex.Message));
            }
            return(null);
        }
Exemplo n.º 34
0
 public byte[] EnPwd_UTF8(byte[] data)
 {
     return(Encoding.UTF8.GetBytes(EncryptHelper.GetSHA512(data)));
 }
Exemplo n.º 35
0
        protected ActionResult Refund()
        {
            //创建请求对象
            RefundRequestHandler reqHandler = new RefundRequestHandler(null);

            //通信对象
            TenPayHttpClient httpClient = new TenPayHttpClient();

            //应答对象
            ClientResponseHandler resHandler = new ClientResponseHandler();

            //-----------------------------
            //设置请求参数
            //-----------------------------
            reqHandler.Init();
            reqHandler.SetKey(TenPayInfo.Key);

            reqHandler.SetParameter("partner", TenPayInfo.PartnerId);
            //out_trade_no和transaction_id至少一个必填,同时存在时transaction_id优先
            //reqHandler.setParameter("out_trade_no", "1458268681");
            reqHandler.SetParameter("transaction_id", "1900000109201103020030626316");
            reqHandler.SetParameter("out_refund_no", "2011030201");
            reqHandler.SetParameter("total_fee", "1");
            reqHandler.SetParameter("refund_fee", "1");
            reqHandler.SetParameter("refund_fee", "1");
            reqHandler.SetParameter("op_user_id", "1900000109");
            reqHandler.SetParameter("op_user_passwd", EncryptHelper.GetMD5("111111", "GBK"));
            reqHandler.SetParameter("service_version", "1.1");

            string requestUrl = reqHandler.GetRequestURL();

            httpClient.SetCertInfo("c:\\key\\1900000109.pfx", "1900000109");
            //设置请求内容
            httpClient.SetReqContent(requestUrl);
            //设置超时
            httpClient.SetTimeOut(10);

            string rescontent = "";

            string result = String.Empty;

            //后台调用
            if (httpClient.Call())
            {
                //获取结果
                rescontent = httpClient.GetResContent();

                resHandler.SetKey(TenPayInfo.Key);
                //设置结果参数
                resHandler.SetContent(rescontent);

                //判断签名及结果
                if (resHandler.IsTenpaySign() && resHandler.GetParameter("retcode") == "0")
                {
                    //商户订单号
                    string out_trade_no = resHandler.GetParameter("out_trade_no");
                    //财付通订单号
                    string transaction_id = resHandler.GetParameter("transaction_id");

                    //业务处理
                    result += "OK,transaction_id=" + resHandler.GetParameter("transaction_id") + "<br>";
                }
                else
                {
                    //错误时,返回结果未签名。
                    //如包格式错误或未确认结果的,请使用原来订单号重新发起,确认结果,避免多次操作
                    result += "业务错误信息或签名错误:" + resHandler.GetParameter("retcode") + "," + resHandler.GetParameter("retmsg") + "<br>";
                }
            }
            else
            {
                //后台调用通信失败
                result += "call err:" + httpClient.GetErrInfo() + "<br>" + httpClient.GetResponseCode() + "<br>";
                //有可能因为网络原因,请求已经处理,但未收到应答。
            }


            //获取debug信息,建议把请求、应答内容、debug信息,通信返回码写入日志,方便定位问题

            result += "http res:" + httpClient.GetResponseCode() + "," + httpClient.GetErrInfo() + "<br>";
            result += "req url:" + requestUrl + "<br/>";
            result += "req debug:" + reqHandler.GetDebugInfo() + "<br/>";
            result += "res content:" + rescontent.HtmlEncode() + "<br/>";
            result += "res debug:" + resHandler.GetDebugInfo().HtmlEncode() + "<br/>";

            return(Content(result));
        }
Exemplo n.º 36
0
        public override async Task Execute()
        {
            var regionKey = "GLA";
            var tenant    = new Tenant()
            {
                Name       = Input.TenantName, TenantName = Input.TenantName, EntryKey = StringHelper.GenerateCode(16),
                AuthorName = Input.Name, RegionKey = regionKey
            };
            var isNew = true;

            if (string.IsNullOrEmpty(Input.TenantId))
            {
                var persistClient = new Persist <Tenant>()
                {
                    Model = tenant
                };
                await DataHandler.Execute(persistClient);

                tenant = persistClient.Model;
            }
            else
            {
                var loaderClient = new Loader <Tenant>()
                {
                    Id = Input.TenantId
                };
                await DataHandler.Execute(loaderClient);

                tenant = loaderClient.Result;
                isNew  = false;
            }

            if (tenant != null && !string.IsNullOrEmpty(tenant.Id))
            {
                var user = new User()
                {
                    TenantId     = tenant.Id, TenantName = Input.TenantName, Name = Input.Name, Email = Input.Email,
                    EncryptedPwd = EncryptHelper.Encrypt(Input.Pwd), AuthorName = Input.Name,
                    Right        = new UserRight()
                    {
                        CanAuth = isNew, CanAdmin = isNew, CanSuperuser = false
                    },
                    RegionKey = regionKey
                };

                var persistUser = new UserSave {
                    Model = user
                };
                await DataHandler.Execute(persistUser);

                if (persistUser.Confirm.Success)
                {
                    if (isNew)
                    {
                        tenant.AuthorId = persistUser.Model.Id;
                        tenant.TenantId = tenant.Id;

                        var persistClient = new Persist <Tenant>()
                        {
                            Model = tenant
                        };
                        await DataHandler.Execute(persistClient);

                        tenant = persistClient.Model;

                        var meetingType = new MeetingType()
                        {
                            TenantId = tenant.Id, TenantName = tenant.Name, Name = "Standard", IsRecur = false,
                            Pretext  = "Standard Meeting Type", RegionKey = regionKey, Prename = "Meeting",
                            AuthorId = persistUser.Model.Id, AuthorName = persistUser.Model.Name
                        };
                        var persistType = new Persist <MeetingType>()
                        {
                            Model = meetingType
                        };
                        await DataHandler.Execute(persistType);
                    }

                    persistUser.Model.AuthorId = persistUser.Model.Id;
                    await DataHandler.Execute(persistUser);

                    await DataHandler.Commit();

                    var signin = new SigninAuth()
                    {
                        Tenant      = tenant, Login = persistUser.Model, LogicHandler = LogicHandler,
                        DataHandler = DataHandler, Config = persistUser.ResultConfig, Settings = CloudHandler.Settings
                    };
                    await LogicHandler.Execute(signin);

                    ResultAuth = signin.Result;

                    Result = ActionConfirm.CreateSuccess(persistUser.Model);

                    var notify = new SimpleNotify
                    {
                        CloudHandler = CloudHandler, DataHandler = DataHandler, CurrentUser = persistUser.Model,
                        LogicHandler = LogicHandler, Model = persistUser.Model,
                        TemplateName = isNew ? "welcomeclient" : "welcomeuser"
                    };
                    await LogicHandler.Execute(notify);
                }
                else
                {
                    Result = ActionConfirm.CreateFailure(persistUser.Confirm.Message);
                }
            }
            else
            {
                Result = ActionConfirm.CreateFailure("Error connecting organisation");
            }
        }
Exemplo n.º 37
0
 /// <summary>
 /// 获取随机字符串
 /// </summary>
 /// <returns></returns>
 public static string GetNoncestr()
 {
     return(EncryptHelper.GetMD5(Guid.NewGuid().ToString(), "UTF-8"));
 }
Exemplo n.º 38
0
        private void carregaDados()
        {
            // Gera novo objeto de Conexao ao banco
            var dataBase = new DatabaseHelper("aniversariantes");

            // Gera Sql para pegar dados do usuario a ser alterado
            var query = string.Format("SELECT id, c_usuario, c_senha, b_ativo, b_admin, c_nome, c_email FROM dados.usuarios WHERE id = {0}", idUsuario);

            // Executa a query
            var result = dataBase.GetDataTable(query);

            // Se não existe o usuario no banco
            if (result.Rows.Count == 0) {
                // Informa que não encontrou o usuário
                MessageBox.Show("Erro ao encontrar usuario");

                Close();
            }

            // Cria novo objeto de Encryptação
            var objEncrypt = new EncryptHelper();

            // Desencrypta a senha
            tbAltSenha.Text = objEncrypt.Decrypt((string) result.Rows[0][2]);

            tbCodigo.Text = Convert.ToString(result.Rows[0][0]);
            tbAltUsuario.Text = (string) result.Rows[0][1];
            cbAtivo.IsChecked = (bool) result.Rows[0][3];
            cbAdmin.IsChecked = (bool) result.Rows[0][4];
            tbAltNome.Text = (string) result.Rows[0][5];
            tbAltEmail.Text = (string) result.Rows[0][6];
        }