private SPField FindField(SPFieldCollection fields, ListFieldLinkDefinition listFieldLinkModel)
        {
            if (listFieldLinkModel.FieldId.HasGuidValue())
            {

                return fields
                    .OfType<SPField>()
                    .FirstOrDefault(f => f.Id == listFieldLinkModel.FieldId.Value);
            }

            if (!string.IsNullOrEmpty(listFieldLinkModel.FieldInternalName))
            {
                return fields
                   .OfType<SPField>()
                   .FirstOrDefault(f => f.InternalName.ToUpper() == listFieldLinkModel.FieldInternalName.ToUpper());
            }

            throw new ArgumentException("FieldId or FieldInternalName should be defined");
        }
        public TreeViewControl(SPFieldCollection fields,
                                   string typeName,
                                   string displayName)
            : base(fields, typeName, displayName)
        {
            try
            {
                _fields = fields;
                _typeName = typeName;
                _displayName = displayName;
                _ContextID = SPContext.Current.GetHashCode().ToString();
            }
            catch (Exception Ex)
            {

                _ContextID = NO_CONTEXT;
            }
            ReadCustomProperties();
        }
 public AutoCompleteFieldType(SPFieldCollection fields, string fieldName)
     : base(fields, fieldName)
 {
     LoadProperties();
     Counter++;
     FieldId = Counter;
 }
Beispiel #4
0
        private void PopulateCascadeList()
        {
            ddlChildList.Items.Clear();

            using (SPWeb web = SPContext.Current.Site.OpenWeb())
            {
                SPFieldCollection columns = SPContext.Current.List.Fields;

                foreach (SPField column in columns)
                {
                    if (column.TypeAsString == "CascadingDropdownsFieldType")
                    {
                        ListItem item = new ListItem();
                        item.Text  = column.Title;
                        item.Value = column.StaticName;
                        if (!String.IsNullOrEmpty(CascadeParent) && item.Value == CascadeParent)
                        {
                            item.Selected = true;
                        }

                        ddlChildList.Items.Add(item);
                    }
                }
            }
        }
 public AutoCompleteFieldType(SPFieldCollection fields, string typeName, string displayName)
     : base(fields, typeName, displayName)
 {
     LoadProperties();
     Counter++;
     FieldId = Counter;
 }
        public virtual SPField GetField(SPFieldCollection fields, Guid?fieldId, string fieldInternalName, string fieldTitle)
        {
            SPField result = null;

            if (fieldId.HasGuidValue())
            {
                result = fields.OfType <SPField>().FirstOrDefault(f => f.Id == fieldId.Value);
            }

            if (result == null && !string.IsNullOrEmpty(fieldInternalName))
            {
                result = fields.OfType <SPField>()
                         .FirstOrDefault(f => String.Equals(f.InternalName, fieldInternalName,
                                                            StringComparison.OrdinalIgnoreCase));
            }

            if (result == null && !string.IsNullOrEmpty(fieldTitle))
            {
                result = fields.OfType <SPField>()
                         .FirstOrDefault(f => String.Equals(f.Title, fieldTitle,
                                                            StringComparison.OrdinalIgnoreCase));
            }

            if (result != null)
            {
                return(result);
            }

            throw new SPMeta2Exception(string.Format("SSOMFieldLookupService.GetField(): cannot find field by fieldId:[{0}],  fieldInternalName:[{1}], fieldTitle:[{2}]",
                                                     fieldId, fieldInternalName, fieldTitle));
        }
Beispiel #7
0
        protected virtual void AddFieldTo(SPFieldCollection fieldCollection, Action <SPField> fieldAction)
        {
            SPField newField = null;

            if (ID != System.Guid.Empty && fieldCollection.Web.AvailableFields.Contains(ID))
            {
                SPField field = fieldCollection.Web.AvailableFields[ID];
                fieldCollection.Add(field);
                newField = fieldCollection[ID];
            }
            else
            {
                newField = CreateField(fieldCollection);
            }

            if (fieldAction != null)
            {
                fieldAction(newField);
            }

            if (!string.IsNullOrEmpty(Title))
            {
                newField.Title = Title;
            }

            if (!string.IsNullOrEmpty(Description))
            {
                newField.Description = Description;
            }

            newField.Update();
        }
Beispiel #8
0
 public ItemShortcutColumn(
     SPFieldCollection fields,
     string typename,
     string name) :
     base(fields, typename, name)
 {
 }
Beispiel #9
0
 public static List <SPField> AvailableSearchFields(this SPFieldCollection fields)
 {
     return(fields.Cast <SPField>().Where(p => !p.Hidden &&
                                          (p.Type != SPFieldType.Computed || p.Id == SPBuiltInFieldId.ContentType) &&
                                          p.Title != "Predecessors" &&
                                          p.Title != "Related Issues").ToList());
 }
