private void changePasswd() { if (txtBoxNewPass.Text == txtBoxConfirmPass.Text) { string username = service.FindUsernameBySessionId(sessionId); DbUser user = new DbUser(); user.Username = username; user.Password = txtBoxNewPass.Text; if (service.UpdatePassword(user)) { LoginForm form = new LoginForm(); form.txtUsername.Text = username; form.ErrorLBL.Text = "Please Login with your new password"; form.ErrorLBL.ForeColor = Color.Green; form.ErrorLBL.Show(); this.Hide(); form.Show(); service.Logout(sessionId); } } else { lbl.ForeColor = Color.Green; lbl.Text = "New Password do not match."; } }
public List<DbUser> GetUserList(AddUser userDetails) { // Home home = new Home(sessionId); //GetUser checkUserName = new GetUser(); int num = client.GetNumOfUsers(userDetails.firstnameTxtbox.Text, userDetails.lastnameTxtbox.Text); DbUser user = new DbUser(); if (num < 1) { user.Username = userDetails.firstnameTxtbox.Text + "." + userDetails.lastnameTxtbox.Text; } else { user.Username = userDetails.firstnameTxtbox.Text + "." + userDetails.lastnameTxtbox.Text + num; } user.Password = "******"; user.FirstName = userDetails.firstnameTxtbox.Text; user.LastName = userDetails.lastnameTxtbox.Text; user.Email = user.Username + "@fdmgroup.com"; user.Location = userDetails.locTxtbox.Text; user.TypeId = userDetails.userTypeCombox.SelectedIndex +1; List<DbUser> userList = new List<DbUser>(); userList.Add(user); return userList.ToList(); }
protected void Page_Load(object sender, EventArgs e) { DbUser user = new DbUser(); user.TypeId = 1; gvAccMan.DataSource = from f in service.FindUser(user) select new { f.FirstName, f.LastName, f.Email, f.Location }; gvAccMan.DataBind(); }
protected void btnChngPwd_Click(object sender, EventArgs e) { if (txtnewPasswd.Text == txtConfirmPasswd.Text) { DbUser user = new DbUser(); user.Username = username; user.Password = txtnewPasswd.Text; if (service.UpdatePassword(user)) { Guid sessionId = (Guid)Session["sessionId"]; service.Logout(sessionId); Response.Redirect("Login.aspx"); } } else { FailureText.Text = "Passwords do not match"; } }
protected override void Seed(ImgBoard.Dal.Context.EndObjects.ImgBoardContext context) { #region Categories var Category1 = new DbCategory { Id = 1, Title = "Nature" }; var Category2 = new DbCategory { Id = 2, Title = "Technology" }; var Category3 = new DbCategory { Id = 3, Title = "Space" }; #endregion #region Users var user1 = new DbUser { Id = 1, Login = "******", Password = "******", UserName = "******" }; var user2 = new DbUser { Id = 2, Login = "******", Password = "******", UserName = "******" }; #endregion #region Images // no cat var image1 = new DbImage { Id = 1, IdCategory = null, IdUploader = 1, Name = null, Description = null, FileId = new Guid("1be96b96ce194f1ab2bc54db0c269df9"), FileExtension = "png" }; var image2 = new DbImage { Id = 2, IdCategory = null, IdUploader = 1, Name = null, Description = null, FileId = new Guid("0c85e4d2fa1443fbaabaa069aa7879f3"), FileExtension = "png" }; var image3 = new DbImage { Id = 3, IdCategory = null, IdUploader = 1, Name = "Some name", Description = null, FileId = new Guid("e7f2cd1471bc4a3ab64ad5dfa4774b64"), FileExtension = "png" }; var image4 = new DbImage { Id = 4, IdCategory = null, IdUploader = 2, Name = "Some cool name", Description = null, FileId = new Guid("e2eb8ffbfc9542c3911ab53c8dbd1da9"), FileExtension = "png" }; var image5 = new DbImage { Id = 5, IdCategory = null, IdUploader = 2, Name = null, Description = "Some description", FileId = new Guid("5d02a31ac3b74a219c72750bcbe683bd"), FileExtension = "png" }; // cat 1 var image6 = new DbImage { Id = 6, IdCategory = 1, IdUploader = 1, Name = "Something", Description = "Something cool", FileId = new Guid("0974ed5725964ad0b71c65314c79bff3"), FileExtension = "png" }; var image7 = new DbImage { Id = 7, IdCategory = 1, IdUploader = 1, Name = "Blabla", Description = null, FileId = new Guid("7fdb4ad242124b07b7c16b772066606f"), FileExtension = "png" }; var image8 = new DbImage { Id = 8, IdCategory = 1, IdUploader = 1, Name = "Nono", Description = "Yolo", FileId = new Guid("1697cdbe47134c64a802446724594b5b"), FileExtension = "png" }; var image9 = new DbImage { Id = 9, IdCategory = 1, IdUploader = 1, Name = null, Description = "Super cool", FileId = new Guid("d8e7e1ad6810461ca5e888215eee456a"), FileExtension = "png" }; var image10 = new DbImage { Id = 10, IdCategory = 1, IdUploader = 1, Name = "Ahaha", Description = null, FileId = new Guid("2749a186cda74da9a090fad2db1aa1ed"), FileExtension = "png" }; var image11 = new DbImage { Id = 11, IdCategory = 1, IdUploader = 2, Name = "Not cool", Description = "Yes", FileId = new Guid("0bd69a48caa4407899283251a2c7aa62"), FileExtension = "png" }; var image12 = new DbImage { Id = 12, IdCategory = 1, IdUploader = 2, Name = "Meh", Description = null, FileId = new Guid("d68a9e301fc64f5c93a095d624617be7"), FileExtension = "jpg" }; var image13 = new DbImage { Id = 13, IdCategory = 1, IdUploader = 2, Name = "Gah", Description = null, FileId = new Guid("45c6107002384fad81649c027ddde337"), FileExtension = "png" }; var image14 = new DbImage { Id = 14, IdCategory = 1, IdUploader = 2, Name = "Ahaha", Description = "Super", FileId = new Guid("fefcfdf503b04350a5c0ccd6e41c0088"), FileExtension = "png" }; var image15 = new DbImage { Id = 15, IdCategory = 1, IdUploader = 2, Name = null, Description = null, FileId = new Guid("3e6c20cc95c34c8cabb436453a3fa476"), FileExtension = "png" }; var image16 = new DbImage { Id = 16, IdCategory = 1, IdUploader = 2, Name = null, Description = "Ouah", FileId = new Guid("8855611b7bff43c1a8c5e3d42c2ae0c7"), FileExtension = "png" }; var image17 = new DbImage { Id = 17, IdCategory = 1, IdUploader = 2, Name = "That's a title", Description = "That's great", FileId = new Guid("db7dc17917344372b27ec4508fb1ea85"), FileExtension = "png" }; // cat 2 var image18 = new DbImage { Id = 18, IdCategory = 2, IdUploader = 1, Name = "Lalala", Description = "That's a rather long description", FileId = new Guid("14f22be857ab433bb20e2a91538e9931"), FileExtension = "png" }; var image19 = new DbImage { Id = 19, IdCategory = 2, IdUploader = 1, Name = "Not good", Description = "Nope nope nope", FileId = new Guid("02f4340c01e14e90844a165ab8027fe1"), FileExtension = "png" }; var image20 = new DbImage { Id = 20, IdCategory = 2, IdUploader = 1, Name = "Something", Description = "That's a rather long description, like really long", FileId = new Guid("2dd1b1661f1d45ceb4aa648dd2e135cb"), FileExtension = "png" }; var image21 = new DbImage { Id = 21, IdCategory = 2, IdUploader = 1, Name = "That's the id 21", Description = null, FileId = new Guid("f316398a86d84f139b7146565e50e0e6"), FileExtension = "png" }; var image22 = new DbImage { Id = 22, IdCategory = 2, IdUploader = 1, Name = "That's the id 22", Description = null, FileId = new Guid("ed7fd773ef0f4ecca0c67bebe23359da"), FileExtension = "png" }; var image23 = new DbImage { Id = 23, IdCategory = 2, IdUploader = 1, Name = null, Description = null, FileId = new Guid("6e11274767b14b6895174d44e7b2b0fe"), FileExtension = "jpg" }; var image24 = new DbImage { Id = 24, IdCategory = 2, IdUploader = 1, Name = "Test", Description = null, FileId = new Guid("e765abae7db941b5bbf605be6102ecaa"), FileExtension = "png" }; var image25 = new DbImage { Id = 25, IdCategory = 2, IdUploader = 2, Name = "That's image 25", Description = "Description", FileId = new Guid("6663128d864045c3ab6b70d8b6d80270"), FileExtension = "png" }; var image26 = new DbImage { Id = 26, IdCategory = 2, IdUploader = 2, Name = "That's image 26", Description = "nghhh", FileId = new Guid("5c68ca911ace45049997365938e1bafa"), FileExtension = "png" }; var image27 = new DbImage { Id = 27, IdCategory = 2, IdUploader = 2, Name = "That's image 27", Description = "That's a rather long description like really super horribly long like is this really necessary stop it now", FileId = new Guid("9b3702bb5598472dab5408d49c0c2987"), FileExtension = "png" }; var image28 = new DbImage { Id = 28, IdCategory = 2, IdUploader = 2, Name = "That's image 28", Description = "Bored", FileId = new Guid("5f153307e70c477491445a9946b118db"), FileExtension = "png" }; var image29 = new DbImage { Id = 29, IdCategory = 2, IdUploader = 2, Name = "That's image 29", Description = "Yololo", FileId = new Guid("ed0303c101ca46dba617cad442d60331"), FileExtension = "png" }; var image30 = new DbImage { Id = 30, IdCategory = 2, IdUploader = 2, Name = "a", Description = "desc", FileId = new Guid("5466bcea687c41bbb70ecfb4309a61f3"), FileExtension = "jpg" }; var image31 = new DbImage { Id = 31, IdCategory = 2, IdUploader = 2, Name = "blah", Description = "not", FileId = new Guid("ba05b9d7ee1145dca93834cedd85c7a1"), FileExtension = "jpg" }; var image32 = new DbImage { Id = 32, IdCategory = 2, IdUploader = 2, Name = "That's image 32", Description = null, FileId = new Guid("34855651602d4fa7889326a22212ff70"), FileExtension = "png" }; var image33 = new DbImage { Id = 33, IdCategory = 2, IdUploader = 2, Name = null, Description = "Description for image 33", FileId = new Guid("b0b37c95a8334ee68946b10f8738e767"), FileExtension = "png" }; var image34 = new DbImage { Id = 34, IdCategory = 2, IdUploader = 2, Name = null, Description = "Description for image 34", FileId = new Guid("35696e783af746ec9a4ed862ebc59620"), FileExtension = "jpg" }; var image35 = new DbImage { Id = 35, IdCategory = 2, IdUploader = 2, Name = "Something something something", Description = "what?", FileId = new Guid("0d8de8d2c57e47a4959841f409cca22f"), FileExtension = "jpg" }; var image36 = new DbImage { Id = 36, IdCategory = 2, IdUploader = 2, Name = null, Description = null, FileId = new Guid("98f7e09d0363492397a1c16e88015909"), FileExtension = "png" }; var image37 = new DbImage { Id = 37, IdCategory = 2, IdUploader = 2, Name = null, Description = null, FileId = new Guid("743ec8da043349db9c6a768a2db5fec4"), FileExtension = "png" }; var image38 = new DbImage { Id = 38, IdCategory = 2, IdUploader = 2, Name = "Lili", Description = "originality", FileId = new Guid("3ebcb683bd0542f9b5959ea0972a409f"), FileExtension = "jpg" }; var image39 = new DbImage { Id = 39, IdCategory = 2, IdUploader = 1, Name = "Stop", Description = "That's a description", FileId = new Guid("0918d9738bff40008a64fdbff5bb3eee"), FileExtension = "png" }; var image40 = new DbImage { Id = 40, IdCategory = 2, IdUploader = 1, Name = "Huge", Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere non magna a luctus. Suspendisse gravida ipsum eu metus dapibus bibendum. Nunc dapibus odio turpis, in maximus nisl hendrerit id. Integer malesuada pharetra nibh, eget cursus sapien molestie nec. Nulla blandit tortor augue, et consectetur lectus egestas sed. Pellentesque blandit consequat euismod. In at feugiat nulla, vel tempor urna. Proin varius, turpis non viverra venenatis", FileId = new Guid("659eb8e26fe140cebd30a52e1378efbe"), FileExtension = "png" }; var image41 = new DbImage { Id = 41, IdCategory = 2, IdUploader = 2, Name = null, Description = null, FileId = new Guid("69f718225c9a4a50a241d1011a1d847a"), FileExtension = "jpg" }; var image42 = new DbImage { Id = 42, IdCategory = 2, IdUploader = 2, Name = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere non magna a luctus. Suspendisse gravida ipsum eu metus", Description = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed posuere non magna a luctus. Suspendisse gravida ipsum eu metus", FileId = new Guid("45ed3c53370b446d83076699d5fdef58"), FileExtension = "png" }; var image43 = new DbImage { Id = 43, IdCategory = 2, IdUploader = 2, Name = "Ffffffff", Description = "boring", FileId = new Guid("1db7b3b8b2604d09956a7101f7a621f7"), FileExtension = "png" }; var image44 = new DbImage { Id = 44, IdCategory = 2, IdUploader = 2, Name = "Finally", Description = "Annoying", FileId = new Guid("5f56e5c7ac66467ea475cd7de17077fb"), FileExtension = "png" }; var image45 = new DbImage { Id = 45, IdCategory = 3, IdUploader = 2, Name = "agagaga", Description = "grrrr", FileId = new Guid("61b8ad267bec46ada3fb2e7fcf8a7de5"), FileExtension = "png" }; #endregion #region Tags var tag1 = new DbTag { Id = 1, Name = "Cool", Images = new List <DbImage>() }; var tag2 = new DbTag { Id = 2, Name = "Meh", Images = new List <DbImage>() }; var tag3 = new DbTag { Id = 3, Name = "Bad", Images = new List <DbImage>() }; #endregion tag1.Images.Add(image1); tag1.Images.Add(image2); tag1.Images.Add(image3); tag1.Images.Add(image4); tag1.Images.Add(image5); tag1.Images.Add(image6); tag1.Images.Add(image7); tag1.Images.Add(image8); tag1.Images.Add(image9); tag1.Images.Add(image10); tag1.Images.Add(image11); tag1.Images.Add(image12); tag1.Images.Add(image13); tag1.Images.Add(image14); tag1.Images.Add(image15); tag1.Images.Add(image16); tag2.Images.Add(image19); tag2.Images.Add(image20); tag2.Images.Add(image21); tag2.Images.Add(image22); tag2.Images.Add(image23); tag2.Images.Add(image24); tag2.Images.Add(image25); tag2.Images.Add(image26); tag2.Images.Add(image27); tag2.Images.Add(image2); tag3.Images.Add(image19); tag3.Images.Add(image20); tag3.Images.Add(image21); tag3.Images.Add(image22); tag3.Images.Add(image23); tag3.Images.Add(image24); tag3.Images.Add(image25); tag3.Images.Add(image26); tag3.Images.Add(image27); tag3.Images.Add(image28); tag3.Images.Add(image29); tag3.Images.Add(image30); tag3.Images.Add(image31); tag3.Images.Add(image32); tag3.Images.Add(image33); tag3.Images.Add(image34); tag3.Images.Add(image35); tag3.Images.Add(image36); tag3.Images.Add(image37); tag3.Images.Add(image38); tag3.Images.Add(image39); tag3.Images.Add(image40); tag3.Images.Add(image41); tag3.Images.Add(image42); tag3.Images.Add(image43); tag3.Images.Add(image44); tag3.Images.Add(image1); tag3.Images.Add(image3); context.Categories.Add(Category1); context.Categories.Add(Category2); context.Categories.Add(Category3); context.Users.Add(user1); context.Users.Add(user2); context.Images.Add(image1); context.Images.Add(image2); context.Images.Add(image3); context.Images.Add(image4); context.Images.Add(image5); context.Images.Add(image6); context.Images.Add(image7); context.Images.Add(image8); context.Images.Add(image9); context.Images.Add(image10); context.Images.Add(image11); context.Images.Add(image12); context.Images.Add(image13); context.Images.Add(image14); context.Images.Add(image15); context.Images.Add(image16); context.Images.Add(image17); context.Images.Add(image18); context.Images.Add(image19); context.Images.Add(image20); context.Images.Add(image21); context.Images.Add(image22); context.Images.Add(image23); context.Images.Add(image24); context.Images.Add(image25); context.Images.Add(image26); context.Images.Add(image27); context.Images.Add(image28); context.Images.Add(image29); context.Images.Add(image30); context.Images.Add(image31); context.Images.Add(image32); context.Images.Add(image33); context.Images.Add(image34); context.Images.Add(image35); context.Images.Add(image36); context.Images.Add(image37); context.Images.Add(image38); context.Images.Add(image39); context.Images.Add(image40); context.Images.Add(image41); context.Images.Add(image42); context.Images.Add(image43); context.Images.Add(image44); context.Images.Add(image45); context.Tags.Add(tag1); context.Tags.Add(tag2); context.Tags.Add(tag3); }
public void UpdateUser(DbUser user) { _userRepository.Update(user); _unitOfWork.Commit(); }
public async Task <IActionResult> RegisterUser([FromBody] RegisterDTO model) { // Auto return errors from viewModel and other global errors return(await HandleRequestAsync(async() => { if (!CaptchaHelper.VerifyAndExpireSolution(this.HttpContext, model.CaptchaKey, model.CaptchaText)) { var invalid = new Dictionary <string, string>(); invalid.Add("captchaText", "Помилка вводу зображення на фото"); return BadRequest(invalid); } var user = _userManager.FindByEmailAsync(model.Email).Result; if (user != null) { var invalid = new Dictionary <string, string>(); invalid.Add("email", "Користувач з даною електронною поштою уже зареєстрований"); return BadRequest(invalid); } string imageName = Path.GetRandomFileName() + ".jpg"; try { this._logger.LogDebug("Start register method RegisterUser..."); string pathSaveImages = InitStaticFiles .CreateImageByFileName(_env, _configuration, new string[] { "ImagesPath", "ImagesPathUser" }, imageName, model.Photo); this._logger.LogDebug("Save image complete method RegisterUser..."); if (pathSaveImages != null) { var profile = new UserProfile() { RegistrationDate = DateTime.Now, FirstName = model.FirstName, LastName = model.LastName, Photo = imageName, }; user = new DbUser() { UserName = model.Email, Email = model.Email, PhoneNumber = model.Phone, UserProfile = profile }; var result = _userManager.CreateAsync(user, model.Password).Result; if (!result.Succeeded) { var errors = CustomValidator.GetErrorsByIdentityResult(result); return BadRequest(errors); } await _signInManager.SignInAsync(user, isPersistent: false); // Return token JwtInfo jwtInfo = new JwtInfo() { Token = _jwtTokenService.CreateToken(user), RefreshToken = _jwtTokenService.CreateRefreshToken(user) }; this._logger.LogDebug("End method RegisterUser..."); return Ok(jwtInfo); } else { throw new Exception("Помила додавання фото в БД"); } } catch (Exception ex) { InitStaticFiles.DeleteImageByFileName(_env, _configuration, new string[] { "ImagesPath", "ImagesPathUser" }, imageName); var errors = new Dictionary <string, string>(); errors.Add("invalid", ex.Message); return BadRequest(errors); } })); }
public void DbUserConstructorTest() { DbUser target = new DbUser(); Assert.Inconclusive("TODO: Implement code to verify target"); }
public static async Task OnHttpRequest(Microsoft.AspNetCore.Http.HttpContext e, DbUser u) { //Get servers var servers = await Program.connection.GetServersByOwnerAsync(u.id); //Convert ServerListResponse response = new ServerListResponse { servers = new List <ServerListResponseServer>(), token = await u.GetServerCreationToken(Program.connection) }; foreach (var s in servers) { //Get map string mapName = null; var mapData = await s.GetMapEntryAsync(Program.connection); if (mapData != null) { mapName = mapData.displayName; } //Write response.servers.Add(new ServerListResponseServer { icon = s.image_url, id = s.id, map = mapName, name = s.display_name }); } //Write await Program.QuickWriteJsonToDoc(e, response); }
public async Task<IActionResult> GetScoreResult( [FromQuery(Name = "v")] ScoreboardType type, [FromQuery(Name = "c")] string fileMd5, [FromQuery(Name = "f")] string f, [FromQuery(Name = "m")] PlayMode playMode, [FromQuery(Name = "i")] int i, [FromQuery(Name = "mods")] Mod mods, [FromQuery(Name = "us")] string us, [FromQuery(Name = "ha")] string pa, [FromServices] IServiceProvider serviceProvider) { try { var dbUser = await DbUser.GetDbUser(_ctx, us); var user = dbUser?.ToUser(); if (dbUser?.IsPassword(pa) != true) return Ok("error: pass"); var cacheHash = Hex.ToHex( Crypto.GetMd5( $"{fileMd5}{playMode}{mods}{type}{user.Id}{user.UserName}" ) ); if (_cache.TryGet($"sora:Scoreboards:{cacheHash}", out string cachedData)) return Ok(cachedData); var scores = await DbScore.GetScores(_ctx, fileMd5, dbUser, playMode, type == ScoreboardType.Friends, type == ScoreboardType.Country, type == ScoreboardType.Mods, mods); var beatmap = DbBeatmap.GetBeatmap(_ctx, fileMd5); BeatmapSet apiSet; if (beatmap == null) { apiSet = await _pisstaube.FetchBeatmapSetAsync(fileMd5); if (apiSet == null) goto JustContinue; var beatmaps = DbBeatmap.FromBeatmapSet(apiSet).ToList(); var beatmapChecksums = beatmaps.Select(s => s.FileMd5); var dbBeatmaps = _ctx.Beatmaps.Where(rset => beatmapChecksums.Any(lFileMd5 => rset.FileMd5 == lFileMd5)) .ToList(); var concurrentLock = new object(); var pool = serviceProvider.GetRequiredService<DbContextPool<SoraDbContext>>(); Task.WaitAll(beatmaps.Select(rawBeatmap => Task.Run(async () => { var context = pool.Rent(); var dbBeatmap = dbBeatmaps.FirstOrDefault(s => s.FileMd5 == rawBeatmap.FileMd5); if (dbBeatmap != null && (dbBeatmap.Flags & DbBeatmapFlags.RankedFreeze) != 0) { rawBeatmap.RankedStatus = dbBeatmap.RankedStatus; rawBeatmap.Flags = dbBeatmap.Flags; } context.Beatmaps.AddOrUpdate(rawBeatmap); await context.SaveChangesAsync(); pool.Return(context); })).ToArray()); beatmap = beatmaps.FirstOrDefault(s => s.FileMd5 == fileMd5); } JustContinue: var ownScore = await DbScore.GetLatestScore(_ctx, new DbScore { FileMd5 = fileMd5, UserId = user.Id, PlayMode = playMode, TotalScore = 0 }); var sScores = scores.Select(s => new Score { Count100 = s.Count100, Count50 = s.Count50, Count300 = s.Count300, Date = s.Date, Mods = s.Mods, CountGeki = s.CountGeki, CountKatu = s.CountKatu, CountMiss = s.CountMiss, FileMd5 = s.FileMd5, MaxCombo = s.MaxCombo, PlayMode = s.PlayMode, TotalScore = s.TotalScore, UserId = s.UserId, UserName = s.ScoreOwner.UserName, }).ToList(); // Fetch the correct position for sScore for (var j = 0; j < scores.Count; j++) { sScores[j].Position = await scores[j].Position(_ctx); } Score ownsScore = null; if (ownScore != null) ownsScore = new Score { Count100 = ownScore.Count100, Count50 = ownScore.Count50, Count300 = ownScore.Count300, Date = ownScore.Date, Mods = ownScore.Mods, CountGeki = ownScore.CountGeki, CountKatu = ownScore.CountKatu, CountMiss = ownScore.CountMiss, FileMd5 = ownScore.FileMd5, MaxCombo = ownScore.MaxCombo, PlayMode = ownScore.PlayMode, TotalScore = ownScore.TotalScore, UserId = dbUser.Id, UserName = dbUser.UserName, Position = await ownScore.Position(_ctx) }; BeatmapSet set = null; if (beatmap != null) set = new BeatmapSet { SetID = beatmap.Id, Artist = beatmap.Artist, Title = beatmap.Title, RankedStatus = beatmap.RankedStatus, ChildrenBeatmaps = new List<Beatmap> { new Beatmap { FileMD5 = beatmap.FileMd5, DiffName = beatmap.DiffName, ParentSetID = beatmap.SetId, BeatmapID = beatmap.Id, Mode = beatmap.PlayMode } } }; var sboard = new Scoreboard(set?.ChildrenBeatmaps.FirstOrDefault(bm => bm.FileMD5 == fileMd5), set, sScores, ownsScore); _cache.Set($"sora:Scoreboards:{cacheHash}", cachedData = sboard.ToOsuString(), TimeSpan.FromSeconds(30)); return Ok(cachedData); } catch (Exception ex) { Logger.Err(ex); return Ok("Failed"); } }
private Maybe <User> MaybeUser(DbUser user) { return(user != null ? new Maybe <User>(user.ToDto()) : Maybe <User> .Fail); }
private void btnCreateUser_Click(object sender, EventArgs e) { try { FormAddUser dlg = new FormAddUser(_context); if (dlg.ShowDialog() == DialogResult.OK) { string extension = Path.GetExtension(dlg.ImageSelect); string nameFile = Path.GetRandomFileName() + extension; var path = Path.Combine(Directory.GetCurrentDirectory(), "images", nameFile); //File.Copy(file, path); var bmp = ImageHelper.CompressImage(Image.FromFile(dlg.ImageSelect), 120, 80); bmp.Save(path, ImageFormat.Jpeg); ICryptoService cryptoService = new PBKDF2(); //New User string password = dlg.UserPassword; //save this salt to the database string salt = cryptoService.GenerateSalt(); //save this hash to the database string hashedPassword = cryptoService.Compute(password); //validate user //compare the password (this should be true since we are rehashing the same password and using the same generated salt) //string hashedPassword2 = cryptoService.Compute(password, salt); //bool isPasswordValid = cryptoService.Compare(hashedPassword, hashedPassword2); //ApplicationDbContext context = new ApplicationDbContext(); DbUser dbUser = new DbUser { FirstName = dlg.UserFN, LastName = dlg.UserLN, Image = nameFile, MobilePhoneNumber = dlg.UserPhone, DateRegistered = DateTime.Now, LastLoginDate = DateTime.Now, Deleted = false, Email = dlg.UserEmail, Password = hashedPassword, PasswordHash = salt }; _context.Users.Add(dbUser); _context.SaveChanges(); int userId = dbUser.Id; foreach (var role in dlg.ListRolesId) { _context.UserRoles.Add(new Entities.DbUserRole { RoleId = role, UserId = userId }); } _context.SaveChanges(); UpdateUsersGrid(); MessageBox.Show("Можна зберігати в БД"); } } catch (Exception ex) { MessageBox.Show("Помилка! Користувача не зареєстровано.\n\n" + ex); } }
public async Task <bool> AddTeacherAsync(AddTeacherModel profile) { try { DbUser user = new DbUser { UserName = profile.Email /*profile.UserName*/, Email = profile.Email, PhoneNumber = profile.PhoneNumber, }; BaseProfile prof = new BaseProfile { Name = profile.Name, LastName = profile.LastName, Surname = profile.Surname, Adress = profile.Adress, DateOfBirth = Convert.ToDateTime(profile.DateOfBirth), PassportString = profile.PassportString, IdentificationCode = profile.IdentificationCode }; string password = PasswordGenerator.GenerationPassword(); if (profile.Rolename == null) { return(false); } await _userManager.CreateAsync(user, password); if (profile.Rolename.Contains("Teacher")) { await _userManager.AddToRoleAsync(user, "Teacher"); } if (profile.Rolename.Contains("Director")) { await _userManager.AddToRoleAsync(user, "Director"); } if (profile.Rolename.Contains("Curator")) { await _userManager.AddToRoleAsync(user, "Curator"); } if (profile.Rolename.Contains("DDeputy")) { await _userManager.AddToRoleAsync(user, "DDeputy"); } if (profile.Rolename.Contains("DepartmentHead")) { await _userManager.AddToRoleAsync(user, "DepartmentHead"); } if (profile.Rolename.Contains("CycleCommisionHead")) { await _userManager.AddToRoleAsync(user, "CycleCommisionHead"); } if (profile.Rolename.Contains("StudyRoomHead")) { await _userManager.AddToRoleAsync(user, "StudyRoomHead"); } prof.Id = user.Id; await _context.BaseProfiles.AddAsync(prof); await _context.SaveChangesAsync(); await _context.TeacherProfiles.AddAsync(new TeacherProfile { Id = prof.Id, //Degree = profile.Degree }); await _context.SaveChangesAsync(); return(true); } catch (Exception ex) { return(false); } }
private void RegisterUser() { DbUser regUser = DbM.RegisterUser(tbRegUsername.Text, tbRegEmail.Text, tbRegPassword.Password.ToString()); UponRegistration(regUser); }
public void backup(Set set, string toolsFolder, string toolsTempFolder) { BackupContents bcs = new BackupContents(); bcs = JsonClassHelper.Json2Class <BackupContents>(set.Backup.Content); if (bcs == null || bcs.content == null) { return; } else { exp_tem_path = toolsFolder; exp_path = toolsTempFolder; dayString = DateTime.Now.Year + "-" + (DateTime.Now.Month < 10 ? "0" + DateTime.Now.Month : DateTime.Now.Month + "") + "-" + (DateTime.Now.Day < 10 ? "0" + DateTime.Now.Day : DateTime.Now.Day + ""); //DateTime.Now.ToShortDateString(); string timeString = DateTime.Now.Hour.ToString() + "-" + DateTime.Now.Minute.ToString() + "--" + DateTime.Now.Second.ToString(); backup_path = set.Backup.Path + "\\backup-" + dayString + "\\" + timeString; if (!System.IO.Directory.Exists(backup_path)) { System.IO.Directory.CreateDirectory(backup_path); } setConfig setconfig = new setConfig(); string ansStr = "开始备份数据\r\n"; if (bcs.content.Find((BackupContent bc) => bc.Name == "sde") != null && bcs.content.Find((BackupContent bc) => bc.Name == "sde").Type.Count > 0) { //备份 sde库 //初始化 esri授权 setArcgis.init(); setArcgis.grant(); } foreach (BackupContent bc in bcs.content) { if (bc.Type == null) { continue; } foreach (BackupContentType bctype in bc.Type) { if (bc.Name == "dmp") { string name = bctype.Name; DbUser dbuser = set.Db.DbUserList.Find((DbUser du) => du.Name == name); if (bctype.Set != null && bctype.Set.Count > 0) { string remoteInfo = bctype.Set.Find((BackupContentSet bcsset) => bcsset.SetKey == "remoteInfo").SetValue; string [] remoteInfos = remoteInfo.Split(','); setBAT.OracleExpdp(exp_tem_path, exp_path, dbuser.User, dbuser.Password, set.Db.Datasource, dbuser.Label, backup_path, remoteInfos[0], remoteInfos[1], remoteInfos[2], bctype.getValueList("excludeTable"), true); setBAT.FilePackage(exp_tem_path, exp_path, "正在压缩" + dbuser.Label + "dmpdp文件", backup_path + "\\EXP-" + dbuser.User.ToUpper() + ".DMPDP", backup_path + "\\exp-" + dbuser.User, false, null, null, true); File.Delete(backup_path + "\\exp-" + dbuser.User + ".dmpdp"); ansStr += dbuser.Label + "数据expdp导出完成\r\n"; } else { setBAT.OracleExp(exp_tem_path, exp_path, dbuser.User, dbuser.Password, set.Db.Datasource, dbuser.Label, backup_path, true); setBAT.FilePackage(exp_tem_path, exp_path, "正在压缩" + dbuser.Label + "dmp文件", backup_path + "\\exp-" + dbuser.User + ".dmp", backup_path + "\\exp-" + dbuser.User, false, null, null, true); File.Delete(backup_path + "\\exp-" + dbuser.User + ".dmp"); ansStr += dbuser.Label + "数据导出完成\r\n"; } } else if (bc.Name == "app") { string type = bctype.Type; string name = bctype.Name; string labelStr = ""; string appfolder = ""; string appfilename = ""; dynamic typeObject = System.Reflection.Assembly.Load("QuickConfig.Model").CreateInstance(type, false);; if (typeObject is ServiceApp) { ServiceApp dbuser = set.Apps.ServiceAppList.Find((ServiceApp du) => du.Name == name); labelStr = dbuser.Label; appfolder = dbuser.Path; appfilename = dbuser.Label; } else if (typeObject is WebApp) { WebApp dbuser = set.Apps.WebAppList.Find((WebApp du) => du.Name == name); labelStr = dbuser.Label; appfolder = dbuser.Path; appfilename = dbuser.Label; } else if (typeObject is App) { App dbuser = set.Apps.AppList.Find((App du) => du.Name == name); labelStr = dbuser.Label; appfolder = dbuser.Path; appfilename = dbuser.Label; } else if (typeObject is Ftp) { Ftp dbuser = set.Apps.FtpList.Find((Ftp du) => du.Name == name); labelStr = dbuser.Label; appfolder = dbuser.Path; appfilename = dbuser.Label; } else if (typeObject is Gxml) { Gxml dbuser = set.Apps.GxmlList.Find((Gxml du) => du.Name == name); labelStr = dbuser.Label; appfolder = dbuser.Path; appfilename = dbuser.Label; } setBAT.FilePackage(exp_tem_path, exp_path, labelStr, appfolder, backup_path + "\\" + appfilename, true, bctype.getValueList("excludeFolder"), bctype.getValueList("excludeFile"), true); ansStr += appfilename + "程序备份完成\r\n"; } else if (bc.Name == "sde") { string name = bctype.Name; DbSdeUser dbuser = set.Db.DbSdeUserList.Find((DbSdeUser du) => du.Name == name); EngineDatabase engine = new EngineDatabase(); engine.createGDBFile(backup_path, dbuser.Tablespace + ".gdb"); string ans1 = engine.exportSDE2GDBWithWorkspace(set.Db.Ip, "sde:oracle10g:" + set.Db.Datasource, dbuser.User, dbuser.Password, backup_path + "\\" + dbuser.Tablespace + ".gdb"); // setBAT.FilePackage(exp_tem_path, exp_path, "正在压缩" + dbuser.Label + "gdb文件", backup_path + "\\" + dbuser.Tablespace + ".gdb", backup_path + "\\" + dbuser.User,true,null,null, true); ansStr += dbuser.Label + "导出结果如下:\r\n" + ans1 + "\r\n"; ansStr += dbuser.Label + "导出导出完成\r\n"; } } } ansStr += "备份结束\r\n"; StreamWriter sw = null; if (!File.Exists(backup_path + "\\" + dayString + ".log")) { //不存在就新建一个文本文件,并写入一些内容 sw = File.CreateText(backup_path + "\\" + dayString + ".log"); } else { sw = new StreamWriter(backup_path + "\\" + dayString + ".log"); } sw.Write(ansStr); sw.Close(); } }
public string Profile() { DbUser currentUser = user.ShowProfile(sessionId); return(HttpUtility.HtmlEncode(currentUser.FirstName)); }
public void DeliveRewards() { //var allRecords = new List<DbDynamicRankRecord>(); // value 1 -> syndicate players inside or user flag num (delivered) // value 2 -> syndicate total players or user lifetime flag num (delivered) // value 3 -> syndicate points or user points // value 4 -> syndicate lifetime points or user lifetime points // value 5 -> syndicate silver reward or user awarded silver // value 6 -> syndicate emoney reward or user awarded emoney foreach (var syn in m_pRanking.Values) { Syndicate pSyn; if (ServerKernel.Syndicates.TryGetValue(syn.ObjectIdentity, out pSyn)) { syn.Value5 = pSyn.MoneyPrize; syn.Value6 = pSyn.EmoneyPrize; pSyn.MoneyPrize = 0; pSyn.EmoneyPrize = 0; } } foreach (var syn in m_pRanking.Values.Where(x => x.Value3 > 0 && (x.Value5 > 0 || x.Value6 > 0))) { //var pDelivered = new Dictionary<uint, Point>(); uint synId = syn.ObjectIdentity; int deliverMoney = 0; int deliverEmoney = 0; foreach (var plr in m_pUserRank.Values.Where(x => x.ObjectIdentity == synId)) { float nPercent = (plr.Value3 / (float)syn.Value3); int money = (int)(syn.Value5 * nPercent); int emoney = (int)(syn.Value6 * nPercent); deliverMoney += money; deliverEmoney += emoney; Client pClient; if (ServerKernel.Players.TryGetValue(plr.PlayerIdentity, out pClient)) { pClient.Character.AwardMoney(money); pClient.Character.AwardEmoney(emoney); //pDelivered.Add(plr.PlayerIdentity, new Point(money, emoney)); pClient.SendMessage(string.Format(ServerString.STR_CTF_AWARDED_PRIZE, plr.Value3, money, emoney), ChatTone.GUILD); } else { DbUser pUser = Database.Characters.SearchByIdentity(plr.PlayerIdentity); if (pUser != null) { pUser.Money = (uint)Math.Min(int.MaxValue, pUser.Money + money); pUser.Emoney = (uint)Math.Min(int.MaxValue, pUser.Emoney + emoney); Database.Characters.SaveOrUpdate(pUser); } } plr.Value5 = money; plr.Value6 = emoney; ServerKernel.Log.GmLog("ctfreward", string.Format("{0}({1}),awarded(money:{2},emoney:{3}),for({4})points", plr.PlayerIdentity, plr.PlayerName, money, emoney, plr.Value3)); } syn.Value5 = 0; syn.Value6 = 0; Syndicate pSyn; if (ServerKernel.Syndicates.TryGetValue(syn.ObjectIdentity, out pSyn)) { //if (pDelivered.Count <= 0) // continue; DbDynamicRankRecord pDyna = m_pUserRank.Values.OrderByDescending(x => x.Value3) .FirstOrDefault(x => x.ObjectIdentity == syn.Identity && x.PlayerIdentity > 0); if (pDyna != null) { pSyn.Send(string.Format(ServerString.STR_CTF_HIGHEST_REWARD, pDyna.PlayerName, pDyna.Value5, pDyna.Value6)); } } m_pRepo.SaveOrUpdate(syn); ServerKernel.Log.GmLog("ctfsynreward", string.Format("syn(id:{0},name{1}),paid({2},{3}),totalprize({4},{5})", syn.ObjectIdentity, syn.ObjectName, deliverMoney, deliverEmoney, syn.Value5, syn.Value6)); } int nCount = 0; foreach (var syn in m_pRanking.Values.OrderByDescending(x => x.Value3).ThenByDescending(x => x.Value1)) { if (nCount >= 8) { break; } Syndicate updateSyn; if (!ServerKernel.Syndicates.TryGetValue(syn.ObjectIdentity, out updateSyn)) { continue; } updateSyn.ChangeFunds(ServerKernel.CTF_MONEY_REWARD[nCount]); updateSyn.ChangeEmoneyFunds((int)ServerKernel.CTF_EMONEY_REWARD[nCount]); nCount++; } }
private static void SeedData(HiggsDbContext context) { if (!context.AllMigrationsApplied()) { return; } var seedUsers = new[] { new SeedUser { AccountId = RobAccountId, UserName = "******" } }; var dbScopes = context.Scopes.ToList().ToDictionary(p => p.Name, p => p, StringComparer.OrdinalIgnoreCase); // Insert new scopes foreach (var scope in Scopes.AllScopes) { if (!dbScopes.ContainsKey(scope.Key)) { context.Scopes.Add(new DbScope { Name = scope.Key, Description = scope.Value }); } } // Delete old scopes foreach (var dbScope in dbScopes) { if (!Scopes.AllScopes.ContainsKey(dbScope.Key)) { context.Scopes.Remove(dbScope.Value); } } foreach (var seedUser in seedUsers) { var existingUser = context.Users.Include(u => u.UserScopes) .FirstOrDefault(u => u.AccountId == seedUser.AccountId); if (existingUser == null) { existingUser = new DbUser { AccountId = seedUser.AccountId, Name = seedUser.UserName }; context.Users.Add(existingUser); } if (existingUser.UserScopes == null) { existingUser.UserScopes = new List <DbUserScope>(); } foreach (var scope in Scopes.AllScopes) { if (existingUser.UserScopes.All(s => !string.Equals(s.ScopeName, scope.Key, StringComparison.OrdinalIgnoreCase))) { context.UserScopes.Add(new DbUserScope { UserId = seedUser.AccountId, ScopeName = scope.Key }); } } } context.SaveChanges(); }
private void authenticateUser(DbUser dbUser) { Session["AuthenticatedUser"] = dbUser; ViewBag.AuthenticatedUser = dbUser; }
public async Task <ActionResult> Post() { SignUpRequest credentials; using (var reader = new StreamReader(Request.Body, Encoding.UTF8)) { credentials = JsonConvert.DeserializeObject <SignUpRequest>(await reader.ReadToEndAsync()); } if (PluginEntry._recaptchaConfig.Enabled) { using var wc = new WebRequest("https://www.google.com/recaptcha/api/siteverify") { Method = HttpMethod.Post }; wc.AddParameter("secret", PluginEntry._recaptchaConfig.PrivateKey); wc.AddParameter("response", credentials.GCaptchaValidation); await wc.PerformAsync(); var gCaptcha = JsonConvert.DeserializeObject <GCaptchaVerificationResponse>(wc.ResponseString); if (!gCaptcha.success) { return(Ok(new { code = 450, message = "Recaptcha failed!" })); } } var u = await DbUser.RegisterUser(_context, Permission.From(Permission.DEFAULT), credentials.UserName, credentials.EMail, credentials.Password, false); if (PluginEntry._sender == null) { return(Ok(new { code = 0, message = "Success" })); } var emailKey = Crypto.RandomString(512); u.Status = UserStatusFlags.Suspended; u.StatusReason = "Verification|" + emailKey; u.StatusUntil = DateTime.Today + TimeSpan.FromDays(365 * 100); // Suspend for 100 years (or until EMail Verified!) _context.Update(u); var em = Email .From("*****@*****.**") .To(u.EMail) .Subject("Email Confirmation") .Body("Your EMail has to be Verificated! Please click <a href=\"" + "http://" + _serverConfig.Server.ScreenShotHostname + "/verificate?k" + emailKey + "\">Here</a>!"); var r = await em.SendAsync(); if (!r.Successful) { throw new Exception( $"Failed to send EMail: {r.Successful} {r.MessageId} {r.ErrorMessages.Aggregate((a, b) => a + ", " + b)}" ); } return(Ok(new { code = 100, message = "EMail Verification Pending" })); }
private void emailConsultantsBTN_Click(object sender, EventArgs e) { DbUser user = new DbUser(); for (int j = 0; j < users.Count(); j++) { if (searchUsersLBX.SelectedItem.ToString() == users[j].Name) { user = users[j]; break; } } DbUser thisUser = service.GetUserByUserName(username)[0]; EmailForm eform = new EmailForm(sessionId, user.Email, thisUser.Email); eform.Show(); }
private string CreateUserToken(DbUser user) { string token = HashProfile.GetSaltedHashData(user.Email, user.PasswordSalt); return(token); }
public static void HandleRegister(Client pClient, MsgRegister pMsg) { Client trash; if (pMsg.CancelRequest) { try { pClient.Disconnect(); } catch { ServerKernel.Players.TryRemove(pClient.Identity, out trash); ServerKernel.CharacterCreation.TryRemove(pClient.Identity, out trash); ServerKernel.CharacterCreation.TryRemove(pClient.AccountIdentity, out trash); } return; } if (ServerKernel.CharacterCreation.TryGetValue(pClient.AccountIdentity, out trash)) { trash = null; if (CheckName(pMsg.Name)) { var pRepository = new CharacterRepository(); if (pRepository.AccountHasCharacter(pClient.AccountIdentity)) { //DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccountHasCharacter); pClient.Send(ServerMessages.CharacterCreation.AccountHasCharacter); return; } if (pRepository.CharacterExists(pMsg.Name)) { //DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.NameTaken); pClient.Send(ServerMessages.CharacterCreation.NameTaken); return; } ProfessionType profession = ((ProfessionType)pMsg.Profession > ProfessionType.INTERN_TAOIST ? ProfessionType.INTERN_TAOIST : (ProfessionType)(pMsg.Profession / 10 * 10)); if (!Enum.IsDefined(typeof(BodyType), pMsg.Body) || !Enum.IsDefined(typeof(ProfessionType), profession)) { // The client is a proxy exploiting the server. Disconnect the client. DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied); return; } switch (profession) { case ProfessionType.INTERN_ARCHER: case ProfessionType.INTERN_NINJA: case ProfessionType.INTERN_TAOIST: case ProfessionType.INTERN_TROJAN: case ProfessionType.INTERN_WARRIOR: case ProfessionType.INTERN_MONK: break; default: { DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied); return; } } ushort hair = 410; uint lookface = 0; if (pMsg.Body == (ushort)BodyType.THIN_MALE || pMsg.Body == (ushort)BodyType.HEAVY_MALE) { if ((pMsg.Profession / 10) == 5) { lookface = (uint)(new Random().Next(103, 107)); } else if ((pMsg.Profession / 10) == 6) { lookface = (uint)(new Random().Next(109, 113)); } else { lookface = (uint)(new Random().Next(1, 102)); } } else { hair = 410; if ((pMsg.Profession / 10) == 5) { lookface = (uint)(new Random().Next(291, 295)); } else if ((pMsg.Profession / 10) == 6) { lookface = (uint)(new Random().Next(300, 304)); } else { lookface = (uint)(new Random().Next(201, 290)); } } #region Initial HairStyle and Lookface for monks switch (profession) { case ProfessionType.INTERN_MONK: if (pMsg.Body == (ushort)BodyType.THIN_MALE) { lookface = (uint)(new Random().Next(109, 113)); hair = 400; } else if (pMsg.Body == (ushort)BodyType.HEAVY_MALE) { lookface = (uint)(new Random().Next(129, 133)); hair = 400; } else if (pMsg.Body == (ushort)BodyType.THIN_FEMALE) { lookface = (uint)(new Random().Next(300, 304)); } else if (pMsg.Body == (ushort)BodyType.HEAVY_FEMALE) { lookface = (uint)(new Random().Next(325, 329)); } break; } #endregion DbPointAllot points = ServerKernel.PointAllot.Values.FirstOrDefault( x => x.Profession == ((pMsg.Profession - (pMsg.Profession % 10)) / 10) && x.Level == 1); if (points == null) { pClient.Send(new MsgTalk("Could not fetch class attribute points.", ChatTone.CHARACTER_CREATION)); return; } int idx = new Random().Next(m_startX.Length - 1); ushort startX = m_startX[idx]; ushort startY = m_startY[idx]; switch (profession) { case ProfessionType.INTERN_TROJAN: case ProfessionType.INTERN_WARRIOR: case ProfessionType.INTERN_ARCHER: case ProfessionType.INTERN_NINJA: case ProfessionType.INTERN_TAOIST: case ProfessionType.INTERN_MONK: { break; } default: DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied); return; } uint money = 100000, emoney = 25; ushort startLife = (ushort)(((points.Agility + points.Strength + points.Spirit) * 3) + points.Vitality * 24); var newUser = new DbUser { AccountId = pClient.AccountIdentity, Name = pMsg.Name, Lookface = pMsg.Body + (lookface * 10000), Profession = (byte)profession, Mate = "None", AdditionalPoints = 0, Agility = points.Agility, Strength = points.Strength, Vitality = points.Vitality, Spirit = points.Spirit, AutoAllot = 1, AutoExercise = 0, BoundEmoney = 4300, Business = 255, CoinMoney = 0, CurrentLayout = 0, Donation = 0, Emoney = emoney, Experience = 0, Level = 1, FirstProfession = 0, Metempsychosis = 0, Flower = 0, HomeId = 0, LastLogin = 0, LastLogout = 0, LastProfession = 0, Life = startLife, LockKey = 0, Hair = hair, Mana = 0, MapId = _START_MAP, MapX = startX, MapY = startY, MeteLevel = 0, Money = money, MoneySaved = 0, Orchids = 0, PkPoints = 0, RedRoses = 0, StudentPoints = 0, Tulips = 0, Virtue = 0, WhiteRoses = 0, EnlightPoints = 0, HeavenBlessing = (uint)(UnixTimestamp.Timestamp() + 60 * 60 * 24 * 30), ExperienceExpires = (uint)(UnixTimestamp.Timestamp() + 60 * 60 * 24), ExperienceMultipler = 10 }; if (pRepository.CreateNewCharacter(newUser)) { uint idUser = newUser.Identity; try { GenerateInitialStatus(idUser, profession); } catch { ServerKernel.Log.SaveLog("Could not create initial status for character " + idUser, true, LogType.ERROR); } ServerKernel.Log.SaveLog(string.Format("User [({0}){1}] has created character {2}.", pClient.AccountIdentity, idUser, newUser.Name), true); pClient.Send(ServerMessages.CharacterCreation.AnswerOk); return; } } else { //DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.InvalidName); pClient.Send(ServerMessages.CharacterCreation.InvalidName); return; } } else { DisconnectWithMsg(pClient, ServerMessages.CharacterCreation.AccessDenied); return; } }
public async Task <ActionResult <AuthResponse> > PostAsync(AuthRequest request) { try { var user = await _db.Users.AsNoTracking().FirstOrDefaultAsync(u => u.Username == request.Username); if (user == null) { user = new DbUser { Username = request.Username, Password = _hash.Hash(request.Password), CreatedTime = DateTime.UtcNow, WebData = new DbWebData { Token = Guid.NewGuid(), Data = "{}" } }; _db.Add(user); await _db.SaveChangesAsync(); _logger.LogInformation($"Created user '{request.Username}'."); _registrations.Inc(); // if user id is 1, set as admin if (user.Id == 1) { user.IsAdmin = true; await _db.SaveChangesAsync(); } } else { if (!_hash.Test(user.Password, request.Password)) { return(Unauthorized("Invalid username or password.")); } _authorizations.Inc(); } return(Ok(new AuthResponse { Token = _auth.CreateToken(user), User = Models.User.FromDbModel(user) })); } catch (Exception e) { var message = $"Could not authenticate user '{request.Username}'."; _logger.LogWarning(e, message); return(BadRequest(message)); } }
protected void Page_Load(object sender, EventArgs e) { Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); Guid sessionId = (Guid)Session["sessionId"]; // user = new DbUser(); user = service.DisplayProfile(sessionId); //trap the selected item if (LBAddedSkills.SelectedIndex > -1) { removeSelectedItem = LBAddedSkills.SelectedItem.ToString(); } if (LBExisitingSkills.SelectedIndex > -1) { addedSelectedItem = LBExisitingSkills.SelectedItem.ToString(); } //refill the bidinglist //add the trapped item to the bindinglist #region Postback if (!Page.IsPostBack) { //newlyAddedSkills; //EditPanel.Visible = false; ViewProfilePanel.Visible = true; EditPanel.Visible = false; //Fill the View and Edit Profile labels and TextBox fields TxtBoxFname.Text = user.FirstName; VPFirstNameLbl.Text = user.FirstName; TxtBoxLName.Text = user.LastName; VPLastNameLbl.Text = user.LastName; TxtBoxEmail.Text = user.Email; VPEmailLbl.Text = user.Email; TxtBoxDegree.Text = user.Degree; VPPDegreeLbl.Text = user.Degree; TxtBoxLocation.Text = user.Location; VPLocLbl.Text = user.Location; TxtBoxModules.Text = user.Modules; VPModulesLbl.Text = user.Modules; //Fill the ComboBox for Status and Stream FillDropDownLists(); CmbBoxStatus.SelectedValue = user.TStatus; VPStatusLbl.Text = user.TStatus; CmbBoxStream.SelectedValue = user.Stream; VpStreamLbl.Text = user.Stream; //Add theImage for the Consultant Add_Image(); //Fill the user existing skills fields userId = int.Parse(Session["userid"].ToString()); userExistingSkills = new BindingList <string>(service.GetUserSkills(userId)); LBAddedSkills.DataSource = userExistingSkills; LBAddedSkills.DataBind(); //Fill the List of available skills from the database dbExistingSkills = new BindingList <string>(service.DisplaySkills()); //Get rid of the skills already added for the user for (int i = 0; i < dbExistingSkills.Count; i++) { foreach (string j in userExistingSkills) { if (j == dbExistingSkills[i]) { dbExistingSkills.RemoveAt(i); } } } LBExisitingSkills.DataSource = dbExistingSkills; LBExisitingSkills.DataBind(); } #endregion userId = int.Parse(Session["userid"].ToString()); userExistingSkills = new BindingList <string>(service.GetUserSkills(userId)); VPSkillsLB.DataSource = userExistingSkills; VPSkillsLB.DataBind(); Label14.Text = ""; Label13.Text = ""; }
public async Task <IActionResult> Facebook([FromBody] FacebookAuthViewModel model) { // 1.generate an app access token var appAccessTokenResponse = await Client.GetStringAsync($"https://graph.facebook.com/oauth/access_token?client_id={_fbAuthSettings.AppId}&client_secret={_fbAuthSettings.AppSecret}&grant_type=client_credentials"); var appAccessToken = JsonConvert.DeserializeObject <FacebookAppAccessToken>(appAccessTokenResponse); // 2. validate the user access token var userAccessTokenValidationResponse = await Client.GetStringAsync($"https://graph.facebook.com/debug_token?input_token={model.AccessToken}&access_token={appAccessToken.AccessToken}"); var userAccessTokenValidation = JsonConvert.DeserializeObject <FacebookUserAccessTokenValidation>(userAccessTokenValidationResponse); if (!userAccessTokenValidation.Data.IsValid) { return(BadRequest(new { invalid = "Invalid facebook token!" })); } // 3. we've got a valid token so we can request user data from fb var userInfoResponse = await Client.GetStringAsync($"https://graph.facebook.com/v2.8/me?fields=id,email,first_name,last_name,name,gender,locale,birthday,picture&access_token={model.AccessToken}"); var userInfo = JsonConvert.DeserializeObject <FacebookUserData>(userInfoResponse); // 4. ready to create the local user account (if necessary) and jwt var user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { string path = _fileService.UploadFacebookImage(userInfo.Picture.Data.Url); user = new DbUser { FirstName = userInfo.FirstName, LastName = userInfo.LastName, Email = userInfo.Email, UserName = userInfo.Email, SignUpTime = DateTime.Now, AvatarUrl = path }; var result = await _userManager.CreateAsync(user, RandomPasswordGenerator.GenerateRandomPassword()); if (!result.Succeeded) { var errors = CustomValidator.GetErrorsByIdentityResult(result); return(BadRequest(errors)); } var roleName = "User"; var roleresult = _roleManager.CreateAsync(new DbRole { Name = roleName }).Result; result = _userManager.AddToRoleAsync(user, roleName).Result; await _signInManager.SignInAsync(user, isPersistent : false); if (!result.Succeeded) { return(BadRequest(new { invalid = "We can't create user" })); } } else { user = await _userManager.FindByEmailAsync(userInfo.Email); if (user == null) { return(BadRequest(new { invalid = "Failed to create local user account." })); } } await _signInManager.SignInAsync(user, isPersistent : false); return(Ok(_jWTTokenService.CreateToken(_configuration, user, _userManager))); }
bool IsCredentialsCorrect(string username, string password, string loginType, DbUser dbUser) { if (dbUser == null) { return(false); } if (dbUser.Password != password) { return(false); } if (dbUser.UserType == "AppUser") { return(false); } return(true); }
public static async Task OnHttpRequest(Microsoft.AspNetCore.Http.HttpContext e, DbUser u, string token) { //Validate challenges if (Program.FindRequestMethod(e) != RequestHttpMethod.delete) { throw new StandardError("A required challenge failed.", StandardErrorCode.MissingRequiredArg); } if (e.Request.Query["chal_name"] != u.screen_name) { throw new StandardError("A required challenge failed.", StandardErrorCode.MissingRequiredArg); } //We're confirmed to delete this user. Go ahead and start removing data //We'll remove analytic data first using (HttpClient hc = new HttpClient()) await hc.PostAsync("https://web-analytics.deltamap.net/v1/destroy?access_token=" + token, new StringContent("")); //Now, delete all servers we own var owned_servers = u.GetOwnedServersAsync(Program.connection).GetAwaiter().GetResult(); foreach (var s in owned_servers) { s.DeleteAsync(Program.connection).GetAwaiter().GetResult(); } //Destroy all of our tokens u.DevalidateAllTokens(Program.connection).GetAwaiter().GetResult(); //Finally, destroy our user u.DeleteAsync(Program.connection).GetAwaiter().GetResult(); //Goodbye! await Program.QuickWriteStatusToDoc(e, true); }
public void CreateUser(DbUser user) { _userRepository.Add(user); _unitOfWork.Commit(); }
protected void UpdateProfile_Click(object sender, EventArgs e) { DbUser user = new DbUser(); user.UserId = int.Parse(Session["userid"].ToString()); user.Username = TxtBoxFname.Text; user.LastName = TxtBoxLName.Text; user.Email = TxtBoxEmail.Text; user.Location = TxtBoxLocation.Text; VPLocLbl.Text = TxtBoxLocation.Text; user.Degree = TxtBoxDegree.Text; VPPDegreeLbl.Text = TxtBoxDegree.Text; user.Modules = TxtBoxModules.Text; VPModulesLbl.Text = TxtBoxModules.Text; user.Stream = CmbBoxStream.SelectedValue; VpStreamLbl.Text = CmbBoxStream.SelectedValue; user.TStatus = CmbBoxStatus.SelectedValue; VPStatusLbl.Text = CmbBoxStatus.SelectedValue; if (service.UpdateProfile(user)) { Label13.Text = "Successfully updated Profile"; Label14.Text = ""; //Page_Load(sender, e); EditPanel.Visible = false; ViewProfilePanel.Visible = true; } else { Label14.Text = "Failed to update the profile"; Label13.Text = ""; } }
private void button1_Click(object sender, RoutedEventArgs e) { if (delUNameTxtbox.Text == "") { delUErrorLbl.Content = "Please enter a username"; delUErrorLbl.Foreground = new SolidColorBrush(Colors.Red); delUErrorLbl.Visibility = Visibility.Visible; } else if (findUserList.SelectedItem == null) { delUErrorLbl.Content = "Please select a user to delete"; delUErrorLbl.Foreground = new SolidColorBrush(Colors.Red); delUErrorLbl.Visibility = Visibility.Visible; } else { delUErrorLbl.Visibility = Visibility.Hidden; DbUser selectedUser = (DbUser)findUserList.SelectedItem; string username = selectedUser.Username; if (jobExists(username)) { AssignJobsToAccMan jobs = new AssignJobsToAccMan(sessionId, jobsList); jobs.setUsername(username); jobs.setAdminAppForm(this); this.Hide(); jobs.Show(); } else if (username == adminUsername) { delUErrorLbl.Content = "Sorry you cannot delete yourself. This action is not permitted"; delUErrorLbl.Foreground = new SolidColorBrush(Colors.Red); delUErrorLbl.Visibility = Visibility.Visible; } else { var result = MessageBox.Show("Are you sure you want to delete the selected user?", "Delete User", MessageBoxButton.YesNo, MessageBoxImage.Question); if (result == MessageBoxResult.Yes) { List <DbUser> users = new List <DbUser>(); selectedUser.Username = username; users.Add(selectedUser); if (client.DeleteUser(users)) { _UserCollection.Clear(); autoFillUserName.Remove(username); // delUErrorLbl.Content = tabControl1.SelectedIndex.ToString(); delUErrorLbl.Content = "User " + username + " has been deleted"; delUErrorLbl.Foreground = new SolidColorBrush(Colors.Green); delUNameTxtbox.Text = ""; delUErrorLbl.Visibility = Visibility.Visible; } else { delUErrorLbl.Content = "Failed to delete the user with username: " + username; delUErrorLbl.Foreground = new SolidColorBrush(Colors.Red); delUErrorLbl.Visibility = Visibility.Visible; } } } } }
protected void Page_Load(object sender, EventArgs e) { Response.Cache.SetExpires(DateTime.UtcNow.AddMinutes(-1)); Response.Cache.SetCacheability(HttpCacheability.NoCache); Response.Cache.SetNoStore(); Guid sessionId = (Guid)Session["sessionId"]; // user = new DbUser(); user = service.DisplayProfile(sessionId); //trap the selected item if (LBAddedSkills.SelectedIndex > -1) { removeSelectedItem = LBAddedSkills.SelectedItem.ToString(); } if(LBExisitingSkills.SelectedIndex > -1) { addedSelectedItem = LBExisitingSkills.SelectedItem.ToString(); } //refill the bidinglist //add the trapped item to the bindinglist #region Postback if (!Page.IsPostBack) { //newlyAddedSkills; //EditPanel.Visible = false; ViewProfilePanel.Visible = true; EditPanel.Visible = false; //Fill the View and Edit Profile labels and TextBox fields TxtBoxFname.Text = user.FirstName; VPFirstNameLbl.Text = user.FirstName; TxtBoxLName.Text = user.LastName; VPLastNameLbl.Text = user.LastName; TxtBoxEmail.Text = user.Email; VPEmailLbl.Text = user.Email; TxtBoxDegree.Text = user.Degree; VPPDegreeLbl.Text = user.Degree; TxtBoxLocation.Text = user.Location; VPLocLbl.Text = user.Location; TxtBoxModules.Text = user.Modules; VPModulesLbl.Text = user.Modules; //Fill the ComboBox for Status and Stream FillDropDownLists(); CmbBoxStatus.SelectedValue = user.TStatus; VPStatusLbl.Text = user.TStatus; CmbBoxStream.SelectedValue = user.Stream; VpStreamLbl.Text = user.Stream; //Add theImage for the Consultant Add_Image(); //Fill the user existing skills fields userId = int.Parse(Session["userid"].ToString()); userExistingSkills = new BindingList<string>(service.GetUserSkills(userId)); LBAddedSkills.DataSource = userExistingSkills; LBAddedSkills.DataBind(); //Fill the List of available skills from the database dbExistingSkills = new BindingList<string>(service.DisplaySkills()); //Get rid of the skills already added for the user for (int i = 0; i < dbExistingSkills.Count; i++) { foreach (string j in userExistingSkills) { if (j == dbExistingSkills[i]) { dbExistingSkills.RemoveAt(i); } } } LBExisitingSkills.DataSource = dbExistingSkills; LBExisitingSkills.DataBind(); } #endregion userId = int.Parse(Session["userid"].ToString()); userExistingSkills = new BindingList<string>(service.GetUserSkills(userId)); VPSkillsLB.DataSource = userExistingSkills; VPSkillsLB.DataBind(); Label14.Text = ""; Label13.Text = ""; }
public UserController() { dbUser = new DbUser(); }
public async Task <IActionResult> Register([FromBody] UserRegisterVM model) { if (!ModelState.IsValid) { var errors = CustomValidator.GetErrorsByModel(ModelState); return(BadRequest(errors)); } var str_name = model.Name; var name_regex = @"^[A-Za-z-а-яА-Я]+$"; var str_email = model.Email; var email_regex = @"^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$"; var match_name = Regex.Match(str_name, name_regex); var match_email = Regex.Match(str_email, email_regex); if (!match_name.Success) { return(BadRequest(new { Name = "Неправильний формат поля." })); } if (!match_email.Success) { return(BadRequest(new { Email = "Неправильний формат поля." })); } string roleName = "Employee"; var role = _roleManager.FindByNameAsync(roleName).Result; if (role == null) { role = new DbRole { Name = roleName }; } var userEmail = model.Email; //var user = _userManager.FindByEmailAsync(userEmail).Result; if (_userManager.FindByEmailAsync(userEmail).Result != null) { return(BadRequest(new { Email = "Така електронна пошта вже існує!" })); } var user = new DbUser { Email = userEmail, UserName = model.Name }; //user.UserRoles = new List<DbRole>(); var result = _userManager.CreateAsync(user, model.Password).Result; if (!result.Succeeded) { return(BadRequest(new { Password = "******" })); } result = _userManager.AddToRoleAsync(user, roleName).Result; if (!result.Succeeded) { return(BadRequest(new { Password = "******" })); } return(Ok( new { token = CreateTokenJwt(user) })); }
public void OnExecute(CommandLineApplication app, IConsole console) { if (string.IsNullOrEmpty(DatabaseConfigurationFile)) { DatabaseConfigurationFile = Application.DefaultDatabaseConfigurationFile; } var user = new DbUser(); Console.Write("Username: "******"Email: "); user.Email = Console.ReadLine(); Console.Write("Password: "******"Password confirmation: "); string passwordConfirmation = ConsoleHelper.ReadPassword(); Console.Write("Password salt: "); string passwordSalt = ConsoleHelper.ReadStringOrDefault(); Console.WriteLine("Authority: "); ConsoleHelper.DisplayEnum <AuthorityType>(); user.Authority = (int)ConsoleHelper.ReadEnum <AuthorityType>(); Console.WriteLine("--------------------------------"); Console.WriteLine("User account informations:"); Console.WriteLine($"Username: {user.Username}"); Console.WriteLine($"Email: {user.Email}"); Console.WriteLine($"Authority: {(AuthorityType)user.Authority}"); Console.WriteLine("--------------------------------"); bool response = ConsoleHelper.AskConfirmation("Create user?"); if (response) { DatabaseFactory.Instance.Initialize(this.DatabaseConfigurationFile); this._database = new Rhisis.Database.Database(); if (this._database.Users.HasAny(x => x.Username.Equals(user.Username, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine($"User '{user.Username}' is already used."); return; } if (!user.Email.IsValidEmail()) { Console.WriteLine($"Email '{user.Email}' is not valid."); return; } if (_database.Users.HasAny(x => x.Email.Equals(user.Email, StringComparison.OrdinalIgnoreCase))) { Console.WriteLine($"Email '{user.Email}' is already used."); return; } if (!user.Password.Equals(passwordConfirmation)) { Console.WriteLine("Passwords doesn't match."); return; } user.Password = MD5.GetMD5Hash(passwordSalt, user.Password); this._database.Users.Create(user); this._database.Complete(); Console.WriteLine($"User '{user.Username}' created."); } }
public async Task<IActionResult> PostSubmitModular() { if (!Directory.Exists("data/replays")) Directory.CreateDirectory("data/replays"); string encScore = Request.Form["score"]; string iv = Request.Form["iv"]; string osuver = Request.Form["osuver"]; string passwd = Request.Form["pass"]; var (pass, score) = ScoreSubmissionParser.ParseScore(encScore, iv, osuver); var dbUser = await DbUser.GetDbUser(_ctx, score.UserName); if (dbUser == null) return Ok("error: pass"); if (!dbUser.IsPassword(passwd)) return Ok("error: pass"); if (!_ps.TryGet(dbUser.Id, out var pr)) return Ok("error: pass"); // User not logged in in Bancho! if (!pass || !RankedMods.IsRanked(score.Mods)) { var lb = await DbLeaderboard.GetLeaderboardAsync(_ctx, dbUser); lb.IncreasePlaycount(score.PlayMode); lb.IncreaseScore((ulong) score.TotalScore, false, score.PlayMode); await lb.SaveChanges(_ctx); // Send to other People await _ev.RunEvent( EventType.BanchoUserStatsRequest, new BanchoUserStatsRequestArgs {UserIds = new List<int> {score.Id}, Pr = pr} ); // Send to self await _ev.RunEvent( EventType.BanchoSendUserStatus, new BanchoSendUserStatusArgs {Status = pr.Status, Pr = pr} ); return Ok("Thanks for your hard work! onii-chyan~"); // even though, we're Sora, we can still be cute! } var replayFileData = Request.Form.Files.GetFile("score"); var dbScore = new DbScore { Accuracy = score.ComputeAccuracy(), Count100 = score.Count100, Count50 = score.Count50, Count300 = score.Count300, Date = score.Date, Mods = score.Mods, CountGeki = score.CountGeki, CountKatu = score.CountKatu, CountMiss = score.CountMiss, FileMd5 = score.FileMd5, MaxCombo = score.MaxCombo, PlayMode = score.PlayMode, ScoreOwner = dbUser, TotalScore = score.TotalScore, UserId = dbUser.Id }; await _pisstaube.DownloadBeatmapAsync(dbScore.FileMd5); await using (var m = new MemoryStream()) { replayFileData.CopyTo(m); m.Position = 0; dbScore.ReplayMd5 = Hex.ToHex(Crypto.GetMd5(m)) ?? string.Empty; if (!string.IsNullOrEmpty(dbScore.ReplayMd5)) { await using var replayFile = System.IO.File.Create($"data/replays/{dbScore.ReplayMd5}"); m.Position = 0; m.WriteTo(replayFile); m.Close(); replayFile.Close(); } } dbScore.PerformancePoints = dbScore.ComputePerformancePoints(); var oldScore = await DbScore.GetLatestScore(_ctx, dbScore); var oldLb = await DbLeaderboard.GetLeaderboardAsync(_ctx, dbScore.ScoreOwner); var oldStdPos = oldLb.GetPosition(_ctx, dbScore.PlayMode); var oldAcc = oldLb.GetAccuracy(_ctx, dbScore.PlayMode); double newAcc; if (oldScore != null && oldScore.TotalScore <= dbScore.TotalScore) { _ctx.Remove(oldScore); System.IO.File.Delete($"data/replays/{oldScore.ReplayMd5}"); await DbScore.InsertScore(_ctx, dbScore); } else if (oldScore == null) { await DbScore.InsertScore(_ctx, dbScore); } else { System.IO.File.Delete($"data/replays/{oldScore.ReplayMd5}"); } var newlb = await DbLeaderboard.GetLeaderboardAsync(_ctx, dbScore.ScoreOwner); newlb.IncreasePlaycount(dbScore.PlayMode); newlb.IncreaseScore((ulong) dbScore.TotalScore, true, dbScore.PlayMode); newlb.IncreaseScore((ulong) dbScore.TotalScore, false, dbScore.PlayMode); newlb.UpdatePp(_ctx, dbScore.PlayMode); await newlb.SaveChanges(_ctx); var newStdPos = newlb.GetPosition(_ctx, dbScore.PlayMode); newAcc = newlb.GetAccuracy(_ctx, dbScore.PlayMode); var newScore = await DbScore.GetLatestScore(_ctx, dbScore); var set = await _pisstaube.FetchBeatmapSetAsync(dbScore.FileMd5); var bm = set?.ChildrenBeatmaps.First(x => x.FileMD5 == dbScore.FileMd5) ?? new Beatmap(); ulong oldRankedScore; ulong newRankedScore; double oldPp; double newPp; switch (dbScore.PlayMode) { case PlayMode.Osu: oldRankedScore = oldLb.RankedScoreOsu; newRankedScore = newlb.RankedScoreOsu; oldPp = oldLb.PerformancePointsOsu; newPp = newlb.PerformancePointsOsu; break; case PlayMode.Taiko: oldRankedScore = oldLb.RankedScoreTaiko; newRankedScore = newlb.RankedScoreTaiko; oldPp = oldLb.PerformancePointsTaiko; newPp = newlb.PerformancePointsTaiko; break; case PlayMode.Ctb: oldRankedScore = oldLb.RankedScoreCtb; newRankedScore = newlb.RankedScoreCtb; oldPp = oldLb.PerformancePointsCtb; newPp = newlb.PerformancePointsCtb; break; case PlayMode.Mania: oldRankedScore = oldLb.RankedScoreMania; newRankedScore = newlb.RankedScoreMania; oldPp = oldLb.PerformancePointsMania; newPp = newlb.PerformancePointsMania; break; default: return Ok(""); } var newScorePosition = newScore != null ? await newScore.Position(_ctx) : 0; var oldScorePosition = oldScore != null ? await oldScore.Position(_ctx) : 0; if (newScorePosition == 1) _sora.SendMessage( $"[http://{_config.Server.ScreenShotHostname}/{dbScore.ScoreOwner.Id} {dbScore.ScoreOwner.UserName}] " + $"has reached #1 on [https://osu.ppy.sh/b/{bm.BeatmapID} {set?.Title} [{bm.DiffName}]] " + $"using {ModUtil.ToString(newScore.Mods)} " + $"Good job! +{newScore.PerformancePoints:F}PP", "#announce", false ); Logger.Info( $"{LCol.RED}{dbScore.ScoreOwner.UserName}", $"{LCol.PURPLE}( {dbScore.ScoreOwner.Id} ){LCol.WHITE}", $"has just submitted a Score! he earned {LCol.BLUE}{newScore?.PerformancePoints:F}PP", $"{LCol.WHITE}with an Accuracy of {LCol.RED}{newScore?.Accuracy * 100:F}", $"{LCol.WHITE}on {LCol.YELLOW}{set?.Title} [{bm.DiffName}]", $"{LCol.WHITE}using {LCol.BLUE}{ModUtil.ToString(newScore?.Mods ?? Mod.None)}" ); var bmChart = new Chart( "beatmap", "Beatmap Ranking", $"https://osu.ppy.sh/b/{bm.BeatmapID}", oldScorePosition, newScorePosition, oldScore?.MaxCombo ?? 0, newScore?.MaxCombo ?? 0, oldScore?.Accuracy * 100 ?? 0, newScore?.Accuracy * 100 ?? 0, (ulong) (oldScore?.TotalScore ?? 0), (ulong) (newScore?.TotalScore ?? 0), oldScore?.PerformancePoints ?? 0, newScore?.PerformancePoints ?? 0, newScore?.Id ?? 0 ); var overallChart = new Chart( "overall", "Global Ranking", $"https://osu.ppy.sh/u/{dbUser.Id}", (int) oldStdPos, (int) newStdPos, 0, 0, oldAcc * 100, newAcc * 100, oldRankedScore, newRankedScore, oldPp, newPp, newScore?.Id ?? 0, AchievementProcessor.ProcessAchievements( _ctx, dbScore.ScoreOwner, score, bm, set, oldLb, newlb ) ); pr["LB"] = newlb; pr.Stats.Accuracy = (float) newlb.GetAccuracy(_ctx, score.PlayMode); pr.Stats.Position = newlb.GetPosition(_ctx, score.PlayMode); switch (score.PlayMode) { case PlayMode.Osu: pr.Stats.PerformancePoints = (ushort) newlb.PerformancePointsOsu; pr.Stats.TotalScore = (ushort) newlb.TotalScoreOsu; pr.Stats.RankedScore = (ushort) newlb.RankedScoreOsu; pr.Stats.PlayCount = (ushort) newlb.PlayCountOsu; break; case PlayMode.Taiko: pr.Stats.PerformancePoints = (ushort) newlb.PerformancePointsTaiko; pr.Stats.TotalScore = (ushort) newlb.TotalScoreTaiko; pr.Stats.RankedScore = (ushort) newlb.RankedScoreTaiko; pr.Stats.PlayCount = (ushort) newlb.PlayCountTaiko; break; case PlayMode.Ctb: pr.Stats.PerformancePoints = (ushort) newlb.PerformancePointsCtb; pr.Stats.TotalScore = (ushort) newlb.TotalScoreCtb; pr.Stats.RankedScore = (ushort) newlb.RankedScoreCtb; pr.Stats.PlayCount = (ushort) newlb.PlayCountCtb; break; case PlayMode.Mania: pr.Stats.PerformancePoints = (ushort) newlb.PerformancePointsMania; pr.Stats.TotalScore = (ushort) newlb.TotalScoreMania; pr.Stats.RankedScore = (ushort) newlb.RankedScoreMania; pr.Stats.PlayCount = (ushort) newlb.PlayCountMania; break; } // Send to other People await _ev.RunEvent( EventType.BanchoUserStatsRequest, new BanchoUserStatsRequestArgs {UserIds = new List<int> {score.Id}, Pr = pr} ); // Send to self await _ev.RunEvent( EventType.BanchoSendUserStatus, new BanchoSendUserStatusArgs {Status = pr.Status, Pr = pr} ); return Ok( $"beatmapId:{bm.BeatmapID}|beatmapSetId:{bm.ParentSetID}|beatmapPlaycount:0|beatmapPasscount:0|approvedDate:\n\n" + bmChart.ToOsuString() + "\n" + overallChart.ToOsuString() ); }
public void OnTimer() { if (m_pState == EventState.ERROR) { return; } DateTime now = DateTime.Now; int nNow = int.Parse(now.ToString("HHmmss")); switch (m_pState) { case EventState.IDLE: { if (nNow % 10000 < 1000 || nNow % 10000 >= 2000) { return; } // todo check what's needed before event start m_pState = EventState.STARTING; break; } case EventState.STARTING: { foreach (var plr in m_pStatistic.Values) { plr.HitsDealtNow = 0; plr.HitsTakenNow = 0; } ServerKernel.SendMessageToAll("Line Skill PK Tournament has started.", ChatTone.TALK); m_pState = EventState.RUNNING; break; } case EventState.RUNNING: { if (nNow % 10000 >= 1000 && nNow % 10000 < 2000) { if (m_pTableTimeOut.ToNextTime()) { SendTable(); } } else { m_pState = EventState.FINISHING; } break; } case EventState.FINISHING: { ServerKernel.SendMessageToAll("The Line Skill PK Tournament has ended.", ChatTone.TOP_LEFT); foreach (var plr in m_pStatistic.Values.OrderByDescending(x => x.KDA) .ThenByDescending(x => x.HitsDealtNow) .ThenBy(x => x.HitsTakenNow) .Where(x => x.HitsDealtNow > 0)) { uint gold = 0; uint emoney = 0; try { switch (GetRank(plr.Identity)) { case 1: gold = ServerKernel.LineSkillGoldReward[0]; emoney = ServerKernel.LineSkillEmoneyReward[0]; ServerKernel.SendMessageToAll( string.Format("Congratulations! {0} has won the Line Skill PK Tournament.", plr.Name), ChatTone.TALK); break; case 2: gold = ServerKernel.LineSkillGoldReward[1]; emoney = ServerKernel.LineSkillEmoneyReward[1]; ServerKernel.SendMessageToAll( string.Format("{0} has taken the 2nd place in the Line Skill PK Tournament.", plr.Name), ChatTone.TALK); break; case 3: gold = ServerKernel.LineSkillGoldReward[2]; emoney = ServerKernel.LineSkillEmoneyReward[2]; ServerKernel.SendMessageToAll( string.Format("{0} has taken the 3rd place in the Line Skill PK Tournament.", plr.Name), ChatTone.TALK); break; default: gold = ServerKernel.LineSkillGoldReward[3]; emoney = ServerKernel.LineSkillEmoneyReward[3]; break; } } catch { ServerKernel.Log.SaveLog("ERROR MESSAGE GET PRIZE LINE SKILL", true, LogType.ERROR); } Client player; if (ServerKernel.Players.TryGetValue(plr.Identity, out player)) { if (player.Character == null) { continue; //? } player.Character.AwardMoney(gold); player.Character.AwardEmoney(emoney); player.Character.Send(string.Format("You received {0} silvers and {1} CPs for playing on the Line Skill PK Tournament.", gold, emoney)); } else { DbUser user = Database.Characters.SearchByIdentity(plr.Identity); if (user == null) { continue; } if (user.Money + gold > int.MaxValue) { user.Money = int.MaxValue; } else { user.Money += gold; } if (user.Emoney + emoney > int.MaxValue) { user.Emoney = int.MaxValue; } else { user.Emoney += emoney; } Database.Characters.SaveOrUpdate(user); } } m_pState = EventState.ENDED; break; } case EventState.ENDED: { foreach (var plr in m_pMap.Players.Values) { plr.ChangeMap(plr.RecordMapX, plr.RecordMapY, plr.RecordMapIdentity); } ServerKernel.SendMessageToAll("Line Skill PK Tournament has ended.", ChatTone.TOP_LEFT); m_pState = EventState.IDLE; break; } } }
private void FillAmCollection() { DbUser findUser = new DbUser(); findUser.Username = username; findUser.TypeId = 1; try { users = client.FindUser(findUser); if (users.Count > 0) { for (int i = 0; i < users.Count; i++) { if (users[i].Username == username) { //i++; } else { DbUser user = users[i]; _AMCollection.Add(new DbUser { FirstName = user.FirstName, LastName = user.LastName, Username = user.Username, Location = user.Location }); } } } } catch (Exception) { } }