public long SaveEntityRecord(int UpdatingUserID, bool AuditChanges) { Logger.Write(LogCategory.General, (this.New ? "Creating new " : (this.Deleted ? "Deleting " : "Updating ")) + "contract", "contract ID " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information); DateTime updateDate = DateTime.Now; TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName()); TopContractsEntities.Contract efContract = null; if (this.New) { efContract = new TopContractsEntities.Contract(); efContract.ContractUpdateDetail = new ContractUpdateDetail(); if (context.FieldGroups.Count(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)) > 0) foreach (FieldGroup grp in context.FieldGroups.Where(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.Inactive == false && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)))//Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fieldsgroup foreach (Field fld in grp.Fields.Where(grpf => grpf.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fields { efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.EntryIdentifier, FieldValue = (fld.FieldType == (int)FieldTypes.ListSingle && fld.UseFirstAsDefault == true ? fld.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } else { efContract = context.Contracts.Where(u => u.ContractID == this.ID).SingleOrDefault(); } if (this.Deleted) { #region DELETING RELATED ENTITIES ----------------------------------------------------------------------------- //For some unknown reason, eliminating the if-count>0 from before each of the foreach(s), throws an "object not set" exception even though alerts exist! context.ContractUpdateDetails.Remove(context.ContractUpdateDetails.Single(entry => entry.ContractID == this.ID)); if (context.ContractFields.Count(entry => entry.ContractID == this.ID) > 0) foreach (TopContractsEntities.ContractField efContractField in context.ContractFields.Where(entry => entry.ContractID == this.ID)) context.ContractFields.Remove(efContractField); foreach (TopContractsEntities.ContractUser efContractUser in context.ContractUsers.Where(entry => entry.ContractID == this.ID)) context.ContractUsers.Remove(efContractUser); #endregion context.Contracts.Remove(efContract); } if (this.New) { updateEfContract(ref efContract, ref context); context.Contracts.Add(efContract); } if (this.New == false & this.Deleted == false) { updateEfContract(ref efContract, ref context); } //Boaz-1 (8-Aug-2012) ------------------------------------------------------ //All Todos which are linked to new events, should be made their "children" in the EF so that the foreign //key values will be automatically generated when saving to the DB foreach (TopContractsEntities.ContractTodo todo in efContract.ContractTodos.Where(td => td.ActivityID < 0)) { efContract.ContractActivities.SingleOrDefault(ca => ca.ActivityID == todo.ActivityID).ContractTodos.Add(todo); } bool updateContractUpdateDetails = false; if (this.Deleted == false) { //If any of the entities related to the contract has changed, the Update-Date of the contract record itself should be updated... foreach (var entry in context.ChangeTracker.Entries()) { //Boaz 7-Aug-2012 //if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified && !(entry.Entity is EFContractRelatedEntryWithUpdate)) if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified || entry.State == System.Data.EntityState.Deleted) { updateContractUpdateDetails = true; } } if (updateContractUpdateDetails) foreach (var entry in context.ChangeTracker.Entries()) { //Boaz 7-Aug-2012 //If any changed was made to a record in any table (entities related to the contract) which has //UpdateDate and UpdateUserID fields, these fields are updated to reflect the change. //These fields are NOT handled by the individual classes committing the changes to the //database - they are handled centrally here to cut-down on the code if (entry.Entity is EFContractRelatedEntryWithUpdate && entry.State != EntityState.Unchanged) //if (entry.Entity is EFContractRelatedEntryWithUpdate) { ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingDate = updateDate; ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingUserID = UpdatingUserID; } } } if (updateContractUpdateDetails) { efContract.ContractUpdateDetail.UpdateDate = updateDate; efContract.ContractUpdateDetail.UpdateUserID = UpdatingUserID; } //We want to keep tracking the changes after calling SaveChanges, for the purpose of auditing ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; objectContext.DetectChanges(); try { //Using SaveOptions.None to keep change-tracking... Requires objectContext.DetectChanges() before and objectContext.AcceptAllChanges() after... int rowsAffected = objectContext.SaveChanges(SaveOptions.None); } catch (System.Data.UpdateException updEx) { if (updEx.InnerException != null) if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") && updEx.InnerException.Message.Contains("FK_ContractTodos_ContractActivities")) //{ // Logger.Write(updEx, System.Diagnostics.TraceEventType.Warning); throw new ExceptionDataContractSaveDeleteEventWithAlert(); //} else if (updEx.InnerException.Message.Contains("FK_Contracts_Contracts") && updEx.InnerException.Message.Contains("ParentContractID")) throw new ExceptionDataContractDeleteDeleteContractWithChild(); else //{ // Logger.Write(updEx, System.Diagnostics.TraceEventType.Error); throw updEx; //} } if (AuditChanges) { HistManager histManager = new HistManager(); int recordsWrittenToHistory = histManager.AuditChanges(updateDate, UpdatingUserID, this.New, this.Deleted, context.ChangeTracker.Entries().Where(e => e.State != System.Data.EntityState.Unchanged || e.Entity is TopContractsEntities.Contract)); } objectContext.AcceptAllChanges(); long contractIdSaved = -1; //will indicate failure, if no number is set foreach (var entry in context.ChangeTracker.Entries()) { Logger.Write("entering the loop - for context.ChangeTracker.Entries()", System.Diagnostics.TraceEventType.Verbose); if (entry.Entity is TopContractsEntities.Contract) { contractIdSaved = ((TopContractsEntities.Contract)entry.Entity).ContractID; } if (entry.Entity is TopContractsEntities.ContractDoc) { TopContractsEntities.ContractDoc efDoc = entry.Entity as TopContractsEntities.ContractDoc; TopContractsDAL10.ContractDoc doc = this.ContractDocs.SingleOrDefault(d => d.FileName == efDoc.FileName); if (doc != null) { if (doc.New) { doc.EntryId = efDoc.DocumentID; //This is done especially for the process of file copying... } } } } if (this.Deleted) return 0; return contractIdSaved; }
/// <summary> /// Save contract (delete or add according to Deleted and New properties) /// </summary> /// <param action="UpdatingUserID">Id of user performing the update</param> /// <param action="AuditChanges">Audit changes of update</param> /// <returns>The ID of the contract saved, or 0 if contract was deleted, or -1 to indicate a failure to save contract</returns> public long Save(int UpdatingUserID, bool AuditChanges) { Logger.WriteGeneralVerbose("Contract class - save", "updating ContractActivity of {0}", this.ID); //Logger.Write(LogCategory.General, (this.New ? "Creating new " : (this.Deleted ? "Deleting " : "Updating ")) + "contract", "contract ID " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information); DateTime updateDate = DateTime.Now; TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName()); TopContractsEntities.Contract efContract = null; if (this.New) { efContract = new TopContractsEntities.Contract(); efContract.ContractUpdateDetail = new ContractUpdateDetail(); //long ContractTypeContractsID = ConfigurationProvider.Default.ContractTypeContracts.ContractTypeContractsID; long ContractTypeContractsID = Utilities.contractTypeContractsID; // Code implemented by Viplav on 17 june 2013 for remove webconfig concept if (context.FieldGroups.Count(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll) > 0) //foreach (FieldGroup grp in context.FieldGroups.Where( // grp => (grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll || grp.FieldGroupsContractTypesMAPs.Any(cTypeMap => cTypeMap.ContractType.ParentContractTypeID == ContractTypeContractsID) == true) && grp.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fieldsgroup foreach (FieldGroup grp in context.FieldGroups.Where( grp => (grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll && grp.Inactive == false)).ToList()) // Jan 31, 2013 - Need to be tested properly as now loop is running for VisibleToAll efFieldGroupsForContractInit { foreach (Field fld in grp.Fields.Where(grpf => grpf.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fields { if (fld.FieldType == (int)FieldTypes.EntityLink) { foreach (TopContractsEntities.ContractTypesFieldsToCreateDefault contDef in context.ContractTypesFieldsToCreateDefaults.Where(c => c.ContractTypeID == fld.LinkedEntityID)) { //efContract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = grp.EntryIdentifier, FieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.FieldID, CatalogFieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } else efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.EntryIdentifier, FieldValue = (fld.FieldType == (int)FieldTypes.ListSingle && fld.UseFirstAsDefault == true ? fld.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } if (context.FieldGroups.Count(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)) > 0) foreach (FieldGroup grp in context.FieldGroups.Where(grp => grp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && grp.Inactive == false && grp.FieldGroupsContractTypesMAPs.Any(mp => mp.ContractTypeID == this.Properties.ContractTypeID)))//Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fieldsgroup foreach (Field fld in grp.Fields.Where(grpf => grpf.Inactive == false)) //Viplav - 16-Oct-2012 // Implemented inactive condition for getting only active fields { if (fld.FieldType == (int)FieldTypes.EntityLink) { foreach (TopContractsEntities.ContractTypesFieldsToCreateDefault contDef in context.ContractTypesFieldsToCreateDefaults.Where(c => c.ContractTypeID == fld.LinkedEntityID)) { //efContract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = grp.EntryIdentifier, FieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.FieldID, CatalogFieldID = contDef.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } else efContract.ContractFields.Add(new TopContractsEntities.ContractField() { OrganizationIdentifier = this.Properties.OrganizationIdentifier, FieldGroupID = grp.EntryIdentifier, FieldID = fld.EntryIdentifier, FieldValue = (fld.FieldType == (int)FieldTypes.ListSingle && fld.UseFirstAsDefault == true ? fld.FieldListItems.ElementAt(0).FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } else { efContract = context.Contracts.Where(u => u.ContractID == this.ID).SingleOrDefault(); } if (this.Deleted) { #region DELETING RELATED ENTITIES ----------------------------------------------------------------------------- //For some unknown reason, eliminating the if-count>0 from before each of the foreach(s), throws an "object not set" exception even though alerts exist! context.ContractUpdateDetails.Remove(context.ContractUpdateDetails.Single(entry => entry.ContractID == this.ID)); if (context.ContractApplications.Count(entry => entry.ContractID == this.ID) > 0) foreach (TopContractsEntities.ContractApplication efContractApplication in context.ContractApplications.Where(entry => entry.ContractID == this.ID)) context.ContractApplications.Remove(efContractApplication); if (context.ContractActivities.Count(entry => entry.ContractID == this.ID) > 0) foreach (TopContractsEntities.ContractActivity efContractActivity in context.ContractActivities.Where(entry => entry.ContractID == this.ID)) { context.ContractActivities.Remove(efContractActivity); } if (context.ContractDocs.Count(entry => entry.ContractID == this.ID) > 0) foreach (TopContractsEntities.ContractDoc efContractDoc in context.ContractDocs.Where(entry => entry.ContractID == this.ID)) context.ContractDocs.Remove(efContractDoc); if (context.ContractGalleries.Count(entry => entry.ContractID == this.ID) > 0) foreach (TopContractsEntities.ContractGallery efContractGallery in context.ContractGalleries.Where(entry => entry.ContractID == this.ID)) { if (efContractGallery.ContractGalleryImages != null && efContractGallery.ContractGalleryImages.Count() > 0) { foreach (TopContractsEntities.ContractGalleryImage image in efContractGallery.ContractGalleryImages.ToList()) { context.ContractGalleryImages.Remove(image); } } context.ContractGalleries.Remove(efContractGallery); } if (context.ContractFields.Count(entry => entry.ContractID == this.ID) > 0) foreach (TopContractsEntities.ContractField efContractField in context.ContractFields.Where(entry => entry.ContractID == this.ID)) context.ContractFields.Remove(efContractField); if (context.ContractTodos.Count(entry => entry.ContractID == this.ID) > 0) { foreach (TopContractsEntities.ContractTodo efContractTodo in context.ContractTodos.Where(entry => entry.ContractID == this.ID)) { if (efContractTodo.ContractTodoRecipients != null) for (int indx = efContractTodo.ContractTodoRecipients.Count - 1; indx >= 0; indx--) context.ContractTodoRecipients.Remove(efContractTodo.ContractTodoRecipients.ElementAt(indx)); if (efContractTodo.ContractTodoUnits != null) for (int indx = efContractTodo.ContractTodoUnits.Count - 1; indx >= 0; indx--) context.ContractTodoUnits.Remove(efContractTodo.ContractTodoUnits.ElementAt(indx)); if (efContractTodo.DoneTodos != null) for (int indx = efContractTodo.DoneTodos.Count - 1; indx >= 0; indx--) context.DoneTodos.Remove(efContractTodo.DoneTodos.ElementAt(indx)); context.ContractTodos.Remove(efContractTodo); } } foreach (TopContractsEntities.ContractUser efContractUser in context.ContractUsers.Where(entry => entry.ContractID == this.ID)) context.ContractUsers.Remove(efContractUser); #endregion context.Contracts.Remove(efContract); } if (this.New) { updateEfContract(ref efContract, ref context); context.Contracts.Add(efContract); } if (this.New == false & this.Deleted == false) { updateEfContract(ref efContract, ref context); } //Boaz-1 (8-Aug-2012) ------------------------------------------------------ //All Todos which are linked to new events, should be made their "children" in the EF so that the foreign //key values will be automatically generated when saving to the DB foreach (TopContractsEntities.ContractTodo todo in efContract.ContractTodos.Where(td => td.ActivityID < 0)) { efContract.ContractActivities.SingleOrDefault(ca => ca.ActivityID == todo.ActivityID).ContractTodos.Add(todo); } // code to remove images from context for a deleted gallery foreach (ContractGallery gallery in this.ContractGalleries) { if (gallery.Deleted) { foreach (TopContractsEntities.ContractGalleryImage galleryImage in context.ContractGalleryImages.Where(g => g.GalleryID == gallery.EntryId)) context.ContractGalleryImages.Remove(galleryImage); } // code to remove a deleted gallery image if (!gallery.New) { foreach (ContractGalleryImage image in gallery.Images) { if (image.Deleted) { if (context.ContractGalleryImages.Any(g => g.GalleryImageID == image.EntryId)) { TopContractsEntities.ContractGalleryImage galleryImage = context.ContractGalleryImages.SingleOrDefault(g => g.GalleryImageID == image.EntryId); context.ContractGalleryImages.Remove(galleryImage); } } } } } bool updateContractUpdateDetails = false; if (this.Deleted == false) { //If any of the entities related to the contract has changed, the Update-Date of the contract record itself should be updated... foreach (var entry in context.ChangeTracker.Entries()) { //Boaz 7-Aug-2012 //if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified && !(entry.Entity is EFContractRelatedEntryWithUpdate)) if (entry.State == System.Data.EntityState.Added || entry.State == System.Data.EntityState.Modified || entry.State == System.Data.EntityState.Deleted) { updateContractUpdateDetails = true; } } if (updateContractUpdateDetails) foreach (var entry in context.ChangeTracker.Entries()) { //Boaz 7-Aug-2012 //If any changed was made to a record in any table (entities related to the contract) which has //UpdateDate and UpdateUserID fields, these fields are updated to reflect the change. //These fields are NOT handled by the individual classes committing the changes to the //database - they are handled centrally here to cut-down on the code if (entry.Entity is EFContractRelatedEntryWithUpdate && entry.State != EntityState.Unchanged) //if (entry.Entity is EFContractRelatedEntryWithUpdate) { ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingDate = updateDate; ((EFContractRelatedEntryWithUpdate)entry.Entity).UpdatingUserID = UpdatingUserID; } if (entry.Entity is TopContractsEntities.ContractDoc && entry.State == EntityState.Deleted) { TopContractsEntities.User Userdetail = context.Users.Where(usr => usr.UserID == UpdatingUserID).SingleOrDefault(); if (Userdetail != null) { if (context.Roles.Where(rol => rol.RoleID == Userdetail.DefaultRoleID).SingleOrDefault().DeleteDocs == false) entry.State = EntityState.Unchanged; } } if (entry.Entity is TopContractsEntities.ContractActivity && entry.State == EntityState.Deleted) { TopContractsEntities.User Userdetail = context.Users.Where(usr => usr.UserID == UpdatingUserID).SingleOrDefault(); if (Userdetail != null) { if (context.Roles.Where(rol => rol.RoleID == Userdetail.DefaultRoleID).SingleOrDefault().DeleteActivities == false) entry.State = EntityState.Unchanged; else //********** Code Implemented for remove contract event with all associated Alerts,AlertsRecipiets & AlertsDone by Viplav on 20-Nov-2013********************************** { List<TopContractsEntities.ContractTodo> contToDos = context.ContractTodos.Where(tod => tod.ActivityID == ((TopContractsEntities.ContractActivity)entry.Entity).ActivityID).ToList(); foreach (TopContractsEntities.ContractTodo cntToDos in contToDos) { foreach (TopContractsEntities.ContractTodoRecipient cntToDosRec in context.ContractTodoRecipients.Where(tod => tod.TodoID == cntToDos.TodoID)) context.ContractTodoRecipients.Remove(cntToDosRec); foreach (TopContractsEntities.DoneTodo doneToDos in context.DoneTodos.Where(todo => todo.OriginalTodoID == cntToDos.TodoID)) context.DoneTodos.Remove(doneToDos); context.ContractTodos.Remove(cntToDos); } }//***************************************************************************************************************************************************************************** } } } } if (updateContractUpdateDetails) { efContract.ContractUpdateDetail.UpdateDate = updateDate; efContract.ContractUpdateDetail.UpdateUserID = UpdatingUserID; } //We want to keep tracking the changes after calling SaveChanges, for the purpose of auditing ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; objectContext.DetectChanges(); try { //Using SaveOptions.None to keep change-tracking... Requires objectContext.DetectChanges() before and objectContext.AcceptAllChanges() after... int rowsAffected = objectContext.SaveChanges(SaveOptions.None); } catch (System.Data.UpdateException updEx) { if (updEx.InnerException != null) if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") && updEx.InnerException.Message.Contains("FK_ContractTodos_ContractActivities")) { // Logger.Write(updEx, System.Diagnostics.TraceEventType.Warning); Logger.WriteGeneralWarning("Contract - Save()", "An attempt has been made to delete an Event With an Alert, in contract #{0}, by user #{1}", this.ID, UpdatingUserID); throw new ExceptionDataContractSaveDeleteEventWithAlert(); } else if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") && updEx.InnerException.Message.Contains("FK_ContractFields_ContractActivities")) { Logger.WriteGeneralWarning("Contract - Save()", "An attempt has been made to delete an Event linked to an event type field, in contract #{0}, by user #{1}", this.ID, UpdatingUserID); throw new ExceptionDataContractSaveDeleteEventWithEventTypeFields(); } else if (updEx.InnerException.Message.Contains("FK_Contracts_Contracts") && updEx.InnerException.Message.Contains("ParentContractID")) { Logger.WriteGeneralWarning("Contract - Save()", "An attempt has been made to delete contract #{0}, by user #{1}, when this contract is a parenty of another contract", this.ID, UpdatingUserID); throw new ExceptionDataContractDeleteDeleteContractWithChild(); } else if (updEx.InnerException.Message.Contains("DELETE statement conflicted with the REFERENCE constraint") && updEx.InnerException.Message.Contains("FK_ContractFields_ContractDocs")) { Logger.WriteGeneralWarning("Contract - Save()", "Contract - Save()", "An attempt has been made to delete a document linked to a document-type field, in contract #{0}, by user #{1}", this.ID, UpdatingUserID); throw new ExceptionDataContractSaveDeleteDocsWithDocumentTypeFields(); } else { // Logger.Write(updEx, System.Diagnostics.TraceEventType.Error); Logger.WriteExceptionError("Contract - Save()", updEx, "The attempt to save contract #{0}, by user #{1}, has failed", this.ID, UpdatingUserID); throw updEx; } } //Boaz-1 (8-Aug-2012) ------------------------------------------------------- //#region Setting the connection between new activities and their related new todos //if (this.Deleted == false) //{ // foreach (var newActivity in context.ChangeTracker.Entries()) // { // if (newActivity.State == System.Data.EntityState.Added && newActivity.Entity is TopContractsEntities.ContractActivity) // { // foreach (var newTodo in context.ChangeTracker.Entries()) // { // if (newTodo.State == System.Data.EntityState.Added && newTodo.Entity is TopContractsEntities.ContractTodo) // { // if ((newTodo.Entity as TopContractsEntities.ContractTodo).ActivityID == (newActivity.Entity as TopContractsEntities.ContractActivity).ActivityID) // { // (newActivity.Entity as TopContractsEntities.ContractActivity).ContractTodos.Add((newTodo.Entity as TopContractsEntities.ContractTodo)); // } // } // } // } // } //} //#endregion //TopContractsEntities.ContractTodo todoToChange = null; if (AuditChanges) { HistManager histManager = new HistManager(); int recordsWrittenToHistory = histManager.AuditChanges(updateDate, UpdatingUserID, this.New, this.Deleted, context.ChangeTracker.Entries().Where(e => e.State != System.Data.EntityState.Unchanged || e.Entity is TopContractsEntities.Contract)); } objectContext.AcceptAllChanges(); long contractIdSaved = -1; //will indicate failure, if no number is set foreach (var entry in context.ChangeTracker.Entries()) { Logger.Write("entering the loop - for context.ChangeTracker.Entries()", System.Diagnostics.TraceEventType.Verbose); if (entry.Entity is TopContractsEntities.Contract) { contractIdSaved = ((TopContractsEntities.Contract)entry.Entity).ContractID; } if (entry.Entity is TopContractsEntities.ContractDoc) { TopContractsEntities.ContractDoc efDoc = entry.Entity as TopContractsEntities.ContractDoc; TopContractsDAL10.ContractDoc doc = this.ContractDocs.SingleOrDefault(d => d.FileName == efDoc.FileName); if (doc != null) { if (doc.New) { doc.EntryId = efDoc.DocumentID; //This is done especially for the process of file copying... } } } if (entry.Entity is TopContractsEntities.ContractGallery) { TopContractsEntities.ContractGallery efGallery = entry.Entity as TopContractsEntities.ContractGallery; foreach (TopContractsDAL10.ContractGallery gallery in this.ContractGalleries.Where(g => g.GalleryName == efGallery.GalleryName).ToList()) { if (gallery.New) { gallery.EntryId = efGallery.GalleryID; //This is done especially for the process of file copying... } } } } if (this.Deleted) return 0; return contractIdSaved; }
/// <summary> /// Save the field groups and its fields into the database. /// </summary> /// <param action="Data">Collection of field groups which are getting saved.</param> /// <param action="AuditChanges">A boolean value equal to true, if application license allows audit changes.</param> /// <param action="UpdatingUserID">Id of the user who is updating the field groups.</param> /// <param action="CascadeDelete">Boolean value if cascade deletion is bieng done.</param> /// <returns>Returns an integer value for the total number of records being updated.</returns> //public static int SaveFields(FieldGroups Data, bool AuditChanges, long UpdatingUserID, bool CascadeDelete) public int SaveFields(FieldGroups Data, bool AuditChanges, long UpdatingUserID, bool CascadeDelete, ref Dictionary<int, long> EntityFieldIDsMap, bool isCatalogField, bool populateMapDictionary = false) { TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName()); TopContractsEntities.FieldGroup efFieldGroup = null; Dictionary<long, long> checkMax = new Dictionary<long, long>(); TopContractsEntities.Field efField = null; TopContractsEntities.FieldListItem efFieldListItem = null; foreach (TopContractsDAL10.SystemTables.FieldGroup fieldGroup in Data.Entries) { if (fieldGroup.New) { efFieldGroup = new TopContractsEntities.FieldGroup(); } else { efFieldGroup = context.FieldGroups.Where(c => c.FieldGroupID == fieldGroup.ID).SingleOrDefault(); } if (fieldGroup.Deleted == false) { efFieldGroup.InitCommonFields(efFieldGroup, fieldGroup, efFieldGroup.FieldGroupsLNGs, this.organizationIdentifier); efFieldGroup.DisplayIndependent = fieldGroup.DisplayIndependent; if (fieldGroup.VisibleToAllContractTypes) { efFieldGroup.ContractTypeVisibility = (byte)FieldGroupContractTypeVisibility.VisibleToAll; if (efFieldGroup.FieldGroupsContractTypesMAPs != null) { for (int i = efFieldGroup.FieldGroupsContractTypesMAPs.Count - 1; i >= 0; i--) { FieldGroupsContractTypesMAP map = efFieldGroup.FieldGroupsContractTypesMAPs.ElementAt(i); efFieldGroup.FieldGroupsContractTypesMAPs.Remove(map); context.FieldGroupsContractTypesMAPs.Remove(map); } } } else { //TODO - add implementation for FieldGroupContractTypeVisibility.HiddenFromTypes efFieldGroup.ContractTypeVisibility = (byte)FieldGroupContractTypeVisibility.VisibleToTypes; if (efFieldGroup.FieldGroupsContractTypesMAPs != null) { //Removing those who are missing from the received list for (int i = efFieldGroup.FieldGroupsContractTypesMAPs.Count - 1; i >= 0; i--) { FieldGroupsContractTypesMAP map = efFieldGroup.FieldGroupsContractTypesMAPs.ElementAt(i); if (fieldGroup.ContractTypeIDsVisible != null) { if (fieldGroup.ContractTypeIDsVisible.Any(v => v == map.ContractTypeID) == false) { if (CascadeDelete) { foreach (TopContractsEntities.Contract contract in map.ContractType.Contracts) { foreach (TopContractsEntities.Field fld in efFieldGroup.Fields) { //Changed by Boaz 16-05-2013: field-id is not used properly in case of catalog-fields - it should be replaced with the "fld.ContractType.SelectorFieldID" for the deletion purpose long fieldID = getFieldIdForContractFields(fld); if (fld.FieldType == (long)FieldTypes.EntityLink) { if (contract.ContractFields.Any(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fld.FieldID && cf.CatalogFieldID == fieldID)) { foreach (long recordCounter in contract.ContractFields.Where(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fld.FieldID && cf.CatalogFieldID == fieldID).Select(u => u.RecordCounter).ToList()) { context.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fld.FieldID && cf.CatalogFieldID == fieldID && cf.RecordCounter == recordCounter)); } } //context.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fld.FieldID && cf.CatalogFieldID == fieldID)); } else { if (contract.ContractFields.Any(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fld.FieldID)) { foreach (long recordCounter in contract.ContractFields.Where(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fld.FieldID).Select(u => u.RecordCounter).ToList()) { context.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fieldID && cf.RecordCounter == recordCounter)); } } //context.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldGroupID == fld.FieldGroupID && cf.FieldID == fieldID )); } } } } efFieldGroup.FieldGroupsContractTypesMAPs.Remove(map); context.FieldGroupsContractTypesMAPs.Remove(map); } } else { if (CascadeDelete) { foreach (TopContractsEntities.Contract contract in map.ContractType.Contracts) { for (int j = contract.ContractFields.Count - 1; j >= 0; j--) { contract.ContractFields.Remove(contract.ContractFields.ElementAt(j)); } } } efFieldGroup.FieldGroupsContractTypesMAPs.Remove(map); context.FieldGroupsContractTypesMAPs.Remove(map); } } } //Adding entries from the received list which don't exist yet if (fieldGroup.ContractTypeIDsVisible != null) { foreach (int indx in fieldGroup.ContractTypeIDsVisible) if (efFieldGroup.FieldGroupsContractTypesMAPs.Any(v => v.ContractTypeID == indx) == false) efFieldGroup.FieldGroupsContractTypesMAPs.Add(new FieldGroupsContractTypesMAP() { OrganizationIdentifier = this.organizationIdentifier, ContractTypeID = indx, FieldGroupID = (int)fieldGroup.ID }); } } if (fieldGroup.VisibleToAllRoles) { efFieldGroup.RolesVisibility = (byte)FieldGroupRoleVisibility.VisibleToAll; if (efFieldGroup.FieldGroupsRolesMAPs != null) { for (int i = efFieldGroup.FieldGroupsRolesMAPs.Count - 1; i >= 0; i--) { FieldGroupsRolesMAP map = efFieldGroup.FieldGroupsRolesMAPs.ElementAt(i); efFieldGroup.FieldGroupsRolesMAPs.Remove(map); context.FieldGroupsRolesMAPs.Remove(map); } } } else { //TODO - add implementation for FieldGroupRoleVisibility.HiddenFromRoles efFieldGroup.RolesVisibility = (byte)FieldGroupRoleVisibility.VisibleToRoles; if (efFieldGroup.FieldGroupsRolesMAPs != null) { //Removing those who are missing from the received list for (int i = efFieldGroup.FieldGroupsRolesMAPs.Count - 1; i >= 0; i--) { FieldGroupsRolesMAP map = efFieldGroup.FieldGroupsRolesMAPs.ElementAt(i); if (fieldGroup.RoleIDsVisible != null) { if (fieldGroup.RoleIDsVisible.Any(v => v == map.RoleID) == false) { efFieldGroup.FieldGroupsRolesMAPs.Remove(map); context.FieldGroupsRolesMAPs.Remove(map); } } else { efFieldGroup.FieldGroupsRolesMAPs.Remove(map); context.FieldGroupsRolesMAPs.Remove(map); } } } //Adding entries from the received list which don't exist yet if (fieldGroup.RoleIDsVisible != null) { foreach (int indx in fieldGroup.RoleIDsVisible) if (efFieldGroup.FieldGroupsRolesMAPs.Any(v => v.RoleID == indx) == false) efFieldGroup.FieldGroupsRolesMAPs.Add(new FieldGroupsRolesMAP() { OrganizationIdentifier = this.organizationIdentifier, RoleID = indx, FieldGroupID = (int)fieldGroup.ID, AllowView = true, AllowEdit = fieldGroup.RoleIDsEditable.Any(x => x == indx) }); else { efFieldGroup.FieldGroupsRolesMAPs.Single(v => v.RoleID == indx).AllowView = true; efFieldGroup.FieldGroupsRolesMAPs.Single(v => v.RoleID == indx).AllowEdit = fieldGroup.RoleIDsEditable.Any(x => x == indx); } } } if (fieldGroup.New == false) { // code to change record counters for the contracts fields (i.e from -999999 to 1) when a // single record field group is converted into a multiple record field group. if (context.FieldGroups.SingleOrDefault(fg => fg.FieldGroupID == efFieldGroup.FieldGroupID).SingleRecord == true && fieldGroup.SingleRecord == false) { List<TopContractsEntities.ContractField> contractFldsToRemoveIfAny = new List<TopContractsEntities.ContractField>(); foreach (TopContractsEntities.ContractField cFld in efFieldGroup.ContractFields) { if (cFld.RecordCounter > 0) contractFldsToRemoveIfAny.Add(cFld); else if (cFld.RecordCounter == (long)RecordCounter.Default) cFld.RecordCounter = 1; } if (contractFldsToRemoveIfAny.Count > 0) foreach (TopContractsEntities.ContractField contractFldToRemove in contractFldsToRemoveIfAny) { context.ContractFields.Remove(contractFldToRemove); } } } efFieldGroup.SingleRecord = fieldGroup.SingleRecord; // code area to remove contract fields if field group is being changed from multiple // record to single record. if (Convert.ToBoolean(efFieldGroup.SingleRecord) && efFieldGroup.ContractFields.Count > 0) { List<TopContractsEntities.ContractField> contractFldsToRemove = new List<TopContractsEntities.ContractField>(); if (efFieldGroup.ContractFields.Any(cf => cf.RecordCounter > 0)) { List<long> mappedContractIds = efFieldGroup.ContractFields.Where(cf => cf.RecordCounter > 0).Select(cf => cf.ContractID).Distinct().ToList(); foreach (long mappedContractId in mappedContractIds) { foreach (TopContractsEntities.ContractField contractFld in efFieldGroup.ContractFields.Where(ctFld => ctFld.ContractID == mappedContractId && ctFld.FieldGroupID == efFieldGroup.FieldGroupID)) { if (contractFld.RecordCounter == 1) { contractFld.RecordCounter = (long)RecordCounter.Default; contractFld.FieldValue = null; contractFld.LinkedUserID = null; contractFld.FieldValueNumeric = null; contractFld.FieldValueDate = null; contractFld.FieldValueTime = null; contractFld.FieldCurrencyID = null; contractFld.LinkedEventID = null; contractFld.LinkedUserID = null; contractFld.LinkedDocumentID = null; contractFld.LinkedContractID = null; } else contractFldsToRemove.Add(contractFld); } } } if (contractFldsToRemove.Count > 0) foreach (TopContractsEntities.ContractField contractFldToRemove in contractFldsToRemove) { context.ContractFields.Remove(contractFldToRemove); } } if (fieldGroup.GroupFields == null) { //do nothing here - no fields } else { foreach (TopContractsDAL10.SystemTables.Field field in fieldGroup.GroupFields.Entries) { if (field.New) { efField = new TopContractsEntities.Field(); } else { efField = context.Fields.Where(c => c.FieldID == field.ID).SingleOrDefault(); } if (field.Deleted == false) { efField.InitCommonFields(efField, field, efField.FieldsLNGs, this.organizationIdentifier); efField.FieldLength = field.FieldLength; efField.UseFirstAsDefault = field.UseFirstAsDefault; efField.FieldType = field.FieldType; efField.Mandatory = field.Mandatory; efField.AllowMultipleSelection = field.AllowMultipleSelection; efField.MandatoryCurrencyID = field.MandatoryCurrencyID; efField.DisplayFormat = field.DisplayFormat; efField.MandatoryEventTypeID = field.MandatoryEventTypeID; efField.Formula = field.Formula; efField.IsCalculatedCurrency = field.IsCalculatedCurrency; efField.FieldIDForCurrency = field.FieldIDForCurrency; efField.AllowUnauthorizedUsers = field.AllowUnauthorizedUsers; efField.LinkedFieldID = field.LinkedFieldID; efField.DefaultValue = field.DefaultValue; efField.IsWholeNumber = field.IsWholeNumber; efField.MinimumNumericValue = field.MinimumNumericValue; efField.MaximumNumericValue = field.MaximumNumericValue; //if (!string.IsNullOrEmpty(field.ExternalID)) // efField.ExternalID = field.ExternalID.Substring(0, field.ExternalID.IndexOf(Constants.entityFieldsDivider)); //Modified by Salil on 19-July-2013; //this condition is true if the catalog field is changed in fieldgroup. Eg:- Catalog A is replcaed by Catalog B in a FieldGroup FG. if (efField.LinkedEntityID != field.LinkedEntityID) { List<long> ctlFldLst = context.ContractTypesFieldsToCreateDefaults.Where(t => t.ContractTypeID == efField.LinkedEntityID).Select(t => t.FieldID).ToList(); foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(fld => fld.FieldGroupID == fieldGroup.ID && fld.FieldID == field.ID && fld.CatalogFieldID != null && ctlFldLst.Contains((long)fld.CatalogFieldID)).ToList()) { context.ContractFields.Remove(contractField); } } efField.LinkedEntityID = field.LinkedEntityID; //if (field.FieldListItems != null && field.FieldType == (int)FieldTypes.ListSingle) if (field.FieldListItems != null) { if (field.FieldListItems.Entries.Count > 0) { //------------------------------------------------ foreach (TopContractsDAL10.SystemTables.FieldListItem fieldListItem in field.FieldListItems.Entries) { if (fieldListItem.New) { efFieldListItem = new TopContractsEntities.FieldListItem(); } else { efFieldListItem = context.FieldListItems.Where(c => c.FieldListItemID == fieldListItem.ID).SingleOrDefault(); } if (fieldListItem.Deleted == false) { efFieldListItem.InitCommonFields(efFieldListItem, fieldListItem, efFieldListItem.FieldListItemsLNGs, this.organizationIdentifier); //efFieldListItem.FieldID = (int)fieldListItem.FieldID; //TODO - any more?... } if (fieldListItem.New) efField.FieldListItems.Add(efFieldListItem); else { if (fieldListItem.Deleted && efFieldListItem != null) { if (CascadeDelete) { string strFieldListItemID = fieldListItem.ID.ToString(); var t = context.Contracts.Where(ct => ct.ContractFields.Any(ctfld => ctfld.FieldID == field.ID && ctfld.FieldValue == strFieldListItemID)); foreach (TopContractsEntities.Contract contract in context.Contracts.Where(ct => ct.ContractFields.Any(ctfld => ctfld.FieldID == field.ID && ctfld.FieldValue == strFieldListItemID))) { if (field.FieldType == (int)FieldTypes.ListSingle) foreach (var ctrlfld in contract.ContractFields.Where(ctfld => ctfld.FieldID == field.ID && ctfld.FieldValue == strFieldListItemID)) ctrlfld.FieldValue = null; else contract.ContractFields.Where(ctfld => ctfld.FieldID == field.ID).SingleOrDefault().FieldValue = null; } if (context.ContractFields.Any(ctfld => ctfld.CatalogFieldID == field.ID && ctfld.FieldValue == strFieldListItemID)) { foreach (TopContractsEntities.Contract contract in context.Contracts.Where(ct => ct.ContractFields.Any(ctfld => ctfld.CatalogFieldID == field.ID && ctfld.FieldValue == strFieldListItemID))) { if (field.FieldType == (int)FieldTypes.ListSingle) foreach (var ctrlfld in contract.ContractFields.Where(ctfld => ctfld.CatalogFieldID == field.ID && ctfld.FieldValue == strFieldListItemID)) ctrlfld.FieldValue = null; } } } efFieldListItem.DeleteLanguageEntries(efFieldListItem, context.FieldListItemsLNGs, efFieldListItem.FieldListItemsLNGs); efFieldListItem.Field.FieldListItems.Remove(efFieldListItem); context.FieldListItems.Remove(efFieldListItem); } } } } //------------------------------------------------ } //TODO - any more?... } if (field.New) efFieldGroup.Fields.Add(efField); else { if (field.Deleted && efField != null) { //if (CascadeDelete && efField.FieldGroup.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll) //{ // foreach (TopContractsEntities.Contract contract in context.Contracts) // { // contract.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldID == efField.EntryIdentifier)); // } // foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(cf => cf.FieldID == efField.EntryIdentifier)) // { // context.ContractFields.Remove(contractField); // } //} //if (CascadeDelete && efField.FieldGroup.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && efField.FieldGroup.FieldGroupsContractTypesMAPs != null) //{ // foreach (TopContractsEntities.FieldGroupsContractTypesMAP contractTypeMap in efField.FieldGroup.FieldGroupsContractTypesMAPs) // { // foreach (TopContractsEntities.Contract contract in contractTypeMap.ContractType.Contracts) // { // contract.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldID == efField.EntryIdentifier)); // } // foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(cf => cf.FieldID == efField.EntryIdentifier)) // { // context.ContractFields.Remove(contractField); // } // } //} if (CascadeDelete) { foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(fld => fld.FieldID == efField.FieldID).ToList()) { context.ContractFields.Remove(contractField); } if (efFieldGroup.FieldGroupsContractTypesMAPs.Count() == 1) { long ContractTypeContractID = Utilities.contractTypeContractsID; if (efFieldGroup.FieldGroupsContractTypesMAPs.First().ContractType.ParentContractTypeID != ContractTypeContractID || efFieldGroup.FieldGroupsContractTypesMAPs.First().ContractType.ParentContractTypeID == null) { foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(fld => fld.CatalogFieldID == efField.FieldID).ToList()) { context.ContractFields.Remove(contractField); } } } } efField.DeleteLanguageEntries(efField, context.FieldsLNGs, efField.FieldsLNGs); for (int indx = efField.FieldListItems.Count() - 1; indx >= 0; indx--) { TopContractsEntities.FieldListItem itm = efField.FieldListItems.ElementAt(indx); itm.DeleteLanguageEntries(itm, context.FieldListItemsLNGs, itm.FieldListItemsLNGs); context.FieldListItems.Remove(itm); } efField.FieldGroup.Fields.Remove(efField); context.Fields.Remove(efField); } } } } } if (fieldGroup.New) context.FieldGroups.Add(efFieldGroup); else { if (fieldGroup.Deleted && efFieldGroup != null) { efFieldGroup.DeleteLanguageEntries(efFieldGroup, context.FieldGroupsLNGs, efFieldGroup.FieldGroupsLNGs); for (int indx = efFieldGroup.Fields.Count() - 1; indx >= 0; indx--) { TopContractsEntities.Field fld = efFieldGroup.Fields.ElementAt(indx); fld.DeleteLanguageEntries(fld, context.FieldsLNGs, fld.FieldsLNGs); for (int indx2 = fld.FieldListItems.Count() - 1; indx2 >= 0; indx2--) { TopContractsEntities.FieldListItem itm = fld.FieldListItems.ElementAt(indx2); itm.DeleteLanguageEntries(itm, context.FieldListItemsLNGs, itm.FieldListItemsLNGs); context.FieldListItems.Remove(itm); } //if (CascadeDelete && fld.FieldGroup.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll) //{ // foreach (TopContractsEntities.Contract contract in context.Contracts) // { // contract.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldID == fld.EntryIdentifier)); // } // foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(cf => cf.FieldID == fld.EntryIdentifier)) // { // context.ContractFields.Remove(contractField); // } //} //if (CascadeDelete && fld.FieldGroup.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToTypes && fld.FieldGroup.FieldGroupsContractTypesMAPs != null) //{ // foreach (TopContractsEntities.FieldGroupsContractTypesMAP contractTypeMap in fld.FieldGroup.FieldGroupsContractTypesMAPs) // { // foreach (TopContractsEntities.Contract contract in contractTypeMap.ContractType.Contracts) // { // contract.ContractFields.Remove(contract.ContractFields.Single(cf => cf.FieldID == fld.EntryIdentifier)); // } // foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(cf => cf.FieldID == fld.EntryIdentifier)) // { // context.ContractFields.Remove(contractField); // } // } //} // Mohit - Added code to remove all the contract field of a Field group being removed. if (CascadeDelete) foreach (TopContractsEntities.ContractField contractField in context.ContractFields.Where(fg => fg.FieldGroupID == efFieldGroup.FieldGroupID).ToList()) { context.ContractFields.Remove(contractField); } context.Fields.Remove(fld); } for (int indx = efFieldGroup.FieldGroupsContractTypesMAPs.Count() - 1; indx >= 0; indx--) { TopContractsEntities.FieldGroupsContractTypesMAP map = efFieldGroup.FieldGroupsContractTypesMAPs.ElementAt(indx); context.FieldGroupsContractTypesMAPs.Remove(map); } for (int indx = efFieldGroup.FieldGroupsRolesMAPs.Count() - 1; indx >= 0; indx--) { TopContractsEntities.FieldGroupsRolesMAP map = efFieldGroup.FieldGroupsRolesMAPs.ElementAt(indx); context.FieldGroupsRolesMAPs.Remove(map); } context.FieldGroups.Remove(efFieldGroup); } } } if (!populateMapDictionary) { context.SaveChanges(); } else { ObjectContext objectContext = ((IObjectContextAdapter)context).ObjectContext; objectContext.DetectChanges(); objectContext.SaveChanges(SaveOptions.None); //This will fill the IDs with new values, needed for the next part... bool structuralChangeOccurred = false; // flag raised when a structural change is occurred. //bool informationalChange = false; // flag raised when a change other than structure is occurred. long nonStructuralChanges = 0; foreach (var changedEntry in context.ChangeTracker.Entries()) { if (changedEntry.State == System.Data.EntityState.Added && changedEntry.Entity is TopContractsEntities.Field) { if (changedEntry.CurrentValues["ExternalID"] != null) { string externalId = changedEntry.CurrentValues["ExternalID"].ToString(); if (externalId.IndexOf(Constants.entityFieldsDivider) >= 0) { string id = externalId.Substring(externalId.IndexOf(Constants.entityFieldsDivider)); id = id.Replace(Constants.entityFieldsDivider, ""); int originalFieldID = Convert.ToInt32(id); EntityFieldIDsMap.Add(originalFieldID, Convert.ToInt64(changedEntry.CurrentValues["FieldID"])); } } if (isCatalogField == false) structuralChangeOccurred = true; else nonStructuralChanges += 1; } else if (changedEntry.Entity is TopContractsEntities.Field && changedEntry.State == System.Data.EntityState.Deleted) { if (isCatalogField == false) structuralChangeOccurred = true; else nonStructuralChanges += 1; } else if (changedEntry.Entity is TopContractsEntities.Field && changedEntry.State == System.Data.EntityState.Modified) { if (isCatalogField == false) nonStructuralChanges += 1; else nonStructuralChanges += 1; } else if (changedEntry.Entity is TopContractsEntities.FieldsLNG && changedEntry.State == System.Data.EntityState.Modified) nonStructuralChanges += 1; else if (changedEntry.Entity is TopContractsEntities.FieldGroup && changedEntry.State == System.Data.EntityState.Added) structuralChangeOccurred = true; else if (changedEntry.Entity is TopContractsEntities.FieldGroup && changedEntry.State == System.Data.EntityState.Deleted) structuralChangeOccurred = true; else if (changedEntry.Entity is TopContractsEntities.FieldGroup && changedEntry.State == System.Data.EntityState.Modified) nonStructuralChanges += 1; else if (changedEntry.Entity is TopContractsEntities.FieldGroupsLNG && changedEntry.State == System.Data.EntityState.Modified) nonStructuralChanges += 1; else if (changedEntry.Entity is TopContractsEntities.FieldGroupsContractTypesMAP && changedEntry.State == System.Data.EntityState.Added) structuralChangeOccurred = true; else if (changedEntry.Entity is TopContractsEntities.FieldGroupsContractTypesMAP && changedEntry.State == System.Data.EntityState.Deleted) structuralChangeOccurred = true; else if (changedEntry.Entity is TopContractsEntities.FieldGroupsRolesMAP && changedEntry.State == System.Data.EntityState.Added) structuralChangeOccurred = true; else if (changedEntry.Entity is TopContractsEntities.FieldGroupsRolesMAP && changedEntry.State == System.Data.EntityState.Deleted) structuralChangeOccurred = true; else if (changedEntry.Entity is TopContractsEntities.FieldGroupsRolesMAP && changedEntry.State == System.Data.EntityState.Modified) structuralChangeOccurred = true; } objectContext.AcceptAllChanges(); //if (isCatalogField && structuralChangeOccurred == false) //{ // foreach (long fieldId in addedFieldIDs) // { // if(structuralChangeOccurred==false) // } //} TopContractsDAL10.CachedData.ClearCachedData(); // To clear cached data of Fields Lng. ApplicationCachedData.reInitCacheData(); // To re-initialize server side cache. if (structuralChangeOccurred) ApplicationCachedData.UpdateContractStructureCacheTicks(); else if (nonStructuralChanges > 0) if (isCatalogField) ApplicationCachedData.UpdateCatalogCacheTicks(); else ApplicationCachedData.UpdateContractDisplayCacheTicks(); } //long ContractTypeContractsID = ConfigurationProvider.Default.ContractTypeContracts.ContractTypeContractsID; long ContractTypeContractsID = Utilities.contractTypeContractsID; // Code implemented by Viplav on 17 june 2013 for remove webconfig concept foreach (TopContractsEntities.FieldGroup efFldGrp in context.FieldGroups.Where(fgrp => fgrp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll || fgrp.FieldGroupsContractTypesMAPs.Any(cTypeMap => cTypeMap.ContractType.ParentContractTypeID == ContractTypeContractsID) == true)) { List<long> contractIDs = new List<long>(); List<long?> recordcounters = new List<long?>(); if (efFldGrp.ContractTypeVisibility == (byte)FieldGroupContractTypeVisibility.VisibleToAll) { foreach (TopContractsEntities.Field efFld in efFldGrp.Fields) foreach (TopContractsEntities.Contract contract in context.Contracts.Where(c => c.ContractType.ParentContractTypeID == ContractTypeContractsID && c.ContractFields.Any(cf => cf.FieldID == efFld.FieldID) == false)) { if (efFld.FieldType == (int)FieldTypes.EntityLink) { foreach (TopContractsEntities.ContractTypesFieldsToCreateDefault contDef in context.ContractTypesFieldsToCreateDefaults.Where(c => c.ContractTypeID == efFld.LinkedEntityID)) { /* change this check */ if (contract.ContractFields.Any(cf => cf.FieldID == efFld.FieldID && cf.FieldGroupID == efFldGrp.FieldGroupID && cf.CatalogFieldID == contDef.FieldID) == false) { recordcounters = contract.ContractFields.Where(fg => fg.FieldGroupID == efFldGrp.FieldGroupID).Select(c => c.RecordCounter).Distinct().ToList(); TopContractsEntities.Field efDefFld = context.Fields.Where(defld => defld.FieldID == contDef.FieldID).SingleOrDefault(); if (recordcounters.Count != 0) { foreach (long? recordcounter in recordcounters) { //**************Code Commented by Viplav on 3 mat 2013 for resolving the issue of save undefined text in contract fields********** //if ((efFld.FieldType == (int)FieldTypes.Autonumber && recordcounter > 0) || efFld.FieldGroup.SingleRecord == true) //{ // CreateCounterforNewField(context, checkMax, efFld, contract, recordcounter); //} //else //{ //***************************************************************************************** contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, CatalogFieldID = efDefFld.FieldID, FieldValue = (efDefFld.FieldType == (int)FieldTypes.ListSingle && efDefFld.FieldListItems.Count > 0 && efDefFld.UseFirstAsDefault == true ? efDefFld.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = (recordcounter == null ? Convert.ToInt64(RecordCounter.Default) : recordcounter) }); //} } } else { contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, CatalogFieldID = efDefFld.FieldID, FieldValue = (efDefFld.FieldType == (int)FieldTypes.ListSingle && efDefFld.FieldListItems.Count > 0 && efDefFld.UseFirstAsDefault == true ? efDefFld.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } } } else { recordcounters = contract.ContractFields.Where(fg => fg.FieldGroupID == efFldGrp.FieldGroupID).Select(c => c.RecordCounter).Distinct().ToList(); if (recordcounters.Count != 0) { foreach (long? recordcounter in recordcounters) { if ((efFld.FieldType == (int)FieldTypes.Autonumber && recordcounter > 0) || (efFld.FieldGroup.SingleRecord == true && efFld.FieldType == (int)FieldTypes.Autonumber)) { CreateCounterforNewField(context, checkMax, efFld, contract, recordcounter); } else { contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, FieldValue = (efFld.FieldType == (int)FieldTypes.ListSingle && efFld.FieldListItems.Count > 0 && efFld.UseFirstAsDefault == true ? efFld.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = (recordcounter == null ? Convert.ToInt64(RecordCounter.Default) : recordcounter) }); } } } else { contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, FieldValue = (efFld.FieldType == (int)FieldTypes.ListSingle && efFld.FieldListItems.Count > 0 && efFld.UseFirstAsDefault == true ? efFld.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } } } else { if (efFldGrp.FieldGroupsContractTypesMAPs != null) foreach (FieldGroupsContractTypesMAP fgcMap in efFldGrp.FieldGroupsContractTypesMAPs) { if (context.Contracts.Any(c => c.ContractTypeID == fgcMap.ContractTypeID)) contractIDs.AddRange(context.Contracts.Where(c => c.ContractTypeID == fgcMap.ContractTypeID && c.ContractType.ParentContractTypeID == ContractTypeContractsID).Select(c => c.ContractID)); } if (contractIDs.Count > 0) foreach (TopContractsEntities.Field efFld in efFldGrp.Fields) { foreach (TopContractsEntities.Contract contract in context.Contracts.Where(c => (c.ContractFields.Any(cf => cf.FieldID == efFld.FieldID) == false) && c.ContractType.ParentContractTypeID == ContractTypeContractsID)) { if (contractIDs.Contains(contract.ContractID)) { if (efFld.FieldType == (int)FieldTypes.EntityLink) { foreach (TopContractsEntities.ContractTypesFieldsToCreateDefault contDef in context.ContractTypesFieldsToCreateDefaults.Where(c => c.ContractTypeID == efFld.LinkedEntityID)) { /* change this check */ if (contract.ContractFields.Any(cf => cf.FieldID == efFld.FieldID && cf.FieldGroupID == efFldGrp.FieldGroupID && cf.CatalogFieldID == contDef.FieldID) == false) { recordcounters = contract.ContractFields.Where(fg => fg.FieldGroupID == efFldGrp.FieldGroupID).Select(c => c.RecordCounter).Distinct().ToList(); if (recordcounters.Count != 0) { foreach (long? recordcounter in recordcounters) { //**************Code Commented by Viplav on 3 mat 2013 for resolving the issue of save undefined text in contract fields********** //if ((efFld.FieldType == (int)FieldTypes.Autonumber && recordcounter > 0) || efFld.FieldGroup.SingleRecord == true) //{ // CreateCounterforNewField(context, checkMax, efFld, contract, recordcounter); //} //else //{ //******************************************************************************** contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, CatalogFieldID = contDef.Field.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.FieldListItems.Count > 0 && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = (recordcounter == null ? Convert.ToInt64(RecordCounter.Default) : recordcounter) }); //} } } else { contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, CatalogFieldID = contDef.Field.FieldID, FieldValue = (contDef.Field.FieldType == (int)FieldTypes.ListSingle && contDef.Field.FieldListItems.Count > 0 && contDef.Field.UseFirstAsDefault == true ? contDef.Field.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } } } else { recordcounters = contract.ContractFields.Where(fg => fg.FieldGroupID == efFldGrp.FieldGroupID).Select(c => c.RecordCounter).Distinct().ToList(); if (recordcounters.Count != 0) { foreach (long? recordcounter in recordcounters) { if ((efFld.FieldType == (int)FieldTypes.Autonumber && recordcounter > 0) || (efFld.FieldGroup.SingleRecord == true && efFld.FieldType == (int)FieldTypes.Autonumber)) { CreateCounterforNewField(context, checkMax, efFld, contract, recordcounter); } else { contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, FieldValue = (efFld.FieldType == (int)FieldTypes.ListSingle && efFld.FieldListItems.Count > 0 && efFld.UseFirstAsDefault == true ? efFld.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = (recordcounter == null ? Convert.ToInt64(RecordCounter.Default) : recordcounter) }); } } } else { contract.ContractFields.Add(new TopContractsEntities.ContractField() { FieldGroupID = efFld.FieldGroupID, FieldID = efFld.FieldID, FieldValue = (efFld.FieldType == (int)FieldTypes.ListSingle && efFld.FieldListItems.Count > 0 && efFld.UseFirstAsDefault == true ? efFld.FieldListItems.First().FieldListItemID.ToString() : ""), RecordCounter = Convert.ToInt64(RecordCounter.Default) }); } } } } } contractIDs = new List<long>(); bool noMap = false; if (efFldGrp.FieldGroupsContractTypesMAPs == null) noMap = true; else if (efFldGrp.FieldGroupsContractTypesMAPs.Count == 0) noMap = true; if (noMap) contractIDs.AddRange(context.Contracts.Select(c => c.ContractID)); else foreach (TopContractsEntities.Contract contract in context.Contracts.Where(c => c.ContractType.ParentContractTypeID == ContractTypeContractsID)) { if (efFldGrp.FieldGroupsContractTypesMAPs.Any(fgcMap => fgcMap.ContractTypeID == contract.ContractTypeID) == false) contractIDs.Add(contract.ContractID); } DateTime updateDate = DateTime.Now; if (contractIDs.Count > 0) foreach (int cId in contractIDs) { TopContractsEntities.Contract contract = context.Contracts.Single(c => c.ContractID == cId); if (contract.ContractFields.Any(cf => cf.FieldGroupID == efFldGrp.FieldGroupID)) { List<TopContractsEntities.ContractField> cFields = contract.ContractFields.Where(cf => cf.FieldGroupID == efFldGrp.FieldGroupID).ToList(); for (int indx = cFields.Count - 1; indx >= 0; indx--) { TopContractsEntities.ContractField efCtrctFld = cFields[indx]; context.ContractFields.Remove(efCtrctFld); if (AuditChanges) { HistManager histManager = new HistManager(); histManager.AuditFieldRemoval(updateDate, UpdatingUserID, efCtrctFld); } } } } } } return context.SaveChanges(); //return -1; }