Beispiel #10
0
        /// <summary>
        /// Writes a publishing Image value as an SPField's default value
        /// </summary>
        /// <param name="parentFieldCollection">The parent field collection within which we can find the specific field to update</param>
        /// <param name="fieldValueInfo">The field and value information</param>
        public override void WriteValueToFieldDefault(SPFieldCollection parentFieldCollection, FieldValueInfo fieldValueInfo)
        {
            var defaultValue = (MediaValue)fieldValueInfo.Value;
            var field        = parentFieldCollection[fieldValueInfo.FieldInfo.Id];

            if (defaultValue != null)
            {
                var sharePointFieldMediaValue = CreateSharePointMediaFieldValue(defaultValue);

                field.DefaultValue = sharePointFieldMediaValue.ToString();
            }
            else if (field.DefaultValue != null)
            {
                // Setting SPField.DefaultValue to NULL will always end up setting it as string.Empty.
                // The Media field type behaves weirdly when string.Empty is its DefaultValue (the NewForm.aspx breaks
                // because of impossible cast from string to MediaFieldValue type).
                // Thus, if the DefaultValue was already NULL, we gotta be carefull not to replace that NULL with an
                // empty string needlessly.
                this.log.Warn(
                    "WriteValueToFieldDefault - Initializing {0} field (fieldName={0}) with default value \"{1}\"."
                    + " Be aware that folder default values on {0}-type field are not well supported by SharePoint and that this default"
                    + " value will not be editable through your document library's \"List Settings > Column default value settings\" options page.",
                    fieldValueInfo.FieldInfo.FieldType,
                    fieldValueInfo.FieldInfo.InternalName,
                    defaultValue);

                field.DefaultValue = null;
            }
        }
Beispiel #11
0
        private bool IsExist(SPFieldCollection myFieldCollection, string str)
        {
            bool isExist = false;

            try
            {
                Console.WriteLine(myFieldCollection[str].InternalName);
                isExist = true;
            }
            catch (Exception e)
            {
                isExist = false;
                return(isExist);
            }

            return(isExist);


            //foreach (SPField item in myFieldCollection)
            //{
            //    if (item.Title == str)
            //    {
            //        isExist = true;
            //        break;
            //    }
            //}
        }
Beispiel #12
0
        // Delete site columns for group
        private static void DeleteCustomSiteColumns(string groupSiteColumnName)
        {
            string groupColumn = groupSiteColumnName;

            using (SPSite oSPSite = new SPSite("http://hostdns/"))
            {
                using (SPWeb oSPWeb = oSPSite.RootWeb)
                {
                    List <SPField>    fieldsInGroup = new List <SPField>();
                    SPFieldCollection allFields     = oSPWeb.Fields;
                    for (int i = 0; i < allFields.Count; i++)
                    {
                        if (allFields[i].Group.Equals(groupColumn))
                        {
                            allFields[i].Delete();
                        }
                    }

                    /*foreach (SPField field in allFields)
                     * {
                     *  if (field.Group.Equals(groupColumn))
                     *  {
                     *      field.Delete();
                     *  }
                     * }*/

                    oSPWeb.Update();
                }
            }
        }
Beispiel #13
0
        public bool CreateDataBaseTable(SPSite site, string tableName, SPFieldCollection fields)
        {
            string dataBaseTableName = this.Adapter.BuildTableName(tableName);
            CacheTableStructXml cacheTableStructXml = new CacheTableStructXml {
                TableName = dataBaseTableName
            };

            foreach (SPField field in fields)
            {
                if (field.Hidden && field.Id != SPBuiltInFieldId.ID &&
                    this.Adapter.IncludedFields.All(f => f != field.InternalName))
                {
                    continue;
                }

                string  columnType = this.Adapter.GetDataBaseType(field.Type);
                Columns column     = new Columns
                {
                    ColumnName =
                        field.Id == SPBuiltInFieldId.ID
                            ? Constants.ColumnSpPrefix + field.InternalName
                            : field.InternalName,
                    ColumnType = columnType
                };
                cacheTableStructXml.Columns.Add(column);
            }

            ArchiveCacheCRUD syncCrud = new ArchiveCacheCRUD(site);
            ErrorCode        result   = syncCrud.CreateOrUpdateTable(cacheTableStructXml);

            return(result == ErrorCode.NoError);
        }
Beispiel #14
0
        /// <summary>
        /// Sets the lookup to a list.
        /// </summary>
        /// <param name="fieldCollection">The field collection.</param>
        /// <param name="fieldId">The field identifier of the lookup field.</param>
        /// <param name="lookupList">The lookup list.</param>
        /// <exception cref="System.ArgumentNullException">
        /// fieldCollection
        /// or
        /// fieldId
        /// or
        /// lookupList
        /// </exception>
        /// <exception cref="System.ArgumentException">Unable to find the lookup field.;fieldId</exception>
        public void SetLookupToList(SPFieldCollection fieldCollection, Guid fieldId, SPList lookupList)
        {
            if (fieldCollection == null)
            {
                throw new ArgumentNullException("fieldCollection");
            }

            if (fieldId == null)
            {
                throw new ArgumentNullException("fieldId");
            }

            if (lookupList == null)
            {
                throw new ArgumentNullException("lookupList");
            }

            this.logger.Info("Start method 'SetLookupToList' for field id: '{0}'", fieldId);

            // Get the field.
            SPFieldLookup lookupField = this.fieldLocator.GetFieldById(fieldCollection, fieldId) as SPFieldLookup;
            if (lookupField == null)
            {
                throw new ArgumentException("Unable to find the lookup field.", "fieldId");
            }

            // Configure the lookup field.
            this.SetLookupToList(lookupField, lookupList);

            this.logger.Info("End method 'SetLookupToList'.");
        }
        public override void AddFieldTo(SPFieldCollection fieldCollection)
        {
            AddFieldTo(fieldCollection, f =>
            {
                TaxonomyField field = (TaxonomyField)f;

                if( TermStoreGuid != System.Guid.Empty && TermSetGuid != System.Guid.Empty )
                {
                    field.SspId = TermStoreGuid;
                    field.TermSetId = TermSetGuid;
                }
                else
                {
                    TaxonomySession session = new TaxonomySession(field.ParentList.ParentWeb.Site);
                    TermStore store = session.DefaultSiteCollectionTermStore != null ? session.DefaultSiteCollectionTermStore : session.TermStores[0];
                    Group group = store.Groups[TermGroup];
                    TermSet set = group.TermSets[TermSet];

                    field.SspId = store.Id;
                    field.TermSetId = set.Id;
                }

                field.AllowMultipleValues = AllowMultipleValues;
            });
        }
