コード例 #1
0
        public SPContentTypeId EnsureContentType(string webUrl, bool removeExcessiveFields)
        {
            SPContentTypeId contentTypeId = SPContentTypeId.Empty;

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                SPSite site = new SPSite(webUrl);
                SPWeb web   = site.OpenWeb();
                try
                {
                    SPContentType cType = EnsureContentTypeExists(ref web);
                    EnsureContentTypeFieldsExist(ref web, ref cType);
                    cType.Update(true, false);

                    if (removeExcessiveFields)
                    {
                        ContentTypeRemoveExcessiveFields(ref cType);
                        cType.Update(true, false);
                    }

                    InvokeOnContentTypeCreated(ref cType);
                    contentTypeId = cType.Id;
                    SetContentTypeId(contentTypeId);
                }
                catch { throw; }
                finally
                {
                    web.Dispose();
                    site.Dispose();
                }
            });
            return(contentTypeId);
        }
コード例 #2
0
        public static void ProvisionContentType(SPWeb spWeb)
        {
            /* Create the content type. */
            SPContentType ct = GetContentType(spWeb);
            if (ct == null)
            {
                ct = new SPContentType(ContentTypeID, spWeb.ContentTypes, ContentTypeName);
                ct.Group = AppConstants.ContentTypeGroupName;
                spWeb.ContentTypes.Add(ct);
            }

            /*Add fields to content type .*/
            if (!ct.Fields.Contains(SiteColumns.HomeworkAssignmentName))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.HomeworkAssignmentName]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Student))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Student]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.IsAssignmentComplete))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.IsAssignmentComplete]);
                ct.FieldLinks.Add(field);
            }

            ct.Update(true);
        }
コード例 #3
0
 public static void ClearFieldLinks(this SPContentType contentType)
 {
     foreach (SPFieldLink fl in contentType.FieldLinks.Cast <SPFieldLink>().ToList())
     {
         contentType.FieldLinks.Delete(fl.Id);
     }
 }
コード例 #4
0
ファイル: Helpers.cs プロジェクト: eduardpaul/SPHelpers
    /// <summary>
    ///
    /// </summary>
    /// <param name="web"></param>
    /// <param name="parentId"></param>
    /// <param name="group"></param>
    /// <param name="name"></param>
    public static void CreateContentType(this SPWeb web, string parentId, string group, string name, string description)
    {
        try
        {
            if (web.AvailableContentTypes[name] == null)
            {
                SPContentType itemCType = web.AvailableContentTypes[new SPContentTypeId(parentId)];

                if (itemCType != null)
                {
                    SPContentType contentType =
                        new SPContentType(itemCType, web.ContentTypes, name)
                    {
                        Group = @group
                    };
                    web.ContentTypes.Add(contentType);
                    contentType.Update();
                }
            }
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CORE:HELPERS", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, String.Format("Exception happened in Helpers:CreateContentType. MESSAGE: {0}. EXCEPTION TRACE: {1} ", ex.Message, ex.StackTrace), ex.StackTrace);
        }
    }
コード例 #5
0
ファイル: SPObjectCache.cs プロジェクト: serenabenny/codeless
        /// <summary>
        /// Adds the given <see cref="Microsoft.SharePoint.SPContentType"/> object to the cache.
        /// </summary>
        /// <param name="contentType">Content type object.</param>
        /// <returns>>An <see cref="Microsoft.SharePoint.SPContentType"/> object in cache. Returned object is not necessary the same instance as the given one.</returns>
        /// <exception cref="System.ArgumentNullException">Throws when input parameter <paramref name="contentType"/> is null.</exception>
        public SPContentType AddContentType(SPContentType contentType)
        {
            CommonHelper.ConfirmNotNull(contentType, "contentType");
            SPContentTypeLookupKey lookupKey = new SPContentTypeLookupKey(contentType);

            return(GetOrAdd(lookupKey, contentType));
        }
コード例 #6
0
ファイル: Helpers.cs プロジェクト: eduardpaul/SPHelpers
    /// <summary>
    ///
    /// </summary>
    /// <param name="web"></param>
    /// <param name="contentName"></param>
    /// <param name="column"></param>
    /// <param name="required"></param>
    /// <param name="readonlyField"></param>
    public static void AddColumntToContentType(this SPWeb web, string contentName, string column, bool required = false, bool readonlyField = false)
    {
        try
        {
            SPContentType contentType = web.ContentTypes[contentName];

            if (contentType != null)
            {
                if (!contentType.Fields.ContainsField(column))
                {
                    SPField field = web.Fields.GetField(column);

                    SPFieldLink fieldLink = new SPFieldLink(field);
                    fieldLink.Required = required;
                    fieldLink.ReadOnly = readonlyField;

                    contentType.FieldLinks.Add(fieldLink);
                    contentType.Update(true);
                }
            }
        }
        catch (Exception ex)
        {
            SPDiagnosticsService.Local.WriteTrace(0, new SPDiagnosticsCategory("CORE:HELPERS", TraceSeverity.Unexpected, EventSeverity.Error), TraceSeverity.Unexpected, String.Format("Exception happened in Helpers:AddColumntToContentType. MESSAGE: {0}. EXCEPTION TRACE: {1} ", ex.Message, ex.StackTrace), ex.StackTrace);
        }
    }
コード例 #7
0
        /// <summary>
        /// Updates the fields of the list content type (listCT) with the
        /// fields found on the source content type (courceCT).
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="listCT">The list CT.</param>
        /// <param name="sourceCT">The source CT.</param>
        private static void UpdateListFields(SPList list, SPContentType listCT, SPContentType sourceCT)
        {
            Logger.Write("PROGRESS: Starting to update fields...");
            foreach (SPFieldLink sourceFieldLink in sourceCT.FieldLinks)
            {
                //has the field changed? If not, continue.
                if (listCT.FieldLinks[sourceFieldLink.Id] != null && listCT.FieldLinks[sourceFieldLink.Id].SchemaXml == sourceFieldLink.SchemaXml)
                {
                    Logger.Write("PROGRESS: Doing nothing to field \"{0}\" from Content Type on: \"{1}\"", sourceFieldLink.Name, list.RootFolder.ServerRelativeUrl);
                    continue;
                }

                if (!FieldExist(sourceCT, sourceFieldLink))
                {
                    Logger.Write("PROGRESS: Doing nothing to field: \"{0}\" on list \"{1}\" field does not exist (in .Fields[]) on source Content Type.", sourceFieldLink.Name, list.RootFolder.ServerRelativeUrl);
                    continue;
                }

                if (listCT.FieldLinks[sourceFieldLink.Id] != null)
                {
                    Logger.Write("PROGRESS: Deleting field \"{0}\" from Content Type on \"{1}\"...", sourceFieldLink.Name, list.RootFolder.ServerRelativeUrl);

                    listCT.FieldLinks.Delete(sourceFieldLink.Id);
                    listCT.Update();
                }

                Logger.Write("PROGRESS: Adding field \"{0}\" from Content Type on \"{1}\"...", sourceFieldLink.Name, list.RootFolder.ServerRelativeUrl);

                listCT.FieldLinks.Add(new SPFieldLink(sourceCT.Fields[sourceFieldLink.Id]));
                //Set displayname, not set by previous operation
                listCT.FieldLinks[sourceFieldLink.Id].DisplayName = sourceCT.FieldLinks[sourceFieldLink.Id].DisplayName;
                listCT.Update();
                Logger.Write("PROGRESS: Done updating fields.");
            }
        }
