/// <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;
        }
        /// <summary>
        /// Updating catalogs (only their names, not their fields or records)
        /// </summary>
        /// <param name="entity">The contract-type defining the catalog</param>
        /// <param name="newEntryTexts">Name/Description of the catalog</param>
        /// <param name="CreateNew">true to signal the creation of a new catalog, false for updating existing catalogs</param>
        public void SaveEntityGroup(TopContractsEntities.ContractType entity, Dictionary<string, SysTableEntryText> newEntryTexts, bool CreateNew)
        {
            TopContractsV01Entities context = new TopContractsV01Entities(Utilities.getTestEnvName());
            TopContractsEntities.FieldGroup efFieldGroup = new TopContractsEntities.FieldGroup();

            //efFieldGroup.InitCommonFields(efFieldGroup, entity, efFieldGroup.FieldGroupsLNGs);
            if (CreateNew)
            {
                foreach (var cTypeLng in entity.ContractTypesLNGs)
                {
                    efFieldGroup.FieldGroupsLNGs.Add(new FieldGroupsLNG { OrganizationIdentifier = this.organizationIdentifier, CultureId = cTypeLng.CultureId, DescShort = cTypeLng.DescShort, DescLong = cTypeLng.DescLong });
                }
                efFieldGroup.OrganizationIdentifier = this.organizationIdentifier;
                efFieldGroup.ContractTypeVisibility = (byte)FieldGroupContractTypeVisibility.VisibleToTypes;
                efFieldGroup.RolesVisibility = (byte)FieldGroupRoleVisibility.VisibleToAll;
                efFieldGroup.Inactive = false;
                efFieldGroup.Locked = false;
                efFieldGroup.DisplayOrder = null;
                efFieldGroup.ExternalID = null;
                efFieldGroup.SingleRecord = true;
                efFieldGroup.FieldGroupsContractTypesMAPs.Add(new FieldGroupsContractTypesMAP { OrganizationIdentifier = this.organizationIdentifier, ContractTypeID = entity.ContractTypeID });
                context.FieldGroups.Add(efFieldGroup);
            }
            else
            {
                // code to modify action of the entity field group when action of an entity is changed.
                if (context.FieldGroupsContractTypesMAPs.Any(u => u.ContractTypeID == entity.ContractTypeID))
                {
                    List<FieldGroupsLNG> fgLngs = context.FieldGroupsContractTypesMAPs.SingleOrDefault(u => u.ContractTypeID == entity.ContractTypeID).FieldGroup.FieldGroupsLNGs.ToList();
                    foreach (var fgLng in fgLngs)
                    {
                        fgLng.DescShort = newEntryTexts.SingleOrDefault(l => l.Key == fgLng.CultureId.Trim()).Value.DescShort;
                        fgLng.DescLong = newEntryTexts.SingleOrDefault(l => l.Key == fgLng.CultureId.Trim()).Value.DescLong;
                    }
                }
            }
            context.SaveChanges();
        }