示例#1
0
        public object JsonDeserializeObject(int mode)
        {
            DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Order));

            using (FileStream fs = new FileStream(_path, FileMode.Open, FileAccess.Read))
            {
                if (mode == 2)
                {
                    object ord = jsonFormatter.ReadObject(fs);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                else if (mode == 0)
                {
                    DESCrypt des = new DESCrypt();
                    object   ord = des.Deserialize(fs, _path, null, null, jsonFormatter);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                else if (mode == 1)
                {
                    AESCrypt aes = new AESCrypt();
                    object   ord = aes.Deserialize(fs, _path, null, null, jsonFormatter);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                return(null);
            }
        }
示例#2
0
        public object BinaryDeserializeObject(int mode)
        {
            BinaryFormatter formatter = new BinaryFormatter();

            using (FileStream fs = new FileStream(Path, FileMode.Open, FileAccess.Read))
            {
                if (mode == 2)
                {
                    object obj = formatter.Deserialize(fs);
                    MessageBox.Show("Object successfully deserialized");
                    return(obj);
                }
                else if (mode == 0)
                {
                    DESCrypt des = new DESCrypt();
                    object   ord = des.Deserialize(fs, Path, null, formatter, null);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                else if (mode == 1)
                {
                    AESCrypt aes = new AESCrypt();
                    object   ord = aes.Deserialize(fs, Path, null, formatter, null);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                return(null);
            }
        }
示例#3
0
        public object DeserializeXmlObject(int cyphermode)
        {
            XmlSerializer sl = new XmlSerializer(typeof(Order));

            using (FileStream fs = new FileStream(Path, FileMode.OpenOrCreate))
            {
                if (cyphermode == 2)
                {
                    object ord = sl.Deserialize(fs);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                else if (cyphermode == 0)
                {
                    DESCrypt des = new DESCrypt();
                    object   ord = des.Deserialize(fs, Path, sl, null);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                else if (cyphermode == 1)
                {
                    AESCrypt aes = new AESCrypt();
                    object   ord = aes.Deserialize(fs, Path, sl, null);
                    MessageBox.Show("Object successfully deserialized");
                    return(ord);
                }
                return(null);
            }
        }
示例#4
0
        public void BinarySerializeObject(int cypherAlgo)
        {
            BinaryFormatter formatter = new BinaryFormatter();

            using (FileStream fs = new FileStream(Path, FileMode.OpenOrCreate))
            {
                if (cypherAlgo == 2)
                {
                    formatter.Serialize(fs, ObjectToSerialize);
                }
                else
                {
                    if (cypherAlgo == 0)
                    {
                        DESCrypt des = new DESCrypt();
                        des.Serialize(fs, ObjectToSerialize, Path, null, formatter, null);
                    }
                    else if (cypherAlgo == 1)
                    {
                        AESCrypt aes = new AESCrypt();
                        aes.Serialize(fs, ObjectToSerialize, Path, null, formatter, null);
                    }
                }
                MessageBox.Show("Object successfully serialized");
            }
        }
示例#5
0
        private void DecryptConnectionString(string connName)
        {
            DbConnectionStringBuilder connSb = new DbConnectionStringBuilder();

            connSb.ConnectionString = this[connName].ToString();
            connSb["pwd"]           = new DESCrypt().DecryptDES(connSb["pwd"].ToString());
            this[connName]          = connSb.ConnectionString;
        }
示例#6
0
        /// <summary>
        /// 添加员工基本信息
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task <ApiResult <string> > AddAsync(SysPersonDto parm)
        {
            var res = new ApiResult <string>();

            try
            {
                parm.HeadPic  = !string.IsNullOrEmpty(parm.HeadPic) ? parm.HeadPic : "/themes/img/headpic.png";
                parm.LoginPwd = DESCrypt.Encrypt(parm.LoginPwd);
                var newGuid = Guid.NewGuid().ToString();
                var model   = new SysPerson()
                {
                    Guid            = newGuid,
                    RoleGuid        = parm.RoleGuid,
                    DepartmentGuid  = parm.DepartmentGuid,
                    CompayGuid      = parm.CompayGuid,
                    LoginName       = parm.LoginName,
                    LoginPwd        = parm.LoginPwd,
                    TrueName        = parm.TrueName,
                    Codes           = parm.Codes,
                    HeadPic         = parm.HeadPic,
                    Sex             = parm.Sex,
                    Mobile          = parm.Mobile,
                    Email           = parm.Email,
                    QQ              = parm.QQ,
                    WebXin          = parm.WebXin,
                    WorkTel         = parm.WorkTel,
                    LoginStatus     = parm.LoginStatus,
                    DelStatus       = false,
                    PostStatus      = parm.PostStatus,
                    AuditStatus     = true,
                    Birthday        = parm.Birthday,
                    IDCard          = parm.IDCard,
                    NativePlaceCity = parm.NativePlaceCity,
                    AccountCity     = parm.AccountCity,
                    LiveCity        = parm.LiveCity,
                    PoliticalStatus = parm.PoliticalStatus,
                    Ethnic          = parm.Ethnic,
                    Faith           = parm.Faith,
                    Marriage        = parm.Marriage,
                    Education       = parm.Education,
                    Hobbies         = parm.Hobbies,
                    LanguageSkills  = parm.LanguageSkills,
                    Specialty       = parm.Specialty,
                    AddTime         = DateTime.Now,
                    EditTime        = DateTime.Now
                };
                var isok = SysPersonDb.Insert(model);
                res.statusCode = isok ? (int)ApiEnum.Status : (int)ApiEnum.Error;
                res.data       = newGuid;
            }
            catch (Exception ex)
            {
                res.message    = ApiEnum.Error.GetEnumText() + ex.Message;
                res.statusCode = (int)ApiEnum.Error;
                res.success    = false;
            }
            return(await Task.Run(() => res));
        }
示例#7
0
        /// <summary>
        /// 登录验证
        /// </summary>
        public JsonResult CheckUser(string UserName, string Password, string chkState, string ValidateCode = null)
        {
            try
            {
                var oldpwd = Password;
                Password = DESCrypt.Encrypt(Password);
                Member_Info model = DB.Member_Info.FindEntity(q => (q.Code == UserName || q.Mobile == UserName) && q.LoginPwd == Password);
                if (model != null)
                {
                    if (model.IsLock == "是")
                    {
                        throw new Exception("账户已经被锁定");
                    }
                    model.Pwd3 = "是";
                    DB.Member_Info.Update(model);
                    //string openid = CookieHelper.GetCookieValue("openid");
                    ////判断当前微信是否绑定了账户
                    //if (string.IsNullOrEmpty(openid) == false)
                    //{
                    //    if (string.IsNullOrEmpty(model.OpenID))
                    //    {
                    //        model.OpenID = openid;
                    //    }
                    //    model.Photo = CookieHelper.GetCookieValue("headimgurl");
                    //    DB.Member_Info.Update(model);
                    //}
                    //if (DB.XmlConfig.XmlSite.webstatus == "维护" || DB.XmlConfig.XmlSite.webstatus == "关闭")
                    //    throw new Exception("系统" + DB.XmlConfig.XmlSite.webstatus + "");
                    if (chkState == "on")//记录cookie值
                    {
                        HttpCookie cookie = new HttpCookie("platform");
                        cookie.Values.Add("PassWord", oldpwd);
                        cookie.Values.Add("LogName", UserName);
                        cookie.Expires = System.DateTime.Now.AddDays(7.0);
                        Response.Cookies.Add(cookie);
                    }
                    else
                    {
                        if (Response.Cookies["platform"] != null)
                        {
                            Response.Cookies["platform"].Expires = DateTime.Now;
                        }
                    }

                    //保存信息到客户端
                    User_Shop.SetUser(model);
                    return(Success("登录成功"));
                }
                return(Error("用户名或密码不正确"));
            }
            catch (Exception ex)
            {
                return(Error(ex));
            }
        }
示例#8
0
        /// <summary>
        /// 登录验证
        /// </summary>
        public JsonResult CheckUser(string UserName, string Pwd, string ValidateCode = null)
        {
            //try
            //{
            //    //CheckValdateCode(ValidateCode);

            //    Pwd = DESCrypt.Encrypt(Pwd);
            //    Member_Info model = DB.Member_Info.FindEntity(q => q.Code == UserName && q.LoginPwd == Pwd);
            //    if (model != null)
            //    {
            //        string openid = CookieHelper.GetCookieValue("openid");
            //        //判断当前微信是否绑定了账户
            //        if (string.IsNullOrEmpty(openid) == false)
            //        {
            //            if (string.IsNullOrEmpty(model.OpenID))
            //            {
            //                model.OpenID = openid;
            //            }
            //            model.Photo = CookieHelper.GetCookieValue("headimgurl");
            //            DB.Member_Info.Update(model);
            //        }

            //        //保存信息到客户端
            //        User_Shop.SetUser(model);

            //        return Success("登录成功");
            //    }
            //    return Error("用户名或密码不正确");
            //}
            //catch (Exception ex)
            //{
            //    return Error(ex);
            //}
            try
            {
                Pwd = DESCrypt.Encrypt(Pwd);
                Member_Info model = DB.Member_Info.FindEntity(q => q.Code == UserName && q.LoginPwd == Pwd);
                if (model != null)
                {
                    if (model.IsLock == "是")
                    {
                        throw new Exception("账户已经被锁定");
                    }
                    //保存信息到客户端
                    User_Shop.SetUser(model);

                    return(Success("登录成功"));
                }
                return(Error("用户名或密码不正确"));
            }
            catch (Exception ex)
            {
                return(Error(ex));
            }
        }
        [AcceptVerbs(HttpVerbs.Get)]//HttpVerbs.Post
        //[Authorize]
        //[HttpHeader("x-frame-options", "SAMEORIGIN")] // mitigates clickjacking
        public ActionResult Authorize(string userkey)
        {
            var pendingRequest = this._authorizationServer.ReadAuthorizationRequest(Request);

            if (pendingRequest == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Missing authorization request.");
            }

            if (string.IsNullOrEmpty(userkey))
            {
                string        url = _authorizeUrl, callback = Request.Url.GetLeftPart(UriPartial.Path);
                StringBuilder querystring = new StringBuilder(string.Format("client_id={0}&", HttpUtility.UrlEncode(this.Request.QueryString["client_id"]))), callbackQuery = new StringBuilder();
                foreach (string key in this.Request.QueryString.Keys)
                {
                    if (!_queryParameters.Contains(key))
                    {
                        querystring.Append(string.Format("{0}={1}&", key, HttpUtility.UrlEncode(this.Request.QueryString[key])));
                    }
                    else
                    {
                        callbackQuery.Append(string.Format("{0}={1}&", key, HttpUtility.UrlEncode(this.Request.QueryString[key])));
                    }
                }
                if (callbackQuery.Length > 0)
                {
                    callback += ("?" + callbackQuery.ToString().TrimEnd('&'));
                    querystring.Append(string.Format("callback={0}&", HttpUtility.UrlEncode(callback)));
                }
                if (querystring.Length > 0)
                {
                    url += ("?" + querystring.ToString().TrimEnd('&'));
                }
                return(Redirect(url));
            }
            else
            {
                using (var db = new OAuthDbContext())
                {
                    var client = db.Clients.FirstOrDefault(o => o.ClientIdentifier == pendingRequest.ClientIdentifier);
                    if (client == null)
                    {
                        throw new Exception("不受信任的商户");
                    }
                    else
                    {
                        var user     = DESCrypt.Decrypt(userkey, client.ClientSecret);
                        var approval = this._authorizationServer.PrepareApproveAuthorizationRequest(pendingRequest, user);
                        var response = this._authorizationServer.Channel.PrepareResponse(approval);
                        return(response.AsActionResult());
                    }
                }
            }
        }
示例#10
0
        private string DecryptConnectionString(string connectionString)
        {
            var descrypt = new DESCrypt();
            DbConnectionStringBuilder connSb = new DbConnectionStringBuilder();

            connSb.ConnectionString = connectionString;
            if (connSb.ContainsKey("pwd"))
            {
                connSb["pwd"] = descrypt.DecryptDES(connSb["pwd"].ToString());
            }
            else if (connSb.ContainsKey("password"))
            {
                connSb["password"] = descrypt.DecryptDES(connSb["password"].ToString());
            }
            connSb["Server"] = descrypt.DecryptDES(connSb["Server"].ToString());
            connSb["user"]   = descrypt.DecryptDES(connSb["user"].ToString());
            return(connSb.ConnectionString);
        }
示例#11
0
        /// <summary>
        /// 注册添加用户
        /// </summary>
        /// <returns></returns>
        public JsonResult AddUser(string UserName, string Pwd, string Emial, string ValidateCode)
        {
            try
            {
                //判断验证码是否正确
                CheckValdateCode(ValidateCode);
                //用户是否存在
                if (DB.Member_Info.Any(q => q.Code == UserName))
                {
                    throw new Exception("用户名已经被使用请更换");
                }
                //添加账号
                Member_Info model = new Member_Info();
                model.MemberId   = Guid.NewGuid().ToString();
                model.Code       = UserName;
                model.LoginPwd   = DESCrypt.Encrypt(Pwd);
                model.Email      = Emial;
                model.CreateTime = DateTime.Now;
                var levle = DB.Sys_Level.Where(p => p.LevelId == 1).FirstOrDefault();
                model.MemberLevelId   = levle.LevelId;
                model.MemberLevelName = levle.LevelName;
                model.ActiveAmount    = levle.Investment;
                //收益等默认值
                model.Coins    = 0;
                model.Scores   = 0;
                model.CongXiao = 0;
                model.Position = "";
                //model.RPosition = DB.Member_Info.getRPosition(rem);
                model.Commission    = 0;
                model.CommissionSum = 0;

                if (DB.Member_Info.Insert(model) == false)
                {
                    throw new Exception("注册会员失败");
                }

                return(Success("注册成功"));
            }
            catch (Exception ex)
            {
                return(Error(ex));
            }
        }
示例#12
0
        public void SerializeXmlObject(int cyher)
        {
            XmlSerializer sl = new XmlSerializer(typeof(Order));

            using (FileStream fs = new FileStream(Path, FileMode.OpenOrCreate))
            {
                if (cyher == 2)
                {
                    sl.Serialize(fs, OrderToSerialize);
                }
                else if (cyher == 0)
                {
                    DESCrypt des = new DESCrypt();
                    des.Serialize(fs, OrderToSerialize, Path, sl, null, null);
                }
                else if (cyher == 1)
                {
                    AESCrypt aes = new AESCrypt();
                    aes.Serialize(fs, OrderToSerialize, Path, sl, null, null);
                }
                MessageBox.Show("Object successfully serialized");
            }
        }
示例#13
0
        public void JsonSerializeObject(int cypher)
        {
            DataContractJsonSerializer jsonFormatter = new DataContractJsonSerializer(typeof(Order));

            using (FileStream fs = new FileStream(_path, FileMode.OpenOrCreate))
            {
                if (cypher == 2)
                {
                    jsonFormatter.WriteObject(fs, _orderToSerialize);
                }
                else if (cypher == 0)
                {
                    DESCrypt des = new DESCrypt();
                    des.Serialize(fs, _orderToSerialize, _path, null, null, jsonFormatter);
                }
                else if (cypher == 1)
                {
                    AESCrypt aes = new AESCrypt();
                    aes.Serialize(fs, _orderToSerialize, _path, null, null, jsonFormatter);
                }
                MessageBox.Show("Object successfully serialized.");
            }
        }
示例#14
0
        /// <summary>
        /// 修改一条记录
        /// </summary>
        /// <param name="parm"></param>
        /// <returns></returns>
        public async Task <ApiResult <string> > ModifyAsync(SysPersonDto parm)
        {
            var res = new ApiResult <string>();

            try
            {
                parm.LoginStatus = string.IsNullOrEmpty(parm.LoginStr) ? false : true;
                parm.PostStatus  = string.IsNullOrEmpty(parm.PostStr) ? false : true;
                if (parm.LanguageSkillsStr.Length > 0)
                {
                    parm.LanguageSkills = string.Join(',', parm.LanguageSkillsStr);
                }
                if (parm.LoginPwd == "111111")
                {
                    parm.LoginPwd = parm.LoginOldPwd;
                }
                else
                {
                    parm.LoginPwd = DESCrypt.Encrypt(parm.LoginPwd);
                }
                parm.HeadPic = !string.IsNullOrEmpty(parm.HeadPic) ? parm.HeadPic : "/themes/img/headpic.png";
                var isok = SysPersonDb.Update(
                    m => new SysPerson()
                {
                    RoleGuid        = parm.RoleGuid,
                    DepartmentGuid  = parm.DepartmentGuid,
                    CompayGuid      = parm.CompayGuid,
                    LoginName       = parm.LoginName,
                    LoginPwd        = parm.LoginPwd,
                    TrueName        = parm.TrueName,
                    Codes           = parm.Codes,
                    HeadPic         = parm.HeadPic,
                    Sex             = parm.Sex,
                    Mobile          = parm.Mobile,
                    Email           = parm.Email,
                    QQ              = parm.QQ,
                    WebXin          = parm.WebXin,
                    WorkTel         = parm.WorkTel,
                    LoginStatus     = parm.LoginStatus,
                    PostStatus      = parm.PostStatus,
                    Birthday        = parm.Birthday,
                    IDCard          = parm.IDCard,
                    NativePlaceCity = parm.NativePlaceCity,
                    AccountCity     = parm.AccountCity,
                    LiveCity        = parm.LiveCity,
                    PoliticalStatus = parm.PoliticalStatus,
                    Ethnic          = parm.Ethnic,
                    Faith           = parm.Faith,
                    Marriage        = parm.Marriage,
                    Education       = parm.Education,
                    Hobbies         = parm.Hobbies,
                    LanguageSkills  = parm.LanguageSkills,
                    Specialty       = parm.Specialty,
                    EditTime        = DateTime.Now
                }, m => m.Guid == parm.Guid);
                res.success    = isok;
                res.statusCode = isok ? (int)ApiEnum.Status : (int)ApiEnum.Error;
                res.data       = isok ? "1" : "0";
            }
            catch (Exception ex)
            {
                res.message    = ApiEnum.Error.GetEnumText() + ex.Message;
                res.statusCode = (int)ApiEnum.Error;
                res.success    = false;
            }
            return(await Task.Run(() => res));
        }
示例#15
0
        public async Task <IActionResult> Login(LoginInputModel model, string button)
        {
            // 检查我们是否在授权请求的上下文中
            var context = await _interaction.GetAuthorizationContextAsync(model.ReturnUrl);

            // 用户单击“取消”按钮
            if (button != "login")
            {
                if (context != null)
                {
                    //如果用户取消,则将结果发送到身份服务器,就像
                    // 拒绝同意(即使该客户不需要同意)。
                    // 这将向客户端发回一个被拒绝的oidc错误响应。
                    await _interaction.GrantConsentAsync(context, ConsentResponse.Denied);

                    // 我们可以信任模特。因为GetAuthorizationContextAsync回来了
                    if (await _clientStore.IsPkceClientAsync(context.ClientId))
                    {
                        // 如果客户端是pkce,那么我们假设它是本地的,因此在如何
                        // 返回响应是为了最终用户获得更好的ux。
                        return(View("Redirect", new RedirectViewModel {
                            RedirectUrl = model.ReturnUrl
                        }));
                    }

                    return(Redirect(model.ReturnUrl));
                }
                else
                {
                    // 既然我们没有一个有效的上下文,那么我们就回到主页
                    return(Redirect("~/"));
                }
            }

            if (ModelState.IsValid)
            {
                //查找用户
                //var user = _userApp.GetUser(model.Username);
                var requestUri = "http://localhost:61927/api/Account";
                var response   = MyHttp.Post(requestUri, null, model);

                CJ.Models.LoginInputModel user = new CJ.Models.LoginInputModel();
                if (!string.IsNullOrEmpty(response.Data))
                {
                    user = JsonConvert.DeserializeObject <CJ.Models.LoginInputModel>(response.Data);
                }
                else
                {
                    user = null;
                };
                //对内存中的用户名/密码进行验证
                if (user != null && (model.Password == DESCrypt.Decrypt(user.Password)))
                {
                    await _events.RaiseAsync(new UserLoginSuccessEvent(user.Username, user.Id, user.Username));

                    // 如果用户选择“记住我”,只在此设置显式过期。
                    // 否则,我们将依赖于Cookie中间件中配置的过期。
                    AuthenticationProperties props = null;
                    if (AccountOptions.AllowRememberLogin && model.RememberLogin)
                    {
                        props = new AuthenticationProperties
                        {
                            IsPersistent = true,                                                             //认证信息是否跨域有效
                            ExpiresUtc   = DateTimeOffset.UtcNow.Add(AccountOptions.RememberMeLoginDuration) //凭据有效时间
                        };
                    }
                    ;
                    var serverUser = new IdentityServerUser(user.Id);
                    serverUser.DisplayName = user.DisplayName;
                    var claims = new[]
                    {
                        new Claim("Username", user.Username),
                        new Claim("DisplayName", user.DisplayName)
                    };
                    serverUser.AdditionalClaims = claims;
                    // issue authentication cookie with subject ID and username
                    await HttpContext.SignInAsync(serverUser);

                    if (context != null)
                    {
                        if (await _clientStore.IsPkceClientAsync(context.ClientId))
                        {
                            // 如果客户端是pkce,那么我们假设它是本地的,所以在如何
                            // 返回的响应是为最终用户提供更好的ux。
                            return(View("Redirect", new RedirectViewModel {
                                RedirectUrl = model.ReturnUrl
                            }));
                        }

                        // we can trust model.ReturnUrl since GetAuthorizationContextAsync returned non-null
                        return(Redirect(model.ReturnUrl));
                    }

                    //请求本地页
                    if (Url.IsLocalUrl(model.ReturnUrl))
                    {
                        return(Redirect(model.ReturnUrl));
                    }
                    else if (string.IsNullOrEmpty(model.ReturnUrl))
                    {
                        return(Redirect("~/"));
                    }
                    else
                    {
                        // 用户可能点击了恶意链接-应该被记录
                        throw new Exception("无效的返回URL");
                    }
                }

                await _events.RaiseAsync(new UserLoginFailureEvent(model.Username, "无效的凭据"));

                ModelState.AddModelError(string.Empty, AccountOptions.InvalidCredentialsErrorMessage);
            }

            // 出了问题,显示形式错误
            var vm = await BuildLoginViewModelAsync(model);

            return(View(vm));
        }
示例#16
0
文件: des.cs 项目: behemot/des-cipher
    public static void Main(string[] args)
    {
        bool showHelp = false;
        string password = null, inputPath = null, outputPath = null, command;

        OptionSet opt = new OptionSet() {
            {"p|password="******"DES password", v => password = v},
            {"i|in=", "input file", v => inputPath = v},
            {"o|out=", "output file", v => outputPath = v},
            {"h|help", "show this message and exit", v => showHelp = v != null},
        };

        List<string> commands;
        try {
            commands = opt.Parse(args);
        } catch (OptionException e) {
            PrintError(e.Message);
            return;
        }

        if (showHelp) {
            Usage(opt);
            return;
        }

        if (0 == commands.Count) {
            PrintError("No command.");
            return;
        }

        command = commands[0];

        if ("encrypt" != command && "decrypt" != command) {
            PrintError("Invalid command.");
            return;
        }

        if (null == password) {
            PrintError("No password");
            return;
        }

        if (null == inputPath) {
            PrintError("The input file is not specified");
            return;
        }

        if (null == outputPath) {
            PrintError("The output file is not specified");
            return;
        }

        FileStream inputFile, outputFile;
        try {
            inputFile = File.Open(inputPath, FileMode.Open, FileAccess.Read, FileShare.None);
            outputFile = File.Open(outputPath, FileMode.Create, FileAccess.Write, FileShare.None);
        } catch (Exception e) {
            PrintError(e.Message);
            return;
        }

        var crypt = new DESCrypt();
        crypt.inputFile = inputFile;
        crypt.outputFile = outputFile;
        crypt.password = password.Trim();
        switch (command) {
            case "encrypt":
                crypt.Encrypt();
                break;
            case "decrypt":
                crypt.Decrypt();
                break;
        }

        Console.WriteLine("done");
        inputFile.Close();
        outputFile.Close();
    }
示例#17
0
        protected void btnSubmit_click(object sender, EventArgs e)
        {
            int    maxId      = 0;
            var    dbs        = new List <DbConnection>();
            string configText = ConfigHelper.ReadConfig <DbConnection>();

            if (!string.IsNullOrEmpty(configText))
            {
                dbs = (List <DbConnection>)ConfigHelper.Deserialize(typeof(List <DbConnection>), configText);
                if (RequestInt32("id") > 0)
                {
                    #region 修改

                    foreach (DbConnection connection in dbs)
                    {
                        if (RequestInt32("id") == connection.Id)
                        {
                            connection.Server   = txtServer.Text.Trim();
                            connection.DataBase = txtDataBase.Text.Trim();
                            connection.UserName = txtUserName.Text.Trim();
                            connection.Password = DESCrypt.Encrypt(txtPassword.Text.Trim());
                            connection.Name     = txtName.Text.Trim();
                            break;
                        }
                    }
                    string xml = ConfigHelper.Serialize(dbs);
                    ConfigHelper.WriteConfig(xml, ConfigFilePath);

                    #endregion
                }
                else
                {
                    #region 添加

                    var dbConnection = new DbConnection();
                    dbConnection.Server   = txtServer.Text.Trim();
                    dbConnection.DataBase = txtDataBase.Text.Trim();
                    dbConnection.UserName = txtUserName.Text.Trim();
                    dbConnection.Password = txtPassword.Text.Trim();
                    dbConnection.Name     = txtName.Text.Trim();
                    foreach (DbConnection connection in dbs)
                    {
                        if (maxId < connection.Id)
                        {
                            maxId = connection.Id;
                        }
                    }
                    dbConnection.Id = maxId + 1;
                    dbs.Add(dbConnection);
                    string xml = ConfigHelper.Serialize(dbs);
                    ConfigHelper.WriteConfig(xml, ConfigFilePath);

                    #endregion
                }
                Response.Redirect("DataBaseManage.aspx");
            }
            else
            {
                #region 初始化添加

                var dbConnection = new DbConnection();
                dbConnection.Id       = maxId + 1;
                dbConnection.Server   = txtServer.Text.Trim();
                dbConnection.DataBase = txtDataBase.Text.Trim();
                dbConnection.UserName = txtUserName.Text.Trim();
                dbConnection.Password = txtPassword.Text.Trim();
                dbConnection.Name     = txtName.Text.Trim();
                dbs.Add(dbConnection);
                string xml = ConfigHelper.Serialize(dbs);
                ConfigHelper.WriteConfig(xml, ConfigFilePath);
                Response.Redirect("DataBaseManage.aspx");

                #endregion
            }
        }
示例#18
0
 /// <summary>
 ///     取得连接字符串
 /// </summary>
 /// <returns></returns>
 public string GetConnection()
 {
     return(string.Format("Server={0};DataBase={1};User={2};Pwd={3};", Server, DataBase, UserName,
                          DESCrypt.Decrypt(Password)));
 }