コード例 #8
0
        private SPContentType EnsureContentTypeExists(ref SPWeb web)
        {
            SPContentType cType = null;

            try
            {
                cType = web.ContentTypes[ContentTypeId];
            }
            catch { /* expected: not found */ }

            if (cType == null)
            {
                int    ctCounter = 0;
                string ctId      = ContentTypeId.ToString();
                string ctName    = Name;
                while (web.AvailableContentTypes[new SPContentTypeId(ctId)] != null && ctCounter < 100)
                {
                    ctCounter++;
                    ctId   = ContentTypeId.ToString() + ctCounter.ToString("00");
                    ctName = string.Concat(Name, ParentSchema.ContentTypeNameSchemaSeparator, ctCounter);
                }

                SPContentType.ValidateName(ctName);
                cType          = new SPContentType(new SPContentTypeId(ctId), web.ContentTypes, ctName);
                cType.Group    = ParentSchema.GroupName;
                cType.ReadOnly = false;
                web.ContentTypes.Add(cType);

                //myContentType.Update();
            }

            return(cType);
        }
コード例 #9
0
        public static SPContentType CreateContentType(this SPWeb web,
                                                      SPContentTypeId parentContentTypeId,
                                                      string ctName,
                                                      Action <SPContentType> action,
                                                      bool updateChildren = false)
        {
            using (SPWeb rootWeb = web.Site.OpenWeb(web.Site.RootWeb.ID))
            {
                SPContentType contentType = rootWeb.ContentTypes[ctName];

                if (contentType == null)
                {
                    SPContentType parentContentType = web.AvailableContentTypes[parentContentTypeId];

                    if (parentContentType != null)
                    {
                        contentType = new SPContentType(parentContentType, rootWeb.ContentTypes, ctName);
                        contentType = rootWeb.ContentTypes.Add(contentType);
                    }
                    else
                    {
                        throw new SPException(string.Format("Content type with Id = \"{0}\" not found or not available.",
                                                            parentContentTypeId));
                    }
                }

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

                contentType.Update(updateChildren);
                return(contentType);
            }
        }
コード例 #10
0
        protected virtual void ProcessFormProperties(SPContentType targetContentType, ContentTypeDefinition contentTypeModel)
        {
            if (!string.IsNullOrEmpty(contentTypeModel.NewFormUrl))
            {
                targetContentType.NewFormUrl = contentTypeModel.NewFormUrl;
            }

            if (!string.IsNullOrEmpty(contentTypeModel.NewFormTemplateName))
            {
                targetContentType.NewFormTemplateName = contentTypeModel.NewFormTemplateName;
            }

            if (!string.IsNullOrEmpty(contentTypeModel.EditFormUrl))
            {
                targetContentType.EditFormUrl = contentTypeModel.EditFormUrl;
            }

            if (!string.IsNullOrEmpty(contentTypeModel.EditFormTemplateName))
            {
                targetContentType.EditFormTemplateName = contentTypeModel.EditFormTemplateName;
            }

            if (!string.IsNullOrEmpty(contentTypeModel.DisplayFormUrl))
            {
                targetContentType.DisplayFormUrl = contentTypeModel.DisplayFormUrl;
            }

            if (!string.IsNullOrEmpty(contentTypeModel.DisplayFormTemplateName))
            {
                targetContentType.DisplayFormTemplateName = contentTypeModel.DisplayFormTemplateName;
            }
        }
コード例 #11
0
        public string[] FetchControlLists(string[] controlListIds, string cultureName)
        {
            //CommonUtilities.ConfirmNotNull(cultureName, "cultureName");
            //ULS.SendTraceTag(0x3670356d, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.Medium, "SharepointPublishingToolboxService.FetchControlLists(, {0})", new object[] { cultureName });
            SPUtility.EnsureAuthentication(SPContext.Current.Site.RootWeb);
            CultureInfo culture = new CultureInfo(cultureName);
            //CommonUtilities.ConfirmNotNull(controlListIds, "controlListIds");
            SPContentTypeCollection contentTypes = this.GetContentTypes();
            TagNameCreator          tagCreator   = new TagNameCreator();

            string[] strArray = new string[controlListIds.Length];
            for (int i = 0; i < controlListIds.Length; i++)
            {
                string str = controlListIds[i];
                if (str == publishingControlspanelTypeIdentifier.ToString())
                {
                    strArray[i] = "";
                }
                else if (contentTypes != null)
                {
                    SPContentTypeId id          = new SPContentTypeId(str);
                    SPContentType   contentType = contentTypes[id];
                    if (contentType == null)
                    {
                        //string message = Resources.GetFormattedStringEx("ErrorContentTypeNotFound", culture, new object[] { str });
                        //ULS.SendTraceTag(0x3670356e, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.Unexpected, "The content type {0} is not found", new object[] { str });
                        SoapException exception = new SoapException("ContentType is Empty", SoapException.ClientFaultCode);
                        throw exception;
                    }
                    strArray[i] = GetInfoFromCT(contentType, contentTypes, tagCreator, culture);
                }
            }
            //ULS.SendTraceTag(0x3670356f, ULSCat.msoulscat_CMS_Publishing, ULSTraceLevel.Medium, "SharepointPublishingToolboxService.GetCustomControlLists ends");
            return(strArray);
        }
コード例 #12
0
 public void InvokeOnContentTypeCreated(ref SPContentType type)
 {
     if (ContentTypeCreated != null)
     {
         ContentTypeCreated(ref type);
     }
 }
コード例 #13
0
        //Content Type Web Site Correspondencia
        public void CreateCustomContentTypes(string nameCustomType, string nameGroupContentType, List <SPField> siteColumns)
        {
            using (SPSite site = oSPSite)
            {
                using (SPWeb oSPWeb = site.RootWeb)
                {
                    // Get a reference to the Document or Item content type.
                    SPContentType parentCType = oSPWeb.AvailableContentTypes[SPBuiltInContentTypeId.Document];

                    // Create a Customer content type derived from the Item content type.
                    SPContentType childCType = new SPContentType(parentCType, oSPWeb.ContentTypes, nameCustomType);

                    childCType.Group = nameGroupContentType;

                    // Add the new content type to the site collection.
                    childCType = oSPWeb.ContentTypes.Add(childCType);

                    foreach (SPField field in siteColumns)
                    {
                        SPFieldLink fieldLink = new SPFieldLink(field);
                        childCType.FieldLinks.Add(fieldLink);
                    }
                    string[] fieldsToHide = new string[] { "Título" };
                    foreach (string fieldDispName in fieldsToHide)
                    {
                        SPField field = childCType.Fields[fieldDispName];
                        childCType.FieldLinks[field.Id].Hidden = true;
                    }

                    childCType.Update();

                    oSPWeb.Update();
                }
            }
        }