Beispiel #16
0
// ----------------------------------------------------------------------------------------------------------
// Works methods

        public static void CreateCustomField(string spsURL, string libName, string fieldName)
        {
            SPWeb             website    = new SPSite(spsURL).OpenWeb();
            SPFieldCollection collFields = website.Lists[libName].Fields;

            collFields.Add(fieldName, SPFieldType.Text, true);
        }
Beispiel #17
0
        public static TF AddField <TF>(
            this SPFieldCollection fields,
            Guid fieldId,
            SPFieldType fieldType,
            string displayName,
            string name,
            bool required,
            Action <TF> action)
            where TF : SPField
        {
            //name = SPHelper.ConvertHebrewToUnicodeHex(name);

            if (!fields.Contains(fieldId))
            {
                string fieldXml =
                    string.Format(
                        @"<Field ID=""{0}"" Name=""{1}"" StaticName=""{1}"" DisplayName=""{2}"" Type=""{3}"" Overwrite=""TRUE"" SourceID=""http://schemas.microsoft.com/sharepoint/v3"" />",
                        fieldId, name, displayName, fieldType);
                name = fields.AddFieldAsXml(fieldXml);
            }

            //TF field = (TF)fields.GetFieldByInternalName(name);
            TF field = (TF)fields.GetField(name);

            field.Required = required;

            if (action != null)
            {
                action(field);
            }

            field.Update();
            return(field);
        }
Beispiel #18
0
        public override void AddFieldTo(SPFieldCollection fieldCollection)
        {
            AddFieldTo(fieldCollection, f =>
            {
                TaxonomyField field = (TaxonomyField)f;

                if (TermStoreGuid != System.Guid.Empty && TermSetGuid != System.Guid.Empty)
                {
                    field.SspId     = TermStoreGuid;
                    field.TermSetId = TermSetGuid;
                }
                else
                {
                    TaxonomySession session = new TaxonomySession(field.ParentList.ParentWeb.Site);
                    TermStore store         = session.DefaultSiteCollectionTermStore != null ? session.DefaultSiteCollectionTermStore : session.TermStores[0];
                    Group group             = store.Groups[TermGroup];
                    TermSet set             = group.TermSets[TermSet];

                    field.SspId     = store.Id;
                    field.TermSetId = set.Id;
                }

                field.AllowMultipleValues = AllowMultipleValues;
            });
        }
Beispiel #19
0
        /// <summary>
        /// Sets the lookup to a list.
        /// </summary>
        /// <param name="fieldCollection">The field collection.</param>
        /// <param name="fieldId">The field identifier of the lookup field.</param>
        /// <param name="lookupList">The lookup list.</param>
        /// <exception cref="System.ArgumentNullException">
        /// fieldCollection
        /// or
        /// fieldId
        /// or
        /// lookupList
        /// </exception>
        /// <exception cref="System.ArgumentException">Unable to find the lookup field.;fieldId</exception>
        public void SetLookupToList(SPFieldCollection fieldCollection, Guid fieldId, SPList lookupList)
        {
            if (fieldCollection == null)
            {
                throw new ArgumentNullException("fieldCollection");
            }

            if (fieldId == null)
            {
                throw new ArgumentNullException("fieldId");
            }

            if (lookupList == null)
            {
                throw new ArgumentNullException("lookupList");
            }

            this.logger.Info("Start method 'SetLookupToList' for field id: '{0}'", fieldId);

            // Get the field.
            SPFieldLookup lookupField = this.fieldLocator.GetFieldById(fieldCollection, fieldId) as SPFieldLookup;

            if (lookupField == null)
            {
                throw new ArgumentException("Unable to find the lookup field.", "fieldId");
            }

            // Configure the lookup field.
            this.SetLookupToList(lookupField, lookupList);

            this.logger.Info("End method 'SetLookupToList'.");
        }
Beispiel #20
0
        public static TF AddCustomField <TF>(
            this SPFieldCollection fields,
            string typeName,
            string name,
            bool required,
            Action <TF> action)
            where TF : SPField
        {
            //name = SPHelper.ConvertHebrewToUnicodeHex(name);

            if (!fields.ContainsField(name))
            {
                name = fields.Add(fields.CreateNewField(typeName, name));
            }

            //TF field = (TF)fields.GetFieldByInternalName(name);
            TF field = (TF)fields.GetField(name);

            field.Required = required;

            if (action != null)
            {
                action(field);
            }

            field.Update();
            return(field);
        }
 public FavoriteColorField(
     SPFieldCollection fields, 
     string typename, 
     string name)
     : base(fields, typename, name)
 {
 }
Beispiel #22
0
        public static TF AddField <TF>(
            this SPFieldCollection fields,
            SPFieldType fieldType,
            string internalName,
            string displayName,
            string groupName,
            bool required,
            Action <TF> action)
            where TF : SPField
        {
            return(fields.AddField <TF>(fieldType, internalName, required,
                                        field =>
            {
                field.Title = displayName;

                if (!string.IsNullOrEmpty(groupName))
                {
                    field.Group = groupName;
                }

                if (action != null)
                {
                    action(field);
                }
            }));
        }
