public async Task Put(NoteAccess item) { IdentityUser me = await _userManager.FindByNameAsync(User.Identity.Name); NoteAccess myAccess = await AccessManager.GetAccess(_db, me.Id, item.NoteFileId, item.ArchiveId); if (!myAccess.EditAccess) { return; } NoteAccess work = await _db.NoteAccess.Where(p => p.NoteFileId == item.NoteFileId && p.ArchiveId == item.ArchiveId && p.UserID == item.UserID) .FirstOrDefaultAsync(); if (work == null) { return; } work.ReadAccess = item.ReadAccess; work.Respond = item.Respond; work.Write = item.Write; work.DeleteEdit = item.DeleteEdit; work.SetTag = item.SetTag; work.ViewAccess = item.ViewAccess; work.EditAccess = item.EditAccess; _db.Update(work); await _db.SaveChangesAsync(); }
public async Task <IActionResult> Create([Bind("Id,HomeFileId,HomeFileName,RemoteFileName,RemoteBaseUri,AcceptFrom,SendTo")] LinkedFile linkedFile) { if (ModelState.IsValid) { if (!linkedFile.RemoteBaseUri.EndsWith('/')) { linkedFile.RemoteBaseUri = linkedFile.RemoteBaseUri.TrimEnd(' ') + "/"; } LinkProcessor lp = new LinkProcessor(_context); if (await lp.Test(linkedFile.RemoteBaseUri)) { _context.Add(linkedFile); await _context.SaveChangesAsync(); return(RedirectToAction(nameof(Index))); } else { return(RedirectToAction(nameof(Error))); } } return(View(linkedFile)); }
public async Task <IActionResult> Create( [HttpTrigger(AuthorizationLevel.Anonymous, nameof(HttpMethods.Post), Route = "notes")] Note note, HttpRequest req, ILogger log) { var user = await accessTokenValidator.Validate(req); if (!user.Identity.IsAuthenticated) { return(new UnauthorizedResult()); } var validation = validator.Validate(note); if (!validation.IsValid) { return(new BadRequestObjectResult( new FluentValidationProblemDetails(validation.Errors))); } note.UserId = user.GetSubjectId(); dbContext.Notes.Add(note); await dbContext.SaveChangesAsync(); log.NoteAdded(note.Id); return(new CreatedResult($"{req.Scheme}://{req.Host}/api/notes/{note.Id}", note)); }
public async Task <Note> Create(Note note) { note.CreatedAt = GetEpochTime(); await _dbContext.Notes.AddAsync(note); await _dbContext.SaveChangesAsync(); return(note); }
public async Task <IActionResult> Create(HomePageMessage homePageMessage) { if (ModelState.IsValid) { homePageMessage.Posted = DateTime.Now.ToUniversalTime(); _context.HomePageMessage.Add(homePageMessage); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } return(View(homePageMessage)); }
public async Task Delete() { List <HomePageMessage> mine = _db.HomePageMessage.ToList(); if (mine == null || mine.Count == 0) { return; } _db.HomePageMessage.RemoveRange(mine); await _db.SaveChangesAsync(); }
public async Task Post(SCheckModel model) { IdentityUser me = await _userManager.FindByNameAsync(User.Identity.Name); Subscription sub = new Subscription { NoteFileId = model.fileId, SubscriberId = me.Id, }; _db.Subscription.Add(sub); await _db.SaveChangesAsync(); }
/// <summary> /// Implementation of CreateNote handler to create a new note /// </summary> /// <returns></returns> public async Task <IActionResult> OnPostCreateNoteAsync() { if (!ModelState.IsValid) { return(Page()); } dbContext.Add(Note); await dbContext.SaveChangesAsync(); return(RedirectToPage("/Notes")); }
public async Task CreateAnnounce() { await CreateNoteFile("announce", "Notes 2021 Announcements"); NoteFile nf4 = await NoteDataManager.GetFileByName(_db, "announce"); int padid = nf4.Id; NoteAccess access = await AccessManager.GetOneAccess(_db, Globals.AccessOtherId(), padid, 0); access.ReadAccess = true; _db.Entry(access).State = EntityState.Modified; await _db.SaveChangesAsync(); }
public async Task <ActionOutput <Notes> > CreateNote(Notes note) { note.CreatedOn = DateTime.Now; note.UpdatedOn = DateTime.Now; await context.StickyNotes.AddAsync(note); await context.SaveChangesAsync(); return(new ActionOutput <Notes>() { Message = "Sticky Note has been created successfully", Status = ActionStatus.Successfull, Object = note }); }
public async Task <IActionResult> OnPostAsync(string returnUrl = null) { returnUrl = returnUrl ?? Url.Content("~/"); ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList(); if (ModelState.IsValid) { var user = new IdentityUser { UserName = Input.Email, Email = Input.Email }; var result = await _userManager.CreateAsync(user, Input.Password); if (result.Succeeded) { _logger.LogInformation("User created a new account with password."); IdentityUser me = await _userManager.FindByNameAsync(Input.Email); string uId = await _userManager.GetUserIdAsync(me); UserData aux = new UserData(); aux.UserId = uId; aux.DisplayName = Input.DisplayName; aux.TimeZoneID = Globals.TimeZoneDefaultID; aux.Ipref2 = 12; _db.UserData.Add(aux); await _db.SaveChangesAsync(); var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code)); var callbackUrl = Url.Page( "/Account/ConfirmEmail", pageHandler: null, values: new { area = "Identity", userId = user.Id, code = code }, protocol: Request.Scheme); await _emailSender.SendEmailAsync(Input.Email, "Confirm your email", $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>."); if (_userManager.Options.SignIn.RequireConfirmedAccount) { return(RedirectToPage("RegisterConfirmation", new { email = Input.Email })); } else { await _signInManager.SignInAsync(user, isPersistent : false); return(LocalRedirect(returnUrl)); } } foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } // If we got this far, something failed, redisplay form return(Page()); }
public async Task AddOrUpdateRefreshToken(string userId, string token) { await RemoveRefreshToken(userId); var newRefreshToken = new RefreshToken { UserId = userId, Token = token, IssuedUtc = DateTime.Now.ToUniversalTime(), ExpiresUtc = DateTime.Now.AddMinutes(Convert.ToDouble(_configuration["JwtExpireMinutes"])) }; await _dbContext.RefreshTokens.AddAsync(newRefreshToken); await _dbContext.SaveChangesAsync(); }
public async Task Post(SCheckModel model) { IdentityUser me = await _userManager.FindByNameAsync(User.Identity.Name); Sequencer tracker = new Sequencer { Active = true, NoteFileId = model.fileId, LastTime = DateTime.Now.ToUniversalTime(), UserId = me.Id, Ordinal = 0, StartTime = DateTime.Now.ToUniversalTime() }; _db.Sequencer.Add(tracker); await _db.SaveChangesAsync(); }
public async Task OnActionExecutionAsync(ActionExecutingContext context, ActionExecutionDelegate next) { var result = await next(); if (result.Exception == null || result.ExceptionHandled) { await _context.SaveChangesAsync(); } }
public async Task <IActionResult> Create(Subscription subscription) { if (ModelState.IsValid) { _context.Subscription.Add(subscription); await _context.SaveChangesAsync(); return(RedirectToAction("Index")); } ViewBag.Db = _context; ViewBag.UserID = _userManager.GetUserId(User); IEnumerable <SelectListItem> files = LocalManager.GetFileNameSelectListWithId(_context); ViewBag.FilesList = files; return(View(subscription)); }
public async Task <IHttpActionResult> PutPersonalNote(int id, NoteDto noteDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != noteDto.Id) { return(BadRequest()); } var personalNote = await db.PersonalNotes.FindAsync(id); if (personalNote == null) { return(NotFound()); } personalNote.Name = noteDto.Name; personalNote.Description = noteDto.Description; personalNote.IsDone = noteDto.IsDone; personalNote.ReminderDate = noteDto.ReminderDate; personalNote.UpdatedOn = DateTime.UtcNow; try { await db.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!PersonalNoteExists(id)) { return(NotFound()); } else { throw; } } return(StatusCode(HttpStatusCode.NoContent)); }
public async Task Put(NoteFile edited) { NoteFile live = await _db.NoteFile.FindAsync(edited.Id); live.LastEdited = DateTime.Now.ToUniversalTime(); live.NoteFileName = edited.NoteFileName; live.NoteFileTitle = edited.NoteFileTitle; live.OwnerId = edited.OwnerId; _db.Update(live); await _db.SaveChangesAsync(); }
public async Task <IActionResult> CreateNoteAsync([FromBody] Note note) { if (note == null) { return(BadRequest("Note object is null")); } note.Id = Guid.NewGuid(); note.Created = note.LastModified = DateTime.UtcNow; note.UserId = GetUserId(); using (dbContext) { await dbContext.Notes.AddAsync(note); await dbContext.SaveChangesAsync(); } string url = $"{Request.Scheme}://{Request.Host}{Request.PathBase}/api/notes/{note.Id}"; return(Created(url, note)); }
public async Task Post(Mark mrk) { UserData me = NoteDataManager.GetUserData(_userManager, User, _db); mrk.UserId = me.UserId; Mark lastMark = await _db.Mark.Where(p => p.UserId == me.UserId) .OrderByDescending(p => p.MarkOrdinal) .FirstOrDefaultAsync(); if (lastMark == null || lastMark.MarkOrdinal == 0) { mrk.MarkOrdinal = 1; } else { mrk.MarkOrdinal = lastMark.MarkOrdinal + 1; } _db.Mark.Add(mrk); await _db.SaveChangesAsync(); }
public async Task <string> CreateLinkNote(LinkCreateModel inputModel) { NoteFile file = await _context.NoteFile .SingleAsync(p => p.NoteFileName == inputModel.linkedfile); if (file == null) { return("Target file does not exist"); } // check for acceptance if (!await AccessManager.TestLinkAccess(_context, file, "")) { return("Access Denied"); } inputModel.header.NoteFileId = file.Id; inputModel.header.ArchiveId = 0; inputModel.header.BaseNoteId = 0; inputModel.header.Id = 0; inputModel.header.NoteContent = null; inputModel.header.NoteFile = null; inputModel.header.NoteOrdinal = 0; inputModel.header.ResponseOrdinal = 0; inputModel.header.ResponseCount = 0; var tags = Tags.ListToString(inputModel.tags); NoteHeader nh = await NoteDataManager.CreateNote(_context, null, inputModel.header, inputModel.content.NoteBody, tags, inputModel.content.DirectorMessage, true, true); if (nh == null) { return("Remote note create failed"); } LinkLog ll = new LinkLog() { Event = "Ok", EventTime = DateTime.UtcNow, EventType = "RcvdCreateBaseNote" }; _context.LinkLog.Add(ll); await _context.SaveChangesAsync(); return("Ok"); }
public async Task <IActionResult> EditContent(NoteContent nc) { NoteContent edited = await _context.NoteContent.SingleAsync(p => p.NoteHeaderId == nc.NoteHeaderId); edited.NoteBody = nc.NoteBody; edited.DirectorMessage = nc.DirectorMessage; await AccessManager.Audit(_context, "EditContent", User.Identity.Name, User.Identity.Name, "Edit Content NoteID " + edited.NoteHeaderId); _context.Entry(edited).State = EntityState.Modified; await _context.SaveChangesAsync(); return(RedirectToAction("Index", new { id = await NoteDataManager.GetNoteById(_context, nc.NoteHeaderId) })); }
public async Task <Response <Note> > Create(Note note) { try { var createdNote = await _context.Notes.AddAsync(note); await _context.SaveChangesAsync(); return(ResponseFactory.Success(createdNote.Entity)); } catch (Exception exception) { _logger.LogError("Failed to create note", exception); return(ResponseFactory.Fail <Note>("Failed to create note")); } }
private async Task ProcessLinkedNotes() { List <LinkQueue> items = await _db.LinkQueue.Where(p => p.Enqueued == false).ToListAsync(); foreach (LinkQueue item in items) { LinkProcessor lp = new LinkProcessor(_db); BackgroundJob.Enqueue(() => lp.ProcessLinkAction(item.Id)); item.Enqueued = true; _db.Update(item); } if (items.Count > 0) { await _db.SaveChangesAsync(); } }
public async Task <Response <bool> > Delete(int noteId) { try { var noteToRemove = await _context.Notes.FindAsync(noteId); _context.Notes.Remove(noteToRemove); await _context.SaveChangesAsync(); return(ResponseFactory.Success(true)); } catch (Exception exception) { _logger.LogError($"Failed to delete note with id: {noteId}", exception); return(ResponseFactory.Fail <bool>($"Failed to delete note with id: {noteId}")); } }
public async Task <IActionResult> Post([FromBody] RegisterModel model) { var newUser = new IdentityUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(newUser, model.Password); if (!result.Succeeded) { var errors = result.Errors.Select(x => x.Description); return(Ok(new RegisterResult { Successful = false, Errors = errors })); } IdentityUser me = await _userManager.FindByEmailAsync(model.Email); UserData userData = new UserData { UserId = me.Id, DisplayName = model.DisplayName, TimeZoneID = Globals.TimeZoneDefaultID, Ipref2 = 12, Pref3 = true, MyGuid = Guid.NewGuid().ToString() }; _db.UserData.Add(userData); // Add all new users to the User role await _userManager.AddToRoleAsync(newUser, "User"); if (newUser.Email == Globals.PrimeAdminEmail) { await _userManager.AddToRoleAsync(newUser, "Admin"); } await _db.SaveChangesAsync(); return(Ok(new RegisterResult { Successful = true })); }
public async Task <Response <Note> > Update(int noteId, Note note) { try { var noteToUpdate = await _context.Notes.FindAsync(noteId); noteToUpdate.Text = note.Text; _context.Notes.Update(noteToUpdate); await _context.SaveChangesAsync(); return(ResponseFactory.Success(noteToUpdate)); } catch (Exception exception) { _logger.LogError($"Failed to update note with id: {noteId}", exception); return(ResponseFactory.Fail <Note>($"Failed to update note with id: {noteId}")); } }
public async Task <IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return(Page()); } dbContext.Attach(Note).State = EntityState.Modified; try { await dbContext.SaveChangesAsync(); } catch (DbUpdateConcurrencyException ex) { throw new Exception($"Note: '{Note.Id}' could not be edited", ex); } return(RedirectToPage("/Notes")); }
public async Task <IActionResult> CreateNote([FromBody] NoteRequestBody body, CancellationToken token) { if (body.Validate()) { EntityEntry <Note> createdNote = await _dbContext.Notes.AddAsync(new Note { Title = body.Title, Description = body.Description, Modification = DateTime.Now }, token); await _dbContext.SaveChangesAsync(token); return(Ok(createdNote.Entity)); } else { return(BadRequest(Error.Create(400, "Body was not valid"))); } }
public async Task Put(NoteAccess item) { NoteAccess work = await _db.NoteAccess.Where(p => p.NoteFileId == item.NoteFileId && p.ArchiveId == item.ArchiveId && p.UserID == item.UserID) .FirstOrDefaultAsync(); if (work == null) { return; } work.ReadAccess = item.ReadAccess; work.Respond = item.Respond; work.Write = item.Write; work.DeleteEdit = item.DeleteEdit; work.SetTag = item.SetTag; work.ViewAccess = item.ViewAccess; work.EditAccess = item.EditAccess; _db.Update(work); await _db.SaveChangesAsync(); }
public async Task<string> ProcessLinkAction(long linkId) { LinkQueue q; try { q = db.LinkQueue.SingleOrDefault(p => p.Id == linkId); } catch (Exception ex) { return ex.Message; } if (q == null) { return "Job not in Queue"; } NoteFile notefile = db.NoteFile.SingleOrDefault(p => p.Id == q.LinkedFileId); string notefilename = notefile.NoteFileName; HttpClient MyClient = new HttpClient { BaseAddress = new Uri(q.BaseUri) }; switch (q.Activity) { case LinkAction.CreateBase: // create base note LinkCreateModel inputModel = new LinkCreateModel(); inputModel.linkedfile = notefilename; inputModel.Secret = q.Secret; inputModel.header = (db.NoteHeader.SingleOrDefault(p => p.LinkGuid == q.LinkGuid)).CloneForLink(); inputModel.content = (db.NoteContent.SingleOrDefault(p => p.NoteHeaderId == inputModel.header.Id)).CloneForLink(); try { inputModel.tags = Tags.CloneForLink(await db.Tags.Where(p => p.NoteFileId == notefile.Id && p.NoteHeaderId == inputModel.header.Id) .ToListAsync()); } catch { inputModel.tags = null; } inputModel.header.Id = 0; HttpResponseMessage resp; try { resp = MyClient.PostAsync("api/ApiLink", new ObjectContent(typeof(LinkCreateModel), inputModel, new JsonMediaTypeFormatter())) .GetAwaiter().GetResult(); } catch (Exception ex) { return ex.Message; } string result = await resp.Content.ReadAsStringAsync(); LinkLog ll = new LinkLog() { EventType = "SendCreateNote", EventTime = DateTime.UtcNow, Event = result }; db.LinkLog.Add(ll); if (result == "Ok") db.LinkQueue.Remove(q); await db.SaveChangesAsync(); return result; case LinkAction.CreateResponse: // create response note LinkCreateRModel inputModel2 = new LinkCreateRModel(); inputModel2.linkedfile = notefilename; inputModel2.Secret = q.Secret; inputModel2.header = (await db.NoteHeader.SingleAsync(p => p.LinkGuid == q.LinkGuid)).CloneForLinkR(); inputModel2.content = (await db.NoteContent.SingleAsync(p => p.NoteHeaderId == inputModel2.header.Id)).CloneForLink(); try { inputModel2.tags = Tags.CloneForLink(await db.Tags.Where(p => p.NoteFileId == notefile.Id && p.NoteHeaderId == inputModel2.header.Id) .ToListAsync()); } catch { inputModel2.tags = null; } NoteHeader basehead = await NoteDataManager.GetBaseNoteHeader(db, inputModel2.header.Id); inputModel2.baseGuid = basehead.LinkGuid; inputModel2.header.Id = 0; HttpResponseMessage resp2; try { resp2 = MyClient.PostAsync("api/ApiLinkR", new ObjectContent(typeof(LinkCreateRModel), inputModel2, new JsonMediaTypeFormatter())) .GetAwaiter().GetResult(); } catch (Exception ex) { return ex.Message; } string result2 = resp2.Content.ReadAsStringAsync().GetAwaiter().GetResult(); LinkLog ll2 = new LinkLog() { EventType = "SendRespNote", EventTime = DateTime.UtcNow, Event = result2 }; db.LinkLog.Add(ll2); if (result2 == "Ok") db.LinkQueue.Remove(q); await db.SaveChangesAsync(); return result2; case LinkAction.Edit: LinkCreateEModel model = new LinkCreateEModel() { tags = string.Empty, linkedfile = notefilename, myGuid = q.LinkGuid, Secret = q.Secret }; model.header = (await db.NoteHeader.SingleAsync(p => p.LinkGuid == q.LinkGuid)).CloneForLinkR(); model.content = (await db.NoteContent.SingleAsync(p => p.NoteHeaderId == model.header.Id)).CloneForLink(); List<Tags> myTags; try { myTags = await db.Tags.Where(p => p.NoteFileId == notefile.Id && p.NoteHeaderId == model.header.Id).ToListAsync(); if (myTags == null || myTags.Count < 1) { model.tags = string.Empty; } else { foreach (var tag in myTags) { model.tags += tag.Tag + " "; } model.tags.TrimEnd(' '); } } catch { model.tags = string.Empty; } model.header.Id = 0; HttpResponseMessage resp3; try { resp3 = MyClient.PutAsync("api/ApiLink", new ObjectContent(typeof(LinkCreateEModel), model, new JsonMediaTypeFormatter())) .GetAwaiter().GetResult(); } catch (Exception ex) { return ex.Message; } string result3 = resp3.Content.ReadAsStringAsync().GetAwaiter().GetResult(); LinkLog ll3 = new LinkLog() { EventType = "EditNote", EventTime = DateTime.UtcNow, Event = result3 }; db.LinkLog.Add(ll3); if (result3 == "Ok") db.LinkQueue.Remove(q); await db.SaveChangesAsync(); return result3; default: return "Bad Link Activity Request"; } }