コード例 #14
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);
            }
        }
コード例 #15
0
        private SPEventReceiverDefinition AddEventReceiverDefinition(SPContentType contentType, SPEventReceiverType type, string assemblyName, string className, SPEventReceiverSynchronization syncType, int sequenceNumber)
        {
            SPEventReceiverDefinition eventReceiverDefinition = null;

            // Try Parse the Assembly Name
            var classType = Type.GetType(string.Format(CultureInfo.InvariantCulture, "{0}, {1}", className, assemblyName));

            if (classType != null)
            {
                var assembly         = Assembly.GetAssembly(classType);
                var isAlreadyDefined = contentType.EventReceivers.Cast <SPEventReceiverDefinition>().Any(x => (x.Class == className) && (x.Type == type));

                // If definition isn't already defined, add it to the content type
                if (!isAlreadyDefined)
                {
                    eventReceiverDefinition                 = contentType.EventReceivers.Add();
                    eventReceiverDefinition.Type            = type;
                    eventReceiverDefinition.Assembly        = assembly.FullName;
                    eventReceiverDefinition.Synchronization = syncType;
                    eventReceiverDefinition.Class           = className;
                    eventReceiverDefinition.SequenceNumber  = sequenceNumber;
                    eventReceiverDefinition.Update();
                    contentType.Update(true);
                }
            }

            return(eventReceiverDefinition);
        }
コード例 #16
0
        public void UploadItem(SPList Lib, DataTable dt, SPContentType ct, string FileName, byte[] file)
        {
            Lib.ParentWeb.AllowUnsafeUpdates = true;

            Hashtable properties = new Hashtable();

            if (dt != null && dt.TableName == ct.Name)
            {
                properties.Add("ContentType", ct.Name);
                foreach (DataRow row in dt.Rows)
                {
                    if (string.IsNullOrEmpty(row["Value"].ToString()) == false)
                    {
                        string id  = row["ID"].ToString();
                        string val = row["Value"].ToString();
                        properties.Add(id, val);
                    }
                }
            }

            SPFolder folder = Lib.RootFolder;

            try
            {
                folder.Files.Add(FileName, file, properties, true);
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("Error uploading File {0}", FileName), ex.InnerException);
            }

            MessageBox.Show(string.Format("{0} uploaded successfully to {1}", FileName, Lib.Title));
        }
コード例 #17
0
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            using (SPWeb web = site.RootWeb)
            {
                SPList approvedEstimatesList = web.GetList(string.Concat(web.ServerRelativeUrl, Constants.approvedEstimatesListLocation));

                SPContentType sowContentType      = AddContentTypeToList(Constants.sowContentTypeId, approvedEstimatesList, web);
                SPContentType estimateContentType = AddContentTypeToList(Constants.estimateContentTypeId, approvedEstimatesList, web);

                Guid[] fieldsToAdd = new Guid[]
                {
                    Constants.estimateStatusFieldId,
                    Constants.estimateValueFieldId,
                    Constants.projectLookupFieldId
                };
                AddFieldsToContentType(web, sowContentType, fieldsToAdd);
                AddFieldsToContentType(web, estimateContentType, fieldsToAdd);

                if (approvedEstimatesList.ContentTypes[Constants.documentContentTypeId] != null)
                {
                    SPContentTypeId spContentTypeIdInList = approvedEstimatesList.ContentTypes.BestMatch(
                        Constants.documentContentTypeId);

                    approvedEstimatesList.ContentTypes.Delete(spContentTypeIdInList);
                    approvedEstimatesList.Update();
                }
            }
        }
コード例 #18
0
        protected void EnsureRequestParamsParsed()
        {
            workflowName = Request.Params["WorkflowName"];

            string strListID = Request.QueryString["List"];
            string strCTID = Request.QueryString["ctype"];

            if (strListID != null)
                list = Web.Lists[new Guid(strListID)];

            if (strCTID != null)
            {
                requestQueryString = "ctype=" + strCTID;

                if (list != null)
                {
                    requestQueryString += "&List=" + strListID;
                    contentType = list.ContentTypes[new SPContentTypeId(strCTID)];
                }
                else
                {
                    contentType = Web.ContentTypes[new SPContentTypeId(strCTID)];
                    useContentTypeTemplate = true;
                }
            }
            else
                requestQueryString = "List=" + strListID;
        }
コード例 #19
0
        public static void CreateList(SPWeb web)
        {
            DeleteList(web);

            // New List

            SPListTemplateType template = SPListTemplateType.GenericList;
            Guid   listId = web.Lists.Add(Language.SMUListName, Language.SMUListDescription, template);
            SPList list   = web.Lists[listId];

            SPContentType ct = web.AvailableContentTypes[Language.SMUChatMessage];

            list.Hidden = true;

#if DEBUG
            list.Hidden = false;
#endif

            list.ContentTypesEnabled = true;

            list.EnableVersioning = false;
            list.ContentTypes.Add(ct);

            // get rid of the item content type
            list.ContentTypes["Item"].Delete();

            CreateDefaultListView(list);

            ApplyGroupRoleAssignments(web, list);
        }
コード例 #20
0
        public ArtDevContentType CreateContentType(string Name, SPContentTypeId parent)
        {
            SPContentType     type       = NewOrRefContentType(Name, parent);
            ArtDevContentType ArtDevType = new ArtDevContentType(type);

            return(ArtDevType);
        }
コード例 #21
0
        /// <summary>
        /// Setea un el Content Type al documento especificado
        /// </summary>
        /// <param name="listItem"></param>
        /// <param name="contentTypeName"></param>
        public static void CambiarContentType(SPListItem listItem, string contentTypeName)
        {
            SPContentType contentType = listItem.ParentList.ContentTypes[contentTypeName];

            listItem["ContentType"]   = contentType.Name;
            listItem["ContentTypeId"] = contentType.Id.ToString();
        }
コード例 #22
0
        public DataTable GetMetadataForCT(SPContentType ct)
        {
            // Create ID-Value DataTable for Metadata
            DataTable dtMetadata = new DataTable(ct.Name);

            dtMetadata.Columns.Add("ID");
            dtMetadata.Columns.Add("Value");
            dtMetadata.Columns[0].ReadOnly = true;

            foreach (SPField field in ct.Fields)
            {
                if (!(field.ReadOnlyField || field.Hidden))
                {
                    if (field.InternalName == "ContentType")
                    {
                        dtMetadata.Rows.Add(field.InternalName, ct.ToString());
                    }
                    else
                    {
                        dtMetadata.Rows.Add(field.InternalName);
                    }
                }
            }

            return(dtMetadata);
        }
