Exemple #1
0
        public void GivenAConfig_ThenTheMockValuesAreReplacedFromKeyVault()
        {
            var service = Substitute.For <ISecretService>();
            var client  = Substitute.For <IKeyVaultClient>();

            client.GetSecretWithHttpMessagesAsync(Arg.Any <string>(), Arg.Is("test1"), Arg.Any <string>(), Arg.Any <Dictionary <string, List <string> > >(), Arg.Any <CancellationToken>())
            .Returns(Task.FromResult(new AzureOperationResponse <SecretBundle> {
                Body = new SecretBundle("secret1")
            }));

            var authedClient = new AuthedClient(client);
            var reader       = new ReadKey(authedClient, "keyvaultbuild", "test1");

            service.ResolveSingleKey(Arg.Is("#{keyvault:keyvaultbuild:test1}")).Returns(reader);

            var keys = new TransformKeys(service);

            var snippet = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <appSettings>
    <add key=""key1"" value=""#{keyvault:keyvaultbuild:test1}"" />
  </appSettings>
</configuration>";

            var expected = @"<?xml version=""1.0"" encoding=""utf-8""?>
<configuration>
  <appSettings>
    <add key=""key1"" value=""secret1"" />
  </appSettings>
</configuration>";

            var val = keys.ReplaceKeys(snippet);

            Assert.AreEqual(expected, val);
        }
Exemple #2
0
 public override void Dispose()
 {
     HandshakeHash?.Dispose();
     KeySchedule?.Dispose();
     KeyShare?.Dispose();
     ReadKey?.Dispose();
     WriteKey?.Dispose();
     GC.SuppressFinalize(this);
 }
Exemple #3
0
        public void Run()
        {
            while (_menuItems != null)
            {
                Display();

                ReadKey <MenuItem> readKey = new ReadKey <MenuItem>(_menuItems);

                readKey.GetKey().Action();
            }
        }
        private void FrmLogin_Load(object sender, EventArgs e)
        {
            if (File.Exists("key.xml"))
            {
                string xml = File.ReadAllText("key.xml");
                myrsa.FromXmlString(xml);

                Microsoft.Win32.RegistryKey ReadKey;
                ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareAccount");

                string UserName = "";
                string Password = "";

                try      {
                    UserName = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("UserName").ToString());
                    Password = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("Password").ToString());
                }
                catch (Exception) { }

                bool SavePass = false;
                try   {
                    SavePass = bool.Parse(ReadKey.GetValue("SavePassword").ToString());
                }
                catch (Exception) { }

                bool ConnectOnline = true;
                try    {
                    //ConnectOnline =bool.Parse(ReadKey.GetValue("ConnectOnline").ToString());
                    ConnectOnline = true;
                }
                catch (Exception)   { }
                chkConnectOptions.Checked = ConnectOnline;

                if (SavePass == true)
                {
                    txtmatkhau.Text     = Password;
                    txttendangnhap.Text = UserName;
                    chkSaveInfo.Checked = true;
                }
                else
                {
                    txtmatkhau.Text     = "";
                    txttendangnhap.Text = "";
                    chkSaveInfo.Checked = false;
                }
            }
            else
            {
                File.WriteAllText("key.xml", myrsa.ToXmlString(true));
            }
        }
        private bool ReadDisk(out string errMessage)
        {
            bool res = true;

            errMessage = "";
            DateTime beginDate, endDate;

            if (cdRButton.Checked)
            {
                _diskKey   = ReadKey.Read(driveBox.Text.Substring(0, 2), ReadKey.DeviceType.CD, ReadKey.DataType.Key);
                _diskTable = ReadKey.Read(driveBox.Text.Substring(0, 2), ReadKey.DeviceType.CD, ReadKey.DataType.Table);
                ReadKey.ReadDates(driveBox.Text.Substring(0, 2), ReadKey.DeviceType.CD, out beginDate, out endDate);
            }
            else
            {
                string isoPath = keyfileTextBox.Text;

                _diskKey   = ReadKey.Read(isoPath, ReadKey.DeviceType.CDImage, ReadKey.DataType.Key);
                _diskTable = ReadKey.Read(isoPath, ReadKey.DeviceType.CDImage, ReadKey.DataType.Table);
                ReadKey.ReadDates(isoPath, ReadKey.DeviceType.CDImage, out beginDate, out endDate);
            }

            keyDateLabel.Text = string.Format(keyDateLabel.Tag.ToString(), beginDate.ToShortDateString(),
                                              endDate.ToShortDateString());

            if (DateTime.Compare(DateTime.Now.Date, beginDate) == -1)
            {
                errMessage += "Период действия ключа ещё не наступил.";
                res         = false;
            }
            if (DateTime.Compare(DateTime.Now.Date, endDate) == 1)
            {
                errMessage += "Истёк срок действия ключа.";
                res         = false;
            }

            if (errMessage.Length == 0)
            {
                errMessage = null;
            }
            //
            return(res);
        }
        private void buttonOK_Click(object sender, EventArgs e)
        {
            if (checkBoxAutoUpdate.Checked == true)
            {
                this.Hide();

                Microsoft.Win32.RegistryKey ReadKey;
                ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareUpdate", true);
                if (ReadKey == null)
                {
                    Microsoft.Win32.RegistryKey key;
                    key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("AutoCareUpdate");
                    key.SetValue("AutoUpdate", true);
                    key.Close();
                }
                else
                {
                    ReadKey.SetValue("AutoUpdate", true);
                    ReadKey.Close();
                }

                DoUpdate();
            }
            else
            {
                Microsoft.Win32.RegistryKey ReadKey;
                ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareUpdate", true);
                if (ReadKey == null)
                {
                    Microsoft.Win32.RegistryKey key;
                    key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("AutoCareUpdate");
                    key.SetValue("AutoUpdate", false);
                    key.Close();
                }
                else
                {
                    ReadKey.SetValue("AutoUpdate", false);
                    ReadKey.Close();
                }
            }
            this.Close();
        }
        private void frmUpdateSoftware_Load(object sender, EventArgs e)
        {
            Microsoft.Win32.RegistryKey ReadKey;
            ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareUpdate");

            bool AutoUpdate = false;

            try
            {
                AutoUpdate = bool.Parse(ReadKey.GetValue("AutoUpdate").ToString());
            }
            catch (Exception) { }

            if (AutoUpdate == true)
            {
                checkBoxAutoUpdate.Checked = true;
            }
            else
            {
                checkBoxAutoUpdate.Checked = false;
            }
        }
Exemple #8
0
        public frmServerConfig()
        {
            InitializeComponent();
            try
            {
                Microsoft.Win32.RegistryKey ReadKey;
                ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareAccount", true);
                if (ReadKey != null)
                {
                    string ServerName       = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("ServerName").ToString());
                    string DatabaseUser     = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("DatabaseUser").ToString());
                    string DatabasePassword = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("DatabasePassword").ToString());
                    string DatabaseName     = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("DatabaseName").ToString());

                    txtDatabaseName.Text = DatabaseName;
                    txtDatabasePass.Text = DatabasePassword;
                    txtDatabaseUser.Text = DatabaseUser;
                    txtServerName.Text   = ServerName;
                }
            }
            catch (Exception)
            {}
        }
Exemple #9
0
        public ReadKey ResolveSingleKey(string keySyntax)
        {
            if (TransformKeys.IsKeySyntax(keySyntax) == false)
            {
                throw new Exception("Invalid key syntax");
            }

            var raw = keySyntax.Trim('#', '{', '}').Split(':').ToArray();

            if (raw.Length != 2 && raw.Length != 3)
            {
                throw new Exception("Invalid number of key parts");
            }

            if (raw.Length == 3)
            {
                raw = raw.Skip(1).ToArray();
            }

            var vault = raw.First();
            var key   = raw.Last();

            if (_vaultAliases.ContainsKey(vault))
            {
                vault = _vaultAliases[vault];
            }

            var cacheKey = $"{vault}:{key}";

            if (_keyCache.ContainsKey(cacheKey) == false)
            {
                _keyCache[cacheKey] = new ReadKey(_client, vault, key);
            }

            return(_keyCache[cacheKey]);
        }
        public void InitializeContact(string username, string agetnId, string placeId, int tenantDbId, string contactAppName, ConfService comObject,
                                      IPluginCallBack listener, int ixnProxyId)
        {
            ContactService contactService = new ContactService();
            OutputValues   output         = contactService.ConnectUCS(comObject, tenantDbId, contactAppName, ContactServerStateNotification);

            //ContactDataContext.GetInstance().UserName = username;
            // ContactDataContext.GetInstance().PlaceID = placeId;
            //ContactDataContext.GetInstance().AgentID = agetnId;
            ContactDataContext.messageToClient = listener;
            ContactDataContext.GetInstance().IxnProxyId = ixnProxyId;

            if (output.MessageCode == "200")
            {
                //ContactDataContext.ComObject = comObject;
                //ContactDataContext.GetInstance().ApplicationName = applicationName;
                // ConfigContainer.Instance().TenantDbId =ConfigContainer.Instance().TenantDbId;
                ConfigContainer.Instance().TenantDbId = tenantDbId;
                //ComClass.GetInstance().GetContactBusinessAttribute("ContactAttributes");
                if (ConfigContainer.Instance().AllKeys.Contains("contactBusinessAttribute"))
                {
                    ContactDataContext.GetInstance().ContactValidAttribute = (Dictionary <string, string>)ConfigContainer.Instance().GetValue("contactBusinessAttribute");
                }
                ContactDataContext.GetInstance().ContactDisplayedAttributes = ReadKey.ReadConfigKeys("contact.displayed-attributes",
                                                                                                     new string[] { "Title", "FirstName", "LastName", "PhoneNumber", "EmailAddress" },
                                                                                                     ContactDataContext.GetInstance().ContactValidAttribute.Keys.ToList());
                ContactDataContext.GetInstance().ContactMandatoryAttributes = ReadKey.ReadConfigKeys("contact.mandatory-attributes",
                                                                                                     new string[] { "Title", "FirstName", "LastName", "PhoneNumber", "EmailAddress" },
                                                                                                     ContactDataContext.GetInstance().ContactDisplayedAttributes);
                ContactDataContext.GetInstance().ContactMultipleValueAttributes = ReadKey.ReadConfigKeys("contact.multiple-value-attributes",
                                                                                                         new string[] { "PhoneNumber", "EmailAddress" },
                                                                                                         ContactDataContext.GetInstance().ContactDisplayedAttributes);

                ComClass.GetInstance().GetAllValues();
            }
        }
Exemple #11
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     Microsoft.Win32.RegistryKey ReadKey;
     ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareAccount", true);
     if (ReadKey == null)
     {
         Microsoft.Win32.RegistryKey key;
         key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("AutoCareAccount");
         key.SetValue("ServerName", AutoCareUtil.Utilities.Encode(txtServerName.Text.Trim()));
         key.SetValue("DatabaseUser", AutoCareUtil.Utilities.Encode(txtDatabaseUser.Text.Trim()));
         key.SetValue("DatabasePassword", AutoCareUtil.Utilities.Encode(txtDatabasePass.Text.Trim()));
         key.SetValue("DatabaseName", AutoCareUtil.Utilities.Encode(txtDatabaseName.Text.Trim()));
         key.Close();
     }
     else
     {
         ReadKey.SetValue("ServerName", AutoCareUtil.Utilities.Encode(txtServerName.Text.Trim()));
         ReadKey.SetValue("DatabaseUser", AutoCareUtil.Utilities.Encode(txtDatabaseUser.Text.Trim()));
         ReadKey.SetValue("DatabasePassword", AutoCareUtil.Utilities.Encode(txtDatabasePass.Text.Trim()));
         ReadKey.SetValue("DatabaseNAme", AutoCareUtil.Utilities.Encode(txtDatabaseName.Text.Trim()));
         ReadKey.Close();
     }
     MessageBox.Show("Đã lưu thông tin cấu hình");
 }
Exemple #12
0
        /// <summary>
        /// Reads the line or key.
        /// </summary>
        /// <param name="inline">if set to <c>true</c> [inline].</param>
        /// <returns></returns>
        // Note: Returns null if user pressed Escape, or the contents of the line if they pressed Enter.
        public static ConsoleOutput ReadLineOrKey(bool inline = false)
        {
            string retString = "";

            int curRightPad,
                curIndex = 0;

            do
            {
                ConsoleKeyInfo readKeyResult = Console.ReadKey(true);

                // handle Enter
                if (readKeyResult.Key == ConsoleKey.Enter)
                {
                    ReadInput?.Invoke(retString);

                    curRightPad = Console.CursorLeft;

                    if (!inline)
                    {
                        Console.WriteLine();
                    }

                    return(new ConsoleOutput(retString)
                    {
                        CurrentRightPad = curRightPad
                    });
                }

                // handle backspace
                if (readKeyResult.Key == ConsoleKey.Backspace)
                {
                    if (curIndex > 0)
                    {
                        retString = retString.Remove(retString.Length - 1);

                        Console.Write(readKeyResult.KeyChar);
                        Console.Write(' ');
                        Console.Write(readKeyResult.KeyChar);

                        --curIndex;
                    }
                }
                else if (readKeyResult.Key == ConsoleKey.Delete)
                {
                    if (retString.Length - curIndex > 0)
                    {
                        // Store current position
                        int curLeftPos = Console.CursorLeft;

                        // Redraw string
                        for (int i = curIndex + 1; i < retString.Length; ++i)
                        {
                            Console.Write(retString[i]);
                        }

                        // Remove last repeated char
                        Console.Write(' ');

                        // Restore position
                        Console.SetCursorPosition(curLeftPos, Console.CursorTop);

                        // Remove string
                        retString = retString.Remove(curIndex, 1);
                    }
                }
                else if (readKeyResult.Key == ConsoleKey.RightArrow)
                {
                    if (curIndex < retString.Length)
                    {
                        ++Console.CursorLeft;
                        ++curIndex;
                    }
                }
                else if (readKeyResult.Key == ConsoleKey.LeftArrow)
                {
                    if (curIndex > 0)
                    {
                        --Console.CursorLeft;
                        --curIndex;
                    }
                }
                else if (readKeyResult.Key == ConsoleKey.Insert)
                {
                    IsInserting        = !IsInserting;
                    Console.CursorSize = IsInserting ? 100 : DefaultCursorSize;
                }
#if DEBUG
                else if (readKeyResult.Key == ConsoleKey.UpArrow)
                {
                    if (Console.CursorTop > 0)
                    {
                        --Console.CursorTop;
                    }
                }
                else if (readKeyResult.Key == ConsoleKey.DownArrow)
                {
                    if (Console.CursorTop < Console.BufferHeight - 1)
                    {
                        ++Console.CursorTop;
                    }
                }
#endif
                else
                // handle all other keypresses
                {
                    if (IsInserting || curIndex == retString.Length)
                    {
                        retString += readKeyResult.KeyChar;
                        Console.Write(readKeyResult.KeyChar);
                        ++curIndex;
                    }
                    else
                    {
                        // Store char
                        char c = readKeyResult.KeyChar;

                        // Write char at position
                        Console.Write(c);

                        // Store cursor position
                        int curLeftPos = Console.CursorLeft;

                        // Clear console from curIndex to end
                        for (int i = curIndex; i < retString.Length; ++i)
                        {
                            Console.Write(' ');
                        }

                        // Go back
                        Console.SetCursorPosition(curLeftPos, Console.CursorTop);

                        // Write the chars from curIndex to end (with the new appended char)
                        for (int i = curIndex; i < retString.Length; ++i)
                        {
                            Console.Write(retString[i]);
                        }

                        // Restore again
                        Console.SetCursorPosition(curLeftPos, Console.CursorTop);

                        // Store in the string
                        retString = retString.Insert(curIndex, new string(c, 1));

                        // Sum one to the cur index (we appended one char)
                        ++curIndex;
                    }

                    ReadInput?.Invoke(retString);
                }

                if (char.IsControl(readKeyResult.KeyChar) &&
                    readKeyResult.Key != ConsoleKey.Enter &&
                    readKeyResult.Key != ConsoleKey.Backspace &&
                    readKeyResult.Key != ConsoleKey.Tab &&
                    readKeyResult.Key != ConsoleKey.Delete &&
                    readKeyResult.Key != ConsoleKey.RightArrow &&
                    readKeyResult.Key != ConsoleKey.LeftArrow &&
                    readKeyResult.Key != ConsoleKey.Insert)
                {
#if DEBUG
                    if (readKeyResult.Key == ConsoleKey.UpArrow || readKeyResult.Key == ConsoleKey.DownArrow)
                    {
                        continue;
                    }
#endif

                    ReadKey?.Invoke(readKeyResult);

                    curRightPad = Console.CursorLeft;

                    if (!inline)
                    {
                        Console.WriteLine();
                    }

                    return(new ConsoleOutput(readKeyResult)
                    {
                        CurrentRightPad = curRightPad
                    });
                }
            }while (true);
        }
        private void bgAutoUpdate_DoWork(object sender, DoWorkEventArgs e)
        {
            TimeSpan interval = new TimeSpan(0, 0, 10);

            Thread.Sleep(interval);
            Microsoft.Win32.RegistryKey ReadKey;
            ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareUpdate");
            if (ReadKey == null)
            {
                Microsoft.Win32.RegistryKey key;
                key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("AutoCareUpdate");
                key.SetValue("AutoUpdate", true);
                key.Close();
            }

            bool AutoUpdate = false;

            try
            {
                AutoUpdate = bool.Parse(ReadKey.GetValue("AutoUpdate").ToString());
            }
            catch (Exception) { }

            if (AutoUpdate == true)
            {
                try
                {
                    DataTable dt = new DataTable();

                    using (SqlConnection cnn = Class.datatabase.getConnection())
                    {
                        cnn.Open();

                        SqlDataAdapter adap = new SqlDataAdapter(@"SELECT TOP 1 * FROM Software_Update ORDER BY SoftwareId DESC", cnn);

                        adap.Fill(dt);

                        if (dt.Rows.Count > 0)
                        {
                            if (dt.Rows[0][3].ToString() != oldversion)
                            {
                                frmMessUpdateSW frm = new frmMessUpdateSW();
                                frm.NameVersion    = dt.Rows[0][1].ToString();
                                frm.OldVerSion     = oldversion;
                                frm.NewVersion     = dt.Rows[0][3].ToString();
                                frm.ChangeLogs     = dt.Rows[0][4].ToString();
                                frm.UpdateLocation = dt.Rows[0][5].ToString();
                                frm.FileSize       = dt.Rows[0][6].ToString();
                                frm.md5            = dt.Rows[0][7].ToString();

                                Uri    location   = new Uri(dt.Rows[0][5].ToString());
                                string fileName   = dt.Rows[0][1].ToString();
                                string idsoftware = dt.Rows[0][0].ToString();
                                string NewVersion = dt.Rows[0][3].ToString();

                                if (frm.ShowDialog() == DialogResult.OK)
                                {
                                    frmUpdateDownload form   = new frmUpdateDownload(location, fileName, idsoftware, oldversion, NewVersion);
                                    DialogResult      result = form.ShowDialog();

                                    if (result == DialogResult.OK)
                                    {
                                        dt.Dispose();
                                    }
                                    else if (result == DialogResult.Abort)
                                    {
                                        MessageBox.Show("Tải về bản cập nhật đã bị hủy bỏ!\nChương trình chưa được cập nhật!", "Hủy bỏ tải về cập nhật", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        dt.Dispose();
                                    }
                                    else
                                    {
                                        MessageBox.Show(" Đã xảy ra vấn đề trong lúc tải về bản cập nhật!\nVui lòng thử lại sau!", "Lỗi tải về bản cập nhật", MessageBoxButtons.OK, MessageBoxIcon.Information);
                                        dt.Dispose();
                                    }
                                }
                            }
                        }
                        cnn.Close();
                    }
                }
                catch (Exception ex) { MessageBox.Show("Lỗi: " + ex.Message + "\nVui lòng kiểm tra lại đường truyền mạng!"); }
            }
        }
        private void btndangnhap_Click(object sender, EventArgs e)
        {
            try            {
                if (chkConnectOptions.Checked == true)
                {
                    //dbconfig dbInfo = new dbconfig("HGUR7339823U43983RHDUHF72GMB938374HNGJDHEU", "MVNFH716188273646589GJFUJF83IU4JHT84IU5898RUT", "99845UU684UJRJTHYEIE83I4U584UIOIRUY84U54Y574I", txttendangnhap.Text.Trim(), txtmatkhau.Text.Trim());
                    //ConnectionDB dbConection = new ConnectionDB(dbInfo);
                    //Class.datatabase.connect = dbConection.GetConnection;
                    //if (dbConection.GetConnection == "")
                    //{
                    //    MessageBox.Show("Tài khoản hoặc mật khẩu không chính xác. Vui lòng kiểm tra lại");
                    //    return;
                    //}
                    //cn = dbConection.GetConnection;
                }
                else
                {
                    Microsoft.Win32.RegistryKey ReadKey;
                    ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareAccount", true);
                    if (ReadKey != null)
                    {
                        string ServerName       = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("ServerName").ToString());
                        string DatabaseUser     = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("DatabaseUser").ToString());
                        string DatabasePassword = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("DatabasePassword").ToString());
                        string DatabaseName     = AutoCareUtil.Utilities.Decode(ReadKey.GetValue("DatabaseName").ToString());

                        cn = "server=" + ServerName + ";uid=" + DatabaseUser + ";pwd=" + DatabasePassword + ";database=" + DatabaseName;
                        Class.datatabase.connect = cn;
                    }
                    //cn = Class.datatabase.connect;
                }
                connect();

                SqlCommand c = new SqlCommand("Select top 1 username,idcongty,idnhanvien,idcuahang,Pass, Quyen, TenNhanVien from NhanVien_TaiKhoanDangNhap where username=@username", con);
                c.Parameters.AddWithValue("@username", txttendangnhap.Text.Trim());
                da = new SqlDataAdapter(c);
                da.Fill(dttkdn);
                if (dttkdn.Rows.Count > 0)
                {
                    DataRow nhanvien = dttkdn.Rows[0];
                    Class.EmployeeInfo.idnhanvien  = Convert.ToInt32(nhanvien["idnhanvien"]);
                    Class.EmployeeInfo.IdCuaHang   = nhanvien["idcuahang"].ToString();
                    Class.EmployeeInfo.TenNhanVien = nhanvien["TenNhanVien"].ToString();
                    Class.EmployeeInfo.IdCongTy    = nhanvien["IdCongty"].ToString();
                    Class.EmployeeInfo.Pass        = nhanvien["Pass"].ToString();
                    Class.EmployeeInfo.Quyen       = nhanvien["Quyen"].ToString();
                    Class.EmployeeInfo.UserName    = nhanvien["username"].ToString();

                    string idconty = nhanvien["IdCongty"].ToString();

                    // lay thong tin cong ty
                    SqlCommand com = new SqlCommand("select * from Congty where idcongty = " + idconty, con);
                    da.SelectCommand = com;
                    da.Fill(tblcongty);
                    if (tblcongty.Rows.Count > 0)
                    {
                        Class.CompanyInfo.tencongty = tblcongty.Rows[0]["tencongty"].ToString();
                        Class.CompanyInfo.diachi    = tblcongty.Rows[0]["diachi"].ToString();
                        Class.CompanyInfo.phone     = tblcongty.Rows[0]["Dienthoai"].ToString();
                        idconty = tblcongty.Rows[0]["idCongty"].ToString();
                        Class.CompanyInfo.idcongty              = idconty;
                        Class.CompanyInfo.quota                 = tblcongty.Rows[0]["QuotaRemain"].ToString();
                        Class.CompanyInfo.secretkey             = tblcongty.Rows[0]["SecretKey"].ToString();
                        Class.CompanyInfo.sotiennhantinbaoduong = int.Parse(tblcongty.Rows[0]["SoTienNhanTinBaoDuong"].ToString());
                        Class.CompanyInfo.GoiPhanMem            = tblcongty.Rows[0]["GoiPhanMem"].ToString();
                    }
                    else
                    {
                        MessageBox.Show("Lỗi dữ liệu: Thông tin công ty của bạn chưa được cung cấp");
                        return;
                    }
                    try                    {
                        Class.CompanyInfo.cauhinhdotbaoduong = new SqlCommand("select ThangNhan from SMSMaintenanceConfig where idcongty=" + idconty, con).ExecuteScalar().ToString();
                    }
                    catch { }
                    // lay thong tin cua hang
                    string idscuahang = "";
                    using (SqlDataReader rd = new SqlCommand("select idcuahang from cuahang where idcongty=" + idconty, con).ExecuteReader())                    {
                        while (rd.Read())
                        {
                            idscuahang += rd[0].ToString() + ",";
                        }
                    }
                    if (idscuahang != "")
                    {
                        Class.CompanyInfo.IdsCuaHang = idscuahang.TrimEnd(',');
                    }

                    // kiem tra thuong hieu
                    object obj = new SqlCommand("select top 1 thuonghieu from ThuongHieu where idcongty=" + idconty, con).ExecuteScalar();
                    if (obj != null)
                    {
                        Class.CompanyInfo.sendername = obj != null?obj.ToString() : "";
                    }
                    else
                    {
                        MessageBox.Show("Lỗi Thương hiệu: Công ty bạn chưa được cấp thương hiệu");
                        return;
                    }
                    // kiem tra mat khau
                    string     pass = Class.Checksum.GetMd5Hash(txtmatkhau.Text, Class.CompanyInfo.secretkey);
                    SqlCommand cmd  = new SqlCommand("select * from Taikhoandangnhap where username=@username and pass=@pass", con);
                    cmd.Parameters.AddWithValue("@username", txttendangnhap.Text);
                    cmd.Parameters.AddWithValue("@pass", pass);
                    bool isPass = false;
                    using (SqlDataReader rd = cmd.ExecuteReader())                    {
                        while (rd.Read())
                        {
                            isPass = true;
                            if (chkSaveInfo.Checked)
                            {
                                //string strencrypt = txttendangnhap.Text + "|" + txtmatkhau.Text;
                                //byte[] strby = myrsa.Encrypt(Encoding.Unicode.GetBytes(strencrypt), false);
                                //File.WriteAllText("info.dat", Convert.ToBase64String(strby));

                                Microsoft.Win32.RegistryKey ReadKey;
                                ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareAccount", true);
                                if (ReadKey == null)
                                {
                                    Microsoft.Win32.RegistryKey key;
                                    key = Microsoft.Win32.Registry.CurrentUser.CreateSubKey("AutoCareAccount");
                                    key.SetValue("UserName", AutoCareUtil.Utilities.Encode(txttendangnhap.Text.Trim()));
                                    key.SetValue("Password", AutoCareUtil.Utilities.Encode(txtmatkhau.Text.Trim()));
                                    key.SetValue("SavePassword", true);
                                    key.SetValue("ConnectOnline", chkConnectOptions.Checked);
                                    key.Close();
                                }
                                else
                                {
                                    ReadKey.SetValue("UserName", AutoCareUtil.Utilities.Encode(txttendangnhap.Text.Trim()));
                                    ReadKey.SetValue("Password", AutoCareUtil.Utilities.Encode(txtmatkhau.Text.Trim()));
                                    ReadKey.SetValue("SavePassword", true);
                                    ReadKey.SetValue("ConnectOnline", chkConnectOptions.Checked);
                                    ReadKey.Close();
                                }
                            }
                            else
                            {
                                try      {
                                    Microsoft.Win32.RegistryKey ReadKey;
                                    ReadKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("AutoCareAccount", true);
                                    ReadKey.SetValue("SavePassword", false);
                                }
                                catch (Exception)   { }
                            }

                            RibMain fmain = new RibMain();
                            fmain.Show();
                            this.Hide();
                        }
                    }
                    if (!isPass)
                    {
                        MessageBox.Show("Bạn đăng nhập không thành công!\n Hãy kiểm tra lại mật khẩu");
                    }
                }
                else
                {
                    MessageBox.Show("Bạn đăng nhập không thành công!\nHãy kiểm tra lại tài khoản đăng nhập.");
                    this.txttendangnhap.Focus();
                }
            }
            catch (Exception ex)  {
                MessageBox.Show("Bạn đăng nhập không thành công kiểm tra lại thông tin kết nối và đường truyền mạng.\n" + ex.Message);
            }
            finally    {
                con.Close();
            }
        }