Esempio n. 1
0
        private void ButtonBase_OnClick(object sender, RoutedEventArgs e)
        {
            Bitmap bitmap = camera.Capture();
            string base64 = Encode.Base64Encode(bitmap);

            File.WriteAllText(@"c:\image.txt", base64);
        }
Esempio n. 2
0
        /// <summary>
        /// Convert an array byte to string
        /// </summary>
        /// <param name="bytes">bytes</param>
        /// <param name="encode">encode</param>
        /// <returns></returns>
        public static string ToString(this Byte[] bytes, Encode encode)
        {
            string result = null;

            switch (encode)
            {
            case Encode.UTF8:
                result = System.Text.Encoding.UTF8.GetString(bytes);
                break;

            case Encode.Base64:
                result = Convert.ToBase64String(bytes, 0, bytes.Length);
                break;

            case Encode.Bit:
                result = BitConverter.ToString(bytes);
                break;

            case Encode.ASCII:
                result = new string(ASCIIEncoding.Default.GetChars(bytes));
                break;
            }

            return(result);
        }
Esempio n. 3
0
        static PhysicalData DefaultPhysicalData(Coordinates initPosition)
        {
            var bytesPos        = Bytes.FromBackingArray(Encode.Vector3f((float)initPosition.x, (float)initPosition.y, (float)initPosition.z));
            var shipPhysicsData = new PhysicalData(bytesPos, Bytes.FromBackingArray(new byte[6]), Bytes.FromBackingArray(new byte[7]), Bytes.FromBackingArray(new byte[6]), 0f, 0f);

            return(shipPhysicsData);
        }
Esempio n. 4
0
        private string ReadString(int i)
        {
            var value = Encode.GetString(orginal.Slice(offset, i).Span);

            offset += i + 1;
            return(value);
        }
        protected void ButtonNewStartTime_Click(object sender, EventArgs e)
        {
            DateTime t0 = new DateTime(); DateTime t1 = new DateTime();

            t0 = System.Convert.ToDateTime(Label_EditTime.Text);//recover the current start time
            try
            {
                t1 = System.Convert.ToDateTime(TextBox_NewStartTime.Text);//recover the new time
                ScheduledComponentList scl1 = new ScheduledComponentList();
                scl1.LoadList(t0.AddMinutes(-1), t0.AddMinutes(1), Label_EditComponentID.Text);
                foreach (ScheduledComponent sc in scl1.m_List)
                {
                    sc.m_Date = t1; sc.Save();
                }
                TextBox_NewStartTime.BackColor = System.Drawing.Color.White;
                VisibiltiyNewStartTime(false);
                t1 = (DateTime)ViewState["EditDate"];
                Encode en = new Encode();
                SqlDataSource1.SelectCommand    = GetQueryStringDay(Year, t0.Month, t0.Day, " ORDER BY DateTime");
                SqlDataSource1.ConnectionString = en.GetDbConnection();
                SqlDataSource1.DataBind();
            }
            catch
            {
                TextBox_NewStartTime.BackColor = System.Drawing.Color.Red;
            }
        }
        protected bool AllDesksAssigned(DateTime t)
        {
            bool   assigned = false;
            string s        = "SELECT ScheduledComponentID ";

            s += " FROM dbo.tbl_Exams_ScheduledComponents ";
            s += " WHERE  (Desk IS NULL) AND (Year = '" + Year.ToString() + "') AND (Season = '" + SeasonCode.ToString() + "')";
            s += " AND (DateTime > CONVERT(DATETIME, '" + t.ToString("yyyy-MM-dd HH:mm:ss") + "', 102))";
            s += " AND (DateTime < CONVERT(DATETIME, '" + t.AddDays(1).ToString("yyyy-MM-dd HH:mm:ss") + "', 102))";
            Encode en = new Encode();

            using (SqlConnection cn = new SqlConnection(en.GetDbConnection()))
            {
                cn.Open();
                using (SqlCommand cm = new SqlCommand(s, cn))
                {
                    using (SqlDataReader dr = cm.ExecuteReader())
                    {
                        if (!dr.Read())
                        {
                            assigned = true;
                        }
                        dr.Close();
                    }
                }
                cn.Close();
            }
            return(assigned);
        }
 protected void Page_Load(object sender, EventArgs e)
 {
     if (!IsPostBack)
     {
         string   dateS = Request.QueryString["Date"];
         DateTime t0    = new DateTime();
         string   sess  = Request.QueryString["Session"];
         bool     Is_AM = true;
         try
         {
             t0 = Convert.ToDateTime(Request.QueryString["Date"]);
             if (sess.Contains("PM"))
             {
                 Is_AM = false;
             }
             ViewState["Session_is_AM"] = Is_AM;
             ViewState["EditDate"]      = t0;
             DateTime t1 = new DateTime();
             DateTime t2 = new DateTime();
             t1 = (Is_AM) ? t0.AddHours(8) : t0.AddHours(13);
             t2 = (Is_AM) ? t0.AddHours(13) : t0.AddHours(18);
             Panel_DayView.Visible = true;
             Label_Date.Text       = t0.ToLongDateString();
             Encode en            = new Encode();
             string orderbyclause = " ORDER BY DateTime";
             SqlDataSource1.SelectCommand    = GetQueryStringDay(Year, t0.Month, t0.Day, orderbyclause);
             SqlDataSource1.ConnectionString = en.GetDbConnection();
             SqlDataSource1.DataBind();
             UpdateButtons(t0);
         }
         catch
         {
         }
     }
 }