コード例 #23
0
        public static T GetCustomSettings <T>(this SPContentType contentType, AIAPortalFeatures featureName, bool lookupInParent)
        {
            string strKey      = Utility.BuildKey <T>(featureName);
            string settingsXml = contentType.XmlDocuments[strKey];

            if (!string.IsNullOrEmpty(settingsXml))
            {
                return((T)SerializationHelper.DeserializeFromXml <T>(settingsXml, strKey));
            }

            if (!lookupInParent)
            {
                return(default(T));
            }

            T objReturn = default(T);

            if (contentType.Parent.Sealed == false)
            {
                objReturn = contentType.Parent.GetCustomSettings <T>(featureName);
            }

            if (objReturn == null && contentType.ParentList != null)
            {
                objReturn = contentType.ParentList.GetCustomSettings <T>(featureName);
            }

            if (objReturn == null && contentType.ParentWeb != null)
            {
                objReturn = contentType.ParentWeb.GetCustomSettings <T>(featureName);
            }

            return(objReturn);
        }
コード例 #24
0
        private void UnbindContentType(object sender, EventArgs e)
        {
            if (selectedList != null)
            {
                SPListItemCollection items    = selectedList.Items;
                SPContentType        searched = null;

                if (lvBoundCT.SelectedItems.Count > 0)
                {
                    searched = (SPContentType)lvBoundCT.SelectedItems[0].Tag;
                }
                else
                {
                    MessageBox.Show("Please select a content type to unbind");
                    return;
                }


                foreach (SPListItem item in items)
                {
                    if (item.ContentType == searched)
                    {
                        MessageBox.Show("Content Type is in use. Please delete entries first");
                        return;
                    }
                }

                selectedList.ContentTypes.Delete(searched.Id);
                RefreshBoundContentTypesTable();
            }
        }
コード例 #25
0
        protected SPContentType GetListContentType(SPList list, ContentTypeLinkDefinition definition)
        {
            SPContentType result = null;

            if (!string.IsNullOrEmpty(definition.ContentTypeName))
            {
                result = list.ContentTypes[definition.ContentTypeName];
            }

            if (result == null && !string.IsNullOrEmpty(definition.ContentTypeId))
            {
                var linkContentType = new SPContentTypeId(definition.ContentTypeId);

                // "Item" ContentTypeLink #1016
                // replacing best match, it does not work on list scoped content types

                // Content type operations within a list
                // http://docs.subpointsolutions.com/spmeta2/kb/kb-m2-000003.html

                //var bestMatch = list.ContentTypes.BestMatch(linkContenType);

                //if (bestMatch.IsChildOf(linkContenType))
                //    result = list.ContentTypes[bestMatch];

                result = list.ContentTypes
                         .OfType <SPContentType>()
                         .FirstOrDefault(ct => ct.Parent.Id == linkContentType);
            }

            return(result);
        }
コード例 #26
0
        private static SPContentType EnsureContentType(SPSite site)
        {
            SPWeb web = site.RootWeb;
            SPContentType configContentType = web.AvailableContentTypes[ConfigurationContentTypeId];

            if (configContentType == null)
            {
                try
                {
                    EnsureSiteColumns(web);
                    configContentType = new SPContentType(ConfigurationContentTypeId, web.ContentTypes, ConfigContentTypeName);

                    web.ContentTypes.Add(configContentType);
                    configContentType.Group = PNPContentTypeGroup;
                    configContentType.FieldLinks.Add(new SPFieldLink(web.AvailableFields[SettingWebIdFieldId]));
                    configContentType.FieldLinks.Add(new SPFieldLink(web.AvailableFields[SettingKeyFieldId]));
                    configContentType.FieldLinks.Add(new SPFieldLink(web.AvailableFields[SettingValueFieldId]));
                    configContentType.Update();
                }
                catch (Exception ex)
                {
                    //try to cleanup
                    configContentType = web.AvailableContentTypes[ConfigurationContentTypeId];

                    if (configContentType != null)
                        web.ContentTypes.Delete(ConfigurationContentTypeId);

                    ConfigurationException configEx = new ConfigurationException(Resources.CreateConfigContentTypeFailed, ex);
                    throw (configEx);
                }
            }

            return configContentType;
        }
コード例 #27
0
 /// <summary>
 /// Processes the content type.
 /// </summary>
 /// <param name="site">The site.</param>
 /// <param name="contentTypeName">Name of the content type.</param>
 /// <param name="verbose">if set to <c>true</c> [verbose].</param>
 /// <param name="updateFields">if set to <c>true</c> [update fields].</param>
 /// <param name="removeFields">if set to <c>true</c> [remove fields].</param>
 public static void Execute(SPSite site, string contentTypeName, bool updateFields, bool removeFields)
 {
     try
     {
         Logger.Write("Pushing content type changes to lists for '" + contentTypeName + "'");
         // get the site collection specified
         using (SPWeb rootWeb = site.RootWeb)
         {
             //Get the source site content type
             SPContentType sourceCT = rootWeb.AvailableContentTypes[contentTypeName];
             if (sourceCT == null)
             {
                 throw new ArgumentException("Unable to find Content Type named \"" + contentTypeName + "\"");
             }
             Execute(sourceCT, updateFields, removeFields);
         }
         return;
     }
     catch (Exception ex)
     {
         Logger.WriteException(new System.Management.Automation.ErrorRecord(new SPException("Unhandled error occured.", ex), null, System.Management.Automation.ErrorCategory.NotSpecified, null));
         throw;
     }
     finally
     {
         Logger.Write("Finished pushing content type changes to lists for '" + contentTypeName + "'");
     }
 }
        public override void FeatureDeactivating(SPFeatureReceiverProperties properties)
        {
            //Get references to the site and web, ensuring correct disposal
            using (SPSite site = (SPSite)properties.Feature.Parent)
            {
                using (SPWeb web = site.RootWeb)
                {
                    //get the custom content type
                    SPContentType myContentType = web.ContentTypes["Product Announcement Content Type"];
                    if (myContentType != null)
                    {
                        //Remove it from the Announcements list
                        SPList annoucementsList = web.Lists["Announcements"];
                        annoucementsList.ContentTypesEnabled = true;
                        SPContentTypeId ctID = annoucementsList.ContentTypes.BestMatch(myContentType.Id);
                        annoucementsList.ContentTypes.Delete(ctID);
                        annoucementsList.Update();

                        //Remove it from the site
                        web.ContentTypes.Delete(myContentType.Id);
                        web.Update();
                    }
                    try {
                        //Remove the field
                        web.Fields.Delete("ContosoProductName");
                        web.Update();
                    }
                    catch
                    {
                        //Field was not in the collection
                    }
                }
            }
        }
コード例 #29
0
        public static IEnumerable <TList> GetListsByContentType <TList>(this SPWeb web, string contentTypeName)
            where TList : SPList
        {
            SPContentType contentType = web.AvailableContentTypes[contentTypeName];

            return(SPHelper.GetListsByContentType <TList>(web, contentType));
        }
コード例 #30
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);
            }
        }
コード例 #31
0
        private static void AddFieldsToContentType(SPWeb web, SPContentType contentType, Guid[] fieldIdArray, bool required)
        {
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

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

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

            foreach (Guid fieldId in fieldIdArray)
            {
                SPField field = web.AvailableFields[fieldId];

                SPFieldLink fieldLink = new SPFieldLink(field);
                fieldLink.Required = required;

                if (contentType.FieldLinks[fieldLink.Id] == null)
                {
                    contentType.FieldLinks.Add(fieldLink);
                }
            }
        }
