protected override void OnBeforeSaving(CatalogDefinition entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (string.IsNullOrWhiteSpace(entity.Name)) { throw new KnownError("Invalid Name."); } //if (mode == OPERATION_MODE.UPDATE) //{ // var original = GetById(entity.Id); // if (original == null) throw new KnownError("Error. Entity no longer exists."); // foreach (var field in entity.Fields) // { // //Delete // if (field.Entry_State == BaseEntity.EntryState.Deleted) // { // //TODO: To delete in Catalog as well? // } // //Update: // if (field.Entry_State == BaseEntity.EntryState.Upserted && field.Id > 0) // { // } // } //} ////Update or New, we always check relationships: //if (field.Relationship == "Has Parent") //{ // Db.Update<CatalogDefinition>(new { ParentType = entity.Name }, e => e.ParentType == original.Name); //} }
protected override void OnBeforeSaving(CatalogType entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (string.IsNullOrWhiteSpace(entity.Name)) { throw new KnownError("Invalid Name."); } if (mode == OPERATION_MODE.UPDATE) { var original = GetById(entity.Id); if (original == null) { throw new KnownError("Error. Entity no longer exists."); } if (original.Name != entity.Name) { Db.Update <Catalog>(new { CatalogType = entity.Name }, e => e.CatalogType == original.Name); Db.Update <CatalogType>(new { ParentType = entity.Name }, e => e.ParentType == original.Name); Db.Update <Catalog>(new { Parent = entity.Name }, e => e.Parent == original.Name); } } ///start:slot:beforeSave<<<///end:slot:beforeSave<<< }
protected override void OnBeforeSaving(Email entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (mode == OPERATION_MODE.ADD) { #region Validations if (entity.ToList.Count() == 0 && entity.CcList.Count() == 0 && entity.BccList.Count == 0) { throw new KnownError("Cannot send email without Recipients."); } #endregion entity.CreatedAt = DateTimeOffset.Now; } #region Send Email //Copy Attachments when resent: if (entity.IsResent) { string baseAttachmentsPath = AppSettings.Get <string>("EmailAttachments"); entity.AttachmentsFolder = AttachmentsIO.CopyAttachments(entity.AttachmentsFolder, entity.Attachments, baseAttachmentsPath); entity.Attachments = entity.Attachments.Where(e => !e.ToDelete).ToList(); } var emailService = new MailgunService { From = Auth.Email, Subject = entity.Subject, Body = entity.Body, AttachmentsFolder = entity.AttachmentsFolder }; foreach (var item in entity.ToList) { emailService.To.Add(item.Email); } foreach (var item in entity.CcList) { emailService.Cc.Add(item.Email); } foreach (var item in entity.BccList) { emailService.Bcc.Add(item.Email); } emailService.Bcc.Add(Auth.Email); //Add sender as recipient as well. try { emailService.SendMail(); } catch (Exception ex) { throw new KnownError("Could not send email:\n" + ex.Message); } #endregion }
protected override void OnBeforeSaving(Approval entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (mode == OPERATION_MODE.ADD) { entity.RequestedDate = DateTimeOffset.Now; entity.Status = entity.Status != "Requested" ? "Created" : entity.Status; } }
protected override void OnBeforeSaving(Catalog entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (string.IsNullOrWhiteSpace(entity.CatalogType)) { throw new KnownError("Error. Catalog Type is a required field."); } ///start:slot:beforeSave<<<///end:slot:beforeSave<<< }
protected override void OnAfterSaving(Catalog entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (entity.Values != null) { entity.Values.ForEach(e => e.CatalogId = entity.Id); //Upserts: Db.SaveAll(entity.Values.Where(e => e.Entry_State == BaseEntity.EntryState.Upserted)); } Cache.FlushAll(); }
protected override void OnAfterSaving(Account entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (mode == OPERATION_MODE.ADD) { var authProvider = (ApiKeyAuthProvider)AuthenticateService.GetAuthProvider(ApiKeyAuthProvider.Name); var apiKeys = authProvider.GenerateNewApiKeys(entity.Id.ToString()); var apiRepo = (IManageApiKeys)AuthRepository; apiRepo.StoreAll(apiKeys); } }
protected override void OnBeforeSaving(Badge entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { ///start:slot:beforeSave<<< //if (string.IsNullOrWhiteSpace(entity.Value)) //{ // throw new KnownError("El campo no puede ir sin data"); //} entity.CheckIn = DateTimeOffset.Now; ///end:slot:beforeSave<<< }
protected override void OnAfterSaving(CatalogDefinition entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (entity.Fields != null) { entity.Fields.ForEach(e => e.CatalogDefinitionId = entity.Id); //Deletes: Db.DeleteAll(entity.Fields.Where(e => e.Entry_State == BaseEntity.EntryState.Deleted)); //Inserts and Updates: Db.SaveAll(entity.Fields.Where(e => e.Entry_State == BaseEntity.EntryState.Upserted)); } Cache.FlushAll(); }
protected override void OnBeforeSaving(AdvancedSort entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { entity.UserName = Auth.UserName; foreach (var item in entity.Sorting) { item.AdvancedSortId = entity.Id; } Db.SaveAll(entity.Sorting); foreach (var item in entity.Filtering) { item.AdvancedSortId = entity.Id; } Db.SaveAll(entity.Filtering); if (mode == OPERATION_MODE.UPDATE) { var originalEntity = GetById(entity.Id); for (int i = originalEntity.Sorting.Count - 1; i >= 0; i--) { var oSort = originalEntity.Sorting[i]; if (!entity.Sorting.Any(e => e.Id == oSort.Id)) { Db.Delete(oSort); } } for (int i = originalEntity.Filtering.Count - 1; i >= 0; i--) { var oFilter = originalEntity.Filtering[i]; if (!entity.Filtering.Any(e => e.Id == oFilter.Id)) { Db.Delete(oFilter); } } } ///start:slot:beforeSave<<<///end:slot:beforeSave<<< }
protected override void OnAfterSaving(Email entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { var recipients = entity.ToList .Concat(entity.CcList) .Concat(entity.BccList) .Select(e => e.Email) .Distinct() .ToCsv(); ActivityLogic.Add(new Activity { Category = "Email", Title = $"Recipients: {recipients}", Description = $"{entity.Body}", ForeignApp = "NCN", ForeignKey = entity.Id, ForeignCommonKey = entity.ForeignCommonKey, ForeignType = "Email", ForeignURL = $"https://ncn.capsonic.com/ncn?id={entity.ForeignCommonKey}" }); }
protected override void OnBeforeSaving(Account entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (string.IsNullOrWhiteSpace(entity.UserName)) { throw new KnownError("Error. [UserName] field is required."); } if (string.IsNullOrWhiteSpace(entity.Email)) { throw new KnownError("Error. [Email] field is required."); } if (mode == OPERATION_MODE.ADD || entity.UpdatePassword) { if (string.IsNullOrWhiteSpace(entity.Password)) { throw new KnownError("Error. [Password] field is required."); } if (string.IsNullOrWhiteSpace(entity.ConfirmPassword)) { throw new KnownError("Error. [Confirm Password] field is required."); } if (entity.Password != entity.ConfirmPassword) { throw new KnownError("Error. [Password] does not match with [Confirm Password]."); } } if (mode == OPERATION_MODE.UPDATE) { if (entity.UpdatePassword) { var account = AuthRepository.GetUserAuthByUserName(entity.UserName); AuthRepository.UpdateUserAuth(account, account, entity.Password); } } }
protected override void OnBeforeSaving(Email entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { ///start:slot:beforeSave<<<///end:slot:beforeSave<<< }
protected override void onBeforeSaving(PurchaseRequest entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (mode == OPERATION_MODE.ADD) { var ctx = context as POContext; if (entity.GeneralManager != null) { ctx.Entry(entity.GeneralManager).State = EntityState.Unchanged; } if (entity.Requisitor != null) { ctx.Entry(entity.Requisitor).State = EntityState.Unchanged; } if (entity.DepartmentAssigned != null) { ctx.Entry(entity.DepartmentAssigned).State = EntityState.Unchanged; } if (entity.DepartmentManager != null) { ctx.Entry(entity.DepartmentManager).State = EntityState.Unchanged; } //if (string.IsNullOrWhiteSpace(entity.FriendlyIdentifier)) //{ // throw new KnownError("Friendly identifier is a required field"); //} #region PR Number Generation DateTimeOffset date = DateTimeOffset.Now; int sequence = 0; var last = ctx.PRNumbers.Where(n => n.CreatedAt.Year == date.Year && n.CreatedAt.Month == date.Month && n.CreatedAt.Day == date.Day).OrderByDescending(n => n.Sequence) .FirstOrDefault(); if (last != null) { sequence = last.Sequence + 1; } string generated = date.Year.ToString().Substring(2) + date.Month.ToString("D2") + date.Day.ToString("D2") + sequence.ToString("D3"); PRNumber cqaNumber = ctx.PRNumbers.Add(new PRNumber() { CreatedAt = date, Sequence = sequence, GeneratedNumber = generated, Revision = "A" }); ctx.SaveChanges(); entity.PRNumberKey = cqaNumber.PRNumberKey; #endregion #region var comment = new Comment(); comment.CommentByUserKey = LoggedUser.LocalUser.UserKey; ctx.Comments.Add(comment); ctx.SaveChanges(); entity.CommentKey = comment.CommentKey; #endregion entity.RequisitorKey = LoggedUser.LocalUser.UserKey; } #region Attachments string baseAttachmentsPath = ConfigurationManager.AppSettings["PR_Attachments"]; if (entity != null && entity.Attachments != null) { foreach (var file in entity.Attachments) { if (file.ToDelete) { string filePath = baseAttachmentsPath + "\\" + file.Directory + "\\" + file.FileName; AttachmentsIO.DeleteFile(filePath); } } } #endregion }
protected override void onAfterSaving(DbContext context, PurchaseRequest entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { var ctx = context as POContext; ctx.Database.Connection.Execute("DELETE FROM PRLine WHERE PurchaseRequestKey = @PurchaseRequestKey", new { PurchaseRequestKey = entity.id }, ctx.Database.CurrentTransaction.UnderlyingTransaction); if (entity.PRLines != null) { foreach (var line in entity.PRLines) { line.PurchaseRequestKey = entity.id; ctx.PRLines.Add(line); ctx.SaveChanges(); } } if (mode == OPERATION_MODE.ADD) { CommonResponse approvalResponse = approvalLogic.CreateInstance(new Approval() { PurchaseRequestKey = entity.id, Title = "Purchase Request - " + entity.FriendlyIdentifier }); Approval approval = (Approval)approvalResponse.Result; approvalLogic.repository.Add(approval); } }
protected override void onBeforeSaving(Approval entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { var ctx = context as MROContext; #region Validations User currentUser = ctx.Users.AsNoTracking().FirstOrDefault(u => u.UserKey == LoggedUser.UserID); if (currentUser == null) { throw new KnownError("Logged User not found or session expired."); } if (entity.Approvers == null) { throw new KnownError("Approvers field is required."); } #endregion foreach (var item in entity.Approvers) { ctx.Users.Attach(item); } if (mode == OPERATION_MODE.ADD) { Email emailEntity = new Email(); emailEntity.CreatedAt = DateTimeOffset.Now; var hyperlink = entity.Hyperlink; EmailService emailService = new EmailService("secure.emailsrvr.com", 587) { EmailAddress = currentUser.Email, Password = currentUser.EmailPassword, From = currentUser.Email, Subject = entity.Title, Body = entity.Title + "<br><br>" + entity.RequestDescription + @"<br><br>Open document here: <a href=""" + hyperlink + @""">" + "Something Descriptive" + "</a>" }; foreach (var item in entity.Approvers) { emailService.To.Add(item.Email); } emailService.Bcc.Add(currentUser.Email); try { emailService.SendMail(); } catch (Exception ex) { throw new KnownError("Could not send email, please verify your Profile settings.\n" + ex.Message); } } }
protected override void onAfterSaving(DbContext context, Approval entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { var ctx = context as MROContext; if (mode == OPERATION_MODE.ADD) { } else { } List <Contact> responsibles = entity.Approvers.Select(u => new Contact() { Email = u.Email, Value = u.Value }).ToList(); taskLogic.SaveTasks(responsibles, entity); }
protected override void OnAfterSaving(CatalogType entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { Cache.FlushAll(); ///start:slot:afterSave<<<///end:slot:afterSave<<< }
protected override void OnAfterSaving(Activity entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { }
protected override void onAfterSaving(DbContext context, InventoryInputDoc entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (mode == OPERATION_MODE.UPDATE) { if (entity.InventoryInputs != null) { foreach (var item in entity.InventoryInputs) { item.InventoryInputDocKey = entity.id; if (item.CatMaterial == null) { throw new KnownError("[Material Number] field is required."); } if (item.CatGeoLocation == null) { throw new KnownError("[Location] field is required."); } #region Clear objects to avoid duplicates item.CatGeoLocation = null; item.CatMaterial = null; #endregion if (item.EF_State == BaseEntity.EF_EntityState.Added) { item.Balance = item.Quantity; context.Entry(item).State = EntityState.Added; } else if (item.EF_State == BaseEntity.EF_EntityState.Modified) { context.Entry(item).State = EntityState.Modified; } else if (item.EF_State == BaseEntity.EF_EntityState.Deleted) { context.Entry(item).State = EntityState.Deleted; } } } context.SaveChanges(); } ///start:slot:afterSave<<<///end:slot:afterSave<<< }
protected override void onBeforeSaving(MRORequestLine entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { ///start:slot:beforeSave<<<///end:slot:beforeSave<<< }
protected override void OnAfterSaving(Catalog entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { ///start:slot:afterSave<<<///end:slot:afterSave<<< }
virtual protected async Task OnBeforeSavingAsync(Entity entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { }
virtual protected void OnBeforeSaving(Entity entity, OPERATION_MODE mode = OPERATION_MODE.NONE) { }
protected virtual void onAfterSaving(DbContext context, Entity entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { }
protected virtual void onBeforeSaving(Entity entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { }
private void toggleOnlineOffline(OPERATION_MODE newMode) { operationMode = newMode; if (operationMode == OPERATION_MODE.ONLINE) { miOffline.Checked = false; miOnline.Checked = true; bSyncRefresh.Text = "Sync"; bUploadAll.Enabled = true; } else if (operationMode == OPERATION_MODE.OFFLINE) { miOnline.Checked = false; miOffline.Checked = true; bSyncRefresh.Text = "Refresh"; bUploadAll.Enabled = false; } sync(); }
protected override void onBeforeSaving(InventoryInputNumber entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { ///start:slot:beforeSave<<<///end:slot:beforeSave<<< }
protected override void onAfterSaving(DbContext context, MRORequestLine entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (mode == OPERATION_MODE.UPDATE) { } ///start:slot:afterSave<<<///end:slot:afterSave<<< }
protected override void onBeforeSaving(User entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (string.IsNullOrWhiteSpace(entity.Value)) { throw new KnownError("[User Name] is a required field."); } if (string.IsNullOrWhiteSpace(entity.UserName)) { throw new KnownError("[User Name] is a required field."); } if (entity.id == 0 || (entity.id > 0 && entity.ChangePassword)) { if (string.IsNullOrWhiteSpace(entity.Password) || string.IsNullOrWhiteSpace(entity.ConfirmPassword)) { throw new KnownError("[Password] and [Confirm Password] are required fields."); } if (entity.Password != entity.ConfirmPassword) { throw new KnownError("[Password] does not match with its confirmation."); } if (entity.Password.Length < 6) { throw new KnownError("[User Name] has to have at least 6 characters."); } } //Updating.. if (entity.id > 0) { User originalUser = repository.GetByID(entity.id); if (originalUser == null) { throw new KnownError("Error. User to be updated not found (Table: Users)."); } using (var authContext = new AuthContext()) { UserManager <IdentityUser> _userManager; _userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(authContext)); IdentityUser user = authContext.Users.FirstOrDefault(u => u.UserName == originalUser.UserName); if (user == null) { throw new KnownError("Error. User to be updated not found (Table: ASPNetUsers)."); } user.UserName = entity.UserName; //password was updated: if (!string.IsNullOrWhiteSpace(entity.Password)) { user.PasswordHash = _userManager.PasswordHasher.HashPassword(entity.Password); } var result = _userManager.Update(user); if (result == null || !result.Succeeded) { throw new KnownError("An error has occurried when trying to update a user:\n" + result.Errors.First()); } } } //Creating.. else { entity.CreatedAt = DateTimeOffset.Now; using (var authContext = new AuthContext()) { UserManager <IdentityUser> _userManager; _userManager = new UserManager <IdentityUser>(new UserStore <IdentityUser>(authContext)); IdentityUser user = new IdentityUser { UserName = entity.UserName }; var result = _userManager.Create(user, entity.Password); if (result == null || !result.Succeeded) { string sError = result.Errors.First(); if (sError.EndsWith("is already taken.")) { throw new KnownError("User is already taken."); } else { throw new KnownError(sError); } } } } //Bitmap identicon; //try //{ // var bg = new StaticColorBrushGenerator(StaticColorBrushGenerator.ColorFromText(entity.UserName)); // identicon = new IdenticonGenerator("MD5") // .WithSize(100, 100) // .WithBackgroundColor(Color.White) // .WithBlocks(4, 4) // .WithBlockGenerators(IdenticonGenerator.ExtendedBlockGeneratorsConfig) // .WithBrushGenerator(bg) // .Create(entity.UserName); //} //catch (Exception ex) //{ // throw new KnownError("Ha ocurrido un error al intentar crear el usuario."); //} //ImageConverter converter = new ImageConverter(); //try //{ // entity.Identicon64 = Convert.ToBase64String(ConvertBitMapToByteArray(identicon)); // entity.Identicon = (byte[])converter.ConvertTo(identicon, typeof(byte[])); //} //catch (Exception ex) //{ // throw new KnownError("Ha ocurrido un error al intentar crear el usuario"); //} entity.EmailServer = "secure.emailsrvr.com"; entity.EmailPort = "587"; //TODO: Hash Password entity.EmailPassword = entity.EmailPassword; }
protected override void onAfterSaving(DbContext context, InventoryInputNumber entity, BaseEntity parent = null, OPERATION_MODE mode = OPERATION_MODE.NONE) { if (mode == OPERATION_MODE.UPDATE) { } ///start:slot:afterSave<<<///end:slot:afterSave<<< }