/// <summary>
        /// Checks whether a role has permission to edit field groups mapped with a contract.
        /// </summary>
        /// <param name="efFieldGroups">List of TopContractEntities.FieldGroup objects mapped with the contract.</param>
        /// <param name="role">TopContractEntities.Role object required to be checked.</param>
        /// <returns>Boolean value to ensure whether role has permission to edit the field groups mapped with the contract</returns>
        public bool RolePermittedToEditContractFields(List<TopContractsEntities.FieldGroup> efFieldGroups, TopContractsEntities.Role role)
        {
            //bool AllowViewFields = false;
            bool AllowEditFields = false;

            foreach (TopContractsEntities.FieldGroup efFieldGroup in efFieldGroups)
            {
                if (efFieldGroup.RolesVisibility == (byte)FieldGroupRoleVisibility.VisibleToAll)
                {
                    AllowEditFields = true;
                }
                else
                {
                    if (efFieldGroup.FieldGroupsRolesMAPs.Any(ro => ro.RoleID == role.RoleID))
                    {
                        if (efFieldGroup.FieldGroupsRolesMAPs.SingleOrDefault(ro => ro.RoleID == role.RoleID).AllowEdit == true)
                            AllowEditFields = true;

                        //if (efFieldGroup.FieldGroupsRolesMAPs.SingleOrDefault(ro => ro.RoleID == role.RoleID).AllowView == true)
                        //    AllowViewFields = false;
                    }
                }

                if (AllowEditFields == true)
                    break;
            }
            return AllowEditFields;
        }
 internal Exception UpdateEfContract(ref TopContractsEntities.Contract efContract, int UpdatingUserID, DateTime UpdateDate)
 {
     try
     {
         efContract.ContractTypeID = Properties.ContractTypeID;
         efContract.DisplayCurrencyID = Properties.DisplayCurrencyID;
         efContract.Description = Properties.Description;
         efContract.ExternalID = Properties.ExternalID;
         efContract.Name = Properties.Name;
         efContract.ParentContractID = Properties.ParentContractID;
         efContract.StatusID = Properties.StatusID;
         if (efContract.ContractUpdateDetail == null) //This is a new entry
             efContract.ContractUpdateDetail = new ContractUpdateDetail() { ContractID = efContract.ContractID };
         efContract.ContractUpdateDetail.UpdateDate = UpdateDate;
         efContract.ContractUpdateDetail.UpdateUserID = UpdatingUserID;
     }
     catch (Exception ex)
     {
         return ex;
     }
     return null;
 }
 private void updateEfContract(ref TopContractsEntities.Contract efContract, ref TopContractsV01Entities context)
 {
     if (this.Properties != null)
         this.Properties.updateEfFields(ref efContract);
     Logger.WriteGeneralVerbose("Contract class - updateEfContract", "updating ContractActivity of {0}", this.ID);
     //Logger.Write("updating ContractActivity of " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
     if (this.ContractActivities != null)
         foreach (ContractActivity activity in this.ContractActivities.Where(ent => (ent.Deleted && ent.New) != true))
             activity.UpdateEntity(ref context, efContract.ContractActivities, context.ContractActivities, this.ID, this.Properties.OrganizationIdentifier);
     Logger.WriteGeneralVerbose("Contract class - updateEfContract", "updating ContractApplications of {0}", this.ID);
     //Logger.Write("updating ContractApplications of " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
     if (this.ContractApplications != null)
         foreach (ContractApplication application in this.ContractApplications.Where(ent => (ent.Deleted && ent.New) != true))
             application.UpdateEntity(ref context, efContract.ContractApplications, context.ContractApplications, this.ID, this.Properties.OrganizationIdentifier);
     Logger.WriteGeneralVerbose("Contract class - updateEfContract", "updating ContractDocs of {0}", this.ID);
     //Logger.Write("updating ContractDocs of " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
     if (this.ContractDocs != null)
         foreach (ContractDoc doc in this.ContractDocs.Where(ent => (ent.Deleted && ent.New) != true))
             doc.UpdateEntity(ref context, efContract.ContractDocs, context.ContractDocs, this.ID, this.Properties.OrganizationIdentifier);
     Logger.WriteGeneralVerbose("Contract class - updateEfContract", "updating ContractGalleries of {0}", this.ID);
     if (this.ContractGalleries != null)
         foreach (ContractGallery gallery in this.ContractGalleries.Where(ent => (ent.Deleted && ent.New) != true))
             gallery.UpdateEntity(ref context, efContract.ContractGalleries, context.ContractGalleries, this.ID, this.Properties.OrganizationIdentifier);
     Logger.WriteGeneralVerbose("Contract class - updateEfContract", "updating ContractFieldGroups of {0}", this.ID);
     //Logger.Write("updating ContractFieldGroups of " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
     if (this.ContractFieldGroups != null)
         foreach (ContractFieldGroup FieldGroup in this.ContractFieldGroups.Where(ent => (ent.Deleted && ent.New) != true))
             FieldGroup.UpdateEntity(ref context, efContract.ContractFields, null, ID, this.Properties.OrganizationIdentifier);
     Logger.WriteGeneralVerbose("Contract class - updateEfContract", "updating ContractTodos of {0}", this.ID);
     //Logger.Write("updating ContractTodos of " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
     if (this.ContractTodos != null)
         foreach (ContractTodo Todo in this.ContractTodos.Where(ent => (ent.Deleted && ent.New) != true))
             //Todo.UpdateEntity(ref context, efContract.ContractTodos, efContract.ContractActivities.First().ContractTodos, this.ID);
             Todo.UpdateEntity(ref context, efContract.ContractTodos, context.ContractTodos, this.ID, this.Properties.OrganizationIdentifier);
     //var xxxx = efContract.ContractActivities.FirstOrDefault().ContractTodos;
     //var yyyy = context.ContractTodos;
     Logger.WriteGeneralVerbose("Contract class - updateEfContract", "updating ContractUsers of {0}", this.ID);
     //Logger.Write("updating ContractUsers of " + this.ID.ToString(), System.Diagnostics.TraceEventType.Information);
     if (this.ContractUsers != null)
         foreach (ContractUser User in this.ContractUsers.Where(ent => (ent.Deleted && ent.New) != true))
             User.UpdateEntity(ref context, efContract.ContractUsers, context.ContractUsers, this.ID, this.Properties.OrganizationIdentifier);
 }
        /// <summary>
        /// Given a field-ID of a contract-field which is of entity-type, this function returns the 
        /// field-ID of the corresponding field of the fields table (a group-field)
        /// </summary>
        /// <param name="context"></param>
        /// <param name="contractField"></param>
        /// <returns></returns>
        private static long getFieldIdFromContractFieldId(TopContractsV01Entities context, TopContractsEntities.ContractField contractField)
        {

            try
            {
                foreach (TopContractsEntities.Field field in contractField.FieldGroup.Fields.Where(flds => flds.ContractType != null))
                {
                    if (field.ContractType != null)
                    {
                        if (field.ContractType.ContractTypesFieldsToCreateDefaults.Any(ftc => ftc.FieldID == contractField.FieldID))
                            return field.FieldID;
                    }
                    //if (field.FieldType == (byte)TopContractsCommon10.FieldTypes.EntityLink)
                    //{
                    //    if (field.ContractType.SelectorFieldID == contractField.FieldID)
                    //        return field.FieldID;
                    //}
                    //else
                    //{
                    //    return field.ContractType.ContractTypesFieldsToCreateDefaults.Single(ftc => ftc.FieldID == contractField.FieldID).FieldID;
                    //}
                }
                return (long)contractField.FieldGroup.Fields.Where(flds => flds.ContractType != null).Single(flds => flds.ContractType.SelectorFieldID == contractField.FieldID).FieldID;
            }
            catch
            {
                return contractField.FieldID;
            }
        }
        /// <summary>
        /// Given a field-ID of a group-field which is of entity-type, this function returns the field-ID 
        /// used for  any contract-field created by that field (instead of the field-ID which would have been created
        /// there for any field which is not of entity-type.
        /// </summary>
        /// <param name="fld"></param>
        /// <returns></returns>
        private static long getFieldIdForContractFields(TopContractsEntities.Field fld)
        {
            if (fld.FieldType == (int)TopContractsCommon10.FieldTypes.EntityLink)
                if (fld.ContractType != null)
                    if (fld.ContractType.SelectorFieldID != null)
                        return (long)fld.ContractType.SelectorFieldID; //The ContractType is linked through the LinkedEntityId column of Fields table

            return fld.FieldID;
        }
        /// <summary>
        ///Here we determine whether a Field-Group is of the kind defining a catalog (then the function returns false),
        ///or it is one that is used by normal contracts (and then the function returns true)
        /// </summary>
        /// <param name="context">The EF context to use for the check</param>
        /// <param name="fldGroup">The field group to check</param>
        /// <returns></returns>
        private static bool groupBelongsToContracts(TopContractsV01Entities context, TopContractsEntities.FieldGroup fldGroup)
        {
            if (fldGroup.ContractTypeVisibility == (byte)TopContractsCommon10.FieldGroupContractTypeVisibility.VisibleToAll)
                return true;
            if (fldGroup.FieldGroupsContractTypesMAPs != null)
            {
                FieldGroupsContractTypesMAP contractTypeMap = fldGroup.FieldGroupsContractTypesMAPs.FirstOrDefault();

                if (contractTypeMap != null)
                    if (contractTypeMap.ContractType.ParentContractTypeID == Utilities.contractTypeContractsID) // Code implemented by Viplav on 17 june 2013 for remove webconfig concept
                        return true;

            }
            return false;
        }
        /// <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();
        }
        public void CreateCounterforNewField(TopContractsV01Entities context, Dictionary<long, long> checkMax, TopContractsEntities.Field efFld, TopContractsEntities.Contract contract, long? recordcounter)
        {
            ContractFieldGroup cfld = new ContractFieldGroup();
            long maxfldValue = 0;
            if (checkMax.ContainsKey(efFld.FieldID))
            {
                checkMax.TryGetValue(efFld.FieldID, out maxfldValue);
                checkMax[efFld.FieldID] = maxfldValue + 1;
            }
            else
            {
                maxfldValue = Convert.ToInt64(context.ContractFields.Where(fld => fld.FieldID == efFld.FieldID).Max(fld => fld.FieldValueNumeric));
                checkMax.Add(efFld.FieldID, maxfldValue + 1);

            }
            string disFormat = cfld.GetAutoNumberDisplayFormat(efFld.DisplayFormat, maxfldValue);
            string getString = disFormat.Substring(disFormat.IndexOf("num=") + 4);
            long noofPadding = Convert.ToInt64(getString.Substring(0, getString.IndexOf("suf=")));
            disFormat = disFormat.Replace("num=", "");
            disFormat = disFormat.Replace("suf=", "");
            contract.ContractFields.Add(new TopContractsEntities.ContractField()
            {
                FieldGroupID = efFld.FieldGroupID,
                FieldID = efFld.FieldID,
                FieldValue = disFormat,
                FieldValueNumeric = noofPadding,
                RecordCounter = (recordcounter == null ? Convert.ToInt64(RecordCounter.Default) : recordcounter)
            });
        }