コード例 #32
0
        public static SPContentTypeId EnsureContentTypeInListWithoutPrivileges(this SPList list, string contentTypeId)
        {
            SPContentTypeId ctIdReturn = SPContentTypeId.Empty;

            if (!list.ContentTypesEnabled)
            {
                list.ContentTypesEnabled = true;
            }

            SPContentTypeId sourceCTId = new SPContentTypeId(contentTypeId);
            SPContentTypeId foundCTId  = list.ContentTypes.BestMatch(sourceCTId);
            bool            found      = (foundCTId.Parent.CompareTo(sourceCTId) == 0);
            SPContentType   ct         = list.ParentWeb.FindContentType(sourceCTId);

            if (found)
            {
                ctIdReturn = list.ContentTypes[ct.Name].Id;
            }
            else
            {
                if (ct != null)
                {
                    ctIdReturn = list.ContentTypes.Add(ct).Id;
                }
            }
            list.Update();

            return(ctIdReturn);
        }
コード例 #33
0
        public void DeleteEventReceiverDefinition(SPContentType contentType, SPEventReceiverType type, string className)
        {
            var eventReceiverDefinition = contentType.EventReceivers.Cast<SPEventReceiverDefinition>().FirstOrDefault(x => (x.Class == className) && (x.Type == type));

            // If definition isn't already defined, add it to the content type
            if (eventReceiverDefinition != null)
            {
                var eventToDelete = contentType.EventReceivers.Cast<SPEventReceiverDefinition>().Where(eventReceiver => eventReceiver.Type == eventReceiverDefinition.Type).ToList();
                eventToDelete.ForEach(c => c.Delete());
                contentType.Update(true);
            }
        }
コード例 #34
0
        private void DeployContentTypeOrder(object modelHost, SPContentType contentType, UniqueContentTypeFieldsOrderDefinition reorderFieldLinksModel)
        {
            var fieldLinks = contentType.FieldLinks.OfType<SPFieldLink>().ToList();
            var fields = contentType.Fields.OfType<SPField>().ToList();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = contentType,
                ObjectType = typeof(SPContentType),
                ObjectDefinition = reorderFieldLinksModel,
                ModelHost = modelHost
            });

            var newOrder = new List<string>();

            // re-order
            foreach (var srcFieldLink in reorderFieldLinksModel.Fields)
            {
                SPField currentField = null;

                if (!string.IsNullOrEmpty(srcFieldLink.InternalName))
                    currentField = fields.FirstOrDefault(c => c.InternalName == srcFieldLink.InternalName);

                if (currentField == null && srcFieldLink.Id.HasValue)
                    currentField = fields.FirstOrDefault(c => c.Id == srcFieldLink.Id.Value);

                if (currentField != null)
                {
                    var ctField = contentType.Fields[currentField.Id];

                    // must always be internal name of the field
                    if (!newOrder.Contains(ctField.InternalName))
                        newOrder.Add(ctField.InternalName);
                }
            }

            if (newOrder.Count > 0)
                contentType.FieldLinks.Reorder(newOrder.ToArray());

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = contentType,
                ObjectType = typeof(SPContentType),
                ObjectDefinition = reorderFieldLinksModel,
                ModelHost = modelHost
            });
        }
コード例 #35
0
        public ContentTypeUsageCollectionNode(SPContentType parent, IList<SPContentTypeUsage> collection)
        {
            this.Text = SPMLocalization.GetString("ContentTypeUsages_Text");
            this.ToolTipText = SPMLocalization.GetString("ContentTypeUsages_ToolTip");
            this.Name = "ContentTypeUsages Collection";
            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"));
        }
コード例 #36
0
        public static void ProvisionContentType(SPWeb spWeb)
        {
            /* Create the content type. */
            SPContentType ct = spWeb.ContentTypes[ContentTypeID];
            if (ct == null)
            {

                ct = new SPContentType(ContentTypeID, spWeb.ContentTypes, ContentTypeName);
                ct.Group = AppConstants.ContentTypeGroupName;
                spWeb.ContentTypes.Add(ct);
            }

            /*Add fields to content type .*/
            if (!ct.Fields.Contains(SiteColumns.Class))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Class]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Student))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Student]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.ClassYear))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.ClassYear]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.TotalPoints))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.TotalPoints]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.TotalPointsAllowed))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.TotalPointsAllowed]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.LetterGrade))
            {
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.LetterGrade]);
                ct.FieldLinks.Add(field);
            }

            ct.Update(true);
        }
コード例 #37
0
ファイル: ContentTypeNode.cs プロジェクト: lucaslra/SPM
        public ContentTypeNode(SPContentType contentType)
        {
            this.Tag = contentType;
            try
            {
                this.SPParent = contentType.Parent;
            }
            catch
            {
                // Do nothing
            }

            //this.ContextMenuStrip = new SiteMenuStrip();

            Setup();
        }
コード例 #38
0
ファイル: ListHelper.cs プロジェクト: JeanNguon/Projet
 public static SPList TryCreateList(SPWeb web, string listName, SPListTemplateType templateType, SPContentType[] contentTypes, string listDescription)
 {
     SPList list = web.Lists.TryGetList(listName);
     if (list == null)
     {
         Guid listId = web.Lists.Add(listName, listDescription, templateType);
         list = web.Lists[listId];
         list.ContentTypesEnabled = true;
         foreach (SPContentType ct in contentTypes)
         {
             list.ContentTypes.Add(ct);
         }
         list.OnQuickLaunch = false;
         list.Update();
     }
     return list;
 }
コード例 #39
0
        private void DeployHideContentTypeLinks(object modelHost, SPContentType contentType, HideContentTypeFieldLinksDefinition hideFieldLinksModel)
        {
            var fieldLinks = contentType.FieldLinks.OfType<SPFieldLink>().ToList();

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioning,
                Object = contentType,
                ObjectType = typeof(SPContentType),
                ObjectDefinition = hideFieldLinksModel,
                ModelHost = modelHost
            });

            // re-order
            foreach (var srcFieldLink in hideFieldLinksModel.Fields)
            {
                SPFieldLink currentFieldLink = null;

                if (!string.IsNullOrEmpty(srcFieldLink.InternalName))
                    currentFieldLink = fieldLinks.FirstOrDefault(c => c.Name == srcFieldLink.InternalName);

                if (currentFieldLink == null && srcFieldLink.Id.HasValue)
                    currentFieldLink = fieldLinks.FirstOrDefault(c => c.Id == srcFieldLink.Id.Value);

                if (currentFieldLink != null)
                {
                    currentFieldLink.ReadOnly = false;
                    currentFieldLink.Required = false;
                    currentFieldLink.Hidden = true;
                }
            }

            InvokeOnModelEvent(this, new ModelEventArgs
            {
                CurrentModelNode = null,
                Model = null,
                EventType = ModelEventType.OnProvisioned,
                Object = contentType,
                ObjectType = typeof(SPContentType),
                ObjectDefinition = hideFieldLinksModel,
                ModelHost = modelHost
            });
        }
コード例 #40
0
        protected SPFieldLink FindExistingFieldLink(SPContentType contentType, ContentTypeFieldLinkDefinition fieldLinkModel)
        {
            if (fieldLinkModel.FieldId.HasValue)
            {
                return contentType.FieldLinks
                      .OfType<SPFieldLink>()
                      .FirstOrDefault(l => l.Id == fieldLinkModel.FieldId);

            }
            else if (!string.IsNullOrEmpty(fieldLinkModel.FieldInternalName))
            {
                return contentType.FieldLinks
                      .OfType<SPFieldLink>()
                      .FirstOrDefault(l => l.Name.ToUpper() == fieldLinkModel.FieldInternalName.ToUpper());
            }

            throw new ArgumentException("FieldId or FieldInternalName must be defined");
        }
コード例 #41
0
        protected override void ProcessRecord()
        {
            var schema = XDocument.Load(SchemaPath);
            XNamespace ns = "http://schemas.microsoft.com/sharepoint/";

            using (var site = new SPSite(Url))
            {
                var web = site.OpenWeb();

                // Process fields.
                foreach (var field in schema.Root.Descendants(ns+"Field"))
                {
                    WriteObject("Processing " + field.Attribute("Name").Value);

                    var fieldName = web.Fields.Add(field.Attribute("Name").Value, SPFieldType.Text, false);
                    var spField = web.Fields.GetFieldByInternalName(fieldName);
                    spField.StaticName = field.Attribute("StaticName").Value;
                    spField.Title = field.Attribute("DisplayName").Value;
                    spField.Update();
                }

                // Process content types.
            }

            return;

            using (var site = new SPSite(Url))
            {
                var web = site.RootWeb;

                var field = web.Fields["URL"];

                var id = new SPContentTypeId("0x01010075425CE93BDC404F8B042629FC235785");
                var termsAndConditionsType = new SPContentType(id, web.ContentTypes, "TermsAndConditionsType");
                web.ContentTypes.Add(termsAndConditionsType);
                termsAndConditionsType = web.ContentTypes[id];
                termsAndConditionsType.Group = "Custom Content Types";
                termsAndConditionsType.Description = "Custom Content Type for Terms and Conditions";
                termsAndConditionsType.Update();
                var l = new SPFieldLink(field) { DisplayName = "My URL" };
                termsAndConditionsType.FieldLinks.Add(l);
                termsAndConditionsType.Update();
            }
        }
コード例 #42
0
        public static void ProvisionContentType(SPWeb spWeb)
        {
            /* Create the content type. */
            SPContentType ct = spWeb.ContentTypes[ContentTypeID];
            if (ct == null)
            {

                ct = new SPContentType(ContentTypeID, spWeb.ContentTypes, ContentTypeName);
                ct.Group = AppConstants.ContentTypeGroupName;
                spWeb.ContentTypes.Add(ct);
            }

            /*Add fields to content type .*/
            //if (!ct.Fields.Contains(SiteColumns.StudentFirstname))
            //{
            //    SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.StudentFirstname]);
            //    ct.FieldLinks.Add(field);
            //}

            //if (!ct.Fields.Contains(SiteColumns.StudentLastname))
            //{
            //    SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.StudentLastname]);
            //    ct.FieldLinks.Add(field);
            //}

            //if (!ct.Fields.Contains(SiteColumns.StudentFullname))
            //{
            //    SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.StudentFullname]);
            //    ct.FieldLinks.Add(field);
            //}
            if (!ct.Fields.Contains(SiteColumns.Student)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Student]);
                ct.FieldLinks.Add(field);
            }

            if (!ct.Fields.Contains(SiteColumns.Parents)){
                SPFieldLink field = new SPFieldLink(spWeb.AvailableFields[SiteColumns.Parents]);
                ct.FieldLinks.Add(field);
            }

            ct.Update(true);
        }
コード例 #43
0
        public static void Execute(SPContentType sourceCT, bool updateFields, bool removeFields)
        {
            using (SPSite site = new SPSite(sourceCT.ParentWeb.Site.ID))
            {
                IList<SPContentTypeUsage> ctUsageList = SPContentTypeUsage.GetUsages(sourceCT);
                foreach (SPContentTypeUsage ctu in ctUsageList)
                {
                    if (!ctu.IsUrlToList)
                        continue;

                    SPWeb web = null;
                    try
                    {
                        try
                        {
                            string webUrl = ctu.Url;
                            if (webUrl.ToLowerInvariant().Contains("_catalogs/masterpage"))
                                webUrl = webUrl.Substring(0, webUrl.IndexOf("/_catalogs/masterpage"));

                            web = site.OpenWeb(webUrl);
                        }
                        catch (SPException ex)
                        {
                            Logger.WriteWarning("Unable to open host web of content type\r\n{0}", ex.Message);
                            continue;
                        }
                        if (web != null)
                        {

                            SPList list = web.GetList(ctu.Url);
                            SPContentType listCT = list.ContentTypes[ctu.Id];
                            ProcessContentType(list, sourceCT, listCT, updateFields, removeFields);
                        }
                    }
                    finally
                    {
                        if (web != null)
                            web.Dispose();
                    }
                }
            }
        }
コード例 #44
0
        public void CreateAutofolder(IContentOrganizerRuleCreationData data, SPContentType ruleContentType, EcmDocumentRouterRule organizeDocument)
        {
            // Ensure the SPField for the autofolder property
            TaxonomyField autoFolderField = ruleContentType.Fields[data.AutoFolderPropertyName] as TaxonomyField;
            if (autoFolderField == null)
                throw new ArgumentException(String.Format("The field {0} is not a valid Taxonomy Field", data.AutoFolderPropertyName));

            // Get a handle to the rule auto folder settings.
            DocumentRouterAutoFolderSettings autoFolderSettings = organizeDocument.AutoFolderSettings;
            // Configure AutoFolderSettings for this rule based on the Taxonomy field.
            autoFolderSettings.AutoFolderPropertyName = autoFolderField.Title;
            autoFolderSettings.AutoFolderPropertyInternalName = autoFolderField.InternalName;
            autoFolderSettings.AutoFolderPropertyId = autoFolderField.Id;
            // Term store Id required to get the value of the field from the document. Required for TaxonomyField types.
            autoFolderSettings.TaxTermStoreId = autoFolderField.SspId;
            // Set a format for the name of the folder.
            autoFolderSettings.AutoFolderFolderNameFormat = data.AutoFolderNameFormat;
            // Enabled automatic folder creation for values of the field.
            autoFolderSettings.Enabled = true;
        }
コード例 #45
0
        public static void SwapPageLayout(PublishingWeb publishingWeb, PageLayout defaultPageLayout, SPContentType ctype)
        {
            string checkInComment = "WET4 Automatic Event Handler Page Layout Fix";
            //
            // Validate the input parameters.
            if (null == publishingWeb)
            {
                throw new System.ArgumentNullException("publishingWeb");
            }
            if (null == defaultPageLayout)
            {
                throw new System.ArgumentNullException("defaultPageLayout");
            }

            SPList list = publishingWeb.PagesList;
            if (list.ContentTypes[defaultPageLayout.AssociatedContentType.Name] == null)
            {
                list.ContentTypes.Add(ctype);
            }
            SPContentType ct = list.ContentTypes[defaultPageLayout.AssociatedContentType.Name];

            PublishingPageCollection publishingPages = publishingWeb.GetPublishingPages();
            foreach (PublishingPage publishingPage in publishingPages)
            {
                if (publishingPage.ListItem.File.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    publishingPage.CheckOut();
                }
                publishingPage.ListItem["ContentTypeId"] = ct.Id;

                switch (publishingPage.Url)
                {
                    default:
                        publishingPage.Layout = defaultPageLayout;
                        publishingPage.Title = publishingWeb.Title;
                        break;
                }
                publishingPage.Update();
                publishingPage.CheckIn(checkInComment);
            }
        }
コード例 #46
0
        /// <summary>
        /// Create the Content Type
        /// </summary>
        /// <param name="id">GUID the ContentType</param>
        /// <returns></returns>
        public bool Create(string id)
        {
            try
            {
                SPContentTypeId idContentType;
                SPContentType contentType;
                if (!string.IsNullOrEmpty(id))
                {
                    idContentType = new SPContentTypeId(id);
                    contentType = Web.ContentTypes[idContentType];
                    if (contentType != null)
                    {
                        return true;
                    }
                    contentType = new SPContentType(idContentType, Web.ContentTypes, Name);
                    Web.ContentTypes.Add(contentType);
                }
                else
                {
                    var itemCType = Web.AvailableContentTypes[Parent];
                    var cType = new SPContentType(itemCType, Web.ContentTypes, Name)
                    {
                        Group = GroupName
                    };
                     contentType = Web.ContentTypes.Add(cType);
                    idContentType = contentType.Id;
                }


                Web.ContentTypes[idContentType].Group = GroupName;
                Web.Update();
                return true;
            }
            catch (Exception exception)
            {
                Logger.Error(string.Concat("Error Create ContentType:", exception.Message));
                return false;
            }
        }
コード例 #47
0
        /// <summary>
        /// Adds the content type.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="contentType">Type of the content.</param>
        /// <exception cref="System.ArgumentNullException">Any null parameter.</exception>
        public void AddContentType(SPList list, SPContentType contentType)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

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

            // Enable content types if not yet done.
            if (!list.ContentTypesEnabled)
            {
                list.ContentTypesEnabled = true;
                list.Update(true);
            }

            this.contentTypeBuilder.EnsureContentType(list.ContentTypes, contentType.Id, contentType.Name);
            list.Update(true);
        }
コード例 #48
0
        public void DeleteContentTypeIfNotUsed(SPContentType contentType)
        {
            // Find where the content type is being used.
            ICollection<SPContentTypeUsage> usages = SPContentTypeUsage.GetUsages(contentType);
            if (usages.Count <= 0)
            {
                // Delete unused content type.
                contentType.ParentWeb.ContentTypes.Delete(contentType.Id);
            }
            else
            {
                // Prepare the query to get all items in a list that uses the content type.
                SPQuery query = new SPQuery()
                {
                    Query = string.Concat(
                            "<Where><Eq>",
                                "<FieldRef Name='ContentTypeId'/>",
                                string.Format(CultureInfo.InvariantCulture, "<Value Type='Text'>{0}</Value>", contentType.Id),
                            "</Eq></Where>")
                };

                // Get the usages that are in a list.
                List<SPContentTypeUsage> listUsages = (from u in usages where u.IsUrlToList select u).ToList();
                foreach (SPContentTypeUsage usage in listUsages)
                {
                    // For a list usage, we get all the items in the list that use the content type.
                    SPList list = contentType.ParentWeb.GetList(usage.Url);
                    SPListItemCollection listItems = list.GetItems(query);

                    // if no items are found...
                    if (listItems.Count <= 0)
                    {
                        // Delete unused content type.
                        list.ContentTypes.Delete(contentType.Id);
                    }
                }
            }
        }
コード例 #49
0
        public void Copy(SPContentType sourceCT, string targetUrl)
        {
            // Make sure the source exists if it was specified.
            if (sourceCT == null)
            {
                throw new SPException("The source content type could not be found.");
            }

            SPFieldCollection sourceFields = sourceCT.ParentWeb.Fields;

            // Get the target content type and fields.
            GetAvailableTargetContentTypes(targetUrl);
            if (_availableTargetContentTypes[sourceCT.Name] == null)
            {
                Logger.Write("Progress: Source content type '{0}' does not exist on target - creating content type...", sourceCT.Name);

                CreateContentType(targetUrl, sourceCT, sourceFields);
            }
            else
            {
                throw new SPException("Content type already exists at target.");
            }
        }
コード例 #50
0
        // Uncomment the method below to handle the event raised after a feature has been activated.
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            using (SPWeb spWeb = properties.Feature.Parent as SPWeb)
            {
                SPContentType newAnnouncement = spWeb
                    .ContentTypes
                    .Cast<SPContentType>()
                    .FirstOrDefault(c => c.Name == "New Announcements");
                if (newAnnouncement != null)
                {
                    newAnnouncement.Delete();
                }

                SPField newField = spWeb.Fields
                    .Cast<SPField>()
                    .FirstOrDefault(f => f.StaticName == "Team Project");
                if (newField != null)
                {
                    newField.Delete();
                }

                SPContentType myContentType =
                    new SPContentType(spWeb.ContentTypes["Announcement"],
                        spWeb.ContentTypes, "New Announcements");
                myContentType.Group = "Custom Content Types";

                spWeb.Fields.Add("Team Project", SPFieldType.Text, true);
                SPFieldLink projFeldLink = new SPFieldLink(spWeb.Fields["Team Project"]);
                myContentType.FieldLinks.Add(projFeldLink);

                SPFieldLink companyFieldLink = new SPFieldLink(spWeb.Fields["Company"]);
                myContentType.FieldLinks.Add(companyFieldLink);

                spWeb.ContentTypes.Add(myContentType);
                myContentType.Update();
            }
        }
コード例 #51
0
        public void AddContentTypeTo(SPContentTypeCollection contentTypeCollection, SPWeb parentWeb = null)
        {
            SPContentType newCt = GetContentType(contentTypeCollection);
            if (newCt != null)
                return;

            if (parentWeb != null && ((newCt = GetContentType(parentWeb.Site.RootWeb.AvailableContentTypes)) != null))
            {
                contentTypeCollection.Add(newCt);
            }
            else
            {
                if (!string.IsNullOrEmpty(ContentTypeId))
                {
                    newCt = new SPContentType(new SPContentTypeId(ContentTypeId), contentTypeCollection, Name);
                }
                else
                {
                    SPContentType parentCt = parentWeb.AvailableContentTypes[ParentContentType];
                    newCt = new SPContentType(parentCt, contentTypeCollection, Name);
                }

                if (!string.IsNullOrEmpty(Group))
                    newCt.Group = Group;
                if (!string.IsNullOrEmpty(Description))
                    newCt.Description = Description;

                try { contentTypeCollection.Add(newCt); }
                catch (SPException)
                {
                    parentWeb.Site.RootWeb.ContentTypes.Add(newCt);
                    newCt = parentWeb.Site.RootWeb.ContentTypes[newCt.Id];
                    contentTypeCollection.Add(newCt);
                }
            }
        }
        /// <summary>
        /// Gets a value indicating whether the document sets are fully deployed.
        /// </summary>
        /// <param name="contentType">The content type.</param>
        /// <returns><c>true</c> if deployed; otherwise, <c>false</c>.</returns>
        private bool Deployed(SPContentType contentType)
        {
            SPFile welcomePage = this.GetWelcomePage(contentType);
            if (welcomePage == null)
            {
                return false;
            }

            if (this.EnsureWebParts)
            {
                return false;
            }

            return GetWelcomePageWebPartmanager(this.GetWelcomePage(contentType)).WebParts.Count > 1;
        }
コード例 #53
0
        protected virtual void ProcessLocalization(SPContentType obj, ContentTypeDefinition definition)
        {
            if (definition.NameResource.Any())
            {
                foreach (var locValue in definition.NameResource)
                    LocalizationService.ProcessUserResource(obj, obj.NameResource, locValue);
            }

            if (definition.DescriptionResource.Any())
            {
                foreach (var locValue in definition.DescriptionResource)
                    LocalizationService.ProcessUserResource(obj, obj.DescriptionResource, locValue);
            }
        }
コード例 #54
0
ファイル: Utility.cs プロジェクト: iburykin/SFPU-Branding
 internal static SPContentType CreateSiteContentType(SPWeb web, string contentTypeName, SPContentTypeId parentItemCTypeId, string group, string perentCT)
 {
     var tt = web.AvailableContentTypes[contentTypeName];
     if (web.AvailableContentTypes[contentTypeName] == null)
     {
         SPContentType itemCType = web.AvailableContentTypes[perentCT];//parentItemCTypeId
         SPContentType contentType =
             new SPContentType(itemCType, web.ContentTypes, contentTypeName) { Group = @group };
         web.ContentTypes.Add(contentType);
         contentType.Update();
         return contentType;
     }
     return web.ContentTypes[contentTypeName];
 }
コード例 #55
0
        private SPListItem CopyFile(SPFile sourceFile, SPFolder destFolder, SPContentType destContentType)
        {
            string filename = BuildDestinationFilename(sourceFile.Name, destFolder);
            byte[] content = sourceFile.OpenBinary();

            Hashtable fileProperties = new Hashtable();
            fileProperties["ContentType"] = destContentType.Name;
            SPFile destFile = destFolder.Files.Add(destFolder.ServerRelativeUrl + "/" + filename, content, fileProperties, true);
            return destFile.Item;
        }
        /// <summary>
        /// Provisions the welcome page.
        /// </summary>
        /// <param name="contentType">The content type.</param>
        /// <returns>The welcome page.</returns>
        private SPFile ProvisionWelcomePage(SPContentType contentType)
        {
            // Guard
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            SPFile file = this.GetWelcomePage(contentType);
            if (file != null)
            {
                return file;
            }

            byte[] buffer =
                File.ReadAllBytes(SPUtility.GetGenericSetupPath(@"Template\Features\DocumentSet\docsethomepage.aspx"));
            SPFolder resourceFolder = contentType.ResourceFolder;
            return resourceFolder.Files.Add(this.DocumentSetWelcomePage, buffer, true);
        }
        /// <summary>
        /// Provisions the document set.
        /// </summary>
        /// <param name="contentType">Type of the content.</param>
        private void ProvisionDocumentSet(SPContentType contentType)
        {
            ProvisionEventHandler(contentType);
            SPFile file = this.ProvisionWelcomePage(contentType);
            using (SPLimitedWebPartManager manager = GetWelcomePageWebPartmanager(file))
            {
                if (this.EnsureWebParts)
                {
                    if (manager.WebParts != null)
                    {
                        List<WebPart> webParts = new List<WebPart>(manager.WebParts.Cast<WebPart>());
                        foreach (WebPart webPart in webParts)
                        {
                            manager.DeleteWebPart(webPart);
                        }
                    }
                }

                this.ProvisionWebParts(manager);
            }
        }
        /// <summary>
        /// Gets the document set welcome page for the specified content type.
        /// </summary>
        /// <param name="contentType">The content type.</param>
        /// <returns>An <see cref="SPFile"/> object representing the document set welcome page.</returns>
        private SPFile GetWelcomePage(SPContentType contentType)
        {
            // Guard
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            if (contentType.ResourceFolder.Files != null)
            {
                IEnumerable<SPFile> files =
                    contentType.ResourceFolder.Files.Cast<SPFile>().Where(f => f.Name.Equals(this.DocumentSetWelcomePage, StringComparison.OrdinalIgnoreCase));
                return files.Count() == 0 ? null : files.First();
            }

            return null;
        }
        /// <summary>
        /// Provisions the event handler.
        /// </summary>
        /// <param name="contentType">The content type.</param>
        private static void ProvisionEventHandler(SPContentType contentType)
        {
            AddEventHandler(
                contentType,
                "DocumentSet ItemUpdated",
                "Microsoft.Office.DocumentManagement, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
                "Microsoft.Office.DocumentManagement.DocumentSets.DocumentSetEventReceiver",
                SPEventReceiverType.ItemUpdated,
                100,
                SPEventReceiverSynchronization.Synchronous);

            AddEventHandler(
                contentType,
                "DocumentSet ItemAdded",
                "Microsoft.Office.DocumentManagement, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c",
                "Microsoft.Office.DocumentManagement.DocumentSets.DocumentSetItemsEventReceiver",
                SPEventReceiverType.ItemAdded,
                100,
                SPEventReceiverSynchronization.Synchronous);
        }
        /// <summary>
        /// Adds the event handler to the content type.
        /// </summary>
        /// <param name="contentType">The content type.</param>
        /// <param name="name">The name of the event.</param>
        /// <param name="assembly">The assembly containing the event receiver.</param>
        /// <param name="className">Name of the event receiver class.</param>
        /// <param name="type">The event receiver type.</param>
        /// <param name="sequence">The sequence.</param>
        /// <param name="sync">The synchronization type.</param>
        public static void AddEventHandler(
            SPContentType contentType,
            string name,
            string assembly,
            string className,
            SPEventReceiverType type,
            int sequence,
            SPEventReceiverSynchronization sync)
        {
            // Guard
            if (contentType == null)
            {
                throw new ArgumentNullException("contentType");
            }

            SPEventReceiverDefinition definition = GetEventHandler(contentType.EventReceivers, name, type);
            if (definition == null)
            {
                contentType.EventReceivers.Add(type, assembly, className);
                definition = GetEventHandler(contentType.EventReceivers, className, type);
            }

            definition.Name = name;
            definition.SequenceNumber = sequence;
            definition.Synchronization = sync;
            definition.Update();
        }