Beispiel #23
0
 //绑定当前列表的数字字段到下拉控件
 void BindSPListFieldData(Guid listid, DropDownList drlist)
 {
     using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
     {
         using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
         {
             drlist.Items.Clear();
             SPList            splist      = web.Lists[listid];
             SPFieldCollection splistfield = splist.Fields;
             foreach (SPField spfsitem in splistfield)
             {
                 if (spfsitem.Reorderable)
                 {
                     if (spfsitem.Type == SPFieldType.Number || spfsitem.Type == SPFieldType.Currency)
                     {
                         string _text  = spfsitem.Title;
                         string _value = spfsitem.InternalName;
                         System.Web.UI.WebControls.ListItem litem = new System.Web.UI.WebControls.ListItem(_text, _value);
                         drlist.Items.Add(litem);
                     }
                 }
             }
         }
     }
 }
 //填充指定列表下的字段
 private void FillListFields(string listGuid)
 {
     SPSecurity.RunWithElevatedPrivileges(delegate()
     {
         using (SPSite site = new SPSite(SPContext.Current.Web.Site.ID))
         {
             using (SPWeb web = site.AllWebs[SPContext.Current.Web.ID])
             {
                 Guid listid   = new Guid(listGuid);
                 SPList splist = web.Lists[listid];
                 SPFieldCollection splistfield = splist.Fields;
                 ddlFieldName.Items.Clear();
                 ListItem litem;
                 foreach (SPField spfsitem in splistfield)
                 {
                     if (spfsitem.Reorderable)
                     {
                         if (spfsitem.Type == SPFieldType.Text && !spfsitem.ReadOnlyField)//
                         {
                             string _text  = spfsitem.Title;
                             string _value = spfsitem.InternalName;
                             litem         = new System.Web.UI.WebControls.ListItem(_text, _value);
                             ddlFieldName.Items.Add(litem);
                         }
                     }
                 }
             }
         }
     });
 }
        /// <summary>
        /// Fetches the properties.
        /// </summary>
        /// <param name="spFieldCollection">The SP field collection.</param>
        /// <param name="listItem">The list item.</param>
        /// <returns>
        /// The Microsoft.SharePoint.RecordsRepositoryProperty[].
        /// </returns>
        private RecordsRepositoryProperty[] FetchProperties(SPFieldCollection spFieldCollection, SPListItem listItem)
        {
            // create a property list/ array for each metadata field
            List <RecordsRepositoryProperty> propertyList = new List <RecordsRepositoryProperty>();

            foreach (SPField spField in spFieldCollection)
            {
                try
                {
                    string value = Convert.ToString(spField.GetFieldValue(Convert.ToString(listItem[spField.Title])));
                    UnifiedLoggingServer.LogMedium("---- CRR_Props[" + spField.Title + "_|_" + spField.TypeAsString + "_|_" + value + "]");
                    RecordsRepositoryProperty property =
                        new RecordsRepositoryProperty
                    {
                        Name  = spField.Title,
                        Type  = spField.TypeAsString,
                        Value = value
                    };

                    propertyList.Add(property);
                }
                catch (Exception e)
                {
                }
            }

            return(propertyList.ToArray());
        }
        private void GetMetaFields()
        {
            Func <SPField, bool> metagroup = null;

            if (metagroup == null)
            {
                metagroup = delegate(SPField f)
                {
                    return(f.Group == settings.GroupName);
                };
            }

            char[] opengraph = new char[2] {
                ':', '.'
            };
            Func <SPField, bool> extended = null;

            if (extended == null)
            {
                extended = delegate(SPField f)
                {
                    return(f.Title.Contains(opengraph.ToString()) == false);
                };
            }

            SPFieldCollection     fields      = SPContext.Current.Site.RootWeb.Fields;
            IEnumerable <SPField> basicFields = fields.Cast <SPField>().Where(f => f.Title.Contains("fb:"));

            //.Where<SPField>(field => field.TypeDisplayName.Contains(""))
            metafields = basicFields.Cast <SPField>().Where <SPField>(metagroup).OrderBy(field => field.Title);
            //metafields = metafields.Except<SPField>(extended);
        }
Beispiel #27
0
 private void ApplyTaxonomyMultiTermStoreMapping(SPFieldCollection fieldCollection, SPField field, TaxonomyMultiFieldInfo taxonomyMultiFieldInfo)
 {
     // Apply the term set mapping (taxonomy picker selection context) for the column
     if (taxonomyMultiFieldInfo.TermStoreMapping != null)
     {
         SPList fieldCollectionParentList = null;
         if (TryGetListFromFieldCollection(fieldCollection, out fieldCollectionParentList))
         {
             this.taxonomyHelper.AssignTermStoreMappingToField(
                 fieldCollectionParentList.ParentWeb.Site,
                 field,
                 taxonomyMultiFieldInfo.TermStoreMapping);
         }
         else
         {
             this.taxonomyHelper.AssignTermStoreMappingToField(
                 fieldCollection.Web.Site,
                 field,
                 taxonomyMultiFieldInfo.TermStoreMapping);
         }
     }
     else
     {
         // the term store mapping is null, we should make sure the field is unmapped
         ClearTermStoreMapping(fieldCollection, taxonomyMultiFieldInfo);
     }
 }
Beispiel #28
0
        private bool FieldExists(SPFieldCollection fieldCollection, string internalName, Guid fieldId)
        {
            if (fieldCollection.Contains(fieldId))
            {
                // If Id is found in the collection.
                this.logger.Warn("Field with id '{0}' is already in the collection.", fieldId);
                return(true);
            }

            SPField field;

            try
            {
                // Throws argument exception if not in collection.
                field = fieldCollection.GetFieldByInternalName(internalName);
            }
            catch (ArgumentException)
            {
                return(false);
            }

            if (field == null)
            {
                // Still can't find the field in the collection
                return(false);
            }
            else
            {
                // We found it!
                this.logger.Warn("Field with display name '{0}' is already in the collection.", internalName);
                return(true);
            }
        }
Beispiel #29
0
        private void ContentTypeRemoveExcessiveFields(ref SPContentType cType)
        {
            SPContentType     parentContentType = cType.Parent;
            SPFieldCollection fields            = cType.Fields;
            List <string>     removeFirst       = new List <string>();
            List <string>     removeSecond      = new List <string>();

            foreach (SPField iField in fields)
            {
                if (!AddedInternalNames.Contains(iField.InternalName) &&
                    !parentContentType.Fields.ContainsFieldWithStaticName(iField.InternalName))
                {
                    if (iField.Type == SPFieldType.Lookup && (iField as SPFieldLookup).IsDependentLookup)
                    {
                        removeFirst.Add(iField.InternalName);
                    }
                    else
                    {
                        removeSecond.Add(iField.InternalName);
                    }
                }
            }
            foreach (string iExcess in removeFirst)
            {
                cType.FieldLinks.Delete(iExcess);
            }
            foreach (string iExcess in removeSecond)
            {
                cType.FieldLinks.Delete(iExcess);
            }
        }
Beispiel #30
0
        // Get field or sitesite columns for group
        public List <SPField> GetCustomSiteColumns(string groupSiteColumnName, string[] fields)
        {
            string         groupColumn = groupSiteColumnName;
            List <SPField> siteColumns = new List <SPField>();

            using (SPWeb oSPWeb = oSPSite.RootWeb)
            {
                List <SPField>    fieldsInGroup = new List <SPField>();
                SPFieldCollection allFields     = oSPWeb.Fields;
                foreach (SPField field in allFields)
                {
                    if (field.Group.Equals(groupColumn))
                    {
                        foreach (string nameColumn in fields)
                        {
                            if (nameColumn == field.StaticName)
                            {
                                siteColumns.Add(field);
                            }
                        }
                    }
                }
            }
            return(siteColumns);
        }
Beispiel #31
0
        public static void DeleteCustomField(string spsURL, string libName, string fieldName)
        {
            SPWeb             website    = new SPSite(spsURL).OpenWeb();
            SPFieldCollection collFields = website.Lists[libName].Fields;

            collFields.Delete(collFields[fieldName].InternalName);
        }
Beispiel #32
0
        protected virtual void HandleIncorectlyDeletedTaxonomyField(FieldDefinition fieldModel,
                                                                    SPFieldCollection fields)
        {
            return;

            // excluded due ot potential data corruption
            // such issues shoud be handled by end user manually

            //var isTaxField =
            //    fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldType.ToUpper()
            //    || fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldTypeMulti.ToUpper();

            //if (!isTaxField)
            //    return;

            //var existingIndexedFieldName = fieldModel.Title.ToUpper() + "_";
            //var existingIndexedField = fields.OfType<SPField>()
            //    .FirstOrDefault(f => f.Title.ToUpper().StartsWith(existingIndexedFieldName));

            //if (existingIndexedField != null && existingIndexedField.Type == SPFieldType.Note)
            //{
            //    // tmp fix
            //    // https://github.com/SubPointSolutions/spmeta2/issues/521
            //    try
            //    {
            //        existingIndexedField.Delete();
            //    }
            //    catch (Exception ex)
            //    {

            //    }
            //}
        }
Beispiel #33
0
        public static TF AddField <TF>(
            this SPFieldCollection fields,
            SPFieldType fieldType,
            string name,
            bool required,
            Action <TF> action)
            where TF : SPField
        {
            //name = SPHelper.ConvertHebrewToUnicodeHex(name);

            if (!fields.ContainsField(name))
            {
                name = AddField(fields, fieldType, name, required, false);
            }

            //TF field = (TF)fields.GetFieldByInternalName(name);
            TF field = (TF)fields.GetField(name);

            if (action != null)
            {
                action(field);
            }

            field.Update();
            return(field);
        }
Beispiel #34
0
        private void EnsureContentTypeDelayedFields(ref SPWeb web, ref SPContentType cType)
        {
            //eg for lookup on self
            bool updateCt = false;

            SiteColumn[] columns = Columns;
            foreach (var iColumn in columns)
            {
                if (iColumn.CreateAfterListCreation)
                {
                    SPFieldCollection siteColumns = web.Fields;
                    SPField           field       = iColumn.EnsureExists(ref siteColumns);
                    if (field != null)
                    {
                        iColumn.EnsureFieldConfiguration(ref web, ref field);
                        iColumn.CallOnColumnCreated(ref field);
                        if (!cType.Fields.ContainsFieldWithStaticName(iColumn.InternalName))
                        {
                            cType.FieldLinks.Add(new SPFieldLink(field));
                        }
                    }
                    updateCt = true;
                }
                AddedInternalNames.Add(iColumn.InternalName);
            }
            if (updateCt)
            {
                cType.Update(true, false);
            }
        }
        public SPField TryGetField(SPFieldCollection siteColumns, Guid fieldID)
        {
            siteColumns.RequireNotNull("siteColumns");
            fieldID.Require(Guid.Empty != fieldID, "fieldID");

            return siteColumns.Contains(fieldID) ? siteColumns[fieldID] : null;
        }
Beispiel #36
0
        /// <summary>
        /// Ensure a field
        /// </summary>
        /// <param name="fieldCollection">The field collection</param>
        /// <param name="fieldInfo">The field info configuration</param>
        /// <returns>The internal name of the field</returns>
        public SPField EnsureField(SPFieldCollection fieldCollection, BaseFieldInfo fieldInfo)
        {
            SPList parentList = null;
            bool isListField = TryGetListFromFieldCollection(fieldCollection, out parentList);
            bool alreadyExistsAsSiteColumn = fieldCollection.Web.Site.RootWeb.Fields.TryGetFieldByStaticName(fieldInfo.InternalName) != null;

            if (fieldInfo.EnforceUniqueValues)
            {
                bool isValidTypeForUniquenessConstraint =
                    fieldInfo is IntegerFieldInfo
                    || fieldInfo is NumberFieldInfo
                    || fieldInfo is CurrencyFieldInfo
                    || fieldInfo is DateTimeFieldInfo
                    || fieldInfo is TextFieldInfo
                    || fieldInfo is UserFieldInfo
                    || fieldInfo is LookupFieldInfo
                    || fieldInfo is TaxonomyFieldInfo;

                if (!isValidTypeForUniquenessConstraint)
                {
                    string msg = "Can't set EnforceUniqueValues=TRUE on your field "
                        + fieldInfo.InternalName + " because only the following field types are support uniqueness constraints: "
                        + " Integer, Number, Currency, DateTime, Text (single line), User (not multi), Lookup (not multi) and Taxonomy (not multi).";
                    throw new NotSupportedException(msg);
                }
            }

            if (isListField && !alreadyExistsAsSiteColumn)
            {
                // By convention, we enfore creation of site column before using that field on a list
                this.InnerEnsureField(fieldCollection.Web.Site.RootWeb.Fields, fieldInfo);
            }

            return this.InnerEnsureField(fieldCollection, fieldInfo);
        }
Beispiel #37
0
 public PrintPreviewColumn(
     SPFieldCollection fields,
     string typename,
     string name) :
     base(fields, typename, name)
 {
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="SharePointListItemConversionArguments"/> class.
 /// </summary>
 /// <param name="propertyName">
 /// Name of the property.
 /// </param>
 /// <param name="propertyType">
 /// Type of the property.
 /// </param>
 /// <param name="valueKey">
 /// The value key.
 /// </param>
 /// <param name="dataRow">
 /// The data row.
 /// </param>
 /// <param name="listItemCollection">
 /// The list Item Collection.
 /// </param>
 /// <param name="fieldValues">
 /// The full dictionary of values being converted
 /// </param>
 public DataRowConversionArguments(string propertyName, Type propertyType, string valueKey, DataRow dataRow, SPFieldCollection fieldCollection, SPWeb web, IDictionary<string, object> fieldValues)
     : base(propertyName, propertyType, valueKey)
 {
     this.FieldCollection = fieldCollection;
     this.Web = web;
     this.DataRow = dataRow;
     this.FieldValues = fieldValues;
 }
 /// <summary>
 /// Fills the values from the entity properties.
 /// </summary>
 /// <param name="sourceEntity">
 /// The source entity.
 /// </param>
 /// <param name="values">
 /// The values.
 /// </param>
 /// <param name="fieldCollection">
 /// The field Collection.
 /// </param>
 /// <param name="web">
 /// The web.
 /// </param>
 public void FromEntity(object sourceEntity, IDictionary<string, object> values, SPFieldCollection fieldCollection, SPWeb web)
 {
     foreach (var binding in this.BindingDetails.Where(x => x.BindingType == BindingType.Bidirectional || x.BindingType == BindingType.WriteOnly))
     {
         var value = binding.EntityProperty.GetValue(sourceEntity, null);
         value = binding.Converter.ConvertBack(value, this.GetConversionArguments(binding, values, fieldCollection, web));
         values[binding.ValueKey] = value;
     }
 }
 public override void AddFieldTo(SPFieldCollection fieldCollection)
 {
     AddFieldTo(fieldCollection, f =>
     {
         SPFieldMultiChoice field = (SPFieldMultiChoice)f;
         field.Choices.Clear();
         field.Choices.AddRange(Choices);
     });
 }
 public override void AddFieldTo(SPFieldCollection fieldCollection)
 {
     AddFieldTo(fieldCollection, f =>
     {
         SPFieldMultiLineText field = (SPFieldMultiLineText)f;
         field.AppendOnly = AppendOnly;
         field.RichText = RichText;
         field.RichTextMode = RichTextMode;
     });
 }
 /// <summary>
 /// Creates the conversion arguments.
 /// </summary>
 /// <param name="bindingDetail">
 /// The binding detail.
 /// </param>
 /// <param name="values">
 /// The values.
 /// </param>
 /// <param name="fieldCollection">
 /// The field Collection.
 /// </param>
 /// <param name="web">
 /// The web.
 /// </param>
 /// <returns>
 /// The conversion arguments.
 /// </returns>
 protected internal override ConversionArguments GetConversionArguments(EntityBindingDetail bindingDetail, IDictionary<string, object> values, SPFieldCollection fieldCollection, SPWeb web)
 {
     var listItemValues = values as ISharePointListItemValues;
     if (listItemValues != null)
     {
         return new SharePointListItemConversionArguments(bindingDetail.EntityProperty.Name, bindingDetail.EntityProperty.PropertyType, bindingDetail.ValueKey, listItemValues.ListItem, values);
     }
     else
     {
         return base.GetConversionArguments(bindingDetail, values, fieldCollection, web);
     }
 }
        /// <summary>
        /// Fills the entity from the values.
        /// </summary>
        /// <param name="targetEntity">
        /// The target entity.
        /// </param>
        /// <param name="values">
        /// The values.
        /// </param>
        /// <param name="fieldCollection">
        /// The field Collection.
        /// </param>
        /// <param name="web">
        /// The web.
        /// </param>
        public virtual void ToEntity(object targetEntity, IDictionary<string, object> values, SPFieldCollection fieldCollection, SPWeb web)
        {
            foreach (var binding in this.BindingDetails.Where(x => x.BindingType == BindingType.Bidirectional || x.BindingType == BindingType.ReadOnly))
            {
                object value;
                if (!values.TryGetValue(binding.ValueKey, out value))
                {
                    value = null;
                }

                value = binding.Converter.Convert(value, this.GetConversionArguments(binding, values, fieldCollection, web));
                binding.EntityProperty.SetValue(targetEntity, value, null);
            }
        }
Beispiel #44
0
        public FieldCollectionNode(Object parent, SPFieldCollection collection)
        {
            this.Text = SPMLocalization.GetString("Fields_Text");
            this.ToolTipText = SPMLocalization.GetString("Fields_ToolTip");
            this.Name = "Fields";
            this.Tag = collection;
            this.SPParent = parent;

            int index = Program.Window.Explorer.AddImage(this.ImageUrl());
            this.ImageIndex = index;
            this.SelectedImageIndex = index;

            this.Nodes.Add(new ExplorerNodeBase("Dummy"));
        }
		public ModelConverters(MetaModel model, SPFieldCollection fields)
		{
			Guard.ThrowIfArgumentNull(model, "model");
			Guard.ThrowIfArgumentNull(fields, "fields");

			Model = model;
			Converters = new Dictionary<string, IFieldConverter>();

			foreach (var metaProperty in model.MetaProperties)
			{
				var field = fields.GetField(metaProperty.SpFieldInternalName);
				Converters.Add(metaProperty.MemberName, InstantiateConverter(metaProperty, field));
			}
		}
        /// <summary>
        /// Adds a field defined in xml to a collection of fields.
        /// </summary>
        /// <param name="fieldCollection">The SPField collection.</param>
        /// <param name="fieldXml">The field XML schema.</param>
        /// <returns>
        /// A string that contains the internal name of the new field.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">
        /// fieldCollection
        /// or
        /// fieldXml
        /// </exception>
        /// <exception cref="System.FormatException">Invalid xml.</exception>
        public string AddField(SPFieldCollection fieldCollection, XElement fieldXml)
        {
            if (fieldCollection == null)
            {
                throw new ArgumentNullException("fieldCollection");
            }

            if (fieldXml == null)
            {
                throw new ArgumentNullException("fieldXml");
            }

            this._logger.Info("Start method 'AddField'");

            Guid id = Guid.Empty;
            string displayName = string.Empty;
            string internalName = string.Empty;

            // Validate the xml of the field and get its
            if (this.IsFieldXmlValid(fieldXml, out id, out displayName, out internalName))
            {
                // Check if the field already exists. Skip the creation if so.
                if (!this.FieldExists(fieldCollection, displayName, id))
                {
                    // If its a lookup we need to fix up the xml.
                    if (this.IsLookup(fieldXml))
                    {
                        fieldXml = this.FixLookupFieldXml(fieldCollection.Web, fieldXml);
                    }

                    string addedInternalName = fieldCollection.AddFieldAsXml(fieldXml.ToString(), false, SPAddFieldOptions.Default);

                    this._logger.Info("End method 'AddField'. Added field with internal name '{0}'", addedInternalName);

                    return addedInternalName;
                }
                else
                {
                    this._logger.Warn("End method 'AddField'. Field with id '{0}' and display name '{1}' was not added because it already exists in the collection.", id, displayName);
                    return string.Empty;
                }
            }
            else
            {
                string msg = string.Format(CultureInfo.InvariantCulture, "Unable to create field. Invalid xml. id: '{0}' DisplayName: '{1}' Name: '{2}'", id, displayName, internalName);
                throw new FormatException(msg);
            }
        }
Beispiel #47
0
        /// <summary>
        /// Updates the specified SPField definitions with new DefaultValues
        /// </summary>
        /// <param name="parentFieldCollection">The SharePoint field collection containing the fields to update.</param>
        /// <param name="defaultFieldValueInfos">The default values to be applied as the SPFields' new defaults.</param>
        public void WriteValuesToFieldDefaults(SPFieldCollection parentFieldCollection, IList<FieldValueInfo> defaultFieldValueInfos)
        {
            if (parentFieldCollection == null)
            {
                throw new ArgumentNullException("parentFieldCollection");
            }

            if (defaultFieldValueInfos == null)
            {
                throw new ArgumentNullException("defaultFieldValueInfos");
            }

            foreach (var fieldValue in defaultFieldValueInfos)
            {
                this.WriteValueToFieldDefault(parentFieldCollection, fieldValue);
            }
        }
Beispiel #48
0
        /// <summary>
        /// Gets the field by identifier.
        /// Returns null if the field is not found in the collection.
        /// </summary>
        /// <param name="fieldCollection">The field collection.</param>
        /// <param name="fieldId">The field identifier.</param>
        /// <returns>The SPField.</returns>
        public SPField GetFieldById(SPFieldCollection fieldCollection, Guid fieldId)
        {
            if (fieldCollection == null)
            {
                throw new ArgumentNullException("fieldCollection");
            }

            if (fieldId == null)
            {
                throw new ArgumentNullException("fieldId");
            }

            SPField field = null;
            if (fieldCollection.Contains(fieldId))
            {
                field = fieldCollection[fieldId] as SPField;
            }

            return field;
        }
 public SPFieldLookup CreateLookup(SPFieldCollection siteColumns, string fieldName, SPList lookupList, SPWeb web, bool required)
 {
     siteColumns.RequireNotNull("siteColumns");
     fieldName.RequireNotNullOrEmpty("fieldName");
     lookupList.RequireNotNull("lookupList");
     string internalFieldName;
     SPField looupField = TryGetField(siteColumns,fieldName);
     if (null == looupField)
     {
         if (null != web)
         {
             internalFieldName = siteColumns.AddLookup(fieldName, lookupList.ID, web.ID, required);
         }
         else
         {
             internalFieldName = siteColumns.AddLookup(fieldName, lookupList.ID, required);
         }
         looupField = siteColumns.GetFieldByInternalName(internalFieldName);
     }
     return looupField as SPFieldLookup;
 }
        public virtual void DeleteField(SPFieldCollection fieldCollection, Guid fieldId)
        {
            SPField field = fieldCollection[fieldId];

            if (fieldCollection.List == null)
            {
                var ctColl = fieldCollection.Web.ContentTypes;

                for (int i = 0; i < ctColl.Count; i++)
                {
                    var ct = ctColl[i];
                    if (ct.FieldLinks[field.Id] != null)
                    {
                        ct.FieldLinks.Delete(field.Id);

                        ct.Update(true);
                    }
                }
            }

            field.Delete();
        }
        protected virtual void AddFieldTo(SPFieldCollection fieldCollection, Action<SPField> fieldAction)
        {
            SPField newField = null;
            if (ID != System.Guid.Empty && fieldCollection.Web.AvailableFields.Contains(ID))
            {
                SPField field = fieldCollection.Web.AvailableFields[ID];
                fieldCollection.Add(field);
                newField = fieldCollection[ID];
            }
            else
                newField = CreateField(fieldCollection);

            if (fieldAction != null)
                fieldAction(newField);

            if (!string.IsNullOrEmpty(Title))
                newField.Title = Title;

            if (!string.IsNullOrEmpty(Description))
                newField.Description = Description;

            newField.Update();
        }
Beispiel #52
0
        private void HandleIncorectlyDeletedTaxonomyField(FieldDefinition fieldModel,
            SPFieldCollection fields)
        {
            var isTaxField =
                fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldType.ToUpper()
                || fieldModel.FieldType.ToUpper() == BuiltInFieldTypes.TaxonomyFieldTypeMulti.ToUpper();

            if (!isTaxField)
                return;

            var existingIndexedFieldName = fieldModel.Title.ToUpper() + "_";
            var existingIndexedField = fields.OfType<SPField>()
                .FirstOrDefault(f => f.Title.ToUpper().StartsWith(existingIndexedFieldName));

            if (existingIndexedField != null && existingIndexedField.Type == SPFieldType.Note)
                existingIndexedField.Delete();
        }
Beispiel #53
0
        private SPField EnsureFieldInFieldsCollection(
            object modelHost,
            SPFieldCollection fields, FieldDefinition fieldModel)
        {
            var currentField = fields.OfType<SPField>()
                                        .FirstOrDefault(f => f.Id == fieldModel.Id);

            if (currentField == null)
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new field");

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = currentField,
                    ObjectType = GetTargetFieldType(fieldModel),
                    ObjectDefinition = fieldModel,
                    ModelHost = modelHost
                });

                var fieldDef = GetTargetSPFieldXmlDefinition(fieldModel);

                // special handle for taxonomy field
                // incorectly removed tax field leaves its indexed field
                // https://github.com/SubPointSolutions/spmeta2/issues/521

                HandleIncorectlyDeletedTaxonomyField(fieldModel, fields);

                var addFieldOptions = (SPAddFieldOptions)(int)fieldModel.AddFieldOptions;
                fields.AddFieldAsXml(fieldDef, fieldModel.AddToDefaultView, addFieldOptions);

                currentField = fields[fieldModel.Id];
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing field");

                currentField = fields[fieldModel.Id];

                InvokeOnModelEvent(this, new ModelEventArgs
                {
                    CurrentModelNode = null,
                    Model = null,
                    EventType = ModelEventType.OnProvisioning,
                    Object = currentField,
                    ObjectType = GetTargetFieldType(fieldModel),
                    ObjectDefinition = fieldModel,
                    ModelHost = modelHost
                });
            }

            return currentField;
        }
Beispiel #54
0
 public RegExpField(SPFieldCollection fields, string typeName, string displayName)
     : base(fields, typeName, displayName)
 {
 }
Beispiel #55
0
 public RegExpField(SPFieldCollection fields, string fieldName)
     : base(fields, fieldName)
 {
 }
 public MaskedInput(SPFieldCollection fields, string typeName, string displayName)
     : base(fields, typeName, displayName)
 {
 }
 public MaskedInput(SPFieldCollection fields, string fieldName)
     : base(fields, fieldName)
 {
 }
Beispiel #58
0
 public JSONField(SPFieldCollection fields, string fieldName)
     : base(fields, fieldName)
 {
 }
 public DigitalSignatureField(SPFieldCollection fields, string typeName, string displayName)
     : base(fields, typeName, displayName)
 {
 }
 public TreeViewControl(SPFieldCollection fields,
                            string fieldName)
     : base(fields, fieldName)
 {
     try
     {
         _fields = fields;
         _fieldName = fieldName;
         _ContextID = SPContext.Current.GetHashCode().ToString();
     }
     catch (Exception Ex)
     {
         _ContextID = NO_CONTEXT;
         throw new Exception(Convert.ToString(Ex.InnerException));
     }
     ReadCustomProperties();
 }