EncryptToString() public method

public EncryptToString ( string TextValue ) : string
TextValue string
return string
Esempio n. 1
0
        private void button3_Click(object sender, EventArgs e)
        {
            StreamWriter sw = new StreamWriter(File.Create(path));

            sw.Write(path);
            SimpleAES enc = new SimpleAES();

            MessageBox.Show(enc.EncryptToString(path));

            FolderBrowserDialog fbd = new FolderBrowserDialog();

            if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                using (StreamWriter writer = new StreamWriter(fbd.SelectedPath + "File_encrypt.txt", true))
                {
                    writer.Write(enc.EncryptToString(path));
                }
            }
            sw.Dispose();
            SaveFileDialog sfd = new SaveFileDialog();

            if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                using (StreamWriter writer = new StreamWriter(sfd.FileName, true))
                {
                    writer.Write(enc.EncryptToString(path));
                }
            }
        }
Esempio n. 2
0
        public rs Login(string username, string password, bool isrememberme, bool api = false)
        {
            rs     r;
            string _pass = aes.EncryptToString(password);
            User   logrs = base.GetList(u => u.Username == username && u.Password == _pass).FirstOrDefault();

            if (logrs != null)
            {
                if (logrs.UserStatusId != 1) //chwa active
                {
                    r = rs.F("Tài khoản này chưa hoạt động! " + logrs.UserStatus.Name);
                }
                else
                {
                    var logvm = new loginVM(logrs);
                    //set session
                    if (!api)
                    {
                        SSLogin(logvm);
                    }
                    //lưu đăng nhập
                    r = rs.T("Đăng nhập thành công, đang chuyển hướng!", logvm);
                }
            }
            else
            {
                r = rs.F("Tài khoản mật khẩu không chính xác");
            }
            return(r);
        }
Esempio n. 3
0
        public JsonResult DoiMatKhauProccess(DoiMatKhauVM model)
        {
            rs        r;
            SimpleAES __aes = new SimpleAES();

            if (ModelState.IsValid)
            {
                var __oldpw = __aes.EncryptToString(model.MatKhauHienTai);
                var __newpw = __aes.EncryptToString(model.MatKhauMoi);
                var __id    = MySsAuthUsers.GetAuth().ID;
                using (var __db = new vuong_cms_context())
                {
                    var user = __db.Users.Find(__id);
                    if (user.Password == __oldpw)
                    {
                        user.Password = __newpw;
                        __db.SaveChanges();
                        r = rs.T("Ok");
                    }
                    else
                    {
                        r = rs.F("Mật khẩu hiện tại không chính xác!");
                    }
                }
            }
            else
            {
                r = rs.F("Vui lòng điền đầy đủ thông tin!");
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
        public bool UpdateTechnicianRecordSync(JT_Technician technician)
        {
            bool returnData = false;

            App_Settings appSettings = App.Database.GetApplicationSettings();

            // set up the proper URL
            string url = GetRestServiceUrl();

            if (!url.EndsWith(@"/"))
            {
                url += @"/";
            }
            url += @"u/JT_Technician";

            HttpClient client = new HttpClient();

            client.BaseAddress = new Uri(url);
            client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            JsonSerializerSettings microsoftDateFormatSettings = new JsonSerializerSettings();

            microsoftDateFormatSettings.DateFormatHandling = DateFormatHandling.MicrosoftDateFormat;

            if (appSettings.DeviceID != null)
            {
                SimpleAES encryptText = new SimpleAES("V&WWJ3d39brdR5yUh5(JQGHbi:FB@$^@", "W4aRWS!D$kgD8Xz@");
                string    authid      = encryptText.EncryptToString(appSettings.DeviceID);
                string    datetimever = encryptText.EncryptToString(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz"));
                client.DefaultRequestHeaders.Add("x-tdws-authid", authid);
                client.DefaultRequestHeaders.Add("x-tdws-auth", datetimever);
            }
            //client.AddHeader("x-tdws-authid", authid);
            //request.AddHeader("x-tdws-auth", datetimever);

            // Make the call and get a valid response
            HttpResponseMessage response = client.PutAsync(client.BaseAddress, new StringContent(JsonConvert.SerializeObject(technician, microsoftDateFormatSettings), null, "application/json")).Result; // TODO.... await

            response.EnsureSuccessStatusCode();

            // Read out the result... it better be JSON!
            string JsonResult = response.Content.ReadAsStringAsync().Result;

            try
            {
                returnData = JsonConvert.DeserializeObject <bool>(JsonResult);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.Message);

                // dch rkl 12/07/2016 Log Error
                ErrorReporting errorReporting = new ErrorReporting();
                errorReporting.sendException(ex, "TechDashboard.Data.UpdatTechnicianRecordSync");
            }

            client.Dispose();
            response.Dispose();

            return(returnData);
        }
        public List <T> GetDataPostSync <T>(string filterType, string filterText)
        {
            App_Settings appSettings = App.Database.GetApplicationSettings();
            // Set up our return data object -- a list of typed objects.
            List <T> returnData = new List <T>();

            // set up the proper URL
            string url = GetRestServiceUrl();

            if (!url.EndsWith(@"/"))
            {
                url += @"/";
            }
            if ((filterType != null) &&
                (filterType.Length > 0) &&
                (filterText != null) &&
                (filterText.Length > 0))
            {
                url += @"q/" + typeof(T).Name + @"/" + filterType;// + @"?v=" + Uri.EscapeDataString(filterText);
            }
            else
            {
                url += @"all/" + typeof(T).Name;
            }

            // Create a HTTP client to call the REST service
            RestSharp.RestClient client = new RestSharp.RestClient(url);

            var request = new RestSharp.RestRequest(Method.POST);

            if (appSettings.DeviceID != null)
            {
                SimpleAES encryptText = new SimpleAES("V&WWJ3d39brdR5yUh5(JQGHbi:FB@$^@", "W4aRWS!D$kgD8Xz@");
                string    authid      = encryptText.EncryptToString(appSettings.DeviceID);
                string    datetimever = encryptText.EncryptToString(DateTime.Now.ToString("yyyy-MM-ddTHH:mm:sszzz"));
                request.AddHeader("x-tdws-authid", authid);
                request.AddHeader("x-tdws-auth", datetimever);
            }
            request.RequestFormat = DataFormat.Json;
            request.AddBody(filterText);
            var response = client.Execute(request);

            if (response.StatusCode != System.Net.HttpStatusCode.OK)
            {
                //throw new Exception("Bad request");
                ErrorReporting errorReporting = new ErrorReporting();
                // dch rkl 12/07/2016 add the call/sub/proc to log
                //errorReporting.sendException(new Exception(response.Content));
                errorReporting.sendException(new Exception(response.Content), "RestClient.cs.GetDataPostSync");
            }

            string JsonResult = response.Content;

            returnData = JsonConvert.DeserializeObject <List <T> >(JsonResult);

            return(returnData);
        }
Esempio n. 6
0
        private static string GetMyEncryptedRealId()
        {
            if (!Settings.Misc.IsRealIdEnabled)
            {
                return(string.Empty);
            }

            return(_myEncryptedRealId ??
                   (_myEncryptedRealId =
                        Crypto.EncryptToString(Common.CleanString(Settings.Misc.RealId))));
        }
Esempio n. 7
0
        private void buttonEncrypt_Click(object sender, EventArgs e)
        {
            SimpleAES crypto = new SimpleAES();

            if (buttonEncryptState && rtBody.Text.Length != 0)
            {
                string encryptedBody;
                encryptedBody = crypto.EncryptToString(rtBody.Text);
                rtBody.Text = encryptedBody;
                buttonEncrypt.Text = "Decrypt";
                buttonEncryptState = false;
            }
            else
            {
                try
                {
                    string decryptedBody;
                    decryptedBody = crypto.DecryptString(rtBody.Text);
                    rtBody.Text = decryptedBody;
                    buttonEncrypt.Text = "Encrypt";
                    buttonEncryptState = true;
                }

                catch (Exception ex)
                {
                    MessageBox.Show("Decrypt error: " + ex.Message);
                }
            }
        }
Esempio n. 8
0
        public JsonResult Edit(FrmCreateUserVM model)
        {
            rs r;

            using (var trans = new TransactionScope())
            {
                try
                {
                    SimpleAES __aes  = new SimpleAES();
                    var       entity = _userServ.SingleOrDefault(s => s.Id == model.ID);
                    entity.RoleId   = model.RoleId;
                    entity.Password = __aes.EncryptToString(model.Password);
                    entity.GioiTinh = model.GioiTinh;
                    entity.Address  = model.Address;
                    entity.Phone    = model.Phone;
                    entity.Email    = model.Email;
                    entity.Fullname = model.Fullname;
                    entity.Image    = model.Image;
                    _userServ.Save();
                    trans.Complete();
                    r = rs.T("Okay");
                }
                catch (Exception ex)
                {
                    r = rs.F("Lỗi: " + ex.Message);
                }
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
        public JsonResult Edit(FrmCreateUserVM model)
        {
            rs r;

            using (var trans = new TransactionScope())
            {
                try
                {
                    SimpleAES __aes  = new SimpleAES();
                    var       entity = _userServ.SingleOrDefault(s => s.Id == model.ID);
                    entity.RoleId   = model.RoleID;
                    entity.Password = __aes.EncryptToString(model.Password);
                    entity.IsVip1   = model.IsVip;

                    if (model.IsVip)
                    {
                        entity.NgayVip     = DateTime.Now;
                        entity.ChuThichVip = "Cập nhật thủ công";
                    }
                    _userServ.Save();
                    trans.Complete();
                    r = rs.T("Okay!");
                }
                catch (Exception ex)
                {
                    r = rs.F("Lỗi: " + ex.Message);
                }
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
        public static string RandomeResetPasswordCode(int iduser)
        {
            SimpleAES aes = new SimpleAES();

            //userid(int)_randome split '_'
            return(aes.EncryptToString(iduser.ToString()) + "_" + LayMaNgauNhien10ChuSo() + NgauNhienSHA256() + NgauNhienSHA256(10));
        }
Esempio n. 11
0
        public int ValidatePassword(user u)
        {
            SimpleAES AES      = new SimpleAES();
            string    passWord = AES.EncryptToString(u.password);

            return(DbContext.users.Where(x => x.password == passWord).Count());
        }
Esempio n. 12
0
        public string Pack(Profile profile)
        {
            SimpleAES enc = new SimpleAES();

            var data = profile.AppName + ":";

            if (!string.IsNullOrWhiteSpace(profile.Action))
            {
                data += ("ACTION=" + profile.Action);
            }
            else
            {
                data += ("ACTION=EMPTY");
            }

            if (!string.IsNullOrWhiteSpace(profile.Specification))
            {
                data += ("SPECIFICATION=" + profile.Specification);
            }
            else
            {
                data += "SPECIFICATION=EMPTY";
            }

            if (!string.IsNullOrWhiteSpace(profile.Password))
            {
                data += ("PASS="******"PASS=EMPTY";
            }

            return(enc.EncryptToString(data));
        }
Esempio n. 13
0
        public string CreateDateTimeToken()
        {
            DateTime time = DateTime.UtcNow;

            string token = time.ToString("s");

            token = simpleAes.EncryptToString(token);
            return(token);
        }
Esempio n. 14
0
        public ActionResult PLogin(Web.ViewModels.User.pLoginVM model)
        {
            rs r;

            if (ModelState.IsValid)
            {
                try
                {
                    SimpleAES __aes    = new SimpleAES();
                    string    __pw_aes = __aes.EncryptToString(model.Password);
                    var       _login   = __db.Users.FirstOrDefault(f => f.Username == model.Username && f.Password == __pw_aes);


                    if (_login != null)
                    {
                        DateTime exp   = DateTime.UtcNow.AddYears(1);
                        var      token = EncodeDecodeJWT.Encode(new Dictionary <string, object>
                        {
                            { "uid", _login.Id },
                            { "exp", exp.toJWTString() }
                        });
                        myCookies.Set("auth", token, exp);
                        loginVM log = new loginVM(_login);
                        MySsAuthUsers.setLogin(log);
                        r = rs.T("Ok!");
                    }
                    else
                    {
                        r = rs.F("Ok!");
                    }
                }
                catch (Exception ex)
                {
                    r = rs.F(ex.Message);
                }
            }
            else
            {
                r = rs.F("Lỗi nhập liệu!");
            }
            if (!r.r)
            {
                ModelState.AddModelError(string.Empty, r.m);
            }
            else
            {
                if (string.IsNullOrEmpty(model.ReturnUrl) == false)
                {
                    return(Redirect(myBase64EncodeDecode.DecodeBase64(model.ReturnUrl)));
                }
                else
                {
                    return(RedirectToAction("Profile", "User"));
                }
            }
            return(View(model));
        }
Esempio n. 15
0
 public static string enkriptuj(string s)
 {
     SimpleAES aes = new SimpleAES();
     if (s != "* * * * * * * * * *" && s != "" && s != "====================" && s != null)
     {
         s=aes.EncryptToString(s);
         return s;
     }
     else return s;
 }
Esempio n. 16
0
        private string EncryptPassword()
        {
            string password = "";

            if (passwordTextBox.Text.Length != 0)
            {
                SimpleAES aes = new SimpleAES ();
                password = aes.EncryptToString (passwordTextBox.Text);
            }
            return password;
        }
Esempio n. 17
0
        private string EncryptPassword()
        {
            string password = "";

            if (passwordTextBox.Text.Length != 0)
            {
                SimpleAES aes = new SimpleAES();
                password = aes.EncryptToString(passwordTextBox.Text);
            }
            return(password);
        }
Esempio n. 18
0
        public Game1(bool on)
        {
            online = on;
            game = this;
            totalTime = 0;
            startTotalTime = false;
            graphics = new GraphicsDeviceManager(this);
            graphics.PreferredBackBufferHeight = 720;
            graphics.PreferredBackBufferWidth = 960;
            Content.RootDirectory = "Content";
            skinManager = new ContentManager(this.Services, "Content");
            finishedSS = false;
            totalRecord = -1;
            commRecord = -1;

            SimpleAES enc = new SimpleAES();
            if (!File.Exists("Content\\records.txt"))
            {
                StreamWriter w = new StreamWriter("Content\\records.txt");
                w.WriteLine(enc.EncryptToString("fullgame 0 -1"));
                w.Flush();
                w.Dispose();
            }
            else
            {
                StreamReader r = new StreamReader("Content\\records.txt");
                bool totalFound = false;
                while (!r.EndOfStream)
                {
                    string s = enc.DecryptString(r.ReadLine());
                    if (s.Split(' ')[1] == "0")
                    {
                        if (s.Split(' ')[0] == "Level_26_-_Credits")
                            beatGame = true;
                        else if (s.Split(' ')[0] == "fullgame")
                        {
                            totalRecord = int.Parse(s.Split(' ')[2]);
                            totalFound = true;
                        }
                        else
                        {
                            if (commRecord == -1)
                                commRecord = 0;
                            commRecord += int.Parse(s.Split(' ')[2]);
                        }
                    }
                }
                if (!totalFound)
                    totalRecord = -1;

                r.Close();
                r.Dispose();
            }
        }
Esempio n. 19
0
        private void SendVerificationEmail(string email, string name)
        {
            SimpleAES           aes          = new SimpleAES();
            string              token        = aes.EncryptToString(email.ToLower());
            string              url          = "http://CareerThesaurus.com/Account/ConfirmEmail/" + token;
            EmailManager        emailManager = new EmailManager();
            EmailTemplateHelper eth          = new EmailTemplateHelper();
            string              body         = eth.GetTemplate("confirmemail");

            body = body.Replace("{{name}}", name);
            body = body.Replace("{{url}}", url);
            emailManager.SendMail("*****@*****.**", "CareerThesaurus", email, "Account Notification - Confirm Email", body);
        }
Esempio n. 20
0
        public ActionResult Register(Models.Registro pUsuario)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    using (var database = new SAPE_MVC.Models.SAPEEntities())
                    {
                        SimpleAES encrypter         = new SimpleAES();
                        string    encryptedPassword = encrypter.EncryptToString(pUsuario.Contrasena);
                        Persona   newPersona        = database.Persona.Create();
                        Usuario   newUsuario        = database.Usuario.Create();

                        newPersona.Nombre    = pUsuario.Nombre;
                        newPersona.Apellido1 = pUsuario.Apellido1;
                        newPersona.Apellido2 = pUsuario.Apellido2;

                        database.Persona.Add(newPersona);
                        database.SaveChanges();

                        newUsuario.FK_idPersona   = newPersona.idPersona;
                        newUsuario.Nombre         = pUsuario.Username;
                        newUsuario.Contrasena     = encryptedPassword;
                        newUsuario.FK_TipoUsuario = pUsuario.TipoUsuario;
                        database.Usuario.Add(newUsuario);
                        database.SaveChanges();

                        return(RedirectToAction("Index", "Home"));
                    }
                }
                else
                {
                    ModelState.AddModelError("", "Data is not correct");
                }
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:", eve.Entry.Entity.GetType().Name, eve.Entry.State);

                    foreach (var ve in eve.ValidationErrors)
                    {
                        Console.WriteLine("- Property: \"{0}\", Error: \"{1}\"", ve.PropertyName, ve.ErrorMessage);
                    }
                }
                throw;
            }

            return(View());
        }
Esempio n. 21
0
 public static void SetAESEncryptToString(string key, string value, DateTime dateExp)
 {
     try
     {
         HttpCookie cookies = new HttpCookie(key);
         cookies.Value   = aes.EncryptToString(value);
         cookies.Expires = dateExp;
         HttpContext.Current.Response.Cookies.Add(cookies);
     }
     catch
     {
         throw;
     }
 }
Esempio n. 22
0
        public JsonResult Create(FrmCreateUserVM model)
        {
            var __auth = MySsAuthUsers.GetAuth();
            rs  r;

            if (_userServ.Count(s => s.Username == model.Username) == 0)
            {
                try
                {
                    SimpleAES __aes  = new SimpleAES();
                    User      entity = new User();
                    //pass encode
                    entity.Username     = model.Username;
                    entity.Password     = __aes.EncryptToString(model.Password);
                    entity.RoleId       = model.RoleId;
                    entity.UserStatusId = 1;
                    entity.Address      = model.Address;
                    entity.Phone        = model.Phone;
                    entity.GioiTinh     = model.GioiTinh;
                    entity.Fullname     = model.Username;
                    entity.OwnerId      = __auth.ID;
                    entity.Image        = model.Image;

                    entity.UserQuans = new Collection <UserQuan>();
                    //danh sach nhan vien quan ly
                    foreach (var item in model.QuanIntIDs)
                    {
                        entity.UserQuans.Add(new UserQuan()
                        {
                            QuanID = item,
                            UserID = entity.Id
                        });
                    }
                    __db.Users.Add(entity);
                    __db.SaveChanges();
                    r = rs.T("Okay");
                }
                catch (Exception ex)
                {
                    r = rs.F("Lỗi: " + ex.Message);
                }
            }
            else
            {
                r = rs.F("Lỗi:tên đăng nhập đã tồn tại vui lòng chọn tên khác");
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
 public ActionResult EmailRobot(SettingEmailRobotVM viewmodel)
 {
     if (ModelState.IsValid)
     {
         SimpleAES __aes  = new SimpleAES();
         var       entity = _settingRepo.GetEntry(1);
         entity.InjectFrom(viewmodel);
         entity.sys_email_robot_pw = __aes.EncryptToString(viewmodel.sys_email_robot_pw);
         _settingRepo.Update(entity);
         _settingRepo.Save();
         CacheServ.ClearAll();
         TempData["message"] = "Update setting successfully!";
         return(RedirectToAction("EmailRobot"));
     }
     return(View(viewmodel));
 }
Esempio n. 24
0
        public JsonResult Edit(FrmCreateUserVM model)
        {
            rs r;

            using (var trans = new TransactionScope())
            {
                try
                {
                    SimpleAES __aes  = new SimpleAES();
                    var       entity = _userServ.SingleOrDefault(s => s.Id == model.ID);
                    entity.RoleId   = model.RoleId;
                    entity.Password = __aes.EncryptToString(model.Password);
                    entity.Phone    = model.Phone;
                    entity.Fullname = model.Fullname;
                    entity.GioiTinh = model.GioiTinh;
                    entity.Email    = model.Email;
                    entity.Address  = model.Address;
                    entity.Image    = model.Image;
                    entity.UserQuans.Clear();

                    //danh sach nhan vien quan ly
                    entity.UserQuans = new List <UserQuan>();
                    if (model.QuanIds != null)
                    {
                        foreach (var item in model.QuanIntIDs)
                        {
                            entity.UserQuans.Add(new UserQuan()
                            {
                                QuanID = item,
                                UserID = entity.Id
                            });
                        }
                    }

                    _userServ.Save();
                    trans.Complete();
                    r = rs.T("Okay");
                }
                catch (Exception ex)
                {
                    r = rs.F("Lỗi: " + ex.Message);
                }
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
Esempio n. 25
0
        private bool IsValid(string pUsername, string pPassword)
        {
            SimpleAES encryptor = new SimpleAES();
            bool      IsValid   = false;

            using (var database = new SAPE_MVC.Models.SAPEEntities())
            {
                var user = database.Usuario.FirstOrDefault(usuario => usuario.Nombre == pUsername);
                if (user != null)
                {
                    if (user.Contrasena == encryptor.EncryptToString(pPassword))
                    {
                        IsValid = true;
                    }
                }
            }
            return(IsValid);
        }
        protected string ConstructSessionKey(params string[] tokens)
        {
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < tokens.Length; i++)
            {
                if (i < tokens.Length - 1)
                {
                    sb.Append(tokens[i] + "|");
                }
                else
                {
                    sb.Append(tokens[i]);
                }
            }
            SimpleAES simpleaes = new SimpleAES();

            return(simpleaes.EncryptToString(sb.ToString()));
        }
Esempio n. 27
0
        public JsonResult mLoginProcess(Web.ViewModels.User.pLoginVM model)
        {
            rs r;

            if (ModelState.IsValid)
            {
                try
                {
                    SimpleAES __aes    = new SimpleAES();
                    string    __pw_aes = __aes.EncryptToString(model.Password);
                    var       _login   = __db.Users.FirstOrDefault(f => f.Username == model.Username && f.Password == __pw_aes);


                    if (_login != null)
                    {
                        DateTime exp   = DateTime.UtcNow.AddYears(1);
                        var      token = EncodeDecodeJWT.Encode(new Dictionary <string, object>
                        {
                            { "uid", _login.Id },
                            { "exp", exp.toJWTString() }
                        });
                        myCookies.Set("auth", token, exp);
                        loginVM log = new loginVM(_login);
                        MySsAuthUsers.setLogin(log);
                        r = rs.T("Ok!");
                    }
                    else
                    {
                        r = rs.F("Ok!");
                    }
                }
                catch (Exception ex)
                {
                    r = rs.F(ex.Message);
                }
            }
            else
            {
                r = rs.F("Lỗi nhập liệu!");
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
        public JsonResult Create(FrmCreateUserVM model)
        {
            rs r;

            if (_userServ.Count(s => s.Username == model.Username) == 0)
            {
                try
                {
                    SimpleAES __aes  = new SimpleAES();
                    User      entity = new User();
                    //pass encode
                    entity.Username     = model.Username;
                    entity.Password     = __aes.EncryptToString(model.Password);
                    entity.RoleId       = model.RoleID;
                    entity.UserStatusId = 1;
                    entity.IsVip1       = model.IsVip;
                    if (model.IsVip)
                    {
                        entity.NgayVip     = DateTime.Now;
                        entity.ChuThichVip = "Nâng cấp thủ công";
                    }
                    else
                    {
                        entity.ChuThichVip = "Tự động";
                    }
                    __db.Users.Add(entity);
                    __db.SaveChanges();
                    r = rs.T("Okay");
                }
                catch (Exception ex)
                {
                    r = rs.F("Lỗi: " + ex.Message);
                }
            }
            else
            {
                r = rs.F("Lỗi:tên đăng nhập đã tồn tại vui lòng chọn tên khác");
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
Esempio n. 29
0
        public JsonResult EditUser(FrmCreateUserVM model)
        {
            var  __auth  = MySsAuthUsers.GetAuth();
            bool isadmin = __auth.RoleId == 1 && __auth.Username == "admin";
            rs   r;

            using (var trans = new TransactionScope())
            {
                try
                {
                    SimpleAES __aes  = new SimpleAES();
                    var       entity = _userServ.SingleOrDefault(s => s.Id == model.ID);
                    entity.RoleId   = model.RoleId;
                    entity.Password = __aes.EncryptToString(model.Password);
                    entity.GioiTinh = model.GioiTinh;
                    entity.Address  = model.Address;
                    entity.Phone    = model.Phone;
                    entity.Email    = model.Email;
                    entity.Fullname = model.Fullname;
                    entity.Image    = model.Image;
                    if (isadmin && entity.Username != model.Username)
                    {
                        if (__db.Users.Any(a => a.Username == model.Username && a.Id != model.ID))
                        {
                            throw new Exception("Tên đăng nhập này đã tồn tại");
                        }
                        entity.Username = model.Username;
                    }
                    _userServ.Save();
                    trans.Complete();
                    r = rs.T("Okay");
                }
                catch (Exception ex)
                {
                    r = rs.F("Lỗi: " + ex.Message);
                }
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
        public static string Encrypt(string plainText)
        {
            SimpleAES aes = new SimpleAES();
            // Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
            // so that the same Salt and IV values can be used when decrypting.
            var saltStringBytes = Generate256BitsOfRandomEntropy();
            var ivStringBytes   = Generate256BitsOfRandomEntropy();
            var plainTextBytes  = Encoding.UTF8.GetBytes(plainText);

            using (var password = new Rfc2898DeriveBytes(passPhrase, saltStringBytes, DerivationIterations))
            {
                var keyBytes = password.GetBytes(Keysize / 8);
                using (var symmetricKey = new RijndaelManaged())
                {
                    symmetricKey.BlockSize = 256;
                    symmetricKey.Mode      = CipherMode.CBC;
                    symmetricKey.Padding   = PaddingMode.PKCS7;
                    using (var encryptor = symmetricKey.CreateEncryptor(keyBytes, ivStringBytes))
                    {
                        using (var memoryStream = new MemoryStream())
                        {
                            using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write))
                            {
                                cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
                                cryptoStream.FlushFinalBlock();
                                // Create the final bytes as a concatenation of the random salt bytes, the random iv bytes and the cipher bytes.
                                var cipherTextBytes = saltStringBytes;
                                cipherTextBytes = cipherTextBytes.Concat(ivStringBytes).ToArray();
                                cipherTextBytes = cipherTextBytes.Concat(memoryStream.ToArray()).ToArray();
                                memoryStream.Close();
                                cryptoStream.Close();
                                return(aes.EncryptToString(Convert.ToBase64String(cipherTextBytes)));
                            }
                        }
                    }
                }
            }
        }
Esempio n. 31
0
        public Room(string[] lines, bool freeroam, ReplayRecorder recorder)
            : this()
        {
            freeroaming = freeroam;
            this.recorder = recorder;

            SimpleAES decryptor = new SimpleAES();
            string[] line;

            // Get level name
            levelName = lines[0];
            custom = false;

            // Get level id
            levelID = lines[1];

            // Check if level will have a leaderboard
            canViewLeaderboards = decryptor.DecryptString(lines[2]) == "1";

            // Get level theme
            line = decryptor.DecryptString(lines[3]).Split(' ');
            Theme = FindTheme(line[0]);
            wallSet = new Tileset(Game1.tileSet[(int)Theme], 32, 32, 3, 3);

            // Get room dimensions
            line = decryptor.DecryptString(lines[4]).Split(' ');
            roomWidth = int.Parse(line[0]);
            roomHeight = int.Parse(line[1]);

            // Get goal times
            // Find record
            int rec = -1;
            if (!File.Exists("Content\\records.txt"))
                File.Create("Content\\records.txt");
            StreamReader findLastLevel = new StreamReader("Content\\records.txt");
            while (!findLastLevel.EndOfStream)
            {
                string[] level = decryptor.DecryptString(findLastLevel.ReadLine()).Split(' ');
                if (level[0] == levelName && level[1] == "0")
                {
                    rec = int.Parse(level[2]);
                    break;
                }
            }
            findLastLevel.Close();
            findLastLevel.Dispose();

            // Check if record is a gold time
            bool gotGold = false;
            string findIndex = levelName.Split('_')[1];
            int ii = int.Parse(findIndex) - 1;
            string[] g = decryptor.DecryptString(Levels.levels[ii][5]).Split(' ');
            if (rec != -1 && rec < int.Parse(g[0]))
                gotGold = true;

            // If it is, unlock platinum time
            goals = new int[gotGold ? 4 : 3];
            line = decryptor.DecryptString(lines[5]).Split(' ');
            for (int i = 0; i < goals.Length; i++)
                goals[i] = int.Parse(line[i]);

            // Get objects and tiles
            int index = 6;
            while (index < lines.Length)
            {
                line = decryptor.DecryptString(lines[index]).Split(' ');
                ParseObjectOrTile(line, freeroam);
                index++;
            }
            BuildTiles();

            // Generate zipline poles
            foreach (ZipLine z in ziplines)
                z.SetPoles(this);

            // Check to see if level is already in records file. If not, add it.
            // This unlocks the level in level select, since main levels (levels hard coded into the game)
            // are added from the records file.
            bool recordFound = false;
            StreamReader reader = new StreamReader("Content\\records.txt");
            while (!reader.EndOfStream)
            {
                string s = decryptor.DecryptString(reader.ReadLine());
                if (s.Split(' ')[0] == levelName)
                {
                    record = int.Parse(s.Split(' ')[2]);
                    recordFound = true;
                    break;
                }
            }
            reader.Close();
            reader.Dispose();
            if (!recordFound)
            {
                record = -1;
                StreamWriter writer = new StreamWriter("Content\\records.txt", true);
                writer.WriteLine(decryptor.EncryptToString(levelName + " 0 -1"));
                writer.Flush();
                writer.Dispose();
            }

            UpdateViewBox(false);
        }
        public object Login([FromBody] LoginReq Req)
        {
            try
            {
                var account = DB.Accounts.Where(u => u.Username == Req.Username && u.Password == MD5(Req.Password));
                if (account.Count() == 0)
                {
                    return(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, "Username or password is invalid"));
                }

                if (String.IsNullOrEmpty(account.First().AccessToken) || account.First().ExpireDate == null ||
                    account.First().ExpireDate < DateTime.Now)
                {
                    account.First().AccessToken = Guid.NewGuid().ToString("N");
                    account.First().ExpireDate  = DateTime.Now.AddDays(60);
                    DB.SubmitChanges();
                }
                SimpleAES AES = new SimpleAES();
                return(SuccessResult(new
                {
                    Name = account.First().Name,
                    Username = account.First().Username,
                    Gender = account.First().Gender,
                    Type = account.First().Type,
                    Birthday = account.First().Birthday,
                    AccessToken = account.First().AccessToken,
                    Avatar = account.First().Avatar,
                    ExpireDate = account.First().ExpireDate,
                    MSAccessToken = account.First().MSAccessToken,
                    MSExpireDate = account.First().MSExpireDate,
                    QR = "https://zxing.org/w/chart?cht=qr&chs=350x350&chld=L&choe=UTF-8&chl=" + AES.EncryptToString(account.First().Username)
                }));
            }
            catch (Exception ex)
            {
                return(FailResult(ex));
            }
        }
Esempio n. 33
0
        public override void Update(GameTime gameTime)
        {
            if (!Keyboard.GetState().IsKeyDown(Keys.Enter))
                entercheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.Up))
                upcheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.Down))
                downcheck = true;

            if (Keyboard.GetState().IsKeyDown(Keys.Up) && upcheck && !deleteCheck)
            {
                upcheck = false;
                if (!selected)
                    selectedIndex = Math.Max(0, selectedIndex - 1);
            }
            if (Keyboard.GetState().IsKeyDown(Keys.Down) && downcheck && !deleteCheck)
            {
                downcheck = false;
                if (!selected)
                    selectedIndex = Math.Min(selectedIndex + 1, selectableControl.Length - 1);
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Left))
            {
                if (selectedIndex == 0)
                {
                    musicVol = Math.Max(0f, musicVol - 0.01f);
                    MediaPlayer.Volume = 0.6f * musicVol;
                    SaveSettings();
                }
                else if (selectedIndex == 1)
                {
                    soundVol = Math.Max(0f, soundVol - 0.01f);
                    Game1.run.Volume = Settings.soundVol;
                    Game1.slide.Volume = Settings.soundVol;
                    SaveSettings();
                }
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Right))
            {
                if (selectedIndex == 0)
                {
                    musicVol = Math.Min(musicVol + 0.01f, 1f);
                    MediaPlayer.Volume = 0.6f * musicVol;
                    SaveSettings();
                }
                else if (selectedIndex == 1)
                {
                    soundVol = Math.Min(soundVol + 0.01f, 1f);
                    Game1.run.Volume = Settings.soundVol;
                    Game1.slide.Volume = Settings.soundVol;
                    SaveSettings();
                }
            }

            if (Keyboard.GetState().IsKeyDown(Keys.Enter) && entercheck && !selected)
            {
                entercheck = false;
                if (!selected)
                    if (selectableControl[selectedIndex] != "")
                        selected = true;
                    else if (selectedIndex == 10)
                        Game1.currentRoom = new SkinSelection();
                    else if (selectedIndex == 11)
                    {
                        ResetToDefault();
                        MediaPlayer.Volume = 0.6f * musicVol;
                        Game1.run.Volume = Settings.soundVol;
                        Game1.slide.Volume = Settings.soundVol;
                        SaveSettings();
                    }
                    else if (selectedIndex == 12)
                        deleteCheck = !deleteCheck;
            }

            if (deleteCheck)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Y))
                {
                    SimpleAES e = new SimpleAES();
                    StreamWriter writer = new StreamWriter("Content\\records.txt");
                    writer.WriteLine(e.EncryptToString("fullgame 0 -1"));
                    writer.Flush();
                    writer.Dispose();
                    verifyCheck = true;
                    deleteCheck = false;
                }
                else if (Keyboard.GetState().IsKeyDown(Keys.N))
                    deleteCheck = false;
            }

            if (selected)
            {
                if (Keyboard.GetState().GetPressedKeys().Count() > 0)
                {
                    if (!(Keyboard.GetState().IsKeyDown(Keys.Enter) && !entercheck))
                    {
                        if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                            entercheck = false;
                        controls[selectableControl[selectedIndex]] = Keyboard.GetState().GetPressedKeys()[0];
                        SaveSettings();
                        selected = false;
                    }
                }
            }
        }
        public LevelSelect(int tab)
        {
            pressDown = false;
            pressUp = false;
            pressEnter = false;
            pressLeft = false;
            pressRight = false;
            lastpage = false;
            pressS = false;
            showingBox = false;
            pressDel = false;
            pressD = false;
            pressY = false;
            pressN = false;
            areYouSure = false;
            pressL = false;

            background = Game1.backgrounds[0];
            roomHeight = 720;
            roomWidth = 960;

            levels = new List<Tuple<string, int, int, bool>>();
            selected = 0;
            scope = 0;
            this.tab = tab;

            dlpage = new List<Tuple<string, string, string, double>>();
            criteria = "";
            sortBy = 0;

            // Add main levels
            SimpleAES decryptor = new SimpleAES();
            if (!File.Exists("Content\\records.txt"))
            {
                StreamWriter newRecords = new StreamWriter("Content\\records.txt");
                newRecords.WriteLine(decryptor.EncryptToString("fullgame 0 -1"));
                newRecords.Flush();
                newRecords.Close();
                newRecords.Dispose();
            }
            StreamReader findMainLevels = new StreamReader("Content\\records.txt");
            while (!findMainLevels.EndOfStream)
            {
                string[] level = decryptor.DecryptString(findMainLevels.ReadLine()).Split(' ');
                if (level[1] == "0" && level[0] != "fullgame")
                    levels.Add(new Tuple<string, int, int, bool>(level[0], -1, -1, false));
            }
            findMainLevels.Close();
            findMainLevels.Dispose();

            // Add custom levels
            if (!Directory.Exists("Content\\rooms"))
                Directory.CreateDirectory("Content\\rooms");
            string[] choices = Directory.GetFiles("Content\\rooms");
            foreach (string s in choices)
                levels.Add(new Tuple<string, int, int, bool>(s.Split('\\')[s.Split('\\').Length - 1].Replace(".srl", ""), -1, -1, true));

            // Find record/medal achieved in each level
            for (int i = 0; i < levels.Count; i++)
            {
                // Find record
                string name = levels[i].Item1;
                StreamReader readRecords = new StreamReader("Content\\records.txt");
                if (readRecords.EndOfStream)
                {
                    readRecords.Close();
                    readRecords.Dispose();
                    break;
                }
                string line = decryptor.DecryptString(readRecords.ReadLine());
                while (line.Split(' ')[0] != name && !readRecords.EndOfStream)
                    line = decryptor.DecryptString(readRecords.ReadLine());
                bool iscustom = true;
                if (line.Split(' ')[0] == name)
                {
                    levels[i] = new Tuple<string, int, int, bool>(levels[i].Item1, int.Parse(line.Split(' ')[2]), -1, levels[i].Item4);
                    iscustom = line.Split(' ')[1] == "1";
                }
                readRecords.Close();
                readRecords.Dispose();

                // Find goal times
                if (!iscustom)
                {
                    if (name != "")
                    {
                        string findIndex = name.Split('_')[1];
                        int index = int.Parse(findIndex) - 1;
                        string[] goals = decryptor.DecryptString(Levels.levels[index][5]).Split(' ');
                        for (int j = 2; j >= 0; j--)
                        {
                            if (levels[i].Item2 != -1 && levels[i].Item2 <= int.Parse(goals[j]))
                                levels[i] = new Tuple<string, int, int, bool>(levels[i].Item1, levels[i].Item2, j, levels[i].Item4);
                        }
                        if (levels[i].Item3 == 0)
                        {
                            if (levels[i].Item2 != -1 && levels[i].Item2 <= int.Parse(goals[3]))
                                levels[i] = new Tuple<string, int, int, bool>(levels[i].Item1, levels[i].Item2, 3, levels[i].Item4);
                        }
                    }
                }
                else
                {
                    StreamReader findGoals = new StreamReader("Content\\rooms\\" + name + ".srl");
                    for (int skip = 1; skip <= 4; skip++)
                        findGoals.ReadLine();
                    string[] goals = decryptor.DecryptString(findGoals.ReadLine()).Split(' ');
                    for (int j = 2; j >= 0; j--)
                    {
                        if (levels[i].Item2 != -1 && levels[i].Item2 <= int.Parse(goals[j]))
                            levels[i] = new Tuple<string, int, int, bool>(levels[i].Item1, levels[i].Item2, j, levels[i].Item4);
                    }
                    findGoals.Close();
                    findGoals.Dispose();
                }
            }

            custompage = new List<Tuple<string, int, int, bool>>();
            var it = from Tuple<string, int, int, bool> t in levels
                     where t.Item4 == (tab == 1)
                     select t;
            foreach (Tuple<string, int, int, bool> t in it)
                custompage.Add(t);
            maxSelected = custompage.Count - 1;

            if (!Game1.playingGrass)
                MediaPlayer.Play(Game1.grassMusic);
            Game1.ResetMusic();
            Game1.playingGrass = true;
        }
Esempio n. 35
0
        public JsonResult Create(FrmCreateUserVM model)
        {
            rs r;

            if (_userServ.Count(s => s.Username == model.Username) == 0)
            {
                using (TransactionScope tx = new TransactionScope())
                {
                    try
                    {
                        SimpleAES __aes  = new SimpleAES();
                        User      entity = new User();
                        //pass encode
                        entity.Username     = model.Username;
                        entity.Password     = __aes.EncryptToString(model.Password);
                        entity.RoleId       = model.RoleId;
                        entity.UserStatusId = 1;
                        entity.Address      = model.Address;
                        entity.GioiTinh     = model.GioiTinh;
                        entity.Phone        = model.Phone;
                        entity.Email        = model.Email;
                        entity.Fullname     = model.Username;
                        entity.Image        = model.Image;
                        __db.Users.Add(entity);
                        __db.SaveChanges();

                        //quan

                        /*Quan quan = new Quan()
                         * {
                         *  UserId = entity.Id,
                         *  TenQuan = "Quán mẫu",
                         *  MaQuan = "QUAN_MAU",
                         *  DiaChi = "Tp. HCM",
                         *  DienThoai = "0123456789",
                         *  BanArr = "1,2,3,4,5,6,7,8,9,10",
                         *  ImageThumbnail =  Utils.RandomAnhSample("/Content/images/sample/shop",1,2,".png")
                         * };
                         * __db.Quan.Add(quan);
                         * __db.SaveChanges();
                         *
                         * //product cat & product
                         * List<ProductCat> product_cat = new List<ProductCat>();
                         * for(var i=0;i<2;i++)
                         * {
                         *  var pc = new ProductCat()
                         *  {
                         *      QuanId = quan.Id,
                         *      Name = "Danh mục mẫu" + (i + 1),
                         *      Products = new Collection<Product>(),
                         *      ImageThumbnail =  Utils.RandomAnhSample("/Content/images/sample/cat",1,2,".png")
                         *  };
                         *  for (var j = 0; j < 2; j++)
                         *  {
                         *       pc.Products.Add(new Product(){
                         *           ProductName = "Sản phẩm "+(j+1),
                         *           MaSo = "MSP-"+j+1,
                         *           Price = Utils.RandomGia(),
                         *           ThumbnailImage = Utils.RandomAnhSample("/Content/images/sample/p",1,5,".png"),
                         *      });
                         *  }
                         *  product_cat.Add(pc);
                         * }
                         * __db.ProductCat.AddRange(product_cat);
                         * __db.SaveChanges();
                         *
                         * //thuc don
                         * var dssp = __db.Product.Where(w => w.ProductCat.QuanId == quan.Id).Select(s=>s.Id).ToList();
                         * List<ThucDon> tds = new List<ThucDon>();
                         * for (var i = 0; i < 2; i++)
                         * {
                         *  ThucDon td = new ThucDon();
                         *  td.QuanId = quan.Id;
                         *  td.Icon = Utils.RandomAnhSample("/Content/images/sample/menu", 1, 3, ".png");
                         *  td.TenThucDon = "Thực đơn mẫu" + (i + 1);
                         *  td.ThucDonCTs = new Collection<ThucDonCT>();
                         *
                         *  td.ThucDonCTs.Add(new ThucDonCT()
                         *  {
                         *      ProductId = dssp[i],
                         *  });
                         *
                         *  tds.Add(td);
                         * }
                         * __db.ThucDon.AddRange(tds);
                         * __db.SaveChanges();
                         */

                        r = rs.T("Okay");
                        tx.Complete();
                    }
                    catch (Exception ex)
                    {
                        r = rs.F("Lỗi: " + ex.Message);
                    }
                }
            }
            else
            {
                r = rs.F("Lỗi:tên đăng nhập đã tồn tại vui lòng chọn tên khác");
            }
            return(Json(r, JsonRequestBehavior.DenyGet));
        }
Esempio n. 36
0
    public string GetSaveString(AreaManager areaManager, FollowerManager followerManager, NPCManager npcManager, BuildingManager buildingManager)
    {
        int    pos  = 0;
        string data = "";

        try
        {
            //Bank 0
            data += "" + GetPlayerBank().GetInventory().ToString();
            pos++;
            //Skills 1
            data += "#" + GetPlayer().GetSkillString();
            pos++;
            //Inventory 2
            data += "#" + GetPlayerInventory().ToString();
            pos++;
            //Areas 3
            data += "#" + areaManager.SaveAreas();
            pos++;
            //Followers 4
            data += "#" + followerManager.ToString();
            pos++;
            //HP 5
            data += "#" + GetPlayer().CurrentHP.ToString();
            pos++;
            //ActiveFollower 6
            if (GetPlayer().activeFollower != null)
            {
                data += "#" + GetPlayer().activeFollower.id;
            }
            else
            {
                data += "#";
            }
            pos++;
            //Recipes 7
            data += "#";
            foreach (string s in GetPlayer().GetRecipes())
            {
                data += s + "/";
            }
            pos++;
            //EquippedItems 8
            data += "#";
            foreach (KeyValuePair <GameItem, int> pair in GetPlayerInventory().GetEquippedItems())
            {
                data += pair.Key.Id + "/";
            }
            pos++;
            //Settings 9
            data += "#";
            data += isSplitView.ToString();
            data += ",";
            data += compactBankView.ToString();
            data += ",";
            data += expensiveItemThreshold;
            pos++;
            //NPC data 10
            data += "#";
            data += npcManager.GetNPCData();
            pos++;
            //Sushi House Data 11
            data += "#";
            data += sushiHouseRice + "," + sushiHouseSeaweed;
            pos++;
            //Tannery Data 12
            data += "#";
            foreach (Building b in buildingManager.GetBuildings())
            {
                if (b.Salt > 0)
                {
                    data += "" + b.ID + "," + b.Salt + "/";
                }
            }
            pos++;
            //Tannery Slot Data 13
            data += "#";
            foreach (Building b in buildingManager.GetBuildings())
            {
                if (b.IsTannery)
                {
                    data += b.ID + ">";
                    foreach (TanningSlot slot in b.TanneryItems)
                    {
                        data += slot.GetString() + "_";
                    }
                    data += "@";
                }
            }
            pos++;
            //GameState.isHunting 14
            data += "#";
            data += isHunting.ToString() + ",";
            data += huntingAreaID + ",";
            data += huntingStartTime.ToString() + ",";
            data += huntingEndTime.ToString();
            //Bank Tabs 15
            data += "#";
            data += GetPlayerBank().GetTabsString();
            data  = Encryptor.EncryptToString(data);
            pos++;
        }
        catch
        {
            data = "Failed to generate save file. Please contact the developer to let him know he messed up. (Error line:" + pos + ")";
        }
        return(data);
    }
        private static string MakeToken(string token)
        {
            SimpleAES aes = new SimpleAES();

            XDocument x = new XDocument(new XElement("T", token));

            string ret = aes.EncryptToString(x.ToString());

            return ret;
        }
Esempio n. 38
0
    public string GetSaveStringEncrypted(AreaManager areaManager, FollowerManager followerManager, NPCManager npcManager, BuildingManager buildingManager, BattleManager battleManager, bool encrypt)
    {
        int    pos  = 0;
        string data = "";

        //Bank 0
        data += "" + GetPlayerBank().GetInventory().ToString();
        pos++;
        //Skills 1
        data += "#" + GetPlayer().GetSkillString();
        pos++;
        //Inventory 2
        data += "#" + GetPlayerInventory().ToStringSorted();
        pos++;
        //Areas 3
        data += "#" + areaManager.SaveAreas();
        pos++;
        //Followers 4
        data += "#" + followerManager.ToString();
        pos++;
        //HP 5
        data += "#" + GetPlayer().CurrentHP.ToString();
        pos++;
        //ActiveFollower 6
        if (GetPlayer().activeFollower != null)
        {
            data += "#" + GetPlayer().activeFollower.id;
        }
        else
        {
            data += "#";
        }
        pos++;
        //Recipes 7
        data += "#";

        /*foreach (string s in GetPlayer().GetRecipes())
         * {
         *  data += s + "/";
         * }*/
        pos++;
        //EquippedItems 8
        data += "#";
        foreach (KeyValuePair <GameItem, int> pair in GetPlayerInventory().GetEquippedItems())
        {
            data += pair.Key.Id + "/";
        }
        pos++;
        //Settings 9
        data += "#";
        data += isSplitView.ToString();
        data += ",";
        data += compactBankView.ToString();
        data += ",";
        data += expensiveItemThreshold;
        data += ",";
        data += totalKills;
        data += ",";
        data += PetShopUnlocked.ToString();
        data += ",";
        data += autoBuySushiSupplies.ToString();
        data += ",";
        data += totalCoinsEarned;
        data += ",";
        data += totalDeaths;
        pos++;
        //NPC data 10
        data += "#";
        data += npcManager.GetNPCData();
        pos++;
        //Sushi House Data 11
        data += "#";
        data += sushiHouseRice + "," + sushiHouseSeaweed;
        pos++;
        //Tannery Data 12
        data += "#";
        foreach (Building b in buildingManager.GetBuildings())
        {
            if (b.Salt > 0)
            {
                data += "" + b.ID + "," + b.Salt + "/";
            }
        }
        pos++;
        //Tannery Slot Data 13
        data += "#";
        foreach (Building b in buildingManager.GetBuildings())
        {
            if (b.IsTannery)
            {
                data += b.ID + ">";
                foreach (TanningSlot slot in b.TanneryItems)
                {
                    data += slot.GetString() + "_";
                }
                data += "@";
            }
        }
        pos++;
        //GameState.isHunting 14
        data += "#";
        data += isHunting.ToString() + ",";
        data += huntingAreaID + ",";
        data += huntingStartTime.ToString() + ",";
        data += huntingEndTime.ToString();
        pos++;
        //Bank Tabs 15
        data += "#";
        data += GetPlayerBank().GetTabsString();
        pos++;
        //Pets 16
        data += "#";
        data += GetPlayer().GetPetString();
        pos++;
        //KC 17
        data += "#";
        data += GetKCString();
        pos++;
        //Dojos 18
        data += "#";
        data += battleManager.GetDojoSaveData();
        pos++;
        if (encrypt)
        {
            data = Encryptor.EncryptToString(data);
        }

        return(data);
    }
Esempio n. 39
0
        public override void Update(GameTime gameTime)
        {
            // Reset keys
            if (!Keyboard.GetState().IsKeyDown(Keys.Down))
                pressDown = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.Up))
                pressUp = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.Enter))
                pressEnter = true;

            // Cycle through choices
            if (Keyboard.GetState().IsKeyDown(Keys.Down) && pressDown)
            {
                pressDown = false;
                selected++;
            }
            else if (Keyboard.GetState().IsKeyDown(Keys.Up) && pressUp)
            {
                pressUp = false;
                selected--;
            }

            // Select a choice
            if (Keyboard.GetState().IsKeyDown(Keys.Enter) && pressEnter)
            {
                if (selected == 0)
                {
                    SimpleAES enc = new SimpleAES();
                    if (!File.Exists("Content\\records.txt"))
                    {
                        StreamWriter w = new StreamWriter("Content\\records.txt");
                        w.WriteLine(enc.EncryptToString("fullgame 0 -1"));
                        w.Flush();
                        w.Dispose();
                    }
                    else
                    {
                        StreamReader r = new StreamReader("Content\\records.txt");
                        string s = enc.DecryptString(r.ReadLine());
                        while (s.Split(' ')[1] != "0" && s.Split(' ')[0] != "fullgame" && !r.EndOfStream)
                            s = enc.DecryptString(r.ReadLine());
                        if (s.Split(' ')[1] == "0" && s.Split(' ')[0] == "fullgame")
                            Game1.totalRecord = int.Parse(s.Split(' ')[2]);
                        else
                            Game1.totalRecord = -1;
                        r.Close();
                        r.Dispose();
                    }
                    Game1.finishedSS = false;
                    Levels.Index = 0;
                    Game1.startTotalTime = true;
                    Game1.currentRoom = new Room(Levels.levels[0], true, new ReplayRecorder());
                }
                else if (selected == 1)
                    Game1.currentRoom = new LevelSelect(0);
                else if (selected == 2)
                    Game1.currentRoom = new Settings();
                else if (selected == 3)
                    Game1.exit = true;
            }

            if (selected < 0)
                selected = 0;
            else if (selected > MAX_SELECTED)
                selected = MAX_SELECTED;
        }
Esempio n. 40
0
        public virtual void Update(GameTime gameTime)
        {
            // Reset keys
            if (!Keyboard.GetState().IsKeyDown(Settings.controls["Restart"]))
                rcheck = true;
            if (!Keyboard.GetState().IsKeyDown(Settings.controls["Pause"]))
                pcheck = true;
            if (!Keyboard.GetState().IsKeyDown(Settings.controls["Freeroam"]))
                fcheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.L))
                lcheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.Up))
                upcheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.Down))
                downcheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.S))
                scheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.O))
                ocheck = true;
            if (!Keyboard.GetState().IsKeyDown(Keys.T))
                tcheck = true;

            // Rate level
            if (Keyboard.GetState().IsKeyDown(Keys.T) && tcheck && Game1.online && custom)
            {
                tcheck = false;
                Paused = true;
                int temp;
                if (int.TryParse(Microsoft.VisualBasic.Interaction.InputBox("Enter a number from 1 to 5, 5 being a great level.", "Rate"), out temp))
                {
                    if (temp > 0 && temp <= 5)
                    {
                        try
                        {
                            WebStuff.SendRating(temp, Game1.userName, levelID);
                        }
                        catch (Exception)
                        {
                            System.Windows.Forms.MessageBox.Show("Rating failed to upload. Please try again later.", "Rating Failed");
                        }
                    }
                    else
                        System.Windows.Forms.MessageBox.Show("Your rating must be a number between 1 and 5");
                }
            }

            // Restart when R is pressed
            if (Keyboard.GetState().IsKeyDown(Settings.controls["Restart"]) && rcheck)
            {
                if (custom)
                    Game1.currentRoom = new Room("Content\\rooms\\" + levelName + ".srl", false, new ReplayRecorder());
                else
                    Game1.currentRoom = new Room(Levels.levels[Levels.Index], false, new ReplayRecorder());
            }
            else if (Keyboard.GetState().IsKeyDown(Settings.controls["Freeroam"]) && fcheck)
            {
                if (custom)
                    Game1.currentRoom = new Room("Content\\rooms\\" + levelName + ".srl", true, new ReplayRecorder());
                else
                    Game1.currentRoom = new Room(Levels.levels[Levels.Index], true, new ReplayRecorder());
            }

            // Pause the game when P is pressed
            if (Keyboard.GetState().IsKeyDown(Settings.controls["Pause"]) && pcheck && !viewingLeaderboards)
            {
                pcheck = false;
                Paused = !Paused;
            }

            // Show leaderboards when L is pressed
            if (Keyboard.GetState().IsKeyDown(Keys.L) && lcheck && (Paused || Finished) && Game1.online && canViewLeaderboards)
            {
                lcheck = false;
                if (!viewingLeaderboards)
                {
                    try
                    {
                        viewingLeaderboards = true;
                        leaderboardData = WebStuff.GetScores(levelID, Game1.userName, leaderboardPage * 10);
                        canScrollDown = leaderboardData.Length == 11;
                    }
                    catch (Exception)
                    {
                        System.Windows.Forms.MessageBox.Show("There was a problem connecting to the leaderboards.", "Connection Error");
                        viewingLeaderboards = false;
                    }
                }
                else
                    viewingLeaderboards = false;
            }

            if (viewingLeaderboards)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Up) && upcheck && leaderboardPage > 0)
                {
                    upcheck = false;
                    try
                    {
                        leaderboardData = WebStuff.GetScores(levelID, Game1.userName, (leaderboardPage - 1) * 10);
                    }
                    catch (Exception)
                    {
                        System.Windows.Forms.MessageBox.Show("There was a problem connecting to the leaderboards.", "Connection Error");
                    }
                    leaderboardPage--;
                    canScrollDown = true;
                }
                else if (Keyboard.GetState().IsKeyDown(Keys.Down) && downcheck && canScrollDown)
                {
                    downcheck = false;
                    try
                    {
                        leaderboardData = WebStuff.GetScores(levelID, Game1.userName, (leaderboardPage + 1) * 10);
                    }
                    catch (Exception)
                    {
                        System.Windows.Forms.MessageBox.Show("There was a problem connecting to the leaderboards.", "Connection Error");
                    }
                    leaderboardPage++;
                    canScrollDown = leaderboardData.Length == 11;
                }
            }

            // Update freeroam cam
            if (freeroaming && !Paused)
            {
                if (Keyboard.GetState().IsKeyDown(Keys.Left))
                    viewBox.X -= 8;
                if (Keyboard.GetState().IsKeyDown(Keys.Right))
                    viewBox.X += 8;
                if (Keyboard.GetState().IsKeyDown(Keys.Up))
                    viewBox.Y -= 8;
                if (Keyboard.GetState().IsKeyDown(Keys.Down))
                    viewBox.Y += 8;
            }

            if (!Finished)
            {
                if (!Paused)
                {
                    if (recorder.playing)
                        recorder.PlayFrame();
                    else
                        recorder.RecordFrame();

                    // Update booster animations
                    foreach (Booster b in boosters)
                        b.Update();

                    // Find platforms
                    var plats = from Wall f in walls
                                where f is FloatingPlatform
                                select f as FloatingPlatform;
                    foreach (FloatingPlatform f in plats)
                        f.Update();

                    // Update boxes
                    foreach (Box b in boxes)
                        b.Update();

                    // Update character
                    Runner.Update();

                    // Update rocket launchers
                    foreach (RocketLauncher r in launchers)
                    {
                        if (r.explosion != null)
                            r.explosion.Update();
                        if (r.Update())
                        {
                            r.explosion = new Explosion(new Vector2(r.rocket.hitBox.X, r.rocket.hitBox.Y), Color.OrangeRed);
                            r.pause = 0;
                            r.rocket.position.X = -10000;
                            r.rocket.position.Y = -10000;
                            r.rocket.hitBox.X = -10000;
                            r.rocket.hitBox.Y = -10000;
                        }
                    }

                    // Update flamethrowers
                    foreach (Flamethrower f in flamethrowers)
                        f.Update();

                    // Move viewbox to keep up with character
                    UpdateViewBox(freeroaming);

                    // If the runner can be moved, increment the timer
                    if (Runner.controllable)
                    {
                        time += gameTime.ElapsedGameTime.Milliseconds;
                        if (!Game1.finishedSS && Game1.startTotalTime && !recorder.playing)
                            Game1.totalTime += gameTime.ElapsedGameTime.Milliseconds;
                    }
                }
                else
                {
                    Game1.run.Stop();
                    Game1.slide.Stop();

                    if (Keyboard.GetState().IsKeyDown(Keys.O) && ocheck)
                    {
                        ocheck = false;
                        System.Windows.Forms.OpenFileDialog openFD = new System.Windows.Forms.OpenFileDialog();
                        if (!Directory.Exists("Content\\replays"))
                            Directory.CreateDirectory("Content\\replays");
                        openFD.InitialDirectory = "Content\\replays";
                        openFD.Filter = "Replay Files (*.rpl)|*.rpl";
                        if (openFD.ShowDialog() == System.Windows.Forms.DialogResult.OK && File.Exists(openFD.FileName))
                        {
                            ReplayRecorder rec = new ReplayRecorder(openFD.FileName);
                            if (custom)
                                Game1.currentRoom = new Room("Content\\rooms\\" + levelName + ".srl", false, rec);
                            else
                                Game1.currentRoom = new Room(Levels.levels[Levels.Index], false, rec);
                        }
                    }
                }
            }
            else
            {
                Game1.run.Stop();
                Game1.slide.Stop();

                // Fix glitch where you can restart at the same time you hit the finish and achieve a time of 0 seconds
                if (time == 0)
                {
                    if (custom)
                        Game1.currentRoom = new Room("Content\\rooms\\" + levelName + ".srl", false, new ReplayRecorder());
                    else
                        Game1.currentRoom = new Room(Levels.levels[Levels.Index], false, new ReplayRecorder());
                    return;
                }

                if (write && !recorder.playing)
                {
                    write = false;

                    // Get goal beaten, if any
                    if (goals.Length > 3 && time <= goals[3])
                        goalBeaten = 0;
                    else if (time <= goals[0])
                        goalBeaten = 1;
                    else if (time <= goals[1])
                        goalBeaten = 2;
                    else if (time <= goals[2])
                        goalBeaten = 3;

                    StreamWriter writer;
                    SimpleAES encryptor = new SimpleAES();

                    // If record is beaten, save new record
                    if (time < record || record == -1)
                    {
                        StreamReader reader = new StreamReader("Content\\records.txt");
                        writer = new StreamWriter("Content\\recordstemp.txt", false);
                        bool found = false;

                        // Rewrite records file, but only change current level's time
                        while (!reader.EndOfStream)
                        {
                            string line = encryptor.DecryptString(reader.ReadLine());
                            if (line.Split(' ')[0] == levelName)
                            {
                                found = true;
                                writer.WriteLine(encryptor.EncryptToString(levelName + " " + (custom ? "1" : "0") + " " + time.ToString()));
                            }
                            else
                                writer.WriteLine(encryptor.EncryptToString(line));
                        }
                        if (!found)
                            writer.WriteLine(encryptor.EncryptToString(levelName + " " + (custom ? "1" : "0") + " " + time.ToString()));
                        reader.Dispose();
                        writer.Flush();
                        writer.Dispose();
                        File.Delete("Content\\records.txt");
                        File.Move("Content\\recordstemp.txt", "Content\\records.txt");
                    }

                    if (Levels.Index == Levels.levels.Length - 2)
                        Game1.beatGame = true;

                    if (!Game1.finishedSS && Game1.startTotalTime && Levels.Index == Levels.levels.Length - 2 && (Game1.totalTime < Game1.totalRecord || Game1.totalRecord == -1))
                    {
                        Game1.finishedSS = true;
                        StreamReader reader = new StreamReader("Content\\records.txt");
                        writer = new StreamWriter("Content\\recordstemp.txt", false);
                        bool found = false;

                        // Rewrite records file, but only change current level's time
                        while (!reader.EndOfStream)
                        {
                            string line = encryptor.DecryptString(reader.ReadLine());
                            if (line.Split(' ')[0] == "fullgame" && line.Split(' ')[1] == "0")
                            {
                                found = true;
                                writer.WriteLine(encryptor.EncryptToString("fullgame 0 " + Game1.totalTime.ToString()));
                            }
                            else
                                writer.WriteLine(encryptor.EncryptToString(line));
                        }
                        if (!found)
                            writer.WriteLine(encryptor.EncryptToString("fullgame 0 " + Game1.totalTime.ToString()));
                        reader.Dispose();
                        writer.Flush();
                        writer.Dispose();
                        File.Delete("Content\\records.txt");
                        File.Move("Content\\recordstemp.txt", "Content\\records.txt");
                    }
                }

                if (upload && canViewLeaderboards && !recorder.playing)
                {
                    // Upload score to leaderboard
                    upload = false;
                    if (Game1.online)
                    {
                        try
                        {
                            WebStuff.WriteScore(time, Game1.userName, levelID);
                            if (Game1.finishedSS && !custom)
                            {
                                WebStuff.WriteScore(Game1.totalTime, Game1.userName, "fullgame");
                                if (Game1.totalTime < Game1.totalRecord)
                                    Game1.totalRecord = Game1.totalTime;
                            }
                        }
                        catch (Exception)
                        {
                            System.Windows.Forms.MessageBox.Show("Uploading score to leaderboards failed.", "Leaderboard Error");
                        }
                        if (Game1.beatGame && !custom)
                        {
                            Game1.commRecord = -1;
                            StreamReader r = new StreamReader("Content\\records.txt");
                            SimpleAES enc = new SimpleAES();
                            while (!r.EndOfStream)
                            {
                                string s = enc.DecryptString(r.ReadLine());
                                if (s.Split(' ')[1] == "0")
                                {
                                    if (s.Split(' ')[0] != "Level_26_-_Credits" && s.Split(' ')[0] != "fullgame")
                                    {
                                        if (Game1.commRecord == -1)
                                            Game1.commRecord = 0;
                                        Game1.commRecord += int.Parse(s.Split(' ')[2]);
                                    }
                                }
                            }
                            r.Close();
                            r.Dispose();
                        }
                    }
                }

                if (writeNext && !custom && Levels.Index < Levels.levels.Count() - 1 && !recorder.playing)
                {
                    // Add next level to level select if not already unlocked
                    writeNext = false;
                    bool recordFound = false;
                    StreamReader reader = new StreamReader("Content\\records.txt");
                    SimpleAES encryptor = new SimpleAES();
                    string name = Levels.levels[Levels.Index + 1][0];
                    while (!reader.EndOfStream)
                    {
                        string s = encryptor.DecryptString(reader.ReadLine());
                        if (s.Split(' ')[0] == name)
                        {
                            recordFound = true;
                            break;
                        }
                    }
                    reader.Close();
                    reader.Dispose();
                    if (!recordFound)
                    {
                        StreamWriter writer = new StreamWriter("Content\\records.txt", true);
                        writer.WriteLine(encryptor.EncryptToString(name + " 0 -1"));
                        writer.Flush();
                        writer.Dispose();
                    }
                }

                // Check if they want to see replay
                if (Keyboard.GetState().IsKeyDown(Keys.W))
                {
                    recorder.playing = true;
                    recorder.start = true;
                    if (custom)
                        Game1.currentRoom = new Room("Content\\rooms\\" + levelName + ".srl", false, recorder);
                    else
                        Game1.currentRoom = new Room(Levels.levels[Levels.Index], false, recorder);
                }

                // Check if they want to save replay
                if (Keyboard.GetState().IsKeyDown(Keys.S) && scheck)
                {
                    scheck = false;
                    recorder.Save(levelName);
                    recorderSaved = true;
                }

                // Move to next level when enter is pressed, or back to menu if custom level
                if (Keyboard.GetState().IsKeyDown(Keys.Enter))
                {
                    if (!custom)
                    {
                        if (!recorder.playing || !recorder.loaded)
                        {
                            if (Game1.startTotalTime && Levels.Index == Levels.levels.Length - 2)
                                Game1.startTotalTime = false;
                            Levels.Index++;
                            if (Levels.Index == Levels.levels.Count())
                                Game1.currentRoom = new MainMenu(false);
                            else
                            {
                                while (Levels.Index < Levels.levels.Length && Levels.levels[Levels.Index][0] == "")
                                    Levels.Index++;
                                Game1.currentRoom = new Room(Levels.levels[Levels.Index], true, new ReplayRecorder());
                            }
                        }
                    }
                    else
                        Game1.currentRoom = new LevelSelect(1);
                }
            }
        }
Esempio n. 41
0
        protected override void Update(GameTime gameTime)
        {
            //			if (Keyboard.GetState().IsKeyDown(Keys.Z))
            //				this.TargetElapsedTime = TimeSpan.FromSeconds(0.5f);
            //			else
            //				this.TargetElapsedTime = TimeSpan.FromSeconds(0.016f);

            if (!Keyboard.GetState().IsKeyDown(Keys.Escape))
                pressEscape = true;
            if (Keyboard.GetState().IsKeyDown(Keys.Escape) && pressEscape || exit)
            {
                if (Game1.finishedSS)
                {
                    Game1.finishedSS = false;
                    SimpleAES enc = new SimpleAES();
                    if (!File.Exists("Content\\records.txt"))
                    {
                        StreamWriter w = new StreamWriter("Content\\records.txt");
                        w.WriteLine(enc.EncryptToString("fullgame 0 -1"));
                        w.Flush();
                        w.Dispose();
                    }
                    else
                    {
                        StreamReader r = new StreamReader("Content\\records.txt");
                        string s = enc.DecryptString(r.ReadLine());
                        while (s.Split(' ')[1] != "0" && s.Split(' ')[0] != "fullgame" && !r.EndOfStream)
                            s = enc.DecryptString(r.ReadLine());
                        if (s.Split(' ')[1] == "0" && s.Split(' ')[0] == "fullgame")
                            totalRecord = int.Parse(s.Split(' ')[2]);
                        else
                            totalRecord = -1;
                        r.Close();
                        r.Dispose();
                    }
                }
                totalTime = 0;
                startTotalTime = false;
                currentRoom.viewingLeaderboards = false;
                pressEscape = false;
                if (currentRoom is MainMenu)
                    this.Exit();
                else if (currentRoom is SkinSelection)
                    currentRoom = new Settings();
                else if (currentRoom is FGLeaderboard)
                    currentRoom = new LevelSelect(0);
                else
                    currentRoom = new MainMenu(true);
            }

            currentRoom.Update(gameTime);
            base.Update(gameTime);
        }