public ActionResult Verify(vmAccountVerify model) { if (ModelState.IsValid) { try { //decrypt oauth string string oauthDecode = HttpUtility.UrlDecode(model.OAuth); oauthDecode = oauthDecode.Replace(" ", "+"); //fix situations where spaces and plus get mixed up string decryptStr = new SimpleAES().Decrypt(oauthDecode); //split into password and username string[] s = Regex.Split(decryptStr, "\\|\\|"); if (Membership.ValidateUser(s[1], s[0]) == true) { if (Membership.Provider.ChangePassword(s[1], s[0], model.Password)) { FormsAuthentication.SetAuthCookie(s[1], true); return(RedirectToAction("Index", "Dashboard")); } } } catch { } TempData["Error"] = "Change password failed."; } else { TempData["Error"] = "Change password failed."; } return(View(model)); }
private void sendResultEmailWithSchool(string name, string email, string selectedschool, string otherschools) { SimpleAES aes = new SimpleAES(); EmailManager emailManager = new EmailManager(); EmailTemplateHelper eth = new EmailTemplateHelper(); string token = aes.EncryptToBase64String(email); string url = "http://www.CareerThesaurus.com/TakeTest/TestReport/" + token; string body = eth.GetTemplate("testresultswithschool"); body = body.Replace("{{name}}", name); body = body.Replace("{{url}}", url); dynamic selected = JObject.Parse(selectedschool); dynamic other = JArray.Parse(otherschools); body = body.Replace("{{schoolname}}", (string)selected["name"]); body = body.Replace("{{schoollogo}}", (string)selected["logo"]); body = body.Replace("{{schoolurl}}", (string)selected["url"]); string str = "<table><tr>"; foreach (dynamic item in other) { if (item["name"] != selected["name"]) { //str += "<td><a href='" + item["url"] + "' ><img src='" + item["logo"] + "' alt='School logo' title='similar school'></a></td>"; str += "<td><a style='margin:0;' href='" + item["url"] + "' ><img src='" + item["logo"] + "' alt='' ></a><a style='padding-right:10px;' href='" + item["url"] + "' >" + item["name"] + "</a></td>"; } } str += "</tr></table>"; body = body.Replace("{{otherschools}}", str); emailManager.SendMail("*****@*****.**", "CareerThesaurus", email, "Your Career Test Results", body); }
public object Validate() { try { SimpleAES AES = new SimpleAES(); return(SuccessResult(new { Name = CurrentAccount.Name, Gender = CurrentAccount.Gender, Type = CurrentAccount.Type, Birthday = CurrentAccount.Birthday, Avatar = CurrentAccount.Avatar, AccessToken = CurrentAccount.AccessToken, ExpireDate = CurrentAccount.ExpireDate, Username = CurrentAccount.Username, MSAccessToken = CurrentAccount.MSAccessToken, MSExpireDate = CurrentAccount.MSExpireDate, Phone = CurrentAccount.Phone, QR = "https://zxing.org/w/chart?cht=qr&chs=350x350&chld=L&choe=UTF-8&chl=" + AES.EncryptToString(CurrentAccount.Username) })); } catch (Exception ex) { return(FailResult(ex)); } }
public void Connect() { errortxt = GameObject.Find("Login").transform.Find("Panel").transform.Find("errorTxt").gameObject; user = nombre.GetComponent <InputField>().text; passwd = password.GetComponent <InputField>().text; if (user.Trim().Equals("") || passwd.Trim().Equals("")) { errortxt.SetActive(true); errortxt.transform.GetComponent <Text>().text = "DEBES RELLENAR LOS CAMPOS"; return; } NetworkTransport.Init(); ConnectionConfig cc = new ConnectionConfig(); reliableChannel = cc.AddChannel(QosType.Reliable); unReliableChannel = cc.AddChannel(QosType.Unreliable); HostTopology topo = new HostTopology(cc, MAX_CONNECTION); hostId = NetworkTransport.AddHost(topo, 0); connectionId = NetworkTransport.Connect(hostId, "127.0.0.1", port, 0, out error); connectionTime = Time.time; isConnected = true; simpleAES = new SimpleAES(); }
public JsonResult CapNhatProccess(CapNhatUserVM model) { rs r; SimpleAES __aes = new SimpleAES(); if (ModelState.IsValid) { var __id = MySsAuthUsers.GetAuth().ID; using (var __db = new vuong_cms_context()) { var user = __db.Users.Find(__id); user.Phone = model.Phone; user.Address = model.Address; user.Fullname = model.Fullname; __db.SaveChanges(); r = rs.T("Ok"); } } else { r = rs.F("Vui lòng điền đầy đủ thông tin!"); } return(Json(r, JsonRequestBehavior.DenyGet)); }
public object ShareByQr([FromBody] SharePlanQrReq Req) { try { SimpleAES AES = new SimpleAES(); var Username = AES.DecryptString(Req.Key); var ParentPlan = DB.WorkoutPlans.Where(u => u.Id == Req.Id).First(); DB.WorkoutPlans.InsertOnSubmit(new Models.WorkoutPlan() { Name = ParentPlan.Name, Username = Username, ParentPlan = ParentPlan.Id, Data = ParentPlan.Data, Image = ParentPlan.Image, CreateDate = ParentPlan.CreateDate, UpdateDate = DateTime.Now, ShareTime = DateTime.Now, Owner = ParentPlan.Username }); DB.SubmitChanges(); return(SuccessResult(Username)); } catch (Exception ex) { return(FailResult(ex)); } }
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)); }
private void OnClick() { string name = GameObject.Find("InputServerName").GetComponent <UIInput>().label.text; int max = int.Parse(GameObject.Find("InputMaxPlayer").GetComponent <UIInput>().label.text); int time = int.Parse(GameObject.Find("InputMaxTime").GetComponent <UIInput>().label.text); string map = GameObject.Find("PopupListMap").GetComponent <UIPopupList>().selection; string difficulty = GameObject.Find("CheckboxHard").GetComponent <UICheckbox>().isChecked ? "hard" : ((!GameObject.Find("CheckboxAbnormal").GetComponent <UICheckbox>().isChecked) ? "normal" : "abnormal"); string daylight = IN_GAME_MAIN_CAMERA.Lighting.ToString().ToLower(); string password = GameObject.Find("InputStartServerPWD").GetComponent <UIInput>().label.text; if (time > 0) { if (password.Length > 0) { password = new SimpleAES().Encrypt(password); } name = name + "`" + map + "`" + difficulty + "`" + time + "`" + daylight + "`" + password + "`" + MathHelper.RandomInt(int.MinValue, int.MaxValue); PhotonNetwork.CreateRoom(name, new RoomOptions { maxPlayers = max, customRoomProperties = new ExitGames.Client.Photon.Hashtable { { "Map", map }, { "Lighting", daylight.ToUpper() } } }, TypedLobby.Default); } }
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); } } }
// GET: Admin/Users/Edit/5 public ActionResult Edit(int?id) { if (id == null) { return(new HttpStatusCodeResult(HttpStatusCode.BadRequest)); } User user = _userServ.GetEntry(id.Value); if (user == null) { return(HttpNotFound()); } ViewBag.ddlRole = _roleServ.GetList().ToList().Select(s => new SelectListItem() { Text = s.Name, Value = s.Id.ToString() }); ViewBag.dsQuyen = _permisionServ.GetList().ToList(); SimpleAES aes = new SimpleAES(); user.Password = aes.DecryptString(user.Password); FrmCreateUserVM model = Mapper.Map <User, FrmCreateUserVM>(user); model.IsVip = user.IsVip1; return(View(model)); }
// GET: Admin/Users/Edit/5 public ActionResult EditUser(int id) { var __auth = MySsAuthUsers.GetAuth(); ViewBag.__auth = __auth; User user = _userServ.GetEntry(id); if (user == null) { return(HttpNotFound()); } ViewBag.ddlRole = _roleServ.GetList(w => w.Id == 2).ToList().Select(s => new SelectListItem() { Text = s.Name, Value = s.Id.ToString() }); ViewBag.dsQuyen = _permisionServ.GetList().ToList(); SimpleAES aes = new SimpleAES(); user.Password = aes.DecryptString(user.Password); FrmCreateUserVM model = Mapper.Map <User, FrmCreateUserVM>(user); model.ddlGioiTinh = new List <SelectListItem>() { new SelectListItem() { Text = "Nam", Value = "Nam" }, new SelectListItem() { Text = "Nữ", Value = "Nữ" } }; return(View(model)); }
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)); }
protected void btnSubmit_onClick(object sender, EventArgs e) { //if (!ValidateNurse()) //{ // FormErrors = _ser.Serialize(_formErrors); // return; //} //ProcessNurse(); string uname = GenerateUniqueUserName("Penney", "C", "1W"); // string password = PasswordUtils.Security.HashPassword(uname); SimpleAES aes = new SimpleAES(); // string password = aes.Encrypt("ADAMSWA"); string password = GeneratePassword("ADAMSWA"); Regex rgx = new Regex("^[a-zA-Z0-9]{8}$"); bool b = rgx.IsMatch("12345678"); string s = String.Concat(uname, DateTime.Now.ToString()); // up.password = _aes.Encrypt(String.Concat(up.username, up.creationDate.ToString())); }
public object AddFriendByQr(string key) { try { SimpleAES AES = new SimpleAES(); var username = AES.DecryptString(key); var Account = DB.Accounts.Where(u => u.Username == username); if (Account.Count() == 0) { return(ErrorResult(1, "Username is not exists")); } if (DB.Friends.Count(u => u.Username == CurrentAccount.Username && u.FriendUser == username) > 0) { return(SuccessResult(username)); } if (DB.Friends.Count(u => u.FriendUser == CurrentAccount.Username && u.Username == username) > 0) { return(SuccessResult(username)); } DB.Friends.InsertOnSubmit(new Models.Friend() { Username = CurrentAccount.Username, FriendUser = username, IsWaiting = 0, RequestTime = DateTime.Now }); DB.SubmitChanges(); return(SuccessResult(username)); } catch (Exception ex) { return(FailResult(ex)); } }
protected void Page_Load(object sender, EventArgs e) { try { string oauthcrd = Request.QueryString["oauthcrd"]; //decrypt oauth string string oauthDecode = System.Web.HttpUtility.UrlDecode(oauthcrd); oauthDecode = oauthDecode.Replace(" ", "+"); //fix situations where spaces and plus get mixed up string decryptStr = new SimpleAES().Decrypt(oauthDecode); //split into password and username string[] s = System.Text.RegularExpressions.Regex.Split(decryptStr, "\\|\\|"); CustMembershipProvider c = new CustMembershipProvider(); if (c.ValidateUser(s[1], s[0]) == false) { lblMsg.Text = "Verification failed"; pnl1.Visible = false; } else { pnl1.Visible = true; } } catch { lblMsg.Text = "Verification failed"; pnl1.Visible = false; } }
// GET: /Account/Verify USED TO SET PERMANENT PASSWORD public ActionResult Verify(string oauthcrd) { if (ModelState.IsValid) { try { //decrypt oauth string string oauthDecode = HttpUtility.UrlDecode(oauthcrd); oauthDecode = oauthDecode.Replace(" ", "+"); //fix situations where spaces and plus get mixed up string decryptStr = new SimpleAES().Decrypt(oauthDecode); //split into password and username string[] s = Regex.Split(decryptStr, "\\|\\|"); if (Membership.ValidateUser(s[1], s[0]) == false) { TempData["Error"] = "Verification failed."; } } catch { TempData["Error"] = "Verification failed."; } } var model = new vmAccountVerify { OAuth = oauthcrd }; return(View(model)); }
public static T LoadPlayer <T>(string name) { Directory.CreateDirectory(savePath); Directory.CreateDirectory(savePathBackUP); T returnValue; var backUpNeeded = false; Load(savePath); if (backUpNeeded) { Load(savePathBackUP); } return(returnValue); void Load(string path) { using (var reader = new StreamReader(path + name + ".txt")) { var formatter = new BinaryFormatter(); var dataToRead = reader.ReadToEnd(); var memoryStream = new MemoryStream(Convert.FromBase64String(SimpleAES.DecryptString(dataToRead, encryptKey))); try { returnValue = (T)formatter.Deserialize(memoryStream); } catch { returnValue = default; backUpNeeded = true; } } } }
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 ActionResult Unsubscribe(int?ux, string key) { T_OE_USERS u = db_Accounts.GetT_OE_USERSByIDX(ux ?? -1); if (u != null) { //decrypt oauth string string oauthDecode = HttpUtility.UrlDecode(key); oauthDecode = oauthDecode.Replace(" ", "+"); //fix situations where spaces and plus get mixed up string decryptStr = new SimpleAES().Decrypt(oauthDecode); if (decryptStr == u.PWD_HASH) { //unsubscribe from newsletter db_Accounts.UpdateT_OE_USERS(u.USER_IDX, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, null, false); TempData["Success"] = "You have successfully unsubscribed."; } else { TempData["Error"] = "Unable to unsubscribe."; } } else { TempData["Error"] = "Unable to unsubscribe."; } return(View()); }
public static string RandomeResetPasswordCode(int iduser) { SimpleAES aes = new SimpleAES(); //userid(int)_randome split '_' return(aes.EncryptToString(iduser.ToString()) + "_" + LayMaNgauNhien10ChuSo() + NgauNhienSHA256() + NgauNhienSHA256(10)); }
public static bool IsValidInvoiceHash(string inString) { if (inString == null) { return(false); } inString = inString.Replace(" ", "+"); string result = SimpleAES.Decrypt(SimpleAES.KeyType.Invoices, inString); if (result == null || !System.Text.RegularExpressions.Regex.IsMatch(result, @"^Mediclinic_\d{4}__\d+$")) { return(false); } string[] resultSplit = result.Split(new string[] { "__" }, StringSplitOptions.None); string DB = resultSplit[0]; string invNbr = resultSplit[1]; if (!Utilities.IsValidDB(DB.Substring(DB.Length - 4))) { return(false); } if (InvoiceDB.GetByID(Convert.ToInt32(invNbr), DB) == null) { return(false); } return(true); }
public ActionResult InterestReport(string id) { if (!string.IsNullOrEmpty(id)) { SimpleAES aes = new SimpleAES(); string email = aes.DecryptFromBase64String(id); LockedModeUserClient lmu = new LockedModeUserClient(); LockedModeUser user = lmu.GetByPartitionAndRowKey(LockedModeUserClient.GetPartitionKeyForEmail(email), email); List <string> interests = new List <string>(); if (user != null) { Type userType = user.GetType(); foreach (var key in userType.GetProperties()) { if (key.CanRead) { object value = key.GetValue(user, null); if (value.ToString() == "1") { interests.Add(key.Name); } } } ViewBag.Interests = interests; return(View()); } } return(RedirectToAction("Index", "Home")); }
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); }
private void OnClick() { string text = GameObject.Find("InputEnterPWD").GetComponent <UIInput>().label.text; SimpleAES eaes = new SimpleAES(); PhotonNetwork.JoinRoom(PanelMultiJoinPWD.roomName); }
private void OnClick() { string text = GameObject.Find("InputServerName").GetComponent <UIInput>().label.text.Replace("\\r\\n", "\r\n").Replace("\\n", "\n").Replace("\\t", "\t").Replace("\\", @"\"); int maxPlayers = int.Parse(GameObject.Find("InputMaxPlayer").GetComponent <UIInput>().label.text); int num2 = int.Parse(GameObject.Find("InputMaxTime").GetComponent <UIInput>().label.text); string selection = GameObject.Find("PopupListMap").GetComponent <UIPopupList>().selection; string str3 = !GameObject.Find("CheckboxHard").GetComponent <UICheckbox>().isChecked ? (!GameObject.Find("CheckboxAbnormal").GetComponent <UICheckbox>().isChecked ? "normal" : "abnormal") : "hard"; string str4 = string.Empty; if (IN_GAME_MAIN_CAMERA.dayLight == DayLight.Day) { str4 = "day"; } if (IN_GAME_MAIN_CAMERA.dayLight == DayLight.Dawn) { str4 = "dawn"; } if (IN_GAME_MAIN_CAMERA.dayLight == DayLight.Night) { str4 = "night"; } string unencrypted = GameObject.Find("InputStartServerPWD").GetComponent <UIInput>().label.text; if (unencrypted.Length > 0) { unencrypted = new SimpleAES().Encrypt(unencrypted); } PhotonNetwork.CreateRoom(string.Concat(text, "`", selection, "`", str3, "`", num2, "`", str4, "`", unencrypted, "`", Random.Range(0, 0xc350)), true, true, maxPlayers); }
protected override bool IsAuthorized(HttpActionContext actionContext) { if (Thread.CurrentPrincipal.Identity.Name.Length == 0) { // Get the header value AuthenticationHeaderValue auth = actionContext.Request.Headers.Authorization; // ensure its schema is correct if (auth != null && string.Compare(auth.Scheme, "Basic", StringComparison.OrdinalIgnoreCase) == 0) { // get the credientials string credentials = UTF8Encoding.UTF8.GetString(Convert.FromBase64String(auth.Parameter)); int separatorIndex = credentials.IndexOf(':'); if (separatorIndex >= 0) { // get user and password string passedUserName = credentials.Substring(0, separatorIndex); string passedPassword = credentials.Substring(separatorIndex + 1); SimpleAES crypto = new SimpleAES(); string userName = crypto.DecryptString(ConfigurationManager.AppSettings.Get(Constants.SIMPLEUSERNAME)); string password = crypto.DecryptString(ConfigurationManager.AppSettings.Get(Constants.SIMPLEUSERPASSWORD)); // validate if (passedUserName == userName && passedPassword == password) { Thread.CurrentPrincipal = actionContext.ControllerContext.RequestContext.Principal = new GenericPrincipal(new GenericIdentity(userName, "Basic"), new string[] { }); } } } } return(base.IsAuthorized(actionContext)); }
public int ValidatePassword(user u) { SimpleAES AES = new SimpleAES(); string passWord = AES.EncryptToString(u.password); return(DbContext.users.Where(x => x.password == passWord).Count()); }
public ActionResult CareerReport(string id) { if (!string.IsNullOrEmpty(id)) { SimpleAES aes = new SimpleAES(); string email = aes.DecryptFromBase64String(id); LockedModeUserClient lmu = new LockedModeUserClient(); LockedModeUser user = lmu.GetByPartitionAndRowKey(LockedModeUserClient.GetPartitionKeyForEmail(email), email); if (user != null) { Response.Cookies["attitude"].Value = user.Attitude; Response.Cookies["attitude"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["endurance"].Value = user.Endurance; Response.Cookies["endurance"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["action"].Value = user.Action; Response.Cookies["action"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["concentration"].Value = user.Concentration; Response.Cookies["concentration"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["information"].Value = user.Information; Response.Cookies["information"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["processing"].Value = user.Processing; Response.Cookies["processing"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["presence"].Value = user.Presence; Response.Cookies["presence"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["patterns"].Value = user.Patterns; Response.Cookies["patterns"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["compensation"].Value = user.Compensation; Response.Cookies["compensation"].Expires = DateTime.UtcNow.AddDays(7); Response.Cookies["resultsEmailed"].Value = "yes"; Response.Cookies["resultsEmailed"].Expires = DateTime.UtcNow.AddDays(7); return(View()); } } return(RedirectToAction("Index", "Home")); }
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)); }
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)); } } }
private void OnClick() { string text = CyanMod.CachingsGM.Find("InputServerName").GetComponent <UIInput>().label.text; int maxPlayers = int.Parse(CyanMod.CachingsGM.Find("InputMaxPlayer").GetComponent <UIInput>().label.text); int num2 = int.Parse(CyanMod.CachingsGM.Find("InputMaxTime").GetComponent <UIInput>().label.text); string selection = CyanMod.CachingsGM.Find("PopupListMap").GetComponent <UIPopupList>().selection; string str3 = !CyanMod.CachingsGM.Find("CheckboxHard").GetComponent <UICheckbox>().isChecked ? (!CyanMod.CachingsGM.Find("CheckboxAbnormal").GetComponent <UICheckbox>().isChecked ? "normal" : "abnormal") : "hard"; string str4 = string.Empty; if (IN_GAME_MAIN_CAMERA.dayLight == DayLight.Day) { str4 = "day"; } if (IN_GAME_MAIN_CAMERA.dayLight == DayLight.Dawn) { str4 = "dawn"; } if (IN_GAME_MAIN_CAMERA.dayLight == DayLight.Night) { str4 = "night"; } string unencrypted = CyanMod.CachingsGM.Find("InputStartServerPWD").GetComponent <UIInput>().label.text; if (unencrypted.Length > 0) { unencrypted = new SimpleAES().Encrypt(unencrypted); } PhotonNetwork.CreateRoom(string.Concat(new object[] { text, "`", selection, "`", str3, "`", num2, "`", str4, "`", unencrypted, "`", UnityEngine.Random.Range(0, 0xc350) }), true, true, maxPlayers); }
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; }
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(); } }
private string EncryptPassword() { string password = ""; if (passwordTextBox.Text.Length != 0) { SimpleAES aes = new SimpleAES (); password = aes.EncryptToString (passwordTextBox.Text); } return password; }
private static string DecryptPassword() { string password = ""; if (Config.Instance.Password.Length != 0) { SimpleAES aes = new SimpleAES (); password = aes.DecryptString (Config.Instance.Password); } return password; }
public object NullSafeGet(IDataReader rs, string[] names, object owner) { object r = rs[names[0]]; if (r == DBNull.Value) return null; // decrypt result and assert the same string returned // Get key for the encryption/decryption var privateKey = File.ReadAllBytes(@"C:\Users\David Peel\Documents\key.txt"); var sharedIV = File.ReadAllBytes(@"C:\Users\David Peel\Documents\iv.txt"); // encrpt a string and store result var simpleAES = new SimpleAES(privateKey, sharedIV); return simpleAES.Decrypt((byte[])r); }
protected void Unsubcribe() { email = AppConstants.GetString("email"); if (email == string.Empty || email == null) { UnsubcribeButton.Enabled = false; return; } else { UnsubcribeButton.Enabled = true; SimpleAES encryptEmail = new SimpleAES(); email = encryptEmail.DecryptString(email); } }
private void Unsubcribe() { email = AppConstants.GetString("email"); if (email == string.Empty || email == null) { ReceiveRelatedStoxEmail.Enabled = false; return; } else { ReceiveRelatedStoxEmail.Enabled = true; SimpleAES encryptEmail = new SimpleAES(); email = encryptEmail.DecryptString(email); } }
public void NullSafeSet(IDbCommand cmd, object value, int index) { object paramVal = DBNull.Value; if (value != null) { // get the keys from the files var privateKey = File.ReadAllBytes(@"C:\Users\David Peel\Documents\key.txt"); var sharedIV = File.ReadAllBytes(@"C:\Users\David Peel\Documents\iv.txt"); // encrpt a string and store result var simpleAES = new SimpleAES(privateKey, sharedIV); paramVal = simpleAES.Encrypt((string)value); } IDataParameter parameter = (IDataParameter)cmd.Parameters[index]; parameter.Value = paramVal; }
public void EncryptDecrypt_WhaenCalled_ReturnsSameValue() { // Get key for the encryption/decryption var privateKey = SimpleAES.GenerateEncryptionKey(); // get an IV for the operation var privateIV = SimpleAES.GenerateEncryptionVector(); // encrpt a string and store result const string SecretString = "jdhsbdsb87dubdlvbd8v7dvd7 my bank details here"; var simpleAES = new SimpleAES(privateKey, privateIV); var encryptedSecret = simpleAES.Encrypt(SecretString); // decrypt result and assert the same string returned var decryptedSecret = simpleAES.Decrypt(encryptedSecret); Assert.That(decryptedSecret, Is.EqualTo(SecretString)); }
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; }
public static string Decrypt(KeyType keyType, string encrypted) { SimpleAES aes = new SimpleAES(keyType); try { return aes._Decrypt(encrypted); } catch(Exception) { return null; } }
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; }
public static string Encrypt(KeyType keyType, string unencrypted) { SimpleAES aes = new SimpleAES(keyType); return aes._Encrypt(unencrypted); }
public Room(string file, bool freeroam, ReplayRecorder recorder) : this() { freeroaming = freeroam; this.recorder = recorder; // Get level name levelName = file.Split('\\')[file.Split('\\').Length - 1].Replace(".srl", ""); custom = true; SimpleAES decryptor = new SimpleAES(); StreamReader levelReader = new StreamReader(file); string[] line; // Get level id levelID = levelReader.ReadLine(); // Check if level will have a leaderboard canViewLeaderboards = decryptor.DecryptString(levelReader.ReadLine()) == "1"; // Get level theme line = decryptor.DecryptString(levelReader.ReadLine()).Split(' '); Theme = FindTheme(line[0]); wallSet = new Tileset(Game1.tileSet[(int)Theme], 32, 32, 3, 3); // Get room dimensions line = decryptor.DecryptString(levelReader.ReadLine()).Split(' '); roomWidth = int.Parse(line[0]); roomHeight = int.Parse(line[1]); // Get goal times goals = new int[3]; line = decryptor.DecryptString(levelReader.ReadLine()).Split(' '); for (int i = 0; i < 3; i++) goals[i] = int.Parse(line[i]); // Get objects and tiles while (!levelReader.EndOfStream) { string s = levelReader.ReadLine(); if (s.Length > 0) { line = decryptor.DecryptString(s).Split(' '); ParseObjectOrTile(line, freeroam); } } levelReader.Dispose(); BuildTiles(); // Generate zipline poles foreach (ZipLine z in ziplines) z.SetPoles(this); // Get current record for this level FindRecord(decryptor); UpdateViewBox(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; }
public TokenService() { simpleAes = new SimpleAES(Configuration.Settings.TokenKey, Configuration.Settings.TokenVector); }
// Searches through records file and finds this level's current record, sets it to -1 if not found private void FindRecord(SimpleAES decryptor) { StreamReader levelReader = new StreamReader("Content\\records.txt"); string nullCheck = levelReader.ReadLine(); if (nullCheck != null) { string recordSearch = decryptor.DecryptString(nullCheck); while (recordSearch.Split(' ')[0] != levelName && !levelReader.EndOfStream) recordSearch = decryptor.DecryptString(levelReader.ReadLine()); if (recordSearch.Split(' ')[0] != levelName) record = -1; else record = int.Parse(recordSearch.Split(' ')[2]); } else record = -1; levelReader.Dispose(); }
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 static string IRCVars(Type type) { SimpleAES aesAll = new SimpleAES(); return aesAll.Decrypt(Encoding.Default.GetBytes(Strings.Split(Config.IRCSettings[(int)type], Config.FSplit4, -1, CompareMethod.Text)[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); }
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 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); } } }