Esempio n. 8
0
 public ActionResult Index()
 {
     // Para fines de prueba, no quiero estar metiendo estos roles directamente en la db
     if (db.ROL.ToList().Count < 1)
     {
         ROL rol1 = new ROL();
         rol1.NOMBRE_ROL      = "administrador";
         rol1.DESCRIPCION_ROL = "administrador";
         db.ROL.Add(rol1);
         ROL rol2 = new ROL();
         rol2.NOMBRE_ROL      = "empleado";
         rol2.DESCRIPCION_ROL = "empleado";
         db.ROL.Add(rol2);
         ROL rol3 = new ROL();
         rol3.NOMBRE_ROL      = "usuario";
         rol3.DESCRIPCION_ROL = "usuario";
         db.ROL.Add(rol3);
         db.SaveChanges();
         ROL rol = db.ROL.ToList().Where(r => r.NOMBRE_ROL == "administrador").First();
         if (rol != null)
         {
             USUARIO usuario = new USUARIO();
             usuario.EMAIL      = "*****@*****.**";
             usuario.HABILITADO = true;
             usuario.PASSWORD   = Encode.EncodePassword("@dminM@x");
             usuario.USERNAME   = "******";
             usuario.ID_ROL     = rol.ID_ROL;
             db.USUARIO.Add(usuario);
             db.SaveChanges();
         }
     }
     return(View());
 }
Esempio n. 9
0
        /// <summary>
        /// 读取内存流中一段字符串
        /// </summary>
        /// <param name="ms"></param>
        /// <returns></returns>
        public string ReadString()
        {
            int lengt = ReadInt32();

            if (lengt == 0)
            {
                return("");
            }

            byte[] buf = new byte[lengt];

            unsafe
            {
                fixed(byte *datap = &Data[current])
                fixed(byte *bufp = &buf[0])
                Buffer.MemoryCopy(datap, bufp, buf.Length, buf.Length);

                //Buffer.BlockCopy(Data, current, buf, 0, buf.Length);
            }
            string values = Encode.GetString(buf, 0, buf.Length);

            current = Interlocked.Add(ref current, lengt);

            return(values);
        }
Esempio n. 10
0
        private static void signatureHeader(HttpWebRequest httpWebRequest, Request request, string contentMD5)
        {
            string   uuid    = Guid.NewGuid().ToString();
            DateTime gmtTime = DateTime.Now;

            httpWebRequest.Method      = request.httpMethod;
            httpWebRequest.Accept      = "application/json";
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Date        = DateTime.Now;

            WebHeaderCollection headers = httpWebRequest.Headers;

            headers.Add("Content-MD5", contentMD5);
            headers.Add("x-acs-version", request.version);
            headers.Add("x-acs-signature-nonce", uuid);
            headers.Add("x-acs-signature-version", request.signatureVersion);
            headers.Add("x-acs-signature-method", request.signatureMethod);

            StringBuilder str = new StringBuilder();

            str.Append("POST\n")
            .Append("application/json\n")
            .Append(contentMD5).Append("\n")
            .Append("application/json\n")
            .Append(gmtTime.ToUniversalTime().ToString("r")).Append("\n")
            .Append("x-acs-signature-method:").Append(request.signatureMethod).Append("\n")
            .Append("x-acs-signature-nonce:").Append(uuid).Append("\n")
            .Append("x-acs-signature-version:").Append(request.signatureVersion).Append("\n")
            .Append("x-acs-version:").Append(request.version).Append("\n")
            .Append(request.path).Append(request.getQueryString());

            string signature = Encode.Base64Encode(Cryptography.HMACSHA1(str.ToString(), request.accessKeySecret));

            headers.Add("Authorization", "acs " + request.accessKeyId + ":" + signature);
        }
Esempio n. 11
0
        private bool Reg_SendEamil(string email, string vCode, out string username, out string pwd)
        {
            username = email.Split('@')[0];
            pwd      = DateTime.Now.ToString("HHmmss") + username;
            StringBuilder postData = new StringBuilder();

            postData.Append("fromUrl=http%3A%2F%2Fwww.csdn.net%2F&userName="******"&email=" + Encode.UrlEncode(email));
            postData.Append("&password="******"&confirmpassword="******"&validateCode=" + vCode + "&agree=on");
            HttpHelpers helper = new HttpHelpers();                                                    //发起请求对象
            HttpItems   items  = new HttpItems();                                                      //请求设置对象
            HttpResults hr     = new HttpResults();                                                    //请求结果

            items.URL       = "http://passport.csdn.net/account/register?action=saveUser&isFrom=true"; //设置请求地址
            items.Postdata  = postData.ToString();
            items.Method    = "Post";
            items.Container = cc;       //自动处理Cookie时,每次提交时对cc赋值即可
            hr = helper.GetHtml(items); //发起请求并得到结果
            if (hr.Html.Contains("请在24小时内点击邮件中的链接继续完成注册"))
            {
                return(true);
            }
            return(false);
        }
        public IHttpActionResult GuiMailTaiKhoan(string _tentaikhoan)
        {
            try
            {
                using (var db = new DB())
                {
                    TaiKhoan taiKhoan = db.TaiKhoans.FirstOrDefault(x => x.tentaikhoan == _tentaikhoan);
                    if (taiKhoan == null)
                    {
                        return(BadRequest("Gửi email thất bại! Thông tin email/tên tài khoản không tồn tại"));
                    }
                    string tokenEncode      = Encode.MD5(_tentaikhoan);
                    string urlResetPasswork = "http://localhost:54328/Login/ResetPasswork?email=" + _tentaikhoan + "&token=" + tokenEncode;
                    taiKhoan.linklaylaitaikhoan     = tokenEncode;
                    taiKhoan.thoigianyeucaulaylaitk = DateTime.Now.AddDays(1);
                    db.SaveChanges();

                    MailHelper.SendMailGuest(taiKhoan.tentaikhoan, "Thông tin tài khoản", "Tài khoản của bạn : " + taiKhoan.tentaikhoan
                                             + ". Vui lòng cập nhật lại mật khẩu theo đường dẫn sau: " + urlResetPasswork);
                    return(Ok(_tentaikhoan));
                }
            }
            catch (Exception ex)
            {
                return(BadRequest(ex.Message));
            }
        }
    void PrintAddressAndBlockExplorer(string desc, byte[] address)
    {
        m_paragraphTransaction.Inlines.Add(desc + ": 0x" + Encode.BytesToHex(address));

        foreach (string url in m_lBlockExplorer)
        {
            if (!url.Contains("<address>"))
            {
                continue;
            }

            Uri uri = new Uri(url.Replace("<address>", Encode.BytesToHex(address)));
            if (uri.IsFile)
            {
                continue;
            }

            Hyperlink hyperlink = new Hyperlink(new Run(uri.Host))
            {
                NavigateUri = uri, ToolTip = uri
            };
            hyperlink.Click += (sender, e) => System.Diagnostics.Process.Start(uri.ToString());
            m_paragraphTransaction.Inlines.Add(" ");
            m_paragraphTransaction.Inlines.Add(hyperlink);
        }

        m_paragraphTransaction.Inlines.Add("\n");
    }
Esempio n. 14
0
 public override void OnAuthorization(HttpActionContext actionContext)
 {
     if (actionContext.Request.Headers.Authorization is null)
     {
         actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new Exception("Bạn không có quyền truy cập tính năng  này"));
     }
     else
     {
         try
         {
             string   authenticationToken       = actionContext.Request.Headers.Authorization.Parameter;
             string   decodeAuthenticationToken = Encode.Decrypt(authenticationToken);
             string[] account  = decodeAuthenticationToken.Split(':');
             string   userName = account[0];
             string   password = Encode.MD5(account[0]);
             using (var db = new DB())
             {
                 if (db.TaiKhoans.FirstOrDefault(x => x.tentaikhoan == userName && x.matkhau == password) == null)
                 {
                     Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), null);
                 }
                 else
                 {
                     actionContext.Response = actionContext.Request.CreateResponse(HttpStatusCode.Unauthorized, new Exception("Bạn không có quyền truy cập tính năng  này"));
                 }
             }
         }
         catch (Exception ex)
         {
             actionContext.Response = actionContext.Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new Exception("Bạn không có quyền truy cập tính năng  này"));
         }
     }
 }
Esempio n. 15
0
        protected string GetCurrentClue(ref string[] result)
        {
            Encode       en = new Encode();
            FileStream   fs = new FileStream(en.GetFilePath("Ez_Hunt.txt"), FileMode.Open, FileAccess.Read, FileShare.Read);
            StreamReader sr = new StreamReader(fs);
            string       s  = sr.ReadLine();//header

            string[] spearator = { "," };
            s      = sr.ReadLine();//current hunt Id and current clue Id
            result = s.Split(spearator, 20, StringSplitOptions.RemoveEmptyEntries);
            string HuntId = result[0]; string currentClueId = result[1];

            while (!sr.EndOfStream)
            {
                s      = sr.ReadLine();
                result = s.Split(spearator, 20, StringSplitOptions.RemoveEmptyEntries);
                if ((result[0] == HuntId) && (result[1] == currentClueId))
                {
                    sr.Close();
                    fs.Close();
                    return(currentClueId);
                }
            }
            sr.Close();
            fs.Close();
            return(currentClueId);
        }
Esempio n. 16
0
        /// <summary>
        /// 读取内存流中一段字符串
        /// </summary>
        /// <param name="ms"></param>
        /// <returns></returns>
        public virtual bool ReadString(out string values)
        {
            int lengt;

            try
            {
                if (ReadInt32(out lengt))
                {
                    Byte[] buf = new Byte[lengt];

                    Buffer.BlockCopy(Data, current, buf, 0, buf.Length);

                    values = Encode.GetString(buf, 0, buf.Length);

                    current = Interlocked.Add(ref current, lengt);

                    return(true);
                }
                else
                {
                    values = "";
                    return(false);
                }
            }
            catch
            {
                values = "";
                return(false);
            }
        }
Esempio n. 17
0
        private static string BarcodeJobTicketPdf(string FullFileName, string JobName, string StockCode)
        {
            string pdfFullName = FullFileName.Replace(" .pdf", ".pdf");

            ceTe.DynamicPDF.Document.AddLicense("DPS70NEDJGMGEGWKOnLLQb4SjhbTTJhXnkpf9bj8ZzxFH+FFxctoPX+HThGxkpidUCHJ5b88fg4oUJSHiRBggzHdghUgkkuIvoag");
            var doc  = new ceTe.DynamicPDF.Document();
            var page = new ceTe.DynamicPDF.Page();

            MergeDocument MyDocJobTicket = new MergeDocument();
            PdfDocument   pdfTemplate    = new PdfDocument(FullFileName);
            var           qrCode         = new ceTe.DynamicPDF.PageElements.Image(Encode.QR(JobName), 300, 50);

            qrCode.Height = 90;
            qrCode.Width  = 90;

            MyDocJobTicket.Append(pdfTemplate);
            MyDocJobTicket.Pages[0].Dimensions.SetMargins(0);

            MyDocJobTicket.Pages[0].Elements.Add(qrCode);
            qrCode        = new ceTe.DynamicPDF.PageElements.Image(Encode.QR(StockCode), 50, 405);
            qrCode.Height = 38;
            qrCode.Width  = 38;
            MyDocJobTicket.Pages[0].Elements.Add(qrCode);
            MyDocJobTicket.FormFlattening = FormFlatteningOptions.Default;
            MyDocJobTicket.Draw(pdfFullName);
            MyDocJobTicket = null;
            FileInfo fi = new FileInfo(FullFileName);

            fi.Delete();
            return(pdfFullName);
        }
Esempio n. 18
0
        public static void Main(string[] args)
        {
            if (!ServiceUtils.IsSiteServerDir)
            {
                Console.WriteLine("当前文件夹不是正确的SiteServer系统根目录");
                Console.ReadLine();
                return;
            }
            if (!ServiceUtils.IsInitialized)
            {
                Console.WriteLine("SiteServer系统未安装或数据库无法正确连接");
                Console.ReadLine();
                return;
            }

            var    invokedVerb         = string.Empty;
            object invokedVerbInstance = null;

            if (args.Length == 0)
            {
                invokedVerb = Run.CommandName;
            }
            else
            {
                var options = new Options();
                if (!Parser.Default.ParseArguments(args, options,
                                                   (verb, subOptions) =>
                {
                    invokedVerb = verb;
                    invokedVerbInstance = subOptions;
                }))
                {
                    Console.WriteLine(options.GetUsage());
                    return;
                }
            }

            if (invokedVerb == Build.CommandName)
            {
                var commitSubOptions = (BuildSubOptions)invokedVerbInstance;
                var isAll            = commitSubOptions != null && commitSubOptions.All;
                Build.Start(isAll);
            }
            else if (invokedVerb == Test.CommandName)
            {
                Test.Start();
            }
            else if (invokedVerb == Encode.CommandName)
            {
                var subOptions = invokedVerbInstance as EncodeSubOptions;
                if (subOptions != null)
                {
                    Encode.Start(subOptions.String);
                }
            }
            else if (invokedVerb == Run.CommandName)
            {
                Run.Start();
            }
        }
        ITopLevelExpression TryReplaceValue(ITopLevelExpression expr, IVariables variables)
        {
            switch (expr)
            {
            case KeyValuePairExpression pair:
                var logicalName = pair.Key?.Text?.LogicalValue ?? "";
                if (!IsOctopusVariableName(logicalName) && variables.IsSet(logicalName))
                {
                    log.Verbose(StructuredConfigMessages.StructureFound(logicalName));

                    var logicalValue = variables.Get(logicalName);
                    var encodedValue = Encode.Value(logicalValue);
                    var newValueExpr = new ValueExpression(new StringValue(logicalValue, encodedValue));

                    // In cases where a key was specified with neither separator nor value
                    // we have to add a separator, otherwise the value becomes part of the key.
                    var separator = pair.Separator ?? new SeparatorExpression(":");
                    return(new KeyValuePairExpression(pair.Key, separator, newValueExpr));
                }
                else
                {
                    return(expr);
                }

            default:
                return(expr);
            }
        }
Esempio n. 20
0
        protected void Button1_Click(object sender, EventArgs e)
        {
            // going to run through db and add any missing uci where we have an exam no...

            SimpleStudentList sl1    = new SimpleStudentList(SimpleStudentList.LIST_TYPE.NOFORM_ONROLE);
            PupilDetails      pupil1 = new PupilDetails();
            string            s      = "";

            ExamFiles ef = new ExamFiles();
            Encode    en = new Encode();
            int       n = 0; int n1 = 0;

            foreach (SimplePupil p in sl1._studentlist)
            {
                pupil1.m_UCI = "";
                pupil1.Load(p.m_StudentId.ToString());
                string year = DateTime.Now.Year.ToString();
                if ((pupil1.m_UCI == "") && (pupil1.m_examNo > 0))
                {
                    pupil1.m_UCI = ef.Calculate_UCI_Checksum("52205", "0", year, pupil1.m_examNo.ToString());
                    s            = "UPDATE dbo.tbl_Core_Students SET StudentUCI='" + pupil1.m_UCI + "' ";
                    s           += "WHERE StudentId = '" + p.m_StudentId.ToString() + "' ";
                    en.ExecuteSQL(s);
                    n++;
                }
                if (pupil1.m_examNo == 0)
                {
                    n1++;
                }
            }
            Label1.Text = "Created " + n.ToString() + " new UCIs.  There were " + n1.ToString() + " students found with no Exam Number!";
        }
Esempio n. 21
0
        public IHttpActionResult PostEmployee(Employee employee)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return(BadRequest(ModelState));
                }
                if (DBOperations.IsUsernameExist(employee.UserName))
                {
                    return(BadRequest("Username Already Exists"));
                }
                if (DBOperations.IsEmailExist(employee.Email_ID))
                {
                    return(BadRequest("Email ID Already Exists"));
                }
                employee.IsEmailVerified = false;

                string VerificationCode = Guid.NewGuid().ToString();
                var    userName         = Encode.Base64Encode(employee.UserName);
                var    link             = "http://localhost:4200/setpassword/" + HttpUtility.UrlEncode(userName);
                VerificationLink.EmailGeneration(employee.Email_ID, VerificationCode, link);

                db.Employees.Add(employee);
                db.SaveChanges();
                DBOperations.UpdateUserinfo(employee.ID, employee.UserName);
                CallStoredProc.RunLeaveEntryForNew(employee);
                return(Ok("Successfully Added"));
            }
            catch (Exception ex)
            {
                LogFile.WriteLog(ex);
                return(BadRequest());
            }
        }
Esempio n. 22
0
        /// <summary>
        /// 加密解密算法实现
        /// </summary>
        /// <param name="data"></param>
        /// <param name="pass"></param>
        /// <returns></returns>
        public override Byte[] EncryptEx(Byte[] data, String pass)
        {
            if (data == null || pass == null)
            {
                return(null);
            }
            Byte[] output = new Byte[data.Length];
            Int64  i      = 0;
            Int64  j      = 0;

            Byte[] mBox = GetKey(Encode.GetBytes(pass), 256);
            // 加密
            for (Int64 offset = 0; offset < data.Length; offset++)
            {
                i = (i + 1) % mBox.Length;
                j = (j + mBox[i]) % mBox.Length;
                Byte temp = mBox[i];
                mBox[i] = mBox[j];
                mBox[j] = temp;
                Byte a = data[offset];
                //Byte b = mBox[(mBox[i] + mBox[j] % mBox.Length) % mBox.Length];
                // mBox[j] 一定比 mBox.Length 小,不需要在取模
                Byte b = mBox[(mBox[i] + mBox[j]) % mBox.Length];
                output[offset] = (Byte)((Int32)a ^ (Int32)b);
            }
            return(output);
        }
    public static List <Tuple <string, string> > ReadAddressInfo(string file)
    {
        var lEntry = new List <Tuple <string, string> >();

        foreach (string line in ReadTrimmedLines(file))
        {
            // format: address [info]

            string address = line;
            string desc    = "";

            int index = line.IndexOf(" ");
            if (index != -1)
            {
                address = line.Substring(0, index);
                desc    = line.Substring(index).Trim();
            }

            byte[] data = Encode.HexToBytes(address, 20);
            if (data != null)
            {
                lEntry.Add(new Tuple <string, string>(Encode.BytesToHex(data), desc));
            }
        }

        return(lEntry);
    }
Esempio n. 24
0
 public IHttpActionResult ResetPassword(string id, PasswordConfirmation password)
 {
     try
     {
         id = Encode.Base64Decode(id);
         string message = VerifyPasswords.Password(password);
         if (message == "Successfull")
         {
             DBOperations.SaveChangedPassword(password, id);
             return(Ok("Password Changed Successfully"));
         }
         else if (message == "Passswords Don't Match")
         {
             return(Ok("Passswords Don't Match"));
         }
         else
         {
             return(Ok("Password Change Not Successful"));
         }
     }
     catch (Exception ex)
     {
         LogFile.WriteLog(ex);
         return(BadRequest());
     }
 }
Esempio n. 25
0
 public bool TryGetRole()
 {
     try
     {
         string token           = Request.Cookies["token"].Value;
         string danhsachmanhinh = Request.Cookies["danhsachmanhinh"].Value;
         string setingstyle     = Request.Cookies["setingstyle"].Value;
         string avatar          = Request.Cookies["avatar"].Value;
         string hoten           = Request.Cookies["hoten"].Value;
         if (token is null || danhsachmanhinh is null)
         {
             return(false);
         }
         Session["userName"]     = Encode.Decrypt(token).Split(':')[0];
         Session["setingstyle"]  = setingstyle;
         Session["avatar"]       = avatar;
         Session["hoten"]        = hoten;
         Session["acceptScreen"] = JsonConvert.DeserializeObject <List <string> >(Encode.Decrypt(danhsachmanhinh));
         return(true);
     }
     catch (Exception ex)
     {
         return(false);
     }
 }
Esempio n. 26
0
        protected void Button_OK_Click(object sender, EventArgs e)
        {
            Panel1.Visible = true;
            Panel2.Visible = false;
            //do it
            string s = "";

            foreach (GridViewRow r in GridView2.Rows)
            {
                if (r.BackColor == System.Drawing.Color.DarkGray)
                {
                    s = r.Cells[0].Text;
                    Exam_Entry ex1 = new Exam_Entry();
                    ex1.Load(s);
                    if (ex1.CanDelete())
                    {
                        s = "delete";
                        ex1.Delete();
                    }
                    else
                    {
                        s = "withdraw";
                        ex1.Withdraw();
                    }
                }
            }
            SqlDataSource2.SelectCommand = GetQueryString();
            Encode en = new Encode();

            SqlDataSource2.ConnectionString = en.GetDbConnection();
            SqlDataSource2.DataBind();
            Button_Delete.Visible = false;
        }
Esempio n. 27
0
 public bool getUser(NguoiDung ND)
 {
     // Validation logic
     if (!ValidateContact(ND))
     {
         return(false);
     }
     // Database logic
     try
     {
         ND.Pass = Encode.md5((ND.Pass));
         NguoiDung key = _repository.getUser(ND);
         if (key != null)
         {
             NhanVien NV = key.NhanVien;
             Information.Nhanvien  = NV;
             Information.Nguoidung = key;
             return(true);
         }
     }
     catch
     {
         return(false);
     }
     return(false);
 }
Esempio n. 28
0
        public void Encode_DecodeTest()
        {
            //Arrange
            string sentMessage = "Message";

            byte[]       file        = Encoding.ASCII.GetBytes(sentMessage);
            IEncode      encoder     = new Encode(file);
            var          blocksCount = encoder.NumberOfBlocks;
            var          overHead    = 20;
            IList <Drop> drops       = new List <Drop>();

            for (int i = 0; i < blocksCount + overHead; i++)
            {
                var drop = encoder.Encode();
                drops.Add(drop);
            }
            IMatrixSolver matrixSolver = new MatrixSolver();
            IDecode       target       = new Decode(matrixSolver);

            //Act
            var actualByte      = target.Decode(drops, blocksCount, encoder.ChunkSize, encoder.FileSize);
            var receievdMessage = Encoding.ASCII.GetString(actualByte);

            //Assert
            Assert.AreEqual(sentMessage, receievdMessage);
        }
Esempio n. 29
0
        private void btn_XacNhan_Click(object sender, EventArgs e)
        {
            //Trường hợp mật khẩu cũ không đúng
            if (!KiemTraMatKhauCu())
            {
                MessageBox.Show("Mật khẩu cũ không đúng , vui lòng kiểm tra lại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            if (this.txt_MatKhauMoi.Text != this.txt_XacNhanMKMoi.Text)
            {
                MessageBox.Show("Mật khẩu mới không khớp, vui lòng kiểm tra lại", "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            DialogResult ret = MessageBox.Show("Bạn chắc chắn muốn đổi mật khẩu chứ ? ", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);

            if (ret == DialogResult.Yes)
            {
                tempUser.PassWord = Encode.Encrypt(this.txt_MatKhauMoi.Text);
                try
                {
                    objUser.Update(tempUser);
                    MessageBox.Show("Đã thay đổi thành công", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    this.Close();
                    frm_Login f = new frm_Login();
                    f.CaiDatThongBao();
                    f.ShowDialog();
                }
                catch (Exception ex)
                {
                    MessageBox.Show("Lỗi đã sảy ra , vui lòng kiểm tra lại hoặc liên hệ kỹ thuật viên với mô tả lỗi dưới đây : \n " + ex.Message, "Lỗi", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 30
0
        public ActionResult Create(String email, String password, String username)
        {
            if (!string.IsNullOrEmpty(email) && !string.IsNullOrEmpty(password) && !string.IsNullOrEmpty(username))
            {
                try
                {
                    USUARIO uSUARIO = new USUARIO {
                        EMAIL = email, USERNAME = username, PASSWORD = Encode.EncodePassword(password), HABILITADO = true
                    };
                    uSUARIO.ID_ROL = db.ROL.ToList().Where(r => r.NOMBRE_ROL == "usuario").First().ID_ROL;
                    db.USUARIO.Add(uSUARIO);
                    db.SaveChanges();
                    ViewBag.Success = "Usuario solicitado con exito, espere el mensaje de confirmacion en su correo";
                }
                catch (Exception e)
                {
                    ViewBag.Error = "Error al guardar, el Usuario ya existe";
                }
                return(View("Create"));
            }
            else
            {
                ViewBag.Error = "Error al guardar, la contraseña debe tener al menos 8 caracteres y caracteres especiales asi como numeros";
            }

            return(View("Create"));
        }
Esempio n. 31
0
 public AmqpPrimitiveType(Type type, Encode encoder, Decode decoder)
     : base(null, type)
 {
     this.encoder = encoder;
     this.decoder = decoder;
 }
Esempio n. 32
0
 public static SerializableType CreatePrimitiveType(Type type, Encode encoder, Decode decoder)
 {
     return new AmqpPrimitiveType(type, encoder, decoder);
 }
Esempio n. 33
0
        /// <summary> 
        /// 获取128图形 
        /// </summary> 
        /// <param name="Code128">文字</param> 
        /// <param name="Code128Type">编码</param>       
        /// <returns>图形</returns> 
        public Bitmap GetCodeImage(string Code128,string title, Encode Code128Type)
        {
            string code128 = Code128;
            string sText = "";
            IList<int> ilistTextNumb = new List<int>();
            int iFist = 0;  //首位
            switch (Code128Type)
            {
                case Encode.Code128C:
                    iFist = 105;
                    if (!((Code128.Length & 1) == 0)) throw new Exception("128C长度必须是偶数");
                    while (Code128.Length != 0)
                    {
                        int _Temp = 0;
                        try
                        {
                            int _CodeNumb128 = Int32.Parse(Code128.Substring(0, 2));
                        }
                        catch
                        {
                            throw new Exception("128C必须是数字!");
                        }
                        sText += GetValue(Code128Type, Code128.Substring(0, 2), ref _Temp);
                        ilistTextNumb.Add(_Temp);
                        Code128 = Code128.Remove(0, 2);
                    }
                    break;
                case Encode.EAN128:
                    iFist = 105;
                    if (!((Code128.Length & 1) == 0)) throw new Exception("EAN128长度必须是偶数");
                    ilistTextNumb.Add(102);
                    sText += "411131";
                    while (Code128.Length != 0)
                    {
                        int _Temp = 0;
                        try
                        {
                            int _CodeNumb128 = Int32.Parse(Code128.Substring(0, 2));
                        }
                        catch
                        {
                            throw new Exception("128C必须是数字!");
                        }
                        sText += GetValue(Encode.Code128C, Code128.Substring(0, 2), ref _Temp);
                        ilistTextNumb.Add(_Temp);
                        Code128 = Code128.Remove(0, 2);
                    }
                    break;
                default:
                    if (Code128Type == Encode.Code128A)
                    {
                        iFist = 103;
                    }
                    else
                    {
                        iFist = 104;
                    }

                    while (Code128.Length != 0)
                    {
                        int _Temp = 0;
                        string _ValueCode = GetValue(Code128Type, Code128.Substring(0, 1), ref _Temp);
                        if (_ValueCode.Length == 0) throw new Exception("无效的字符集!" + Code128.Substring(0, 1).ToString());
                        sText += _ValueCode;
                        ilistTextNumb.Add(_Temp);
                        Code128 = Code128.Remove(0, 1);
                    }
                    break;
            }
            if (ilistTextNumb.Count == 0) throw new Exception("错误的编码,无数据");
            sText = sText.Insert(0, GetValue(iFist)); //获取开始位

            for (int i = 0; i != ilistTextNumb.Count; i++)
            {
                iFist += ilistTextNumb[i] * (i + 1);
            }
            iFist = iFist % 103;           //获得严效位
            sText += GetValue(iFist);  //获取严效位
            sText += "2331112"; //结束位
            Bitmap _CodeImage = GetImage(sText);
            GetViewText(_CodeImage, title);
            return _CodeImage;
        }
Esempio n. 34
0
 /// <summary> 
 /// 获取目标对应的数据 
 /// </summary> 
 /// <param name="Code128Type">编码</param> 
 /// <param name="Code128">数值 A b  30</param> 
 /// <param name="p_SetID">返回编号</param> 
 /// <returns>编码</returns> 
 private string GetValue(Encode Code128Type, string Code128, ref int p_SetID)
 {
     if (code128Table == null)
         return "";
     DataRow[] _Row = code128Table.Select(Code128Type.ToString() + "='" + Code128 + "'");
     if (_Row.Length != 1)
         throw new Exception("错误的编码" + Code128.ToString());
     p_SetID = Int32.Parse(_Row[0]["ID"].ToString());
     return _Row[0]["BandCode"].ToString();
 }
Esempio n. 35
0
        private static List<Encode> loadUnicodes()
        {
            List<Encode> encodes = new List<Encode>();
            unicodeFile = Application.StartupPath + "\\unicodes.txt";
            StreamReader sr = new StreamReader(unicodeFile);
            TextReader tr = sr;
            while (!sr.EndOfStream)
            {
                string line = tr.ReadLine();
                // ignore comments and blank lines
                if (!line.Trim().StartsWith(";") && line.Trim().Length > 0)
                {
                    string[] ss = line.Split(' ');
                    if (line.Contains('"'))
                    {
                        int strStart = line.IndexOf('"');
                        ss[3] = line.Substring(
                            strStart,
                            (int)Math.Min(
                                (uint)line.IndexOf('"', strStart + 1) - strStart + 1,
                                (uint)line.Length - strStart
                            ));
                    }
                    try
                    {
                        Encode enc = new Encode(
                            new byte[] {
                                byte.Parse(ss[0].Replace(",", "").Trim()),
                                byte.Parse(ss[1].Replace(",", "").Trim()),
                                byte.Parse(ss[2].Replace(",", "").Trim())
                            }, ss[3]);
                        encodes.Add(enc);
                    }
                    catch
                    {
                    }
                }
            }
            sr.Close();

            return encodes;
        }
Esempio n. 36
0
        internal static bool TryGetCodec(Type type, out Encode encoder, out Decode decoder)
        {
            Serializer codec = (Serializer)codecByType[type];
            if (codec == null && type.IsArray)
            {
                codec = serializers[20];
            }

            if (codec != null)
            {
                encoder = codec.Encoder;
                decoder = codec.Decoder;
                return true;
            }
            else
            {
                encoder = null;
                decoder = null;
                return false;
            }
        }
Esempio n. 37
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EncoderInfo"/> class.
 /// </summary>
 /// <param name="tag">
 /// The tag.
 /// </param>
 /// <param name="serialize">
 /// The serialize delegate.
 /// </param>
 internal EncoderInfo(Tags tag, Serialize serialize)
 {
     this.Tag = tag;
     this.encode = null;
     this.serialize = serialize;
 }
Esempio n. 38
0
            /// <summary>
            /// 获取128图形
            /// </summary>
            /// <param name="p_Text">文字</param>
            /// <param name="p_Code">编码</param>      
            /// <returns>图形</returns>
            public Bitmap GetCodeImage(string p_Text, Encode p_Code)
            {
                string _ViewText = p_Text;
                string _Text = "";
                IList<int> _TextNumb = new List<int>();
                int _Examine = 0;  //首位
                switch (p_Code)
                {
                    case Encode.Code128C:
                        _Examine = 105;
                        if (!((p_Text.Length & 1) == 0)) throw new Exception("128C长度必须是偶数");
                        while (p_Text.Length != 0)
                        {
                            int _Temp = 0;
                            try
                            {
                                int _CodeNumb128 = Int32.Parse(p_Text.Substring(0, 2));
                            }
                            catch
                            {
                                throw new Exception("128C必须是数字!");
                            }
                            _Text += GetValue(p_Code, p_Text.Substring(0, 2), ref _Temp);
                            _TextNumb.Add(_Temp);
                            p_Text = p_Text.Remove(0, 2);
                        }
                        break;
                    case Encode.EAN128:
                        _Examine = 105;
                        if (!((p_Text.Length & 1) == 0)) throw new Exception("EAN128长度必须是偶数");
                        _TextNumb.Add(102);
                        _Text += "411131";
                        while (p_Text.Length != 0)
                        {
                            int _Temp = 0;
                            try
                            {
                                int _CodeNumb128 = Int32.Parse(p_Text.Substring(0, 2));
                            }
                            catch
                            {
                                throw new Exception("128C必须是数字!");
                            }
                            _Text += GetValue(Encode.Code128C, p_Text.Substring(0, 2), ref _Temp);
                            _TextNumb.Add(_Temp);
                            p_Text = p_Text.Remove(0, 2);
                        }
                        break;
                    default:
                        if (p_Code == Encode.Code128A)
                        {
                            _Examine = 103;
                        }
                        else
                        {
                            _Examine = 104;
                        }

                        while (p_Text.Length != 0)
                        {
                            int _Temp = 0;
                            string _ValueCode = GetValue(p_Code, p_Text.Substring(0, 1), ref _Temp);
                            if (_ValueCode.Length == 0) throw new Exception("无效的字符集!" + p_Text.Substring(0, 1).ToString());
                            _Text += _ValueCode;
                            _TextNumb.Add(_Temp);
                            p_Text = p_Text.Remove(0, 1);
                        }
                        break;
                }
                if (_TextNumb.Count == 0) throw new Exception("错误的编码,无数据");
                _Text = _Text.Insert(0, GetValue(_Examine)); //获取开始位

                for (int i = 0; i != _TextNumb.Count; i++)
                {
                    _Examine += _TextNumb[i] * (i + 1);
                }
                _Examine = _Examine % 103;           //获得严效位
                _Text += GetValue(_Examine);  //获取严效位
                _Text += "2331112"; //结束位
                Bitmap _CodeImage = GetImage(_Text);
                GetViewText(_CodeImage, _ViewText);
                return _CodeImage;
            }
Esempio n. 39
0
 /// <summary>
 /// 获取目标对应的数据
 /// </summary>
 /// <param name="p_Code">编码</param>
 /// <param name="p_Value">数值 A b  30</param>
 /// <param name="p_SetID">返回编号</param>
 /// <returns>编码</returns>
 private string GetValue(Encode p_Code, string p_Value, ref int p_SetID)
 {
     if (m_Code128 == null) return "";
     DataRow[] _Row = m_Code128.Select(p_Code.ToString() + "='" + p_Value + "'");
     if (_Row.Length != 1) throw new Exception("错误的编码" + p_Value.ToString());
     p_SetID = Int32.Parse(_Row[0]["ID"].ToString());
     return _Row[0]["BandCode"].ToString();
 }
Esempio n. 40
0
 /// <summary>
 /// Initializes a new instance of the <see cref="EncoderInfo"/> class.
 /// </summary>
 /// <param name="tag">
 /// The tag.
 /// </param>
 /// <param name="encode">
 /// The encode delegate.
 /// </param>
 internal EncoderInfo(Tags tag, Encode encode)
 {
     this.Tag = tag;
     this.encode = encode;
     this.serialize = null;
 }
Esempio n. 41
0
 private void Antuorization()
 {
     int num;
     ISACTIVED = true;
     string str = "1B3F1E4B5F1B3F5F80300206A7";
     Encode encode = new Encode();
     string hardDiskID = encode.GetHardDiskID();
     string cPUID = encode.GetCPUID();
     str = str + encode.GetSHA1MachineCode(hardDiskID + cPUID);
     for (num = 0; num < 0x18; num++)
     {
         ConstantValues.TPOACTIVED[num] = false;
         ConstantValues.TPOEXPLANATION[num] = false;
     }
     XMLFileReader reader = new XMLFileReader("license.xml");
     for (num = 1; num < 0x1c; num++)
     {
         string attr = reader.GetAttr("//licenses/license[@name='TPO" + num.ToString() + "']/@value");
         try
         {
             string str5 = encode.Decode(attr);
             if (str5.Contains(str + "TPO" + num.ToString()))
             {
                 ConstantValues.TPOACTIVED[num] = true;
             }
             if (str5.Contains("EXP"))
             {
                 ConstantValues.TPOEXPLANATION[num] = true;
             }
         }
         catch
         {
         }
     }
     ConstantValues.TPOACTIVED[1] = true;
     ConstantValues.TPOACTIVED[0x12] = true;
     ConstantValues.TPOEXPLANATION[1] = true;
     ConstantValues.TPOEXPLANATION[0x12] = true;
 }