public async Task <IActionResult> AddItem(IFormCollection request) { try { if (string.IsNullOrEmpty(request.Str("navitem"))) { return(BadRequest(new ResponseHelper("Something went wrong, please try again later", "No nav-item data was sent"))); } NavItem newItem = JsonConvert.DeserializeObject <NavItem>(request.Str("navitem")); // Give an order index that places this at the end of the list, for its section newItem.OrderIndex = await _Db.NavItems.Where(n => n.Section == newItem.Section).DefaultIfEmpty().MaxAsync(m => m.OrderIndex) + 1; await _Db.AddAsync(newItem); // Add new dropdowns, if any if (newItem.NavItemPages != null) { await _Db.AddRangeAsync(newItem.NavItemPages); } await _Db.SaveChangesAsync(); return(Ok(newItem.Id)); } catch (Exception ex) { _Logger.LogError("Error creating new navlink", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later.", ex.Message))); } }
public async Task <IActionResult> Create(IFormCollection request) { try { Enum.TryParse(request.Str("noticeboard"), out Noticeboard noticeboard); Notice n = new Notice { Title = request.Str("title"), Noticeboard = noticeboard, LongDesc = request.Str("long_desc"), Urgent = request.Bool("urgent") ? 1 : 0, Active = request.Bool("active"), }; await _Database.AddAsync(n); await _Database.SaveChangesAsync(); return(Ok($"Notice \"{n.Title}\" has been issued.")); } catch (Exception ex) { _Logger.LogError("Error saving notice: {0}", ex.Message); _Logger.LogTrace(ex.StackTrace); return(BadRequest(new ResponseHelper("Error issuing the notice, try again later.", ex.Message))); } }
public async Task <IActionResult> Index(IFormCollection request) { Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync(); if (account != null) { _Logger.LogDebug("Unable to create account using {0} as an account already exists for this email address", request.Str("email")); return(BadRequest(new ResponseHelper("An account with that email address already exists"))); } try { account = new Account { Email = request.Str("email"), Name = request.Str("name"), Active = false, }; account.Password = _Hasher.HashPassword(account, RandomString(30)); await _Db.AddAsync(account); PasswordReset reset = new PasswordReset( account, DateTime.UtcNow.AddHours(_Config["LoginSettings:NewAccountResetTokenLength"].ToInt()) ); await _Db.AddAsync(reset); await _Db.SaveChangesAsync(); _Logger.LogInformation("New account created - Name: {0}, Email: {1}", account.Name, account.Email); await _EmailService.SendNewAccountEmailAsync(reset, User, Request.BaseUrl()); return(Ok(Url.Action("Index", "Users", new { area = "admin" }))); } catch (Exception ex) { _Logger.LogError("Error while creating new account: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message))); } }
public async Task <IActionResult> AddTrack(string name) { if (string.IsNullOrEmpty(name)) { return(BadRequest(new ResponseHelper("You must provide a track name."))); } Track track = new Track { Name = name, Active = false }; await _Db.AddAsync(track); await _Db.SaveChangesAsync(); return(Ok(track.Id)); }
public async Task <IActionResult> AddQuiz(QuizArgs data) { if (!ModelState.IsValid) { return(new BadRequestObjectResult(ModelState)); } Quiz newQuiz = new Quiz { Title = data.Title, ImageId = (int)data.ImageId, Shuffle = (bool)data.Shuffle, UnlockCode = data.UnlockCode }; await _Db.AddAsync(newQuiz); await _Db.SaveChangesAsync(); return(Ok(newQuiz.Id)); }
public async Task <IActionResult> Index(IFormCollection request) { try { Account account = await _Db.Accounts.Where(c => c.Email == request.Str("email")).FirstOrDefaultAsync(); if (account != null) { List <PasswordReset> oldTokens = await _Db.PasswordResets.Where(c => c.Account.Id == account.Id).ToListAsync() ?? new List <PasswordReset>(); foreach (PasswordReset resetToken in oldTokens) { resetToken.ExpiresAt = DateTime.UtcNow; } PasswordReset reset = new PasswordReset( account, DateTime.UtcNow.AddMinutes(_Config["LoginSettings:PasswordResetTokenLength"].ToInt()) ); await _Db.AddAsync(reset); await _Db.SaveChangesAsync(); await _EmailService.SendPasswordResetEmailAsync(reset, this.Request.BaseUrl()); _Logger.LogInformation("Password reset requested for account belonging to {0}", account.Name); } return(Ok()); } catch (Exception ex) { _Logger.LogError("Error requesting password reset for account belonging to {0}: {1}", request.Str("email"), ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again later", ex.Message))); } }
//POST: /admin/pages/create public async Task <IActionResult> Create(IFormCollection request, [Bind("Name", "Description", "Section")] Page page) { PageTemplate template = await _Db.PageTemplates.FindAsync( request.Int("templateId")); if (template == null) { return(NotFound($"The chosen template was not found.")); } if (!ModelState.IsValid) { return(BadRequest("Server side validation failed.")); } try { await _Db.AddAsync(page); // Create initial page revision PageRevision pageRevision = new PageRevision { Page = page, Template = template, CreatedBy = await _Db.Accounts.FindAsync(User.AccountId()) }; await _Db.AddAsync(pageRevision); // Create empty text fields, and associate to new page for (int i = 0; i < template.TextAreas; i++) { TextComponent textField = new TextComponent { SlotNo = i }; await _Db.AddAsync(textField); await _Db.AddAsync(new RevisionTextComponent { TextComponent = textField, PageRevision = pageRevision, }); } // Create empty media fields, and associate to new page for (int i = 0; i < template.MediaAreas; i++) { MediaComponent mediaComponent = new MediaComponent { SlotNo = i }; await _Db.AddAsync(mediaComponent); await _Db.AddAsync(new RevisionMediaComponent { PageRevisionId = pageRevision.Id, MediaComponentId = mediaComponent.Id }); } // Save all to database in one transaction await _Db.SaveChangesAsync(); // Return new page URL to the caller return(Ok(page.AbsoluteUrl)); } catch (Exception ex) { _Logger.LogWarning("Error creating new page: {0}", ex.Message); _Logger.LogWarning(ex.StackTrace); return(BadRequest("There was an error creating the page. Please try again later.")); } }
public async Task <IActionResult> Index(IFormCollection request) { try { // Create required directories if not existing EnsureInit(); // Deserialize cropping data if applicable CropData cropData = null; if (request.Str("cropData") != null) { cropData = JsonConvert.DeserializeObject <CropData>(request.Str("cropData")); } // Original filename string uploadedName = request.Str("filename"); // Generate a backend filename for the uploaded file - same extension as uploaded file. string filename = Guid.NewGuid().ToString() + Path.GetExtension(uploadedName); string fileType = request.Str("fileType"); // Determine what type of file has been uploaded and act accordingly (may want to refactor these) // FOR IMAGES if (MediaType.MimesForCategory(MediaCategory.Image).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Images", filename); // Save image and all associated versions of it. var filedata = ImageUtils.SaveImage(request.Str("file") .Split(',')[1], filepath, cropData); // Create database record to track images ImageMedia dbImageMedia = new ImageMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = filedata["size"], Title = request.Str("title"), Alt = request.Str("alt"), Width = filedata["width"], Height = filedata["height"], Versions = filedata["versions"] }; await _Db.AddAsync(dbImageMedia); } // FOR AUDIO else if (MediaType.MimesForCategory(MediaCategory.Audio).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Audio", filename); // Save the audio file byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes(); await System.IO.File.WriteAllBytesAsync(filepath, bytes); // Read the audio file to determine its duration - it will either be mp3(mpeg) or wav // Configure ffprobe path using appsettings values FFProbe probe = new FFProbe(); probe.ToolPath = _Config["ffprobePath"]; // If running linux, look for ffprobe instaed of ffprobe.exe if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { probe.FFProbeExeName = "ffprobe"; } // Get audio file metadata MediaInfo mediaInfo = probe.GetMediaInfo(Path.Combine(_HostingEnv.ContentRootPath, filepath)); // Create the media database record AudioMedia audioMedia = new AudioMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = new FileInfo(filepath).Length, Duration = Math.Round(mediaInfo.Duration.TotalSeconds) }; await _Db.AddAsync(audioMedia); } // FOR GENERAL else if (MediaType.MimesForCategory(MediaCategory.General).Contains(fileType)) { string filepath = Path.Combine("Storage", "Media", "Documents", filename); // Save the file byte[] bytes = request.Str("file").Split(',')[1].DecodeBase64Bytes(); System.IO.File.WriteAllBytes(filepath, bytes); // Create the media database record GeneralMedia generalMedia = new GeneralMedia { Name = Path.GetFileNameWithoutExtension(uploadedName), MediaType = MediaType.FromString(fileType), FilePath = filepath, Size = new FileInfo(filepath).Length, }; await _Db.AddAsync(generalMedia); } else { return(new UnsupportedMediaTypeResult()); } await _Db.SaveChangesAsync(); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error uploading file: {0}", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please contact the devloper if the problem persists", ex.Message))); } }
public async Task <IActionResult> CreateRevision(int pageId, IFormCollection request) { /* To be supplied in request body - * * Reason for change - e.g. Updated pricing information * Template ID * Collection of text components * Collection of media components * */ try { // Load page from database Page page = await _Db.Pages.FindAsync(pageId); if (page == null) { return(BadRequest("No page exists for given page ID")); } List <TextComponent> newRevisionTextComponents = request.Deserialize(typeof(List <TextComponent>), "textComponents"); List <MediaComponent> newRevisionMediaComponents = request.Deserialize(typeof(List <MediaComponent>), "imageComponents"); // Todo: Do this after the view has had template switching enabled // Load template from database // PageTemplate template = await _Db.PageTemplates // .FindAsync(request.Int("templateId")); // Fetch the original revision PageRevision old = await _Db.PageRevisions .Include(pr => pr.Template) .Include(pr => pr.RevisionMediaComponents) .ThenInclude(rmc => rmc.MediaComponent) .Include(pr => pr.RevisionTextComponents) .ThenInclude(rtc => rtc.TextComponent) .ThenInclude(tc => tc.CmsButton) .Where(pr => pr.Page == page) .OrderByDescending(pr => pr.CreatedAt) .FirstOrDefaultAsync(); var oldRevision = new { old.Template, TextComponents = old.RevisionTextComponents .Select(rtc => rtc.TextComponent) .OrderBy(tc => tc.SlotNo) .ToList(), MediaComponents = old.RevisionMediaComponents .Select(rmc => rmc.MediaComponent) .OrderBy(tc => tc.SlotNo) .ToList() }; // Create the new page revision PageRevision newRevision = new PageRevision { Page = page, Template = oldRevision.Template, Reason = request.Str("reason"), CreatedBy = await _Db.Accounts.FindAsync(User.AccountId()), }; // Assign the new revision an ID await _Db.AddAsync(newRevision); for (int i = 0; i < newRevision.Template.TextAreas; i++) { TextComponent textComponentToSave = null; // Only save a new text component if it has changed if (!newRevisionTextComponents[i].Equals(oldRevision.TextComponents[i])) { textComponentToSave = newRevisionTextComponents[i]; // Set ID to 0 so that EF Core assigns us a new one textComponentToSave.Id = 0; // Save a new button if the components button does not yet exist in database. if (textComponentToSave.CmsButton != null && !textComponentToSave.CmsButton.Equals(oldRevision.TextComponents[i].CmsButton)) { await _Db.AddAsync(textComponentToSave.CmsButton); } // Generate ID for the new TextComponent await _Db.AddAsync(textComponentToSave); } // Add association between component and new revision await _Db.AddAsync(new RevisionTextComponent { // Use the new components ID if it exists, other use existing (unchanged) component // from previous revision TextComponentId = textComponentToSave?.Id ?? oldRevision.TextComponents[i].Id, PageRevisionId = newRevision.Id }); } // Do the same for media components for (int i = 0; i < newRevision.Template.MediaAreas; i++) { MediaComponent mediaComponentToSave = null; // Only create new media component if the old one was modified if (!newRevisionMediaComponents[i].Equals(oldRevision.MediaComponents[i])) { mediaComponentToSave = newRevisionMediaComponents[i]; // Generate new ID mediaComponentToSave.Id = 0; await _Db.AddAsync(mediaComponentToSave); } // Add association to new revision await _Db.AddAsync(new RevisionMediaComponent { PageRevisionId = newRevision.Id, MediaComponentId = mediaComponentToSave?.Id ?? oldRevision.MediaComponents[i].Id }); } // Save changes await _Db.SaveChangesAsync(); _Logger.LogDebug("New page revision created for page {0} ({1}): {2}", pageId, page.Name, newRevision.Reason); return(Ok()); } catch (Exception ex) { _Logger.LogError("Error creating new revision for page {0}: {1}", pageId, ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest("Something went wrong, please try again later.")); } }
public async Task <IActionResult> AddEntry(int categoryId, IFormCollection form) { try { FactFileEntry entryToSave = new FactFileEntry(); // Validate inputs first // // // entryToSave.Active = form.Bool("active"); entryToSave.CategoryId = categoryId; // Update text fields entryToSave.PrimaryName = form.Str("primaryName"); entryToSave.AltName = form.Str("altName"); entryToSave.BodyText = form.Str("bodyText"); // Update media fields entryToSave.ListenAudioId = form.Int("listenAudioId"); entryToSave.PronounceAudioId = form.Int("pronounceAudioId"); if (entryToSave.ListenAudioId == 0) { entryToSave.ListenAudioId = null; } if (entryToSave.PronounceAudioId == 0) { entryToSave.PronounceAudioId = null; } entryToSave.MainImageId = form.Int("mainImageId"); await _Db.AddAsync(entryToSave); await _Db.SaveChangesAsync(); // to generate id // Remove and rebuild fact file entry image records int[] imageArray = JsonConvert.DeserializeObject <int[]>(form.Str("images")); entryToSave.FactFileEntryImages = new List <FactFileEntryImage>(); foreach (int imageId in imageArray) { entryToSave.FactFileEntryImages.Add(new FactFileEntryImage { FactFileEntryId = entryToSave.Id, MediaFileId = imageId }); } // Remove and rebuild fact file nugget records FactFileNugget[] updatedNuggets = JsonConvert.DeserializeObject <FactFileNugget[]>(form.Str("nuggets")); entryToSave.FactFileNuggets = new List <FactFileNugget>(); for (int i = 0; i < updatedNuggets.Length; i++) { updatedNuggets[i].OrderIndex = i; entryToSave.FactFileNuggets.Add(updatedNuggets[i]); } await _Db.SaveChangesAsync(); return(Ok(entryToSave.Id)); } catch (Exception ex) { _Logger.LogError("Error saving new entry", ex.Message); _Logger.LogError(ex.StackTrace); return(BadRequest(new ResponseHelper("Something went wrong, please try again in a few minutes.", ex.Message))); } }