protected void Application_Error(object sender, EventArgs e) { //http://stackoverflow.com/questions/2416182/garbled-error-page-output-using-gzip-in-asp-net-iis7 HttpApplication app = sender as HttpApplication; app.Response.Filter = null; // Get the exception object. Exception exc = Server.GetLastError(); // Handle HTTP errors if (exc.GetType() == typeof(HttpException)) { if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength")) { return; } } AuditLogManager.ReportWebException(Server, AuditEventType.SystemErrorAPI); Server.ClearError(); Response.StatusCode = 500; Response.End(); }
protected void UpdateDefaultButton_Click(object sender, EventArgs e) { foreach (DataGridItem dgi in AssetFilePathsDataGrid.Items) { HiddenField AssetFilePathIdHiddenField = (HiddenField)dgi.FindControl("AssetFilePathIdHiddenField"); RadioButton IsDefaultRadioButton = (RadioButton)dgi.FindControl("IsDefaultRadioButton"); if (IsDefaultRadioButton.Checked) { int assetFilePathId = NumericUtils.ParseInt32(AssetFilePathIdHiddenField.Value, 0); try { AssetFilePathManager.SetDefault(assetFilePathId); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ChangeDefaultFilepath, string.Format("Changed default file path to AssetFilePathId: {0}", assetFilePathId)); MessageLabel1.SetSuccessMessage("Default asset file path updated successfully"); } catch (InvalidAssetFilePathException ifpx) { MessageLabel1.SetErrorMessage("Unable to change default path", ifpx.Errors); } break; } } }
protected void Application_Error(object sender, EventArgs e) { //http://stackoverflow.com/questions/2416182/garbled-error-page-output-using-gzip-in-asp-net-iis7 HttpApplication app = sender as HttpApplication; var filter = app.Response.Filter; app.Response.Filter = null; // Get the exception object. Exception exc = Server.GetLastError(); // Handle HTTP errors if (exc.GetType() == typeof(HttpException)) { if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength")) { return; } } AuditLogManager.ReportWebException(Server, AuditEventType.SystemErrorAPI); Server.ClearError(); Response.StatusCode = 500; HttpContext.Current.Response.Flush(); // Sends all currently buffered output to the client. HttpContext.Current.Response.SuppressContent = true; // Gets or sets a value indicating whether to send HTTP content to the client. HttpContext.Current.ApplicationInstance.CompleteRequest(); // Causes ASP.NET to bypass all events and filtering in the HTTP pipeline chain of execution and directly execute the EndRequest event. }
protected void AssetFilePathsDataGrid_OnItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "add") { try { TextBox NewFilePathTextBox = (TextBox)e.Item.FindControl("NewFilePathTextBox"); string path = NewFilePathTextBox.Text; AssetFilePathManager.CreateNew(path); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.AddFilepath, string.Format("Added file path: {0}", path)); MessageLabel1.SetSuccessMessage("Asset file path added successfully"); BindList(); } catch (InvalidAssetFilePathException iafpex) { ErrorList errors = iafpex.Errors; if (errors.Count == 1) { MessageLabel1.SetErrorMessage(errors[0].ToString()); } else { MessageLabel1.SetErrorMessage("Unable to add new file path", errors); } } } }
protected void SaveButton_Click(object sender, EventArgs e) { AssetTypeFileExtension atfe = SaveATFE(); if (!atfe.IsNull) { AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.ModifyFileExtension, string.Format("File Extension: {0}, ID: {1}", atfe.Extension, atfe.AssetTypeFileExtensionId)); } }
protected override void Grid_DeleteCommand(object source, DataGridCommandEventArgs e) { int id = Convert.ToInt32(e.CommandArgument); IpAddress.Delete(id); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteIpAddress, string.Format("Deleted Ip Address with IpAddressId: {0}", id)); BindGrid(CurrentPage); MessageLabel1.SetSuccessMessage("IP Address deleted successfully"); }
protected void DuplicateButton_Click(object sender, EventArgs e) { AssetTypeFileExtension atfe = SaveATFE(); if (!atfe.IsNull) { string ext = atfe.Extension; AssetTypeFileExtensionManager.Duplicate(atfe); AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DuplicateFileExtension, string.Format("File Extension: {0} (temp ext: {1}), ID: {2}", ext, atfe.Extension, atfe.AssetTypeFileExtensionId)); Response.Redirect("ManageFileExtensionsForm.aspx?Action=Duplicate&AssetTypeFileExtensionId=" + atfe.AssetTypeFileExtensionId); } }
public void RefreshStats() { try { var paramList = new object[] { }; this.dataModel.Database.ExecuteSqlCommand("procUpdateOCMStats", paramList); AuditLogManager.Log(null, AuditEventType.StatisticsUpdated, "Statistics Updated", ""); } catch (Exception) { ;; } }
public ActionResult NewCouncil(CouncilElectionForm form) { ModelFieldsAccessibility fieldsInfo = NewCouncilFieldsInfo; // Ignore stuff that isn't supposed to be in new election fieldsInfo.ReplaceUneditableWithOldValues(form, new CouncilElectionForm()); this.RemoveIgnoredErrors(fieldsInfo); if (ModelState.IsValid) { Election election = Mapper.Map <Election>(form); election.Type = ElectionType.StudentCouncil; CouncilElectionData councilData = Mapper.Map <CouncilElectionData>(form); councilData.Election = election; ElectionStateChange createChangeInfo = new ElectionStateChange { Election = election, PreviousState = null, TargetState = election.State, IsCausedByUser = true, InstigatorUsername = User.Identity.GetUserId(), CompletedAt = DateTime.Now }; db.Elections.Add(election); db.CouncilElectionData.Add(councilData); db.ElectionStateChanges.Add(createChangeInfo); using (DbContextTransaction transaction = db.Database.BeginTransaction()) { db.SaveChanges(); // This needs to be after the first big transaction - otherwise EF gets confused about order of actions election.PopulateAutomaticStateTransitions(); db.SaveChanges(); transaction.Commit(); } AuditLogManager.RecordNewElection(createChangeInfo); return(RedirectToAction("Details", new { id = election.Id })); } ViewData[FormConstants.FieldsInfoKey] = fieldsInfo; return(View(form)); }
public ActionResult NewCourseRep(ElectionForm form) { ModelFieldsAccessibility fieldsInfo = NewDefaultFieldsInfo; // Ignore stuff that isn't supposed to be in new election fieldsInfo.ReplaceUneditableWithOldValues(form, new ElectionForm()); this.RemoveIgnoredErrors(fieldsInfo); if (ModelState.IsValid) { Election election = Mapper.Map <Election>(form); election.Type = ElectionType.CourseRepresentative; election.PositionGenerationInProcess = true; ElectionStateChange createChangeInfo = new ElectionStateChange { Election = election, PreviousState = null, TargetState = election.State, IsCausedByUser = true, InstigatorUsername = User.Identity.GetUserId(), CompletedAt = DateTime.Now }; db.Elections.Add(election); db.ElectionStateChanges.Add(createChangeInfo); using (DbContextTransaction transaction = db.Database.BeginTransaction()) { db.SaveChanges(); // This needs to be after the first big transaction - otherwise EF gets confused about order of actions election.PopulateAutomaticStateTransitions(); db.SaveChanges(); transaction.Commit(); } AuditLogManager.RecordNewElection(createChangeInfo); // Schedule the job to loop over the DB to generate the positions BackgroundJob.Enqueue(() => GeneratePositions.Execute(election.Id, JobCancellationToken.Null)); return(RedirectToAction("Details", new { id = election.Id })); } ViewData[FormConstants.FieldsInfoKey] = fieldsInfo; return(View(form)); }
public ActionResult ExpToExcel(AuditLogViewModel ALVM, string command) { bool result = false; if (command == "toExcel") { AuditLogManager ALM = new AuditLogManager(); result = ALM.ExportToExcel(ALVM); } else if (command == "toPDF") { AuditLogManager ALM = new AuditLogManager(); result = ALM.ExportToPDF(ALVM); } return(RedirectToAction("Index")); }
private void ChangeStateByUserAndRecord(Election election, ElectionState newState) { ElectionStateChange stateChange = new ElectionStateChange() { Election = election, PreviousState = election.State, TargetState = newState, IsCausedByUser = true, InstigatorUsername = User.Identity.GetUserId(), CompletedAt = DateTime.Now }; db.ElectionStateChanges.Add(stateChange); election.State = newState; AuditLogManager.RecordElectionStateChange(stateChange); }
protected override void Grid_DeleteCommand(object source, DataGridCommandEventArgs e) { int id = Convert.ToInt32(e.CommandArgument); try { CompanyManager.DeleteCompany(id); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteCompany, string.Format("Deleted Company with CompanyId: {0}", id)); MessageLabel1.SetSuccessMessage("Company deleted successfully"); BindGrid(CurrentPage); } catch (Exception ex) { MessageLabel1.SetErrorMessage("Error deleting company: " + ex.Message); } }
protected override void Grid_DeleteCommand(object source, DataGridCommandEventArgs e) { try { int assetTypeId = Convert.ToInt32(e.CommandArgument); AssetType assetType = AssetTypeCache.Instance.GetById(assetTypeId); AssetTypeManager.DeleteAssetType(assetTypeId); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteAssetType, string.Format("Deleted Asset Type: {0}, AssetTypeId: {1}", assetType.Name, assetTypeId)); MessageLabel1.SetSuccessMessage("Asset type deleted successfully"); } catch (SystemException sysex) { MessageLabel1.SetErrorMessage(sysex.Message); } BindGrid(CurrentPage); }
protected void DeleteButton_Click(object sender, EventArgs e) { // Get the ID of the extension to be deleted int id = WebUtils.GetIntRequestParam("AssetTypeFileExtensionId", 0); // Get the file extension to be deleted AssetTypeFileExtension atfe = AssetTypeFileExtension.Get(id); // Now actually delete it AssetTypeFileExtensionManager.Delete(atfe); // Update audit log AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DeleteFileExtension, string.Format("File Extension: {0}, ID: {1}", atfe.Extension, atfe.AssetTypeFileExtensionId)); // Update UI FormPanel.Visible = false; SuccessPanel.Visible = true; MessageLabel2.SetSuccessMessage("File extension deleted successfully"); }
protected void SaveChangesButton_Click(object sender, EventArgs e) { // Get the user data from the database // This is to ensure it is up-to-date, rather than just using the current user in // session in case the user has been updated by an admin since the user logged in. User user = Data.User.Get(CurrentUser.UserId); // Initialise user from posted values user.FirstName = UserDetailsForm1.FirstName; user.LastName = UserDetailsForm1.LastName; user.Email = UserDetailsForm1.Email; user.SetConfirmPassword(UserDetailsForm1.ConfirmPassword); user.IsEmployee = UserDetailsForm1.IsStaffUser; user.CompanyName = UserDetailsForm1.CompanyName; user.PrimaryBrandId = UserDetailsForm1.BrandId; user.CountryId = UserDetailsForm1.CountryId; user.PhoneNumber = UserDetailsForm1.PhoneNumber; user.MobileNumber = UserDetailsForm1.MobileNumber; if (!StringUtils.IsBlank(UserDetailsForm1.Password)) { user.SetPassword(UserDetailsForm1.Password); if (user.PasswordChanged) { user.PasswordExpiryDate = DateTime.Now.AddDays(UserManager.PasswordExpiryDays); } } try { UserManager.Update(user); SessionInfo.Current.User = user; AuditLogManager.LogUserAction(user, AuditUserAction.AccountUpdate, "Profile updated successfully."); FeedbackLabel1.SetSuccessMessage("Your profile has been updated"); } catch (InvalidUserException iuex) { FeedbackLabel1.SetErrorMessage("the following errors occured:", iuex.Errors); } }
// GET: AuditLog public ActionResult Index() { // Validate log in and user access UserAccessSession UASession = (UserAccessSession)Session["UserAccess"]; if (UASession == null || !UASession.AUL) { return(RedirectToAction("Login", "Account")); } Session["CurrentPage"] = new CurrentPageSession("AUL", "HOME", "LOG"); AuditLogViewModel ULViewModel = new AuditLogViewModel(); AuditLogManager ALManager = new AuditLogManager(); List <AuditLogViewModel> ALList = ALManager.GetAuditLog(); ViewData["ModelList"] = ALList; return(View()); }
/// <summary> /// Creates new <see cref="AuditLog" /> object and fills it with provided data. /// </summary> /// <param name="description">Audit Log entry description.</param> /// <param name="dateTime">Audit Log entry created date/time.</param> /// <param name="userId">Audit Log entry DNN user ID.</param> /// <returns>Newly created <see cref="AuditLog" /> object or null if object creation failed.</returns> /// <exception cref="ArgumentNullException"><paramref name="description" /> is a null reference.</exception> static public AuditLog AddLog(string description, DateTime dateTime, string keywords, int userId) { // Exceptions if (description == null) { throw new ArgumentNullException("description"); } // Create and fill new AuditLog object AuditLog newAuditLog = (AuditLog)AuditLogManager.CreateObject(); newAuditLog.Description = description; newAuditLog.DateTime = dateTime; newAuditLog.UserId = userId; newAuditLog.Keywords = keywords; // Return newly created object if it was saved in the DB return(newAuditLog.Save() ? newAuditLog : null); }
public override void ProcessRequest() { int assetFileId = GetIdFromFilename(); int assetId = WebUtils.GetIntRequestParam("AssetId", 0); if (assetFileId <= 0) { throw new SystemException("Invalid attached file id: " + assetFileId); } if (assetId <= 0) { throw new SystemException("Invalid asset id: " + assetId); } // Get the asset file AssetFile assetFile = AssetFile.Get(assetFileId); if (assetFile.AssetId != assetId) { throw new SystemException("Asset mismatch"); } if (assetFile.IsNull) { throw new SystemException("Asset file not found"); } if (assetFile.Asset.RestrictAttachedFiles && !EntitySecurityManager.CanUserDownloadAsset(SessionInfo.Current.User, assetFile.Asset)) { throw new SystemException("Access denied"); } // Log the download string notes = string.Format("Downloaded file: {0}", assetFile.Filename); AuditLogManager.LogAssetAction(assetFile.AssetId, SessionInfo.Current.User, AuditAssetAction.DownloadedAttachedFile, notes); AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DownloadAttachedFile, notes); // Send the file SiteUtils.SendAttachedFile(assetFile); }
protected override void Grid_UpdateCommand(object source, DataGridCommandEventArgs e) { TextBox EntityTextBox = (TextBox)e.Item.FindControl("EntityTextBox"); int id = Convert.ToInt32(e.CommandArgument); try { string ipAddress = EntityTextBox.Text; IpAddressManager.Update(id, ipAddress); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ModifyIpAddress, string.Format("Modified Ip Address: {0}, IpAddressId: {1}", id, ipAddress)); ResetGridState(); MessageLabel1.SetSuccessMessage("IP Address updated successfully"); } catch (InvalidIpAddressException ex) { MessageLabel1.SetErrorMessage(ex.Message); } }
protected void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs // Get the exception object. Exception exc = Server.GetLastError(); // Handle HTTP errors if (exc.GetType() == typeof(HttpException) || exc.GetType() == typeof(System.Runtime.Serialization.SerializationException)) { if (exc.Message.Contains("NoCatch") || exc.Message.Contains("maxUrlLength") || exc.Message.Contains("InMemoryTokenManager") || exc.Message.Contains("non-serializable") || exc.Message.Contains("The controller for path")) { return; } } AuditLogManager.ReportWebException(Server, AuditEventType.SystemErrorWeb); Server.ClearError(); Response.RedirectToRoute(new { controller = "Home", action = "GeneralError" }); }
protected void RenewButton_Click(object sender, EventArgs e) { CheckAssetList(); int months = Convert.ToInt32(ExtendByMonthsDropDownList.SelectedValue); AssetFinder finder = new AssetFinder(); finder.AssetIdList.Add(0); finder.AssetIdList.AddRange(AssetIdList); List <Asset> assetList = Asset.FindMany(finder); foreach (Asset asset in assetList) { asset.ExpiryDate = asset.ExpiryDate.AddMonths(months); Asset.Update(asset); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.EditAsset, "Updated expiry date to " + asset.ExpiryDate.ToString(Global.DateFormat)); } Response.Redirect("AssetList.aspx?PostAction=BulkAssetRenewalSuccessful"); }
protected override void Grid_ItemCommand(object source, DataGridCommandEventArgs e) { if (e.CommandName == "add") { TextBox NewEntityTextBox = (TextBox)e.Item.FindControl("NewEntityTextBox"); string ipAddress = NewEntityTextBox.Text.Trim(); try { IpAddress ipa = IpAddressManager.Add(ipAddress); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.AddIpAddress, string.Format("Added Ip Address: {0}, IpAddressId: {1}", ipa.IpAddressValue, ipa.IpAddressId)); ResetGridState(); MessageLabel1.SetSuccessMessage("IP Address added successfully"); } catch (InvalidIpAddressException ex) { MessageLabel1.SetErrorMessage(ex.Message); } } }
public ActionResult ViewVotes(int id) { Election election = db.Elections.Find(id); if (election == null) { return(HttpNotFound()); } db.AdminActionRecords.Add( CreateActionRecord(election, AdminActionRecord.RecordType.ViewVotes) ); db.SaveChanges(); AuditLogManager.RecordViewVotes(User, election); return(View(new ViewVotesData( election, new NomineeFetcher(new TimetableUserRepository()).Fetch(election.Positions)) )); }
public void Execute(Guid transitionId) { ElectionStateChange transition = GetTransition(transitionId); if (transition.CompletedAt != null) { throw new ArgumentOutOfRangeException( nameof(transitionId), "This transition is already executed" ); } // We don't need the return, but this does validation which we want (before executing the change) DecideTransitionKind(transition); transition.Election.State = transition.TargetState; transition.CompletedAt = DateTime.Now; _db.SaveChanges(); AuditLogManager.RecordElectionStateChange(transition); }
protected void DeleteButton_Command(object sender, CommandEventArgs e) { try { // Get brand Id int brandId = NumericUtils.ParseInt32(e.CommandArgument.ToString(), 0); // Get the brand Brand brand = BrandCache.Instance.GetById(brandId); // Delete brand from database BrandManager.Delete(brandId); // Update log AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.DeleteBrand, string.Format("Deleted brand: {0}. Brand ID: {1}", brand.Name, brand.BrandId)); // Delete brand folder. string brandFolderPath = Server.MapPath(string.Format("~/Brands/Brand_{0}/", brandId)); if (Directory.Exists(brandFolderPath)) { Directory.Delete(brandFolderPath, true); m_Logger.InfoFormat("Deleted brand folder: {0}", brandFolderPath); } else { m_Logger.InfoFormat("Brand folder not deleted, does not exist: {0}", brandFolderPath); } // Redirect back to brand list Response.Redirect("ManageBrands.aspx?message=BrandDeletedSuccessfully"); } catch (Exception ex) { MessageLabel1.SetErrorMessage("Error deleting brand", ex.Message); } }
protected override void Grid_UpdateCommand(object source, DataGridCommandEventArgs e) { int assetTypeId = Convert.ToInt32(e.CommandArgument); TextBox NameTextBox = (TextBox)e.Item.FindControl("NameTextBox"); CheckBox IsVisibleCheckBox = (CheckBox)e.Item.FindControl("IsVisibleCheckBox"); try { AssetType assetType = AssetType.Get(assetTypeId); assetType.Name = NameTextBox.Text.Trim(); assetType.IsVisible = IsVisibleCheckBox.Checked; AssetTypeManager.SaveAssetType(assetType); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.ModifyAssetType, string.Format("Modified Asset Type: {0}, AssetTypeId: {1}", assetType.Name, assetType.AssetTypeId)); ResetGridState(); MessageLabel1.SetSuccessMessage("Asset type updated successfully"); } catch (InvalidAssetTypeException imtex) { MessageLabel1.SetErrorMessage("Unable to update asset type", imtex.Message); BindGrid(CurrentPage); } }
protected void DelegateButton_Click(object sender, EventArgs e) { CheckAssetList(); string email = EmailTextBox.Text; if (StringUtils.IsBlank(email)) { MessageLabel1.SetErrorMessage("Email address is required"); return; } User user = Data.User.GetByEmail(email); if (user.IsNull) { MessageLabel1.SetErrorMessage("Email address does not belong to a registered user"); return; } AssetFinder finder = new AssetFinder(); finder.AssetIdList.Add(0); finder.AssetIdList.AddRange(AssetIdList); List <Asset> assetList = Asset.FindMany(finder); foreach (Asset asset in assetList) { asset.UploadedByUserId = user.UserId.GetValueOrDefault(); asset.ContactEmail = user.Email; Asset.Update(asset); AuditLogManager.LogUserAction(CurrentUser, AuditUserAction.EditAsset, "Delegated asset to " + asset.ContactEmail); } Response.Redirect("AssetList.aspx?PostAction=BulkAssetDelegationSuccessful"); }
public ActionResult Edit(int id) { Election election = db.Elections.Find(id); if (election == null) { return(HttpNotFound()); } CouncilElectionData councilData = null; CouncilElectionForm councilForm = null; ElectionForm form; if (election.Type == ElectionType.StudentCouncil) { councilData = db.CouncilElectionData.First(data => data.ElectionId == election.Id); form = councilForm = GenerateFormForCouncil(election, councilData); } else { form = GenerateFormForCourseRep(election); } ModelFieldsAccessibility fieldsInfo = ElectionLifecycleInfo.GetWhatCanBeEditedCouncil(election); ViewData[FormConstants.FieldsInfoKey] = fieldsInfo; ViewBag.Election = election; fieldsInfo.EnsureAllowedDefaultKind( ModelFieldsAccessibility.Kind.Editable, nameof(AdminElectionsController) + "." + nameof(Edit) ); if (Request.HttpMethod.ToUpper() != "POST") { // Just show the template return(View("Edit", form)); } AntiForgery.Validate(); // Update the form based on data that we received // ReSharper disable once ConvertIfStatementToNullCoalescingExpression - we need the compiler to specify different generic arguments if (councilForm != null) { TryUpdateModel(councilForm); } else { TryUpdateModel(form); } // Get the original form so that we use old values for uneditable fields CouncilElectionForm councilOriginalForm = null; ElectionForm originalForm; if (councilForm != null) { originalForm = councilOriginalForm = GenerateFormForCouncil(election, councilData); } else { originalForm = GenerateFormForCourseRep(election); } // Replace all uneditable values with old ones fieldsInfo.ReplaceUneditableWithOldValues(form, originalForm); // As the role IDs are sent from user, we need to make sure that they weren't changed if (councilForm != null && fieldsInfo.CanBeChangedByUser(nameof(CouncilElectionForm.Roles))) { IEnumerable <int?> initialRoleIds = councilOriginalForm.Roles.Select(role => role.Id); IEnumerable <int?> newRoleIds = councilForm.Roles.Select(role => role.Id); if (!initialRoleIds.SequenceEqual(newRoleIds)) { throw new Exception("The IDs of roles were changed by user input"); } } // Validate again (since some rules are relative to other fields and can be affected by operations above) TryValidateModel(form); // Ignore the failures from uneditable fields this.RemoveIgnoredErrors(fieldsInfo); if (!ModelState.IsValid) { // The validation failed so we just display the form again return(View("Edit", form)); } // Record the admin action AdminActionRecord actionRecord = CreateActionRecord(election, AdminActionRecord.RecordType.Edit); actionRecord.SetFormChangeSet(FormChangeSet.Generate(form, originalForm)); db.AdminActionRecords.Add(actionRecord); // Validation passed with the fields that are allowed to change. Persist the changes Mapper.Map(form, election); if (councilData != null) { Mapper.Map(form, councilData); } db.SaveChanges(); BackgroundJob.Enqueue <SynchronizeDelayedJobsJob>(job => job.Execute(election.Id)); AuditLogManager.RecordElectionEdit(User, election); return(RedirectToAction("Details", new { id })); }
public override void ProcessRequest() { // Get querystring values int assetId = GetIdFromFilename(); int assetImageSizeId = WebUtils.GetIntRequestParam("assetImageSizeId", 0); DownloadFormat downloadFormat = GeneralUtils.ParseEnum(WebUtils.GetRequestParam("AssetImageFormat"), DownloadFormat.Original); bool logDownload = (WebUtils.GetIntRequestParam("logDownload", 1) == 1); bool original = (WebUtils.GetIntRequestParam("original", 0) == 1); // Downloads should ALWAYS be logged from normal users, regardless of the querystring if (SessionInfo.Current.User.UserRole == UserRole.Normal) { logDownload = true; } // Ensure asset id is specified if (assetId == 0) { throw new HttpException(500, "Invalid asset id"); } // Get asset Asset asset = Asset.Get(assetId); // Make sure asset is valid if (asset.IsNull) { Context.Response.Redirect("~/Errors/AssetMissing.htm"); return; } // Check if user can download asset bool isAuthorised = EntitySecurityManager.CanUserDownloadAsset(SessionInfo.Current.User, asset); if (!isAuthorised) { throw new SecurityException("Access denied"); } // Get the asset file info AssetFileInfo info = new AssetFileInfo(asset); // Ensure file exists if (!info.FileExists) { Context.Response.Redirect("~/Errors/AssetFileMissing.htm"); return; } // Asset file path string path = info.FilePath; // Update the audit history if (logDownload) { AuditLogManager.LogAssetAction(assetId, SessionInfo.Current.User, AuditAssetAction.DownloadedAssetFile); AuditLogManager.LogUserAction(SessionInfo.Current.User, AuditUserAction.DownloadAsset, string.Format("Downloaded asset with AssetId: {0}", assetId)); } DownloadAsset(asset, path, original, downloadFormat, assetImageSizeId); }