public void TestEncryptStringShouldSucceed()
        {
            var encryptionHelper = new EncryptionHelper(testFileDeploymentDirectory);
            var encryptedString = encryptionHelper.EncryptAndBase64(TestString);

            encryptedString.Should().NotBeNullOrEmpty("Encryptiong failed");
            encryptedString.Length.Should().BeGreaterThan(0, "Encryption failed");
        }
        public void TestEncryptBinaryShouldSucceed()
        {
            var encryptionHelper = new EncryptionHelper(testFileDeploymentDirectory);
            var bytesToEncrypt = File.ReadAllBytes(Path.Combine(testFileDeploymentDirectory, TestFileName));
            var encryptedBytes = encryptionHelper.EncryptBytes(bytesToEncrypt);

            encryptedBytes.Should().NotBeNull("EncryptionFailed");
        }
        public void TestDecryptBinaryShouldSucceed()
        {
            var pathToTestFile = Path.Combine(testFileDeploymentDirectory, TestFileName);
            var encryptionHelper = new EncryptionHelper(testFileDeploymentDirectory);
            var bytesToEncrypt = File.ReadAllBytes(pathToTestFile);
            var encryptedBytes = encryptionHelper.EncryptBytes(bytesToEncrypt);

            var decryptedBytes = encryptionHelper.DecryptBytes(encryptedBytes);
            decryptedBytes.Should().NotBeNull("EncryptionFailed");

            var decryptedTestContent = System.Text.Encoding.UTF8.GetString(decryptedBytes);
            var originalContent = File.ReadAllText(pathToTestFile);

            Assert.IsTrue(decryptedTestContent.Equals(originalContent, StringComparison.InvariantCultureIgnoreCase));
        }
Exemple #4
0
        public void EncryptDecrypt()
        {
            // Arrange
            var subject = new EncryptionHelper();
            var originalString = "Testing123!£$";

            // Act
            var encryptedString1 = subject.Encrypt(originalString);
            var encryptedString2 = subject.Encrypt(originalString);
            var decryptedString1 = subject.Decrypt(encryptedString1);
            var decryptedString2 = subject.Decrypt(encryptedString2);

            // Assert
            originalString.Should().Be(decryptedString1, "Decrypted string should match original string");
            originalString.Should().Be(decryptedString2, "Decrypted string should match original string");
            originalString.Should().Be(encryptedString1, "Encrypted string should not match original string");
            encryptedString1.Should().Be(encryptedString2, "String should never be encrypted the same twice");
        }
Exemple #5
0
 public AdministratorsController()
 {
     UsersCount       = new UsersCountViewModel();
     EncryptionHelper = new EncryptionHelper(ConfigurationManager.AppSettings["EncryptionKey"]);
 }
 public void TestTearDown()
 {
     var encryptionHelper = new EncryptionHelper(testFileDeploymentDirectory);
     encryptionHelper.KeyTableManager.DeleteTableIfExists();
 }
    /// <summary>
    /// Initializes the control properties.
    /// </summary>
    protected void SetupControl()
    {
        if (this.StopProcessing)
        {
            // Do nothing
        }
        else
        {
            // Classic repeater+dataset
            if (this.UseClassicDataset)
            {
                // Set SharePoint datasource properties
                SPDataSource.Username          = this.Username;
                SPDataSource.Password          = EncryptionHelper.DecryptData(this.Password);
                SPDataSource.ListName          = this.ListName;
                SPDataSource.SPServiceURL      = this.SPServiceURL;
                SPDataSource.ShowReturnedCAML  = this.ShowReturnedCAML;
                SPDataSource.RowLimit          = this.RowLimit;
                SPDataSource.Query             = this.Query;
                SPDataSource.ViewFields        = this.ViewFields;
                SPDataSource.UseClassicDataset = this.UseClassicDataset;
                SPDataSource.Fields            = this.Fields;
                SPDataSource.Mode              = this.Mode;
                SPDataSource.ItemIDField       = this.ItemIDField;
                SPDataSource.ItemIDFieldType   = this.ItemIDFieldType;
                SPDataSource.CacheItemName     = this.CacheItemName;
                SPDataSource.CacheDependencies = this.CacheDependencies;
                SPDataSource.CacheMinutes      = this.CacheMinutes;

                // Set basic datagrid properties
                BasicDataGrid.DataBindByDefault = false;
                BasicDataGrid.EnableViewState   = true;

                BasicDataGrid.HideControlForZeroRows = HideControlForZeroRows;
                BasicDataGrid.ZeroRowsText           = ZeroRowsText;

                if (!StandAlone && (PageCycle < PageCycleEnum.Initialized) && (ValidationHelper.GetString(Page.StyleSheetTheme, "") == ""))
                {
                    BasicDataGrid.SkinID = SkinID;
                }

                BasicDataGrid.SortAscending  = SortAscending;
                BasicDataGrid.AllowSorting   = AllowSorting;
                BasicDataGrid.ProcessSorting = ProcessSorting;
                BasicDataGrid.SortField      = SortField;

                BasicDataGrid.AllowPaging       = AllowPaging;
                BasicDataGrid.AllowCustomPaging = AllowCustomPaging;
                BasicDataGrid.PageSize          = PageSize;
                BasicDataGrid.PagerStyle.Mode   = PagingMode;

                BasicDataGrid.ShowHeader = ShowHeader;
                BasicDataGrid.ShowFooter = ShowFooter;
                BasicDataGrid.ToolTip    = ToolTip;
                BasicDataGrid.SetFirstPageAfterSortChange = SetFirstPageAfterSortChange;

                // Load and bind data
                LoadData();
            }
            else
            {
                throw new Exception("XSLT transformation not supported in this webpart. Use SharePoint repeater.");
            }
        }
    }
        public void GenerateSaltedHash_ReturnsSameHash_ForValue()
        {
            var password1 = "password1";
            var password2 = "QWERTY";

            Assert.Equal("CF-EB-3D-62-D1-1A-C9-40-E1-02-FA-EA-5C-E4-85-6F-8E-F9-3C-61-BA-B5-A4-9E-FB-BA-4B-64-F9-75-BA-3E", EncryptionHelper.GenerateSaltedHash(password1, "123456"));
            Assert.Equal("14-F3-50-09-43-02-44-DE-0B-C3-E6-3C-15-2C-CE-42-CC-22-45-1E-88-68-6B-02-C4-0C-0B-A7-E1-28-1E-01", EncryptionHelper.GenerateSaltedHash(password2, "ABCDEF"));
        }
 public void GetMd5Hash_ReturnsSameHash_ForValue()
 {
     Assert.Equal("5b514b79bc38a9eb7d2a86193456549c", EncryptionHelper.GetMd5Hash(source));
 }
Exemple #10
0
        //#act
        public static string Act(string funcName, string[] funcParamArray)
        {
            var returnStr = "";

            try
            {
                if (funcName.ToLower() == "CreateDirectory".ToLower())
                {
                    if (!Directory.Exists(funcParamArray[0]))
                    {
                        Directory.CreateDirectory(funcParamArray[0]);
                    }
                    if (funcParamArray[1] == "true")
                    {
                        var di = new DirectoryInfo(funcParamArray[0]);
                        if (!((di.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden))
                        {
                            di.Attributes = FileAttributes.Hidden;
                        }
                    }
                }
                else if (funcName.ToLower() == "OpenDirectory".ToLower())
                {
                    if (!Directory.Exists(funcParamArray[0]))
                    {
                        throw new ArgumentException("Directory does not exist! ");;
                    }
                    else
                    {
                        System.Diagnostics.Process.Start(funcParamArray[0]);
                    }
                }
                else if (funcName.ToLower() == "SelectAndRenameFile".ToLower())
                {
                    var dlgOpenFile = new OpenFileDialog();

                    dlgOpenFile.Title            = funcParamArray[0];
                    dlgOpenFile.Filter           = funcParamArray[1];
                    dlgOpenFile.InitialDirectory = funcParamArray[2];
                    dlgOpenFile.Multiselect      = false;
                    dlgOpenFile.RestoreDirectory = true;
                    if (dlgOpenFile.ShowDialog() == DialogResult.OK)
                    {
                        if (dlgOpenFile.FileNames.Length > 0)
                        {
                            var firstFilePath = dlgOpenFile.FileNames[0];
                            var folder        = FileHelper.GetFileDetailByOption(firstFilePath, FilePathComposition.Directory);
                            if (File.Exists(firstFilePath))
                            {
                                File.Move(firstFilePath, folder + "\\" + funcParamArray[3]);
                            }
                            else
                            {
                                throw new ArgumentException("File does not exist! ");;
                            }
                        }
                    }
                    else
                    {
                        //throw new ArgumentException("Operation Cancelled! ");
                    }
                }

                else if (funcName.ToLower() == "Run".ToLower())
                {
                    var actArgsStr = "";
                    if (funcParamArray.Length > 1)
                    {
                        actArgsStr = funcParamArray[1];
                    }
                    ProcessHelper.Run(funcParamArray[0], actArgsStr);
                }


                else if (funcName.ToLower() == "OpenFile".ToLower())
                {
                    var actArgsStr = "";
                    ProcessHelper.OpenFile(funcParamArray[0], actArgsStr);
                }
                else if (funcName.ToLower() == "OpenFolder".ToLower())
                {
                    ProcessHelper.OpenFolder(funcParamArray[0]);
                }


                else if (funcName.ToLower() == ("Redirect").ToLower())
                {
                    ProcessHelper.Redirect(funcParamArray[0]);
                }

                else if (funcName.ToLower() == "SendLocalEmail".ToLower())
                {
                    var mailTo  = funcParamArray[0];
                    var subject = funcParamArray[1];
                    var body    = "";
                    if (funcParamArray.Length > 2)
                    {
                        body = funcParamArray[2];
                    }
                    if (body.Contains("\r\n"))
                    {
                        body = body.Replace("\r\n", "%0D%0A");
                    }
                    if (body.Contains("\\r\\n"))
                    {
                        body = body.Replace("\\r\\n", "%0D%0A");
                    }
                    LocalEmailHelper.Send(mailTo, subject, body);
                }

                else if (funcName.ToLower() == ("RunCmd".ToLower()) | funcName.ToLower() == ("ExecCmd".ToLower()))
                {
                    var actArgsStr     = "";
                    var inputStr       = "";
                    var execCmdModeStr = "0";
                    if (funcName.ToLower() == ("RunCmd".ToLower()))
                    {
                        if (!File.Exists(funcParamArray[0]))
                        {
                            throw new ArgumentException("File:'" + funcParamArray[0] + "' does not exist!");
                        }
                        if (funcParamArray.Length > 1)
                        {
                            actArgsStr = funcParamArray[1];
                        }
                        if (funcParamArray.Length > 2)
                        {
                            if (funcParamArray[2].IsPlusInteger())
                            {
                                execCmdModeStr = funcParamArray[2];
                            }
                        }
                        inputStr = actArgsStr.IsNullOrEmpty() ? funcParamArray[0] : funcParamArray[0] + " " + actArgsStr;
                    }

                    else if (funcName.ToLower() == "ExecCmd".ToLower())
                    {
                        if (funcParamArray.Length > 1)
                        {
                            if (funcParamArray[1].IsPlusInteger())
                            {
                                execCmdModeStr = funcParamArray[1];
                            }
                        }
                        inputStr = funcParamArray[0];
                    }

                    var execCmdModeInt = (ExecCmdMode)Convert.ToInt16(execCmdModeStr);
                    var execCmdMode    = (ExecCmdMode)(execCmdModeInt);
                    returnStr = ProcessHelper.Cmd(inputStr, execCmdMode);
                }

                else if (funcName.ToLower() == "ExportToExcel".ToLower())
                {
                    var content = funcParamArray[0];
                    content = "UTF格式";
                    var title  = "ExpertToExcel".ToUniqueStringByNow();
                    var folder = DirectoryHelper.GetSpecialDir("personal");

                    var path = folder + "\\" + title + ".xls";
                    File.WriteAllText(path, content, Encoding.Default);
                    ProcessHelper.OpenFile(path, "");
                }
                else if (funcName.ToLower() == "EncryptTextFile".ToLower())
                {
                    var path = funcParamArray[0];
                    path = FileHelper.GetFilePath(path, Path.GetDirectoryName(Application.ExecutablePath));
                    var folder    = FileHelper.GetFileDetailByOption(path, FilePathComposition.Directory);
                    var fileTitle = FileHelper.GetFileDetailByOption(path, FilePathComposition.FileTitle);
                    var postfix   = FileHelper.GetFileDetailByOption(path, FilePathComposition.Postfix);
                    var txt       = EncryptionHelper.SmEncrypt(File.ReadAllText(path));
                    var path1     = folder + "\\" + fileTitle + ".E" + postfix.Substring(1, postfix.Length - 1);
                    File.WriteAllText(path1, txt, Encoding.Default);

                    if (funcParamArray.Length > 1 & funcParamArray[1].ToLower() == "true")
                    {
                        File.Delete(path);
                    }
                }
                else
                {
                    return("OutOfScope");
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException("\n>> " + TypeName + ".Act error: " + ex.Message);
            }
            return(returnStr);
        }
Exemple #11
0
 public UserEntity Login(string username, string password)
 {
     return(this.userRepository.Login(username, EncryptionHelper.EncryptSHA256(password)));
 }
Exemple #12
0
 protected string GetDownloadLink(string filename)
 {
     return(this.Page.ResolveUrl("~/Admin/DigitalGoods/Download.ashx") + "?F=" + Server.UrlEncode(EncryptionHelper.EncryptAES(_RelativeDigitalGoodPath + filename)));
 }
Exemple #13
0
        private void GetMemberCard(string openid, string weixincode, string weixinpass, int comid)
        {
            //如果SESSION有值,进行赋值
            if (openid == "" && Session["Openid"] != null)
            {
                openid = Session["Openid"].ToString();
            }

            //判断商家是否微信认证
            if (weixincode != "")//进行过微信认证,微信认证登陆
            {
                //如果微信ID,递实现自动登陆
                GetOpenId(weixincode, comid);
            }
            else if (openid != "" && weixinpass != "")
            {
                //最后判断传递过来的微信一次性密码
                VerifyOneOffPass(openid, weixinpass);
            }



            //判断登陆状态
            if (Session["AccountId"] != null)
            {
                //先判断Session
                AccountId = int.Parse(Session["AccountId"].ToString());
                B2bCrmData dateuser = new B2bCrmData();
                B2b_crm    userinfo = dateuser.Readuser(AccountId, comid);
                if (userinfo != null)
                {
                    Readuser(userinfo.Idcard, comid);
                }
            }
            else
            {//再判断COOKIES
                if (Request.Cookies["AccountId"] != null)
                {
                    string accountmd5 = "";
                    AccountId = int.Parse(Request.Cookies["AccountId"].Value);
                    if (Request.Cookies["AccountKey"] != null)
                    {
                        accountmd5 = Request.Cookies["AccountKey"].Value;
                    }
                    B2b_crm userinfo;
                    var     data = CrmMemberJsonData.WeixinCookieLogin(AccountId.ToString(), accountmd5, comid, out userinfo);
                    if (data == "OK")
                    {
                        Session["AccountId"]   = userinfo.Id;
                        Session["AccountName"] = userinfo.Name;
                        Session["AccountCard"] = userinfo.Idcard;
                        Session["Com_id"]      = comid;
                        HttpCookie cookie = new HttpCookie("AccountId");     //实例化HttpCookie类并添加值
                        cookie.Value   = userinfo.Id.ToString();
                        cookie.Expires = DateTime.Now.AddDays(120);
                        Response.Cookies.Add(cookie);
                        var returnmd5 = EncryptionHelper.ToMD5(userinfo.Idcard.ToString() + userinfo.Id.ToString(), "UTF-8");
                        cookie         = new HttpCookie("AccountKey"); //实例化HttpCookie类并添加值
                        cookie.Value   = returnmd5;
                        cookie.Expires = DateTime.Now.AddDays(120);
                        Response.Cookies.Add(cookie);

                        cookie         = new HttpCookie("openid"); //实例化HttpCookie类并添加值
                        cookie.Value   = userinfo.Weixin;
                        cookie.Expires = DateTime.Now.AddDays(120);
                        Response.Cookies.Add(cookie);

                        if (userinfo != null)
                        {
                            Readuser(userinfo.Idcard, comid);//读取用户信息
                        }

                        Response.Redirect(Request.Url.ToString()); //登陆成功,刷新页面
                    }
                    else
                    {
                        //当cookie错误无法登陆则清除所有COOKIE
                        HttpCookie aCookie; string cookieName;
                        int        limit = Request.Cookies.Count;
                        for (int i = 0; i < limit; i++)
                        {
                            cookieName      = Request.Cookies[i].Name;
                            aCookie         = new HttpCookie(cookieName);
                            aCookie.Expires = DateTime.Now.AddDays(-1);
                            Response.Cookies.Add(aCookie);
                        }

                        if (Request.Cookies["AccountId"] != null)
                        {
                            HttpCookie mycookie;
                            mycookie = Request.Cookies["AccountId"];
                            TimeSpan ts = new TimeSpan(0, 0, 0, 0);  //时间跨度
                            mycookie.Expires = DateTime.Now.Add(ts); //立即过期
                            Response.Cookies.Remove("AccountId");    //清除
                            Response.Cookies.Add(mycookie);          //写入立即过期的*/
                            Response.Cookies["AccountId"].Expires = DateTime.Now.AddDays(-1);
                        }
                        if (Request.Cookies["AccountName"] != null)
                        {
                            HttpCookie mycookie = Request.Cookies["AccountName"];
                            TimeSpan   ts       = new TimeSpan(0, 0, 0, 0); //时间跨度
                            mycookie.Expires = DateTime.Now.Add(ts);        //立即过期
                            Response.Cookies.Remove("AccountName");         //清除
                            Response.Cookies.Add(mycookie);                 //写入立即过期的*/
                            Response.Cookies["AccountName"].Expires = DateTime.Now.AddDays(-1);
                        }
                        if (Request.Cookies["AccountKey"] != null)
                        {
                            HttpCookie mycookie = Request.Cookies["AccountKey"];
                            TimeSpan   ts       = new TimeSpan(0, 0, 0, 0); //时间跨度
                            mycookie.Expires = DateTime.Now.Add(ts);        //立即过期
                            Response.Cookies.Remove("AccountKey");          //清除
                            Response.Cookies.Add(mycookie);                 //写入立即过期的*/
                            Response.Cookies["AccountKey"].Expires = DateTime.Now.AddDays(-1);
                        }


                        if (weixincode != "")
                        {//如果微信认证代码,微信认证登陆
                            GetOpenId(weixincode, comid);
                        }
                        else if (openid != "" && weixinpass != "")
                        {
                            VerifyOneOffPass(openid, weixinpass);
                        }
                    }
                }
            }
        }
Exemple #14
0
    void PopulateFields()
    {
        if (Session["UserIdDetails"].ToString() != "" && Session["UserIdDetails"] != null)
        {
            Label1.Text       = "Edit user";
            Label2.Text       = "UPDATE";
            deleteBt1.Visible = true;
            string connstring = ConfigurationManager.ConnectionStrings["AVAConnectionString"].ConnectionString;
            //string sCommand = "";

            query = "SELECT t1.* FROM tblUsers t1 WHERE t1.UserId=@UserId ";
            using (conn = new SqlConnection(connstring))
            {
                using (cmd = new SqlCommand(query, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@UserId", Session["UserIdDetails"]);
                    oReader = cmd.ExecuteReader();
                    if (oReader.HasRows)
                    {
                        while (oReader.Read())
                        {
                            UserName.Value     = oReader["UserName"].ToString();
                            UserPassword.Value = EncryptionHelper.Decrypt(oReader["UserPassword"].ToString());
                            EmailAdd.Value     = oReader["EmailAdd"].ToString();
                            FirstName.Value    = oReader["FirstName"].ToString();
                            LastName.Value     = oReader["LastName"].ToString();
                            CompanyName.Value  = oReader["CompanyName"].ToString();
                            //UserType.SelectedValue = oReader["UserType"].ToString();
                            //CompanyName1.SelectedValue = oReader["VendorId"].ToString();
                        }
                    }
                    conn.Close();
                }
            }
            UserType.DataBind();
            query = "SELECT t1.* FROM tblUserTypes t1 WHERE t1.UserId=@UserId ";
            using (conn = new SqlConnection(connstring))
            {
                using (cmd = new SqlCommand(query, conn))
                {
                    conn.Open();
                    cmd.Parameters.AddWithValue("@UserId", Session["UserIdDetails"]);
                    oReader = cmd.ExecuteReader();
                    if (oReader.HasRows)
                    {
                        while (oReader.Read())
                        {
                            //UserType.SelectedValue = oReader["UserType"].ToString();
                            foreach (ListItem listItem in UserType.Items)
                            {
                                if (listItem.Value == oReader["UserType"].ToString())
                                {
                                    listItem.Selected = true;
                                }
                            }
                        }
                    }
                    conn.Close();
                }
            }
        }
    }
Exemple #15
0
        protected void Page_Load(object sender, EventArgs e)
        {
            string u  = Request.ServerVariables["HTTP_USER_AGENT"];
            bool   bo = detectmobilebrowser.HttpUserAgent(u);

            RequestUrl = Request.ServerVariables["SERVER_NAME"].ToLower();
            //根据域名读取商户ID,如果没有绑定域名直接跳转后台
            if (Domain_def.Domain_yanzheng(RequestUrl))//如果符合shop101.etown.cn的格式,则从多微信商户基本信息表中获取comid
            {
                //先通过正则表达式获取COMid
                comid = Int32.Parse(Domain_def.Domain_Huoqu(RequestUrl).ToString());
                if (comid == 0)
                {
                    comid = new WeiXinBasicData().GetWeiXinBasicByDomain(RequestUrl).Comid;
                }
            }
            else
            {
                B2b_company_info companyinfo = B2bCompanyData.GetComId(RequestUrl);
                if (companyinfo != null)
                {
                    comid = companyinfo.Com_id;
                }
            }

            //if (bo == false)
            //{
            //    if (comid == 101)
            //    {
            //        Response.Redirect("http://vctrip.etown.cn/");
            //    }
            //    Response.Redirect("http://shop" + comid + ".etown.cn");
            //}

            if (openid != null && openid != "")
            {
                //只要传递过来微信ID 直接SESSION
                Session["Openid"] = openid;
            }



            //判断登陆状态
            if (Session["AccountId"] != null)
            {//先判断Session
                AccountId   = Int32.Parse(Session["AccountId"].ToString());
                AccountName = Session["AccountName"].ToString();
                AccountCard = Session["AccountCard"].ToString();
                Today       = DateTime.Now.ToString("yyyy-MM-dd");
                //comid = int.Parse(Session["Com_id"].ToString());


                //AccountId = Int32.Parse(Session["AccountId"].ToString());
                B2bCrmData dateuser1 = new B2bCrmData();
                B2b_crm    modeluser = dateuser1.Readuser(AccountId, comid);

                if (modeluser != null)
                {
                    openid          = modeluser.Weixin;
                    Accountphone    = modeluser.Phone;
                    AccountName     = modeluser.Name;
                    AccountCard     = modeluser.Idcard.ToString();
                    AccountBirthday = modeluser.Birthday;
                    Accountsex      = modeluser.Sex;
                    year            = AccountBirthday.Year.ToString();
                    month           = AccountBirthday.Month.ToString();
                    day             = AccountBirthday.Day.ToString();

                    comid = int.Parse(modeluser.Com_id.ToString());
                }



                B2bCrmData dateuser = new B2bCrmData();
                dateuser.WeixinConPass(openid, comid);//只要包含SESSION登陆成功,清空微信密码
            }
            else
            {//再判断COOKIES
                //comid = Request["comid"].ConvertTo<int>(0);
                if (Request.Cookies["AccountId"] != null && Request.Cookies["AccountKey"] != null)
                {
                    AccountId = Int32.Parse(Request.Cookies["AccountId"].Value);
                    string  accountmd5 = Request.Cookies["AccountKey"].Value;
                    B2b_crm userinfo;

                    var data = CrmMemberJsonData.WeixinCookieLogin(AccountId.ToString(), accountmd5, comid, out userinfo);
                    if (data == "OK")
                    {
                        Session["AccountId"]   = userinfo.Id;
                        Session["AccountName"] = userinfo.Name;
                        Session["AccountCard"] = userinfo.Idcard;
                        Session["Com_id"]      = comid;
                        //Accountsex = userinfo.Sex;
                        openid = userinfo.Weixin;


                        HttpCookie cookie = new HttpCookie("AccountId", userinfo.Id.ToString());     //实例化HttpCookie类并添加值
                        cookie.Expires = DateTime.Now.AddDays(120);
                        Response.Cookies.Add(cookie);
                        cookie         = new HttpCookie("AccountName", userinfo.Name.ToString()); //实例化HttpCookie类并添加值
                        cookie.Expires = DateTime.Now.AddDays(120);
                        Response.Cookies.Add(cookie);
                        var returnmd5 = EncryptionHelper.ToMD5(userinfo.Idcard.ToString() + userinfo.Id.ToString(), "UTF-8");
                        cookie         = new HttpCookie("AccountKey", returnmd5); //实例化HttpCookie类并添加值
                        cookie.Expires = DateTime.Now.AddDays(120);
                        Response.Cookies.Add(cookie);
                    }
                }
            }
        }
Exemple #16
0
    //CREATE User
    void SaveToDB()
    {
        string connstring = ConfigurationManager.ConnectionStrings["AVAConnectionString"].ConnectionString;

        //string sCommand = "";

        query = "SELECT UserName FROM tblUsers WHERE UserName = @UserName";
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@UserName", UserName.Value.Trim());
                //cmd.Parameters.AddWithValue("@EmailAdd", EmailAdd.Value.Trim());
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        if (oReader["UserName"].ToString() != "")
                        {
                            UserNameExists = true;
                        }
                        else
                        {
                            UserNameExists = false;
                        }
                    }
                }
                conn.Close();
            }
        }

        if (UserNameExists)
        {
            errNotification.Text      = "User already exists";
            errNotification.ForeColor = Color.Red;
        }
        else if (
            UserName.Value == "" ||
            UserPassword.Value == "" ||
            FirstName.Value == "" ||
            LastName.Value == "" ||
            !UserTypeIsChecked(Session["UserIdDetails"].ToString()) || !IsEmail(EmailAdd.Value)
            )
        {
            errNotification.Text      = "Required fields.";
            errNotification.ForeColor = Color.Red;
        }
        else
        {
            query = "IF NOT EXISTS (SELECT 1 FROM tblUsers WHERE UserName = @UserName) BEGIN INSERT INTO tblUsers (UserName, UserPassword, EmailAdd, FirstName, LastName, CompanyName, Status) VALUES (@UserName, @UserPassword, @EmailAdd, @FirstName, @LastName, @CompanyName, @Status) END";
            //query = "sp_GetVendorInformation"; //##storedProcedure
            using (conn = new SqlConnection(connstring))
            {
                using (cmd = new SqlCommand(query, conn))
                {
                    //cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure
                    cmd.Parameters.AddWithValue("@UserName", UserName.Value.Trim());
                    cmd.Parameters.AddWithValue("@UserPassword", EncryptionHelper.Encrypt(UserPassword.Value.Trim()));
                    cmd.Parameters.AddWithValue("@EmailAdd", EmailAdd.Value.Trim());
                    cmd.Parameters.AddWithValue("@FirstName", FirstName.Value.Trim());
                    cmd.Parameters.AddWithValue("@LastName", LastName.Value.Trim());
                    cmd.Parameters.AddWithValue("@CompanyName", CompanyName.Value.Trim());
                    cmd.Parameters.AddWithValue("@Status", 1);
                    conn.Open(); cmd.ExecuteNonQuery(); conn.Close();
                }
            }

            foreach (ListItem listItem in UserType.Items)
            {
                if (listItem.Selected)
                {
                    sCommand = "INSERT INTO tblUserTypes (UserId, UserType) SELECT UserId, " + listItem.Value + " as UserType FROM tblUsers WHERE UserName = '******' AND UserPassword = '******'";
                    SqlHelper.ExecuteNonQuery(connstring, CommandType.Text, sCommand);
                }
            }

            errNotification.Text      = "User successfully added";
            errNotification.ForeColor = Color.Blue;
            UserName.Value            = "";
            UserPassword.Value        = "";
            UserType.SelectedIndex    = 0;
            EmailAdd.Value            = "";
            FirstName.Value           = "";
            LastName.Value            = "";
            CompanyName.Value         = "";
            Session["UserIdDetails"]  = "";
        }
    }
Exemple #17
0
    //UPDATE User
    void UpdateUser()
    {
        string connstring = ConfigurationManager.ConnectionStrings["AVAConnectionString"].ConnectionString;

        //string sCommand = "";
        query = "SELECT UserName FROM tblUsers WHERE (UserName = @UserName) AND UserId != " + Session["UserIdDetails"];
        using (conn = new SqlConnection(connstring))
        {
            using (cmd = new SqlCommand(query, conn))
            {
                conn.Open();
                cmd.Parameters.AddWithValue("@UserName", UserName.Value.Trim());
                //cmd.Parameters.AddWithValue("@EmailAdd", EmailAdd.Value.Trim());
                oReader = cmd.ExecuteReader();
                if (oReader.HasRows)
                {
                    while (oReader.Read())
                    {
                        if (oReader["UserName"].ToString() != "")
                        {
                            UserNameExists = true;
                        }
                        else
                        {
                            UserNameExists = false;
                        }
                    }
                }
                conn.Close();
            }
        }

        if (UserNameExists)
        {
            errNotification.Text      = "User already exists";
            errNotification.ForeColor = Color.Red;
        }
        else if (
            UserName.Value == "" ||
            UserPassword.Value == "" ||
            EmailAdd.Value == "" ||
            FirstName.Value == "" ||
            LastName.Value == "" ||
            CompanyName.Value == "" ||
            !UserTypeIsChecked(Session["UserIdDetails"].ToString()) || !IsEmail(EmailAdd.Value)
            )
        {
            errNotification.Text      = "Required fields.";
            errNotification.ForeColor = Color.Red;
        }
        else
        {
            if (UserPassword.Value != "")
            {
                query = "UPDATE tblUsers SET UserName=@UserName, UserPassword=@UserPassword, EmailAdd=@EmailAdd, FirstName=@FirstName, LastName=@LastName, CompanyName=@CompanyName, Status=@Status WHERE UserId =@UserId";
            }
            else
            {
                query = "UPDATE tblUsers SET UserName=@UserName, EmailAdd=@EmailAdd, FirstName=@FirstName, LastName=@LastName, CompanyName=@CompanyName, Status=@Status WHERE UserId =@UserId";
            }
            //query = "sp_GetVendorInformation"; //##storedProcedure
            using (conn = new SqlConnection(connstring))
            {
                using (cmd = new SqlCommand(query, conn))
                {
                    //cmd.CommandType = CommandType.StoredProcedure; //##storedProcedure
                    cmd.Parameters.AddWithValue("@UserName", UserName.Value.Trim());
                    cmd.Parameters.AddWithValue("@UserPassword", EncryptionHelper.Encrypt(UserPassword.Value.Trim()));
                    cmd.Parameters.AddWithValue("@EmailAdd", EmailAdd.Value.Trim());
                    cmd.Parameters.AddWithValue("@FirstName", FirstName.Value.Trim());
                    cmd.Parameters.AddWithValue("@LastName", LastName.Value.Trim());
                    cmd.Parameters.AddWithValue("@CompanyName", CompanyName.Value.Trim());
                    cmd.Parameters.AddWithValue("@Status", 1);
                    cmd.Parameters.AddWithValue("@UserId", Session["UserIdDetails"].ToString());
                    conn.Open(); cmd.ExecuteNonQuery(); conn.Close();
                }
            }
            conn.Close();
            //Response.Write(CompanyName.Value.Trim());


            sCommand = "DELETE FROM tblUserTypes WHERE UserId = " + Session["UserIdDetails"];
            SqlHelper.ExecuteNonQuery(connstring, CommandType.Text, sCommand);
            foreach (ListItem listItem in UserType.Items)
            {
                if (listItem.Selected)
                {
                    sCommand = "INSERT INTO tblUserTypes (UserId, UserType) VALUES (" + Session["UserIdDetails"] + ", " + listItem.Value + ")";
                    SqlHelper.ExecuteNonQuery(connstring, CommandType.Text, sCommand);
                }
            }

            errNotification.Text      = "User successfully updated";
            errNotification.ForeColor = Color.Blue;
            UserName.Value            = "";
            UserPassword.Value        = "";
            UserType.SelectedIndex    = 0;
            EmailAdd.Value            = "";
            FirstName.Value           = "";
            LastName.Value            = "";
            CompanyName.Value         = "";
            Session["UserIdDetails"]  = "";
        }
    }
Exemple #18
0
 public AdministratorsController(ApplicationUserManager userManager, ApplicationSignInManager signInManager)
 {
     UsersCount       = new UsersCountViewModel();
     EncryptionHelper = new EncryptionHelper(ConfigurationManager.AppSettings["EncryptionKey"]);
 }
Exemple #19
0
        private void SaveRememberMeInfo()
        {
            var pathDirectory     = Application.UserAppDataPath;
            var filePathDirectory = Path.Combine(pathDirectory, $"remembermeinfo.txt");

            try
            {
                // Check if file already exists. If yes, delete it.
                if (File.Exists(filePathDirectory))
                {
                    File.Delete(filePathDirectory);
                }

                // Create a new file
                using (FileStream fs = File.Create(filePathDirectory))
                {
                    // Add some text to file
                    Byte[] loginInfo = new UTF8Encoding(true).GetBytes("");

                    if (checkRememberMe.Checked)
                    {
                        // Add some text to file
                        loginInfo = new UTF8Encoding(true).GetBytes($"{txtUsername.Text}|{EncryptionHelper.Encrypt(txtPassword.Text)}|true");
                    }

                    fs.Write(loginInfo, 0, loginInfo.Length);
                }
            }
            catch (Exception Ex)
            {
                Console.WriteLine(Ex.ToString());
            }
        }
        /*******************************************************************
         *  Model DB configuration
         ********************************************************************/
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity <Currency>(
                entity =>
            {
                entity.ToTable("Currencies");

                entity.HasKey(c => c.Id);

                entity.Property(c => c.Id).ValueGeneratedOnAdd();

                entity.HasQueryFilter(r => r.IsDeleted == false);

                entity.HasIndex(c => c.Code).IsUnique();

                entity.Property(c => c.Code).HasMaxLength(3)
                .IsFixedLength()
                .IsRequired();

                entity.Property(c => c.Description).IsRequired();
            }
                );

            modelBuilder.Entity <CurrencyRate>(
                entity =>
            {
                entity.ToTable("CurrencyRates");

                entity.HasKey(r => r.Id);

                entity.Property(r => r.Id).ValueGeneratedOnAdd();

                entity.HasQueryFilter(r => r.IsDeleted == false);



                entity.HasIndex(r => new { r.BaseCurrencyId, r.TargetCurrencyId })
                .IsUnique();

                entity.HasOne(r => r.BaseCurrency)
                .WithMany(c => c.CurrencyRates)
                .HasForeignKey(r => r.BaseCurrencyId);

                entity.HasOne(r => r.TargetCurrency)
                .WithMany()
                .HasForeignKey(r => r.TargetCurrencyId);

                entity.Property(r => r.Rate).HasColumnType("decimal(18, 10)");
            }
                );

            modelBuilder.Entity <User>(
                entity =>
            {
                entity.ToTable("Users");

                entity.HasKey(r => r.Id);

                entity.Property(r => r.Id).ValueGeneratedOnAdd();

                entity.HasQueryFilter(r => r.IsDeleted == false);

                if (Database.IsInMemory())
                {
                    entity.Property(c => c.Id).HasValueGenerator <InMemoryIntegerValueGenerator <long> >();
                }
            }
                );

            modelBuilder.Entity <UserRole>(
                entity =>
            {
                entity.ToTable("UserRoles");

                entity.HasKey(r => r.Id);

                entity.Property(r => r.Id).ValueGeneratedOnAdd();

                entity.HasIndex(r => r.Description).IsUnique();
            }
                );

            modelBuilder.Entity <UserRoleRelation>(
                entity =>
            {
                entity.ToTable("UserRoleRelations");

                entity.HasKey(r => r.Id);

                entity.Property(r => r.Id).ValueGeneratedOnAdd();

                entity.HasQueryFilter(r => r.IsDeleted == false);

                if (Database.IsInMemory())
                {
                    entity.Property(c => c.Id).HasValueGenerator <InMemoryIntegerValueGenerator <long> >();
                }

                entity.HasIndex(r => new { r.UserId, r.RoleId })
                .IsUnique();

                entity.HasOne(r => r.User)
                .WithMany(u => u.UserRoleRelations)
                .HasForeignKey(r => r.UserId);

                entity.HasOne(r => r.Role)
                .WithMany()
                .HasForeignKey(r => r.RoleId);
            }
                );

            /*******************************************************************
             *  DATA SEEDING
             ********************************************************************/
            modelBuilder.Entity <User>().HasData(
                new User
            {
                Id           = 1,
                UserName     = "******",
                Email        = "*****@*****.**",
                PasswordHash = EncryptionHelper.Encrypt("admin123", "this_is_a_demo_project"),
                CreatedAt    = DateTime.UtcNow,
                IsActive     = true,
                IsDeleted    = false
            },
                new User
            {
                Id           = 2,
                UserName     = "******",
                Email        = "*****@*****.**",
                PasswordHash = EncryptionHelper.Encrypt("user123", "this_is_a_demo_project"),
                CreatedAt    = DateTime.UtcNow,
                IsActive     = true,
                IsDeleted    = false
            }
                );

            modelBuilder.Entity <UserRole>().HasData(
                new UserRole {
                Id = 1, Description = "user"
            },
                new UserRole {
                Id = 2, Description = "admin-currencies"
            },
                new UserRole {
                Id = 3, Description = "admin-rates"
            },
                new UserRole {
                Id = 4, Description = "admin-users"
            }
                );

            modelBuilder.Entity <UserRoleRelation>().HasData(
                new UserRoleRelation {
                Id = 1, UserId = 2, RoleId = 1, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new UserRoleRelation {
                Id = 2, UserId = 1, RoleId = 1, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new UserRoleRelation {
                Id = 3, UserId = 1, RoleId = 2, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new UserRoleRelation {
                Id = 4, UserId = 1, RoleId = 3, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new UserRoleRelation {
                Id = 5, UserId = 1, RoleId = 4, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            }
                );

            modelBuilder.Entity <Currency>().HasData(
                new Currency {
                Id = 1, Code = "EUR", Description = "Euro", CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new Currency {
                Id = 2, Code = "USD", Description = "US Dollar", CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new Currency {
                Id = 3, Code = "CHF", Description = "Swiss Franc", CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new Currency {
                Id = 4, Code = "GBP", Description = "British Pound", CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new Currency {
                Id = 5, Code = "JPY", Description = "Japan Yen", CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new Currency {
                Id = 6, Code = "CAD", Description = "Canadian Dollar", CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            }
                );

            modelBuilder.Entity <CurrencyRate>().HasData(
                new CurrencyRate {
                Id = 1, BaseCurrencyId = 1, TargetCurrencyId = 2, Rate = 1.3764m, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new CurrencyRate {
                Id = 2, BaseCurrencyId = 1, TargetCurrencyId = 3, Rate = 1.2079m, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new CurrencyRate {
                Id = 3, BaseCurrencyId = 1, TargetCurrencyId = 4, Rate = 0.8731m, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new CurrencyRate {
                Id = 4, BaseCurrencyId = 2, TargetCurrencyId = 5, Rate = 76.7200m, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new CurrencyRate {
                Id = 5, BaseCurrencyId = 3, TargetCurrencyId = 2, Rate = 1.1379m, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            },
                new CurrencyRate {
                Id = 6, BaseCurrencyId = 4, TargetCurrencyId = 6, Rate = 1.5648m, CreatedAt = DateTime.UtcNow, IsActive = true, IsDeleted = false
            }
                );
        }
Exemple #21
0
        //#GetText
        public static string GetText(string funcName, string[] funcParamArray)
        {
            try
            {
                //common
                if (funcName.ToLower() == "empty" | funcName.ToLower() == "null")
                {
                    return(string.Empty);
                }


                else if (funcName.ToLower() == "GetInputText".ToLower())
                {
                    var dlg          = new TextInputDialog();
                    var verifyRule   = funcParamArray.Length > 0 ? funcParamArray[0] : "";
                    var verifyParams = funcParamArray.Length > 1 ? funcParamArray[1] : "";
                    dlg.VerificationRule   = verifyRule;
                    dlg.VerificationParams = verifyParams;
                    dlg.ShowDialog();
                    return(dlg.InputText);
                }

                else if (funcName.ToLower() == "GetInputDateTime".ToLower())
                {
                    var dlg          = new DateTimeInputDialog();
                    var customFormat = funcParamArray.Length > 0 ? funcParamArray[0] : "";
                    var verifyRule   = funcParamArray.Length > 1 ? funcParamArray[1] : "";
                    var verifyParams = funcParamArray.Length > 2 ? funcParamArray[2] : "";

                    dlg.VerificationRule   = verifyRule;
                    dlg.VerificationParams = verifyParams;
                    dlg.CustomFormat       = customFormat;
                    dlg.ShowDialog();
                    return(dlg.InputText);
                }

                else if (funcName.ToLower() == "LineQty".ToLower())
                {
                    int qty = funcParamArray[0].Split('\n').Length;
                    return(Convert.ToString(qty));
                }
                else if (funcName.ToLower() == "LinesBySearch".ToLower())
                {
                    var strArry    = funcParamArray[0].Split('\n');
                    var schStrArry = funcParamArray[1].Split(',');
                    var strList    = new List <string>();
                    foreach (var v in strArry)
                    {
                        foreach (var s in schStrArry)
                        {
                            if (v.ToLower().Contains(s.ToLower()))
                            {
                                strList.Add(v);
                            }
                        }
                    }

                    var strList1 = strList.Distinct();
                    var strBlder = new StringBuilder();
                    foreach (var v in strList1)
                    {
                        if (!string.IsNullOrEmpty(v))
                        {
                            strBlder.AppendLine(v);
                        }
                    }

                    return(strBlder.ToString());
                }

                else if (funcName.ToLower() == "DateTime".ToLower())
                {
                    var customFormat = "yyyy-MM-dd HH:mm:ss";
                    if (funcParamArray[0].ToLower() == "UtcNow".ToLower())
                    {
                        var time = SystemTimeHelper.UtcNow(); //
                        return(time.ToString(customFormat, DateTimeFormatInfo.InvariantInfo));
                    }
                    else if (funcParamArray[0].ToLower() == "Now".ToLower())
                    {
                        var time = SystemTimeHelper.Now(); //
                        return(time.ToString(customFormat, DateTimeFormatInfo.InvariantInfo));
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no param " + funcParamArray[0] + "! ");
                    }
                }
                else if (funcName.ToLower() == "UniqueString".ToLower())
                {
                    if (funcParamArray[0] == "ByNow")
                    {
                        var seperator = funcParamArray[1];
                        return(funcParamArray[2].ToUniqueStringByNow(seperator));
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no param '" + funcParamArray[0] + "'! ");
                    }
                }

                else if (funcName.ToLower() == "Format".ToLower())
                {
                    if (funcParamArray[0].ToLower() == "upper")
                    {
                        return(funcParamArray[1].ToUpper());
                    }
                    else if (funcParamArray[0].ToLower() == "lower")
                    {
                        return(funcParamArray[1].ToLower());
                    }
                    else if (funcParamArray[0].ToLower() == "timespan")
                    {
                        return(SystemTimeHelper.GetTimeSpanString(Convert.ToDouble(funcParamArray[1]), funcParamArray[2],
                                                                  false));
                    }
                    else if (funcParamArray[0].ToLower() == "real")
                    {
                        return(string.Format(funcParamArray[2], Convert.ToDouble(funcParamArray[1])));
                    }

                    else if (funcParamArray[0].ToLower() == "FormatString")
                    {
                        return(string.Format(funcParamArray[1], funcParamArray[2]));
                    }
                    else
                    {
                        throw new ArgumentException(funcName + " has no param '" + funcParamArray[0] + "'! ");
                    }
                }
                else if (funcName.ToLower() == "Replace".ToLower())
                {
                    return(funcParamArray[1].Length == 0 ? funcParamArray[0]
                        : funcParamArray[0].Replace(funcParamArray[1], funcParamArray[2]));
                }

                else if (funcName.ToLower() == "Split".ToLower())
                {
                    var seperator   = funcParamArray[1][0];
                    var tmpStrArray = funcParamArray[0].Split(seperator);
                    var index       = Convert.ToInt16(funcParamArray[2]);
                    if (index > tmpStrArray.Length || index == tmpStrArray.Length)
                    {
                        return("");
                    }
                    else
                    {
                        return(tmpStrArray[index]);
                    }
                }
                else if (funcName.ToLower() == "Combine".ToLower())
                {
                    var separator   = funcParamArray[0].GetSubParamSeparator();
                    var tmpStrArray = funcParamArray[0].Split(separator);
                    var rtStr       = "";
                    var i           = 0;
                    foreach (var tmpStr in tmpStrArray)
                    {
                        rtStr = rtStr + tmpStr;
                    }
                    return(rtStr);
                }
                else if (funcName.ToLower() == "SubString".ToLower())
                {
                    var   tmStr    = funcParamArray[0];
                    Int16 sttIndex = Convert.ToInt16(funcParamArray[1]);
                    Int16 len      = Convert.ToInt16(funcParamArray[2]);
                    return(tmStr.Substring(sttIndex, len));
                }

                //file
                else if (funcName.ToLower() == "FileDetail".ToLower())
                {
                    if (funcParamArray[1].IsNullOrEmpty())
                    {
                        throw new ArgumentException("file path can't be empty! ");
                    }
                    if (funcParamArray[0].ToLower() == "Directory".ToLower())
                    {
                        return(FileHelper.GetFileDetailByOption(funcParamArray[1], FilePathComposition.Directory));
                    }
                    else if (funcParamArray[0].ToLower() == "FileName".ToLower())
                    {
                        return(FileHelper.GetFileDetailByOption(funcParamArray[1], FilePathComposition.FileName));
                    }
                    else if (funcParamArray[0].ToLower() == "FileTitle".ToLower())
                    {
                        return(FileHelper.GetFileDetailByOption(funcParamArray[1], FilePathComposition.FileTitle));
                    }
                    else if (funcParamArray[0].ToLower() == "Suffix".ToLower())
                    {
                        return(FileHelper.GetFileDetailByOption(funcParamArray[1], FilePathComposition.Suffix));
                    }
                    else if (funcParamArray[0].ToLower() == "Postfix".ToLower())
                    {
                        return(FileHelper.GetFileDetailByOption(funcParamArray[1], FilePathComposition.Postfix));
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no param '" + funcParamArray[0] + "'! ");
                    }
                }
                else if (funcName.ToLower() == "ChooseFile".ToLower())
                {
                    var dlg = new OpenFileDialog();
                    dlg.Title = "Choose File";
                    if (!string.IsNullOrEmpty(funcParamArray[0]))
                    {
                        dlg.InitialDirectory = funcParamArray[0];
                    }
                    if (!string.IsNullOrEmpty(funcParamArray[1]))
                    {
                        dlg.Filter = funcParamArray[1];
                    }

                    dlg.Multiselect      = false;
                    dlg.RestoreDirectory = true;
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        if (dlg.FileNames.Count() > 0)
                        {
                            var firstFilePath = dlg.FileNames[0];
                            return(firstFilePath);
                        }
                    }
                    return(string.Empty);
                }

                //no use yet
                else if (funcName.ToLower() == "CompareFile".ToLower())
                {
                    //var result = FileHelper.Compare2Files(funcParamArray[1], funcParamArray[2]).ToString();
                    return(string.Empty);
                }

                //dir
                else if (funcName.ToLower() == "ChooseDirectory".ToLower())
                {
                    var dlg = new FolderBrowserDialog();
                    dlg.Description  = @"Choose Directory";
                    dlg.SelectedPath = funcParamArray[0];
                    if (dlg.ShowDialog() == DialogResult.OK)
                    {
                        return(dlg.SelectedPath);
                    }
                    return(string.Empty);
                }

                //calc
                else if (funcName.ToLower() == "Calc".ToLower())
                {
                    if (funcParamArray[0].ToLower() == "add".ToLower())
                    {
                        return((Convert.ToDouble(funcParamArray[1]) + Convert.ToDouble(funcParamArray[2])).ToString());
                    }
                    else if (funcParamArray[0].ToLower() == "sub".ToLower())
                    {
                        return((Convert.ToDouble(funcParamArray[1]) - Convert.ToDouble(funcParamArray[2])).ToString());
                    }
                    else if (funcParamArray[0].ToLower() == "mtp".ToLower())
                    {
                        return((Convert.ToDouble(funcParamArray[1]) * Convert.ToDouble(funcParamArray[2])).ToString());
                    }
                    else if (funcParamArray[0].ToLower() == "div".ToLower())
                    {
                        return((Convert.ToDouble(funcParamArray[1]) / Convert.ToDouble(funcParamArray[2])).ToString());
                    }
                    else if (funcParamArray[0].ToLower() == "rnd".ToLower())
                    {
                        return((Math.Round(Convert.ToDouble(funcParamArray[1]))).ToString());
                    }
                    else if (funcParamArray[0].ToLower() == "spls".ToLower())
                    {
                        return((Convert.ToDouble(funcParamArray[1]) % (Convert.ToDouble(funcParamArray[2]))).ToString());
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no param: " + funcParamArray[0] + "! ");
                    }
                }
                //ifelse
                else if (funcName.ToLower() == "IfElse".ToLower())
                {
                    var con         = funcParamArray[0];
                    var returnVal   = funcParamArray[1];
                    var returnVal1  = funcParamArray[2];
                    var conArry     = con.Split(con.GetSubParamSeparator());
                    var compareVar  = conArry[0];
                    var compareFlag = conArry[1];
                    var compareVal  = "";
                    if (conArry.Length > 2)
                    {
                        compareVal = conArry[2];
                    }
                    if (compareFlag.ToLower().Trim() == "Contain".ToLower().Trim())
                    {
                        if (compareVar.Contains(compareVal))
                        {
                            if (!string.IsNullOrEmpty(compareVal))
                            {
                                return(returnVal);
                            }
                        }
                    }
                    else if (compareFlag.ToLower().Trim() == "Equal".ToLower().Trim())
                    {
                        if (compareVar == compareVal)
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "VEqual".ToLower())
                    {
                        if (Convert.ToDouble(compareVar) == Convert.ToDouble(compareVal))
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "VGreater".ToLower())
                    {
                        if (Convert.ToDouble(compareVar) > Convert.ToDouble(compareVal))
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "VGreaterEqual".ToLower())
                    {
                        if (Convert.ToDouble(compareVar) >= Convert.ToDouble(compareVal))
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "VLess".ToLower())
                    {
                        if (Convert.ToDouble(compareVar) < Convert.ToDouble(compareVal))
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "VLessEqual".ToLower())
                    {
                        if (Convert.ToDouble(compareVar) <= Convert.ToDouble(compareVal))
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "NotEqual".ToLower())
                    {
                        if (compareVar.Trim() != compareVal.Trim())
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "IsNull".ToLower())
                    {
                        if (compareVar.IsNullOrEmpty())
                        {
                            return(returnVal);
                        }
                    }
                    else if (compareFlag.ToLower() == "IsNotNull".ToLower())
                    {
                        if (!compareVar.IsNullOrEmpty())
                        {
                            return(returnVal);
                        }
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no compare Flag: '" + compareFlag + "'! ");
                    }

                    return(returnVal1);
                } //IfElse ends

                //Status
                else if (funcName.ToLower() == "GetFinalStatus".ToLower())
                {
                    if (funcParamArray.All(v => v.ToLower() == "true"))
                    {
                        return("true");
                    }
                    if (funcParamArray.Any(v => v.ToLower() == "unknown"))
                    {
                        return("unknown");
                    }
                    return("false");
                }

                //getbool
                else if (funcName.ToLower() == "GetBool".ToLower())
                {
                    if (funcParamArray[0].ToLower() == "TotalStatus".ToLower())
                    {
                        var returnStr         = "true";
                        var subfuncParamArray = funcParamArray[1].Split(',');
                        if (subfuncParamArray.Any(v => v.ToLower() != "1"))
                        {
                            returnStr = "false";
                        }
                        return(returnStr);
                    }
                    else if (funcParamArray[0].ToLower() == "And".ToLower())
                    {
                        var returnStr         = "true";
                        var subfuncParamArray = funcParamArray[1].Split(',');
                        if (subfuncParamArray.Any(v => v.ToLower() != "true"))
                        {
                            returnStr = "false";
                        }
                        return(returnStr);
                    }
                    else if (funcParamArray[0].ToLower() == "Or".ToLower())
                    {
                        var returnStr         = "false";
                        var subfuncParamArray = funcParamArray[1].Split(',');
                        if (subfuncParamArray.Any(v => v.ToLower() == "true"))
                        {
                            returnStr = "true";
                        }
                        return(returnStr);
                    }
                    else if (funcParamArray[0].ToLower() == "Not".ToLower())
                    {
                        var returnStr = "true";
                        if (funcParamArray[1].ToLower() == "true")
                        {
                            returnStr = "false";
                        }
                        return(returnStr);
                    }

                    else if (funcParamArray[0].ToLower() == "JudgeStringIsNull".ToLower())
                    {
                        var returnStr = "false";
                        if (string.IsNullOrEmpty(funcParamArray[1]))
                        {
                            returnStr = "true";
                        }
                        return(returnStr);
                    }
                    else if (funcParamArray[0].ToLower() == "JudgeStringIsNotNull".ToLower())
                    {
                        var returnStr = "false";
                        if (!string.IsNullOrEmpty(funcParamArray[1]))
                        {
                            returnStr = "true";
                        }
                        return(returnStr);
                    }
                    else if (funcParamArray[0].ToLower() == "JudgeIfDirectoryExists".ToLower())
                    {
                        var returnStr = "false";
                        if (Directory.Exists(funcParamArray[1]))
                        {
                            returnStr = "true";
                        }
                        return(returnStr);
                    }
                    else if (funcParamArray[0].ToLower() == "JudgeIsDirectoryHidden".ToLower())
                    {
                        if (!Directory.Exists(funcParamArray[1]))
                        {
                            return("false");
                        }
                        var returnStr = "false";
                        var di        = new DirectoryInfo(funcParamArray[1]);
                        if ((di.Attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
                        {
                            returnStr = "true";
                        }
                        return(returnStr);
                    }

                    else if (funcParamArray[0].ToLower() == "VerifyInput".ToLower())
                    {
                        var returnStr    = "false";
                        var dlg          = new TextInputDialog();
                        var verifyRule   = funcParamArray[1];
                        var verifyParams = funcParamArray.Length > 2 ? funcParamArray[2] : "";
                        dlg.VerificationRule   = verifyRule;
                        dlg.VerificationParams = verifyParams;
                        dlg.ShowDialog();
                        returnStr = dlg.IsOk.ToString().ToLower();
                        return(returnStr);
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no param: " + funcParamArray[0] + "! ");
                    }
                }

                else if (funcName.ToLower() == "GetEncryptedText".ToLower())
                {
                    if (funcParamArray[0].ToLower() == "Md5".ToLower())
                    {
                        //return EncryptionHelper.Md5Encrypt(funcParamArray[1]);
                        return(string.Empty);
                    }
                    else if (funcParamArray[0].ToLower() == "Rsa".ToLower())
                    {
                        //return EncryptionHelper.RsaEncrypt(funcParamArray[1]);
                        return(string.Empty);
                    }
                    else if (funcParamArray[0].ToLower() == "Bitwise".ToLower())
                    {
                        //return EncryptionHelper.BitwiseEncrypt(funcParamArray[1]);
                        return(string.Empty);
                    }
                    else if (funcParamArray[0].ToLower() == "Symmetric".ToLower())
                    {
                        return(EncryptionHelper.SmEncrypt(funcParamArray[1]));
                    }
                    else if (funcParamArray[0].ToLower() == "TimeDynamic".ToLower())
                    {
                        return(string.Empty);
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no param: " + funcParamArray[0] + "! ");
                    }
                }

                else if (funcName.ToLower() == "GetDecryptedText".ToLower())
                {
                    if (funcParamArray[0].ToLower() == "Rsa".ToLower())
                    {
                        //return EncryptionHelper.RsaDecrypt(funcParamArray[1]);
                        return(string.Empty);
                    }
                    if (funcParamArray[0].ToLower() == "Symmetric".ToLower())
                    {
                        //return EncryptionHelper.SmDecrypt(funcParamArray[1]);
                        return(string.Empty);
                    }
                    else
                    {
                        throw new ArgumentException("funcName: " + funcName + " has no param: " + funcParamArray[0] + "! ");
                    }
                }

                //xml
                else if (funcName.ToLower() == "GetTableXmlNodeVal".ToLower())
                {
                    var path   = funcParamArray[0];
                    var xmlMgr = new XmlHandler(path);
                    return(xmlMgr.GetNodeInnerTextByTagName(funcParamArray[1], 0));
                }

                //following can be extended to impl in AdapterGetHelper
                else if (funcName.ToLower() == "GetValidationResult".ToLower())
                {
                    var retStr = TextValidationHelper.Validate(funcParamArray[0], funcParamArray[1]);
                    if (retStr == "OutOfScopeOfTextValidationHelper")
                    {
                        return("OutOfScope");
                    }
                    else
                    {
                        return(retStr);
                    }
                }

                else if (funcName.ToLower() == "GetJson".ToLower())
                {
                    return("OutOfScope");
                }

                else
                {
                    return("OutOfScope");
                }
            }
            catch (Exception ex)
            {
                throw new ArgumentException("\n>> " + TypeName + ".GetText error: " + ex.Message);
            }
        }
Exemple #22
0
        public static string ResetPasswordByGroup(string resetData, string groupId, bool sendMail)
        {
            int         siteId  = 0;
            Hashtable   cusHash = EncryptionHelper.Unpack(EncryptionHelper.Decrypt(resetData, cryptKey));
            GCDCustomer retCus  = new GCDCustomer(cusHash);

            retCus.Success = false;

            if (cusHash.ContainsKey("Email") && int.TryParse(groupId, out siteId))
            {
                using (CastleClubEntities entities = new CastleClubEntities())
                {
                    Site site = entities.Sites.FirstOrDefault(x => x.GroupId == siteId.ToString());
                    if (site != null)
                    {
                        siteId = site.Id;
                        string   email    = cusHash["Email"].ToString();
                        Customer customer = entities.Customers.FirstOrDefault(c => c.SiteId == siteId && c.Email == email);
                        if (customer != null)
                        {
                            /*Password password = new Password();
                             * customer.Password = password.SaltedPassword;
                             * customer.SaltKey = password.SaltKey;
                             * entities.SaveChanges();
                             * retCus.Success = true;*/

                            if (sendMail && !string.IsNullOrEmpty(retCus.Password))
                            {
                                string smtpAddress   = CastleClub.BusinessLogic.Data.GlobalParameters.Smtp;
                                string emailFrom     = site.Email;
                                string passwordEmail = site.PasswordEmail; //CastleClub.BusinessLogic.Data.GlobalParameters.EmailPassword;
                                string subject       = string.Format(Properties.Resources.SetPasswordSubjectEmail, site.Name);
                                var    url           = string.Format(GlobalParameters.UrlResetPassword, retCus.Password, retCus.Validator);
                                //pasamos el dominio en password y el guid en validator
                                string body = string.Format(Properties.Resources.SetPasswordBodyEmail, url, site.Name);

                                Utils.Email.SendEmail(emailFrom, passwordEmail, smtpAddress, subject, body, new List <string>()
                                {
                                    customer.Email
                                }, true);
                                retCus.Success = true;
                            }
                            else if (!sendMail && !string.IsNullOrEmpty(retCus.Password))
                            {
                                Password password = new Password(retCus.Password);
                                customer.Password = password.SaltedPassword;
                                customer.SaltKey  = password.SaltKey;
                                entities.SaveChanges();
                                retCus.Success = true;
                            }
                        }
                        else
                        {
                            retCus.Messages = "Invalid Email";
                        }
                    }
                    else
                    {
                        retCus.Messages = "Invalid GroupId";
                    }
                }
            }
            else
            {
                retCus.Messages = "Invalid Email";
            }
            CastleClub.BusinessLogic.Utils.EventViewer.WriteToFile("Log Web Service", retCus.Messages, "c:\\users\\administrator\\desktop\\log.txt");
            return(EncryptionHelper.Encrypt(retCus.ToString(), cryptKey));
        }
Exemple #23
0
 public UserEntity AddUser(UserEntity userEntity)
 {
     userEntity.Password = EncryptionHelper.EncryptSHA256(userEntity.Password);
     return(this.userRepository.AddUser(userEntity));
 }
Exemple #24
0
        public static string CreateCustomer(string data, bool sendEmail)
        {
            try
            {
                var         hash     = EncryptionHelper.Unpack(EncryptionHelper.Decrypt(data, cryptKey));
                GCDSite     site     = new GCDSite(hash);
                GCDCustomer customer = new GCDCustomer(hash);
                customer.CreatedAt = DateTime.Now;
                customer.Success   = false;

                if (!string.IsNullOrEmpty(site.GroupID) && !string.IsNullOrEmpty(customer.CreditCardNumber) && !string.IsNullOrEmpty(customer.Email))
                {
                    CustomerDT customerDT = new CustomerDT()
                    {
                        Address       = customer.Address1,
                        BadLoginCount = 0,
                        CancelledDate = null,
                        City          = customer.City,
                        ClearPassword = customer.Password,
                        CreatedAt     = customer.CreatedAt,
                        Email         = customer.Email,
                        FirstName     = customer.FirstName,
                        LastName      = customer.LastName,
                        MemberId      = customer.MemberID,
                        NcId          = 0,
                        NextBillDate  = DateTime.Now.AddDays(30),
                        Phone         = customer.Phone,
                        StateId       = CastleClub.BusinessLogic.Managers.LocationsManager.GetStates().FirstOrDefault(x => x.Name.ToLower() == customer.State.ToLower()).Id,
                        Status        = CustomerStatus.ACTIVE,
                        ZipCode       = customer.Zip
                    };
                    //var siteDT = CastleClub.BusinessLogic.Managers.SitesManager.GetSite(customerDT.SiteId);
                    customerDT = CastleClub.BusinessLogic.Managers.CustomersManager.NewCustomer(site.GroupID, customerDT, customer.CreditCardNumber, CreditCardHelper.GetExpDate(customer.CreditCardMonthExpired, customer.CreditCardYearExpired));
                    if (customerDT != null)
                    {
                        customer.Success = true;

                        //if (sendEmail)

                        /****
                        *  if ((siteDT.SendWelcomeEmail) && (siteDT.WelcomeEmailDelay != null) && (siteDT.WelcomeEmailDelay == 0))
                        *   //send welcome email if it hasn't a delay
                        *  {
                        *   string smtpAddress = siteDT.SmtpAddress;//CastleClub.BusinessLogic.Data.GlobalParameters.Smtp;
                        *   //var siteDT = CastleClub.BusinessLogic.Managers.SitesManager.GetSite(customerDT.SiteId);
                        *
                        *   string emailFrom = siteDT.Email;
                        *   string passwordEmail = siteDT.PasswordEmail;//CastleClub.BusinessLogic.Data.GlobalParameters.EmailPassword;
                        *   string subject = string.Format(Properties.Resources.WelcomeSubjectEmail, siteDT.Name);
                        *   // + " " + customer.LastName
                        *   string body = string.Format(Properties.Resources.WelcomeBodyEmail, customer.FirstName,
                        *                               customer.Email, customer.Password, siteDT.Name, siteDT.Name, "PartsGeek",
                        *                               siteDT.Price, siteDT.PricePerQuarter, siteDT.Phone, siteDT.Email, siteDT.OfferDomain);
                        *
                        *   Utils.Email.SendEmail(emailFrom, passwordEmail, smtpAddress, subject, body, new List<string>() { customer.Email }, true);
                        *  }
                        * **/
                    }
                }
                else
                {
                    customer.Messages = "Credit card and email are necessary.";
                }
                return(EncryptionHelper.Encrypt(customer.ToString(), cryptKey));
            }catch (Exception e)
            {
                Utils.EventViewer.Writte("WEBSERVICE", "Create Customers", e.Message + " " + e.StackTrace, System.Diagnostics.EventLogEntryType.Error);
                throw e;
            }
        }
Exemple #25
0
 public SqlServerConnectionProvider(IOptions <ConnectionProviderOptions> connProvOpts, EncryptionHelper encHelper)
 {
     _connectionProviderOptions = connProvOpts;
     _encryptionHelper          = encHelper;
 }
Exemple #26
0
        public static string UpdateCustomer(string customerData, bool sendEmail)
        {
            int           updateCustomerId = 0;
            Hashtable     cusHash          = EncryptionHelper.Unpack(EncryptionHelper.Decrypt(customerData, cryptKey));
            GCDCustomer   retCus           = new GCDCustomer(cusHash);
            GCDCreditCard retCreditCard    = new GCDCreditCard(cusHash);

            retCus.Success = false;
            if (cusHash.ContainsKey("CustomerID") && int.TryParse(cusHash["CustomerID"].ToString(), out updateCustomerId))
            {
                using (CastleClubEntities entities = new CastleClubEntities())
                {
                    Customer customer = entities.Customers.Where(c => c.Id == updateCustomerId).FirstOrDefault();
                    if (customer != null)
                    {
                        Password passwordHash = new Password(cusHash["PasswordOld"].ToString(), customer.SaltKey);
                        if (customer.Password == passwordHash.SaltedPassword)
                        {
                            customer.FirstName = retCus.FirstName;
                            customer.LastName  = retCus.LastName;
                            customer.Address   = retCus.Address1;
                            customer.City      = retCus.City;
                            State state = entities.States.FirstOrDefault(s => s.Name.ToLower() == retCus.State.ToLower());
                            customer.StateId = state != null?state.Id.ToString() : string.Empty;

                            customer.Email   = retCus.Email;
                            customer.Phone   = retCus.Phone;
                            customer.ZipCode = retCus.Zip;

                            var creditCard = customer.CreditCards.FirstOrDefault();
                            if (creditCard != null && !string.IsNullOrEmpty(retCreditCard.CreditCard) && Utils.CreditCardHelper.Valid(retCreditCard.CreditCard, false))
                            {
                                var today = DateTime.Now;
                                if (today.Year > retCus.CreditCardYearExpired || (today.Year == retCus.CreditCardYearExpired && today.Month >= retCreditCard.Month))
                                {
                                    throw new Exception("The credit card is invalid.");
                                }

                                var    encryptData   = CastleClub.BusinessLogic.Utils.EncryptionHelper.EncryptRSACertificate("ccNum:" + retCreditCard.CreditCard + ";cVV:;ccExp:" + Utils.CreditCardHelper.GetExpDate(retCreditCard.Month, retCreditCard.Year));
                                string lastFourDigit = retCreditCard.CreditCard.Substring(retCreditCard.CreditCard.Length - 4, 4);
                                string type          = Utils.CreditCardHelper.GetCardType(retCreditCard.CreditCard);

                                creditCard.CreatedAt     = DateTime.Now;
                                creditCard.Data          = encryptData;
                                creditCard.LastFourDigit = lastFourDigit;
                                creditCard.Type          = type;

                                long   newPaymentProfile;
                                string message = string.Empty;
                                if (CastleClub.BusinessLogic.AuthorizeAPI.CIM.CreateNewCustomerPaymentProfile(customer.Site.GetDT(), customer.GetDT(false), retCreditCard.CreditCard, Utils.CreditCardHelper.GetExpDate(retCreditCard.Month, retCreditCard.Year), out newPaymentProfile, out message))
                                {
                                    creditCard.AuthorizePaymentProfileId = newPaymentProfile;
                                }
                                else
                                {
                                    throw new Exception(message);
                                }
                            }

                            bool setPassword = false;
                            if (!string.IsNullOrEmpty(retCus.PasswordNow))
                            {
                                Password password = new Password(retCus.PasswordNow);
                                customer.Password = password.SaltedPassword;
                                customer.SaltKey  = password.SaltKey;
                                setPassword       = true;
                            }

                            retCus.Success = true;

                            entities.SaveChanges();

                            if (sendEmail && setPassword)
                            {
                                string smtpAddress   = CastleClub.BusinessLogic.Data.GlobalParameters.Smtp;
                                string emailFrom     = customer.Site.Email;
                                string passwordEmail = customer.Site.PasswordEmail; //CastleClub.BusinessLogic.Data.GlobalParameters.EmailPassword;
                                string subject       = string.Format(Properties.Resources.SetPasswordSubjectEmail, customer.Site.Name);
                                string body          = string.Format(Properties.Resources.SetPasswordBodyEmail, customer.Site.Name, retCus.PasswordNow);

                                Utils.Email.SendEmail(emailFrom, passwordEmail, smtpAddress, subject, body, new List <string>()
                                {
                                    customer.Email
                                }, false);
                            }
                        }
                        else
                        {
                            retCus.Success  = false;
                            retCus.Messages = "The password for the customer not match.";
                        }
                    }
                    else
                    {
                        retCus.Messages = "Error custmer ID.";
                    }
                }
            }
            return(EncryptionHelper.Encrypt(retCus.ToString(), cryptKey));
        }
 public void EncryptStringAes_ReturnsSameValue_WhenDecrypted()
 {
     Assert.Equal(source, EncryptionHelper.DecryptStringAes(EncryptionHelper.EncryptStringAes(source, "123456", "ABCDEFGHIJK"), "123456", "ABCDEFGHIJK"));
 }
Exemple #28
0
        public ActionResult SignIn(UserCommon model)
        {
            //Uri myUrl= Request.Url;           //to get working url
            //var action = myUrl.LocalPath;
            //RedirectToRoute(action);
            string ip      = Request.ServerVariables["REMOTE_ADDR"];
            string browser = Request.Browser.Browser + " Version :" + Request.Browser.Version;

            var user     = model.Email;
            var password = EncryptionHelper.Encrypt(model.Password);
            var response = buss.SignIn(user, password);

            if (response.UserId != null)
            {
                Session["AccountType"]    = response.AccountType;
                Session["FirstName"]      = response.FirstName;
                Session["MiddleName"]     = response.MiddleName;
                Session["LastName"]       = response.LastName;
                Session["UserId"]         = response.UserId;
                Session["User"]           = response.User;
                Session["Address"]        = response.Address;
                Session["District"]       = response.District;
                Session["State"]          = response.State;
                Session["Country"]        = response.Country;
                Session["MobileNo"]       = response.MobileNo;
                Session["Email"]          = response.Email;
                Session["BirthDate"]      = response.BirthDate;
                Session["Gender"]         = response.Gender;
                Session["ShopAddress"]    = response.ShopAddress;
                Session["Language"]       = response.Language;
                Session["StoreName"]      = response.StoreName;
                Session["StoreAddress"]   = response.StoreAddress;
                Session["StoreNo"]        = response.StoreNo;
                Session["PANNO"]          = response.PANNO;
                Session["ProductType"]    = response.ProductType;
                Session["StoreContactNo"] = response.StoreContactNo;
                Session["Longitude"]      = response.Longitude;
                Session["Latitude"]       = response.Latitude;
                int check = this.HttpContext.Session.Timeout = 40;
            }
            else
            {
                ViewData["msg"] = "The user name or password provided is incorrect.";
                //DbResponse resp = new DbResponse();
                //resp.ErrorCode = 1;
                //resp.Message = "Email Or Password Is Not valid";
                //StaticData.SetMessageInSession(resp);
                return(View(model));
            }

            var action = Session["Action"].ToString();

            if (response.PANNO != "" && action == "/")
            {
                return(RedirectToAction("SupplierDashboard"));// View("SupplierDashboard");
            }
            if (action == "/ProductDetail/Search")
            {
                return(RedirectToAction("Index", "Home"));
            }
            return(Redirect(action));
        }
        public static string CreateSessionCookie(AuthToken token)
        {
            string encryptedToken = Convert.ToBase64String(EncryptionHelper.EncryptToken(token.AsBytes()));

            return(HttpUtility.UrlEncode(encryptedToken));
        }
Exemple #30
0
        public void TestHelperEncrypteDecryptSerialize()
        {
            #region longstring for testing
            string testString =
                @"
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ  
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ  
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ  
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ  
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ  
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ
                    ABCDEFGHIJKLMNOPQRSTUVWXYZ      
                    ";
            #endregion

            int size = 0;

            EncryptedItem item = EncryptionHelper.Encrypt(
                Encoding.Unicode.GetBytes(testString));
            size = item.EncryptedSize;

            string testPath = Path.Combine(
                AppDomain.CurrentDomain.BaseDirectory,
                @"..\..\TestData\Encryption\TestingSerialize.enc");

            File.WriteAllBytes(
                testPath, Encoding.Unicode.GetBytes(item.ToString()));

            byte[] encryptedFile = File.ReadAllBytes(testPath);

            EncryptedItem tmpItem =
                EncryptedItem.FromXml(
                    Encoding.Unicode.GetString(encryptedFile));

            Assert.AreEqual(size, tmpItem.EncryptedSize);
            string result =
                Encoding.Unicode.GetString(EncryptionHelper.Decrypt(item));

            Assert.AreNotEqual(
                testString, Encoding.Unicode.GetString(item.Data));
            Assert.AreEqual(testString, result);
            File.Delete(testPath);
        }
 public void TestConstructorSucceeds()
 {
     var encryptionHelper = new EncryptionHelper(testFileDeploymentDirectory);
     encryptionHelper.Should().NotBeNull("Constructor failed");
 }
        private static async Task ProtectedAddFifty(string[] Integer)
        {
            try
            {
                Console.WriteLine(WaitMessage);
                if (_APIKey == null)
                {
                    throw new Exception(EmptyUser);
                }
                if (_PublicKey == null)
                {
                    throw new Exception("Client doesn’t yet have the public key");
                }
                string number = (Integer.Length == 0) ? "" : Integer[0];
                if (!int.TryParse(number, out int testInput))
                {
                    throw new Exception("A valid integer must be given!");
                }

                client.DefaultRequestHeaders.Add("APIKey", _APIKey);

                _AES.GenerateKey();
                _AES.GenerateIV();
                _RSA.FromXmlStringCore22(_PublicKey);

                byte[] byteInteger      = BitConverter.GetBytes(int.Parse(number));
                byte[] encryptedInteger = _RSA.Encrypt(byteInteger, true);
                var    hexInteger       = EncryptionHelper.ByteArrayToHexString(encryptedInteger);

                byte[] encryptedAESKey = _RSA.Encrypt(_AES.Key, true);
                var    hexAESKey       = EncryptionHelper.ByteArrayToHexString(encryptedAESKey);

                byte[] encryptedAESIV = _RSA.Encrypt(_AES.IV, true);
                var    hexAESIV       = EncryptionHelper.ByteArrayToHexString(encryptedAESIV);

                string path = "api/protected/addfifty?encryptedInteger=" + hexInteger
                              + "&encryptedSymKey=" + hexAESKey + "&encryptedIV=" + hexAESIV;

                Task <string> task = GetStringAsync(path);
                if (await Task.WhenAny(task, Task.Delay(5000)) == task)
                {
                    var result = await EncryptionHelper.AESDecrypt(task.Result, _AES.Key, _AES.IV);

                    if (!int.TryParse(result, out int testResult) || int.Parse(result) != int.Parse(Integer[0]) + 50)
                    {
                        throw new Exception("An error occurred!");
                    }

                    Console.WriteLine(result);
                }

                else
                {
                    throw new TimeoutException("Resquest Time Out");
                }
                MainMenu();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);

                MainMenu();
            }
        }
Exemple #33
0
        public static string LogonSecureByGroup(string logonData, string groupId)
        {
            GCDCustomer retCus = new GCDCustomer();

            retCus.Success       = false;
            retCus.AccountLocked = false;

            if (string.IsNullOrEmpty(groupId))
            {
                groupId = "1181";
            }

            using (CastleClubEntities entities = new CastleClubEntities())
            {
                Site site = entities.Sites.Where(s => s.GroupId == groupId).FirstOrDefault();
                if (site != null)
                {
                    string   li   = EncryptionHelper.Decrypt(logonData, cryptKey);
                    string[] linf = li.Split('&');

                    if (linf.Length == 2)
                    {
                        string[] cinf  = linf[0].Split('=');
                        string[] pinf  = linf[1].Split('=');
                        string   email = cinf[1];

                        if (cinf.Length == 2 && pinf.Length == 2)
                        {
                            Customer customer = entities.Customers.Where(c => c.SiteId == site.Id && c.Email == email).FirstOrDefault();
                            if (customer != null)
                            {
                                string   chkPass = pinf[1];
                                Password pwd     = new Password(chkPass, customer.SaltKey);
                                if (customer.BadLoginCount < 5 && customer.Password == pwd.SaltedPassword)
                                {
                                    if (customer.Status != CustomerStatus.ACTIVE)
                                    {
                                        retCus.Messages = "Customer Account Not Found, Invalid or Cancelled";
                                    }
                                    else
                                    {
                                        retCus.FirstName    = customer.FirstName;
                                        retCus.LastName     = customer.LastName;
                                        retCus.Address1     = customer.Address;
                                        retCus.Address2     = String.Empty;
                                        retCus.City         = customer.City;
                                        retCus.State        = entities.States.Where(s => s.Id == customer.StateId).FirstOrDefault().Name;
                                        retCus.Country      = "USA";
                                        retCus.Email        = customer.Email;
                                        retCus.Phone        = customer.Phone;
                                        retCus.CustomerID   = customer.Id;
                                        retCus.RegisterDate = customer.CreatedAt;
                                        retCus.MemberID     = "M" + site.GroupId + "-" + customer.Id;
                                        retCus.Validator    = logonData;
                                        retCus.Success      = true;
                                        retCus.Zip          = customer.ZipCode;

                                        retCus.CreatedAt = customer.CreatedAt;
                                        var creditCard = customer.CreditCards.FirstOrDefault();
                                        if (creditCard != null)
                                        {
                                            retCus.CreditCardNumber       = creditCard.LastFourDigit;
                                            retCus.CreditCardType         = creditCard.Type;
                                            retCus.CreditCardMonthExpired = 1;
                                            retCus.CreditCardYearExpired  = DateTime.Now.Year;
                                        }

                                        customer.BadLoginCount = 0;
                                        entities.SaveChanges();
                                    }
                                }
                                else
                                {
                                    retCus.Messages = "Logon Failed";
                                    if (customer.BadLoginCount > 4)
                                    {
                                        retCus.AccountLocked = true;
                                    }
                                    else
                                    {
                                        customer.BadLoginCount = customer.BadLoginCount + 1;
                                        entities.SaveChanges();

                                        retCus.AccountLocked = false;
                                    }
                                }
                            }
                        }
                    }
                    else
                    {
                        retCus.Messages = "Missing or Null Data Field";
                    }

                    if (retCus.Success == false && retCus.Messages.Length == 0)
                    {
                        retCus.Messages = "Logon Failed";
                    }
                    return(EncryptionHelper.Encrypt(retCus.ToString(), cryptKey));
                }
                else
                {
                    return(String.Empty);
                }
            }
        }
Exemple #34
0
 public void AddUser(ulong discordId, string serliazedData)
 {
     Query($@"INSERT INTO users (discordInfo, serializedData) values (""{discordId}"", ""{
             EncryptionHelper.Encrypt(serliazedData)
         }"")");
 }
Exemple #35
0
        /// <summary>
        /// 初始化配置
        /// </summary>
        /// <param name="config">配置对象</param>
        /// <param name="element">XML流</param>
        public static void ConfigureFromXML(ConfigSection config, XmlElement element)
        {
            XmlNodeList list1 = element.GetElementsByTagName("DomainDataProvider");

            if (list1.Count == 0)
            {
                //throw new Exception("ConfigSection: XML configuration does not contain a <DomainDataProvider> element. Configuration Aborted.");
                ExceptionManager.Raise(typeof(ConfigSection), "$Error_XML_Configuration_DataProvider", null, null);
            }
            if (list1.Count > 1)
            {
                //throw new Exception("ConfigSection: XML configuration contains [" + list1.Count + "] <DomainDataProvider> elements. Only one is allowed. Configuration Aborted.");
                ExceptionManager.Raise(typeof(ConfigSection), "$Error_XML_Configuration_Contain_DataProvider", string.Format("[$ListCount={0}]", list1.Count), null);
            }

            if (list1[0].Attributes["Type"] == null)
            {
                //throw new Exception("ConfigSection: element <DomainDataProvider> does not contain an attribute <Type> . Configuration Aborted.");
                ExceptionManager.Raise(typeof(ConfigSection), "$Error_DomainDataProvider_Type", null, null);
            }
            config.DomainSetting.DataProviderType = list1[0].Attributes["Type"].Value;

            XmlNodeList listPersistBrokers = element.GetElementsByTagName("PersistBroker");

            if (listPersistBrokers.Count == 0)
            {
                //throw new Exception("ConfigSection: XML configuration does not contain a <PersistBroker> element. Configuration Aborted.");
                ExceptionManager.Raise(typeof(ConfigSection), "$Error_DomainDataProvider_PersistBroker", null, null);
            }
            else
            {
                foreach (XmlNode item in listPersistBrokers)
                {
                    PersistBrokerSetting setting = new PersistBrokerSetting();
                    setting.Text              = item.Attributes["Text"].Value;
                    setting.Name              = item.Attributes["Name"].Value;
                    setting.Default           = bool.Parse(item.Attributes["Default"].Value);
                    setting.PersistBrokerType = item.Attributes["Type"].Value;
                    setting.NLS           = item.Attributes["NLS"].Value;
                    setting.ConnectString = EncryptionHelper.DESDecryption(item.Attributes["ConnectString"].Value);

                    if (setting.PersistBrokerType == "ODPPersistBroker" && setting.ConnectString.ToUpper().IndexOf("PROVIDER") >= 0)
                    {
                        int i1 = setting.ConnectString.ToUpper().IndexOf("PROVIDER");
                        int i2 = setting.ConnectString.ToUpper().IndexOf(";", i1);
                        if (i2 < 0)
                        {
                            i2 = setting.ConnectString.Length - 1;
                        }
                        setting.ConnectString = setting.ConnectString.Remove(i1, i2 - i1 + 1);
                    }

                    config.DomainSetting.AddSetting(setting);

                    //if (setting.Default)
                    //{
                    //    config.DomainSetting.PersistBrokerType = setting.PersistBrokerType;
                    //    config.DomainSetting.ConnectString = setting.ConnectString;
                    //}
                }
            }

            #region old flow

            /* //marked by carey.cheng on 2010-05-19 for muti db support
             *          XmlNodeList list2 = element.GetElementsByTagName("PersistBroker");
             *          if (list2.Count == 0)
             *          {
             *                  //throw new Exception("ConfigSection: XML configuration does not contain a <PersistBroker> element. Configuration Aborted.");
             *                  ExceptionManager.Raise(typeof(ConfigSection),"$Error_DomainDataProvider_PersistBroker",null,null);
             *
             *          }
             *          if (list2.Count > 1)
             *          {
             *                  //throw new Exception("ConfigSection: XML configuration contains [" + list2.Count + "] <PersistBroker> elements. Only one is allowed. Configuration Aborted.");
             *                  ExceptionManager.Raise(typeof(ConfigSection),"$Error_DomainDataProvider_PersistBroker_Contain_More_Than_One",string.Format("[$listCount={0}]", list2.Count),null);
             *          }
             *
             *          if (list2[0].Attributes["Type"] == null)
             *          {
             *                  //throw new Exception("ConfigSection: element <PersistBroker> does not contain an attribute <Type> . Configuration Aborted.");
             *                  ExceptionManager.Raise(typeof(ConfigSection),"$Error_DomainDataProvider_PersistBroker_Type",null,null);
             *          }
             *
             *          if (list2[0].Attributes["ConnectString"] == null)
             *          {
             *                  //throw new Exception("ConfigSection: element <PersistBroker> does not contain an attribute <ConnectString> . Configuration Aborted.");
             *                  ExceptionManager.Raise(typeof(ConfigSection),"$Error_DomainDataProvider_PersistBroker_ConnectString",null,null);
             *          }
             *
             *          if (list2[0].Attributes["IsPool"] == null)
             *          {
             *                  config.DomainSetting.IsPool  = 0;
             *          }
             *          else
             *          {
             *                  config.DomainSetting.IsPool = config.DomainSetting.PoolSize = System.Int32.Parse (list2[0].Attributes["IsPool"].Value);
             *          }
             *
             *          if (list2[0].Attributes["PoolSize"] == null)
             *          {
             *                  config.DomainSetting.PoolSize = 1;
             *                  //				//throw new Exception("ConfigSection: element <PersistBroker> does not contain an attribute <ConnectString> . Configuration Aborted.");
             *                  //				ExceptionManager.Raise(typeof(ConfigSection),"$Error_DomainDataProvider_PersistBroker_PoolSize",null,null);
             *          }
             *          else
             *          {
             *                  config.DomainSetting.PoolSize = System.Int32.Parse (list2[0].Attributes["PoolSize"].Value);
             *          }
             *
             *          XmlNodeList list3 = element.GetElementsByTagName("RealTimeReportAutoRefresh");
             *          if (list3.Count == 0)
             *          {
             *                  //throw new Exception("ConfigSection: XML configuration does not contain a <DomainDataProvider> element. Configuration Aborted.");
             *                  //ExceptionManager.Raise(typeof(ConfigSection),"$Error_XML_Configuration_RealTimeReportAutoRefresh",null,null);
             *                  config.DomainSetting.Interval  = 300000;
             *          }
             *          else
             *          {
             *                  if(list3[0].Attributes["Seconds"] != null)
             *                  {
             *                          config.DomainSetting.Interval = System.Int32.Parse(list3[0].Attributes["Seconds"].Value);
             *                  }
             *                  else
             *                  {
             *                          config.DomainSetting.Interval  = 300000;
             *                   }
             *          }
             *
             *          XmlNodeList list4 = element.GetElementsByTagName("DateRange");
             *          if (list4.Count == 0)
             *          {
             *                  //throw new Exception("ConfigSection: XML configuration does not contain a <DomainDataProvider> element. Configuration Aborted.");
             *                  //ExceptionManager.Raise(typeof(ConfigSection),"$Error_XML_Configuration_RealTimeReportAutoRefresh",null,null);
             *                  config.DomainSetting.MaxDateRange  = 30;
             *          }
             *          else
             *          {
             *                  if(list4[0].Attributes["Max"] != null)
             *                  {
             *                          config.DomainSetting.MaxDateRange = System.Int32.Parse(list4[0].Attributes["Max"].Value);
             *                  }
             *                  else
             *                  {
             *                          config.DomainSetting.MaxDateRange  = 30;
             *                  }
             *          }
             *
             *
             *          config.DomainSetting.PersistBrokerType = list2[0].Attributes["Type"].Value;
             *          //sammer kong encryption
             *          config.DomainSetting.ConnectString = EncryptionHelper.DESDecryption(list2[0].Attributes["ConnectString"].Value);
             *          // Added by Icyer 2006/11/03
             *          if (config.DomainSetting.PersistBrokerType == "ODPPersistBroker")
             *          {
             *                  if (config.DomainSetting.ConnectString.ToUpper().IndexOf("PROVIDER") >= 0)
             *                  {
             *                          int i1 = config.DomainSetting.ConnectString.ToUpper().IndexOf("PROVIDER");
             *                          int i2 = config.DomainSetting.ConnectString.ToUpper().IndexOf(";", i1);
             *                          if (i2 < 0)
             *                                  i2 = config.DomainSetting.ConnectString.Length - 1;
             *                          config.DomainSetting.ConnectString = config.DomainSetting.ConnectString.Remove(i1, i2 - i1 + 1);
             *                  }
             *          }
             *          // Added end
             *
             *          //SPC connection string
             *          XmlNodeList list5 = element.GetElementsByTagName("SPCPersistBroker");
             *          if(list5.Count > 0)
             *          {
             *                  config.DomainSetting.SPCConnectString = EncryptionHelper.DESDecryption(list5[0].Attributes["ConnectString"].Value);
             *                  config.DomainSetting.SPCPersistBrokerType = list5[0].Attributes["Type"].Value;
             *                  // Added by Icyer 2006/11/03
             *                  if (config.DomainSetting.SPCPersistBrokerType == "ODPPersistBroker")
             *                  {
             *                          if (config.DomainSetting.SPCConnectString.ToUpper().IndexOf("PROVIDER") >= 0)
             *                          {
             *                                  int i1 = config.DomainSetting.SPCConnectString.ToUpper().IndexOf("PROVIDER");
             *                                  int i2 = config.DomainSetting.SPCConnectString.ToUpper().IndexOf(";", i1);
             *                                  if (i2 < 0)
             *                                          i2 = config.DomainSetting.SPCConnectString.Length - 1;
             *                                  config.DomainSetting.SPCConnectString = config.DomainSetting.SPCConnectString.Remove(i1, i2 - i1 + 1);
             *                          }
             *                  }
             *                  // Added end
             *          }
             *
             *          //SAP DB connection string
             *          XmlNodeList listSAP = element.GetElementsByTagName("SAPDBPersistBroker");
             *          if(listSAP.Count > 0)
             *          {
             *                  config.DomainSetting.SAPDBConnectString = EncryptionHelper.DESDecryption(listSAP[0].Attributes["ConnectString"].Value);
             *                  config.DomainSetting.SAPDBPersistBrokerType = listSAP[0].Attributes["Type"].Value;
             *                  // Added by Icyer 2006/11/03
             *                  if (config.DomainSetting.SAPDBPersistBrokerType == "ODPPersistBroker")
             *                  {
             *                          if (config.DomainSetting.SAPDBConnectString.ToUpper().IndexOf("PROVIDER") >= 0)
             *                          {
             *                                  int i1 = config.DomainSetting.SAPDBConnectString.ToUpper().IndexOf("PROVIDER");
             *                                  int i2 = config.DomainSetting.SAPDBConnectString.ToUpper().IndexOf(";", i1);
             *                                  if (i2 < 0)
             *                                          i2 = config.DomainSetting.SAPDBConnectString.Length - 1;
             *                                  config.DomainSetting.SAPDBConnectString = config.DomainSetting.SAPDBConnectString.Remove(i1, i2 - i1 + 1);
             *                          }
             *                  }
             *                  // Added end
             *          }
             *
             *
             *
             *          //ERP DB connection string
             *          XmlNodeList listERP = element.GetElementsByTagName("ODBCPersistBroker");
             *          if(listERP.Count > 0)
             *          {
             *                  config.DomainSetting.ERPConnectString = EncryptionHelper.DESDecryption(listERP[0].Attributes["ConnectString"].Value);
             *                  config.DomainSetting.ERPPersistBrokerType = listERP[0].Attributes["Type"].Value;
             *                  // Added by Icyer 2006/11/03
             *                  if (config.DomainSetting.ERPPersistBrokerType == "ODPPersistBroker")
             *                  {
             *                          if (config.DomainSetting.ERPConnectString.ToUpper().IndexOf("PROVIDER") >= 0)
             *                          {
             *                                  int i1 = config.DomainSetting.ERPConnectString.ToUpper().IndexOf("PROVIDER");
             *                                  int i2 = config.DomainSetting.ERPConnectString.ToUpper().IndexOf(";", i1);
             *                                  if (i2 < 0)
             *                                          i2 = config.DomainSetting.ERPConnectString.Length - 1;
             *                                  config.DomainSetting.ERPConnectString = config.DomainSetting.ERPConnectString.Remove(i1, i2 - i1 + 1);
             *                          }
             *                  }
             *                  // Added end
             *          }
             *
             *          //His DB connection string
             *          XmlNodeList listHIS = element.GetElementsByTagName("HisPersistBroker");
             *          if(listHIS.Count > 0)
             *          {
             *                  config.DomainSetting.HisConnectString = EncryptionHelper.DESDecryption(listHIS[0].Attributes["ConnectString"].Value);
             *                  config.DomainSetting.HisPersistBrokerType = listHIS[0].Attributes["Type"].Value;
             *                  // Added by Icyer 2006/11/03
             *                  if (config.DomainSetting.HisPersistBrokerType == "ODPPersistBroker")
             *                  {
             *                          if (config.DomainSetting.HisConnectString.ToUpper().IndexOf("PROVIDER") >= 0)
             *                          {
             *                                  int i1 = config.DomainSetting.HisConnectString.ToUpper().IndexOf("PROVIDER");
             *                                  int i2 = config.DomainSetting.HisConnectString.ToUpper().IndexOf(";", i1);
             *                                  if (i2 < 0)
             *                                          i2 = config.DomainSetting.HisConnectString.Length - 1;
             *                                  config.DomainSetting.HisConnectString = config.DomainSetting.HisConnectString.Remove(i1, i2 - i1 + 1);
             *                          }
             *                  }
             *                  // Added end
             *          }
             */
            #endregion

            //JobClassName 导入日志类型
            XmlNodeList listJobClass = element.GetElementsByTagName("MESJobClassName");
            if (listJobClass.Count > 0)
            {
                config.DomainSetting.MESJobClassName = listJobClass[0].Attributes["Type"].Value;
            }

            // Added By Hi1/venus.feng on 20080813 for Hisense Version : Add change NLS_LANG register
            XmlNodeList listNLS = element.GetElementsByTagName("NLSRegister");
            if (listNLS.Count > 0)
            {
                if (listNLS[0].Attributes["NLSDIR"] != null)
                {
                    config.DomainSetting.NLSDIR = listNLS[0].Attributes["NLSDIR"].Value;
                }
                else
                {
                    config.DomainSetting.NLSDIR = string.Empty;
                }
                //marked by carey.cheng on 2010-05-19 for muti db support
                //if (listNLS[0].Attributes["NLS"] != null)
                //{
                //    config.DomainSetting.NLS = listNLS[0].Attributes["NLS"].Value;
                //}
                //else
                //{
                //    config.DomainSetting.NLS = string.Empty;
                //}
                //end marked by carey.cheng on 2010-05-19 for muti db support
            }

            XmlNodeList list3 = element.GetElementsByTagName("RealTimeReportAutoRefresh");
            if (list3.Count == 0)
            {
                //throw new Exception("ConfigSection: XML configuration does not contain a <DomainDataProvider> element. Configuration Aborted.");
                //ExceptionManager.Raise(typeof(ConfigSection),"$Error_XML_Configuration_RealTimeReportAutoRefresh",null,null);
                config.DomainSetting.Interval = 300000;
            }
            else
            {
                if (list3[0].Attributes["Seconds"] != null)
                {
                    config.DomainSetting.Interval = System.Int32.Parse(list3[0].Attributes["Seconds"].Value);
                }
                else
                {
                    config.DomainSetting.Interval = 300000;
                }
            }
            // End Added
        }
Exemple #36
0
        public override int Execute(string[] args)
        {
            // sanity check
            if (args.Length != 6)
            {
                throw new ArgumentException("incorrect number of arguments");
            }

            Progress.Message = "Searching";
            var  filePattern     = args[1];
            var  pretag          = args[2];
            var  key             = args[3];
            var  salt            = args[4];
            bool deleteEncrypted = true;

            bool.TryParse(args[5], out deleteEncrypted);

            var root = Directory.GetCurrentDirectory();

            IO.CheckRootAndPattern(ref root, ref filePattern);
            var files = IO.GetAllFiles(root, filePattern);

            if (!this.commandHub.NoWarning)
            {
                if (this.commandHub.Debug)
                {
                    foreach (string file in files)
                    {
                        ConsoleHelper.Write("found: ", ConsoleColor.Cyan);
                        ConsoleHelper.WriteLine(StringHelper.TrimStart(file, root.Length));
                    }
                }

                ConsoleHelper.WriteLine(files.Count.ToString() + " file" + ((files.Count != 1) ? "s" : "") + " found");
            }

            int counter = 0;

            if (files.Count > 0)
            {
                foreach (string file in files)
                {
                    Progress.Message = "Decrypting " + StringHelper.TrimStart(file, root.Length);

                    try
                    {
                        var fileName       = Path.GetFileName(file);
                        var fileRoot       = Path.GetDirectoryName(file);
                        var encryptedName  = pretag + "." + fileName;
                        var dencryptedPath = Path.Combine(fileRoot, encryptedName);

                        string decryptedName;
                        if (fileName.StartsWith(pretag + "."))
                        {
                            decryptedName = StringHelper.TrimStart(fileName, (pretag + ".").Length);
                        }
                        else if (fileName.StartsWith(pretag))
                        {
                            decryptedName = StringHelper.TrimStart(fileName, pretag.Length);
                        }
                        else
                        {
                            decryptedName = "decrpyted." + fileName;
                        }

                        var decryptedPath = Path.Combine(fileRoot, decryptedName);
                        EncryptionHelper.DecryptFile(file, decryptedPath, key, salt);
                        counter++;
                        ConsoleHelper.WriteLine("File: " + decryptedName + " decrypted", ConsoleColor.DarkYellow);

                        if (deleteEncrypted)
                        {
                            File.Delete(file);
                        }
                    }
                    catch (Exception ex)
                    {
                        ConsoleHelper.Write("failed: ", ConsoleColor.Red);
                        ConsoleHelper.WriteLine(StringHelper.TrimStart(file, root.Length));

                        if (this.commandHub.Debug)
                        {
                            ConsoleHelper.WriteException(ex);
                        }
                    }
                }
            }

            ConsoleHelper.WriteLine(counter.ToString() + " File" + ((counter != 1) ? "s" : "") + " Dencrypted", ConsoleColor.DarkYellow);
            return(ConsoleHelper.EXIT_OK);
        }