Exemplo n.º 1
0
        private void DeleteFieldLink(string contentTypeGuid, string[] fieldNames, SPWeb web)
        {
            SPContentTypeId contentTypeId = new SPContentTypeId(contentTypeGuid);
            SPContentType   contentType   = web.ContentTypes[contentTypeId];

            DeleteFieldLink(contentType, fieldNames, web);
        }
        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
                    }
                }
            }
        }
        public override int IsMatch(Microsoft.SharePoint.SPList list, SPContentTypeId ctId, int ItemId)
        {
            if (string.IsNullOrEmpty(ContentTypeID))
            {
                return(SearchMatchLevel.NONE);
            }
            SPContentTypeId ct;

            try
            {
                ct = new SPContentTypeId(ContentTypeID);
                if (ct.CompareTo(ctId) == 0)
                {
                    return(SearchMatchLevel.ITEM_BY_CT_ID_EXACTLY);
                }
                if ((IncludingChilds) && (ct.IsChildOf(ctId) || (ct.CompareTo(ctId) == 0)))
                {
                    return(SearchMatchLevel.ITEM_BY_CT_ID_INHERITED);
                }
            }
            catch (Exception ex)
            {
                Logger.WriteTrace(ex, Logging.SeverityEnum.Error);
            }
            return(SearchMatchLevel.NONE);
        }
        public SPContentTypeInstance GetContentTypeById(object contentTypeId)
        {
            if (contentTypeId == Undefined.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "A Content Type Id must be provided as the first argument.");
            }

            SPContentTypeId spContentTypeId;

            if (contentTypeId is SPContentTypeIdInstance)
            {
                spContentTypeId = (contentTypeId as SPContentTypeIdInstance).ContentTypeId;
            }
            else if (contentTypeId is GuidInstance)
            {
                spContentTypeId = new SPContentTypeId((contentTypeId as GuidInstance).Value.ToString());
            }
            else
            {
                spContentTypeId = new SPContentTypeId(TypeConverter.ToString(contentTypeId));
            }

            var result = m_contentTypeCollection[spContentTypeId];

            return(result == null
        ? null
        : new SPContentTypeInstance(this.Engine.Object.InstancePrototype, result));
        }
 protected void AddFileItem()
 {
     SPContentTypeId listItemContentTypeId = new SPContentTypeId(_ContentTypeId);
     _FieldValues.Add("ContentType", _SPWeb.ContentTypes[listItemContentTypeId].Name);
     _File= _List.RootFolder.Files.Add(_FileName, _FileData, _FieldValues, _Overwrite);
     _ListItem = _File.Item;
 }
        public override void WithResolvingModelHost(object modelHost, DefinitionBase model, Type childModelType, Action<object> action)
        {
            var siteModelHost = modelHost.WithAssertAndCast<SiteModelHost>("modelHost", value => value.RequireNotNull());

            var site = siteModelHost.HostSite;
            var contentTypeDefinition = model as ContentTypeDefinition;

            if (site != null && contentTypeDefinition != null)
            {
                var rootWeb = site.RootWeb;
                var contentTypeId = new SPContentTypeId(contentTypeDefinition.GetContentTypeId());

                // SPBug, it has to be new SPWen for every content type operation inside feature event handler
                using (var tmpRootWeb = site.OpenWeb(rootWeb.ID))
                {
                    var targetContentType = tmpRootWeb.ContentTypes[contentTypeId];

                    if (childModelType == typeof(ModuleFileDefinition))
                    {
                        action(targetContentType.ResourceFolder);
                    }
                    else
                    {
                        action(targetContentType);
                    }

                    targetContentType.Update(true);
                    tmpRootWeb.Update();
                }
            }
            else
            {
                action(modelHost);
            }
        }
Exemplo n.º 7
0
        //public static DefinitionBase OnCreating(this DefinitionBase model, Action<ListDefinition, SPList> action)
        //{
        //    model.RegisterModelUpdatingEvent(action);

        //    return model;
        //}

        //public static DefinitionBase OnCreated(this DefinitionBase model, Action<ListDefinition, SPList> action)
        //{
        //    model.RegisterModelUpdatedEvent(action);

        //    return model;
        //}

        #endregion

        #region add content type

        public static ModelNode AddContentTypeLink(this ModelNode model, SPContentTypeId contentTypeId)
        {
            return(ContentTypeLinkDefinitionSyntax.AddContentTypeLink(model, new ContentTypeLinkDefinition
            {
                ContentTypeId = contentTypeId.ToString()
            }));
        }
Exemplo n.º 8
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);
        }
Exemplo n.º 9
0
 public MoveCommand(SPListItem item, SPWeb web, string targetUrl)
     : base(item, web)
 {
     _TargetUrl = targetUrl;
     _ContentTypeId = item.ContentTypeId;
     _SourceUrl = string.Format("{0}/{1}", web.Url, item.Url);
 }
Exemplo n.º 10
0
        private static void ResolveContentTypeId(SPContentTypeAttribute contentTypeAttribute, Type targetType)
        {
            string contentTypeIdString = contentTypeAttribute.ContentTypeIdString;

            if (!contentTypeIdString.StartsWith("0x01"))
            {
                SPModelDescriptor descriptor;
                if (TargetTypeDictionary.TryGetValue(targetType.BaseType, out descriptor) && !(descriptor is SPModelInterfaceTypeDescriptor))
                {
                    contentTypeIdString = String.Concat(descriptor.ContentTypeIds.First(), contentTypeIdString);
                }
                if (!contentTypeIdString.StartsWith("0x01"))
                {
                    contentTypeIdString = String.Concat(SPBuiltInContentTypeIdString.Item, contentTypeIdString);
                }
            }

            SPContentTypeId contentTypeId;

            try {
                contentTypeId = new SPContentTypeId(contentTypeIdString);
            } catch (ArgumentException) {
                throw new SPModelProvisionException(String.Format("Invalid content type ID '{0}' for type '{1}'", contentTypeIdString, targetType.Name));
            }
            if (ContentTypeDictionary.ContainsKey(contentTypeId))
            {
                throw new SPModelProvisionException(String.Format("Type '{0}' uses duplicated content type ID with another model class", targetType));
            }
            contentTypeAttribute.SetFullContentTypeId(contentTypeId);
        }
Exemplo n.º 11
0
 public static ModelNode AddContentTypeLink(this ModelNode model, SPContentTypeId contentTypeId)
 {
     return ContentTypeLinkDefinitionSyntax.AddContentTypeLink(model, new ContentTypeLinkDefinition
     {
         ContentTypeId = contentTypeId.ToString()
     });
 }
Exemplo n.º 12
0
        public SPDocumentSetInstance AddDocumentSet(string name, object contentType, [DefaultParameterValue(null)] object properties, [DefaultParameterValue(true)] bool provisionDefaultContent)
        {
            var contentTypeId = SPContentTypeId.Empty;

            if (contentType is SPContentTypeIdInstance)
            {
                contentTypeId = (contentType as SPContentTypeIdInstance).ContentTypeId;
            }
            else if (contentType is SPContentTypeInstance)
            {
                contentTypeId = (contentType as SPContentTypeInstance).ContentType.Id;
            }
            else if (contentType is string)
            {
                contentTypeId = new SPContentTypeId(contentType as string);
            }

            if (contentTypeId == SPContentTypeId.Empty)
            {
                return(null);
            }

            var htProperties = SPHelper.GetFieldValuesHashtableFromPropertyObject(properties);

            var docSet = DocumentSet.Create(m_folder, name, contentTypeId, htProperties, provisionDefaultContent);

            return(new SPDocumentSetInstance(Engine.Object.InstancePrototype, null, null, docSet));
        }
Exemplo n.º 13
0
 private static void SaveAssemblyName(SPSite site, SPContentTypeId contentTypeId, Assembly assembly)
 {
     using (site.RootWeb.GetAllowUnsafeUpdatesScope()) {
         site.RootWeb.AllProperties["SPModel." + contentTypeId.ToString().ToLower() + ".Assembly"] = assembly.FullName;
         site.RootWeb.Update();
     }
 }
Exemplo n.º 14
0
        public override void WithResolvingModelHost(object modelHost, DefinitionBase model, Type childModelType, Action <object> action)
        {
            var siteModelHost = modelHost.WithAssertAndCast <SiteModelHost>("modelHost", value => value.RequireNotNull());

            var site = siteModelHost.HostSite;
            var contentTypeDefinition = model as ContentTypeDefinition;

            if (site != null && contentTypeDefinition != null)
            {
                var rootWeb       = site.RootWeb;
                var contentTypeId = new SPContentTypeId(contentTypeDefinition.GetContentTypeId());

                // SPBug, it has to be new SPWen for every content type operation inside feature event handler
                using (var tmpRootWeb = site.OpenWeb(rootWeb.ID))
                {
                    var targetContentType = tmpRootWeb.ContentTypes[contentTypeId];

                    if (childModelType == typeof(ModuleFileDefinition))
                    {
                        action(targetContentType.ResourceFolder);
                    }
                    else
                    {
                        action(targetContentType);
                    }

                    targetContentType.Update(true);
                    tmpRootWeb.Update();
                }
            }
            else
            {
                action(modelHost);
            }
        }
        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            try
            {
                SPSite          thisSite = properties.Feature.Parent as SPSite;
                SPWeb           rootWeb  = thisSite.RootWeb;
                SPContentTypeId itemCtId = new SPContentTypeId("0x01");
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.Categories, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.Departments, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.InventoryLocations, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.MachineDepartments, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.MachineParts, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.Machines, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.Manufacturers, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.Parts, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.PartSuppliers, itemCtId);
                RemoveCTDirectDescendantFromList(rootWeb, Constants.ListUrls.Suppliers, itemCtId);

                //Restrict deletion of list items that would create a broken lookup
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.InventoryLocations, Constants.Fields.Guids.Part);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.Machines, Constants.Fields.Guids.Manufacturer);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.Machines, Constants.Fields.Guids.Category);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.MachineDepartments, Constants.Fields.Guids.Department);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.MachineDepartments, Constants.Fields.Guids.Machine);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.MachineParts, Constants.Fields.Guids.Machine);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.MachineParts, Constants.Fields.Guids.Part);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.PartSuppliers, Constants.Fields.Guids.Part);
                RestrictDeleteOnLookupField(rootWeb, Constants.ListUrls.PartSuppliers, Constants.Fields.Guids.Supplier);

                // Add views
                AddAllViewFilesToLists(properties);
            }
            catch (Exception e) { System.Diagnostics.Trace.WriteLine(e.ToString()); }
        }
Exemplo n.º 16
0
        private SPContentType GetContentType(string contentTypeGuid, SPWeb web)
        {
            SPContentTypeId contentTypeId = new SPContentTypeId(contentTypeGuid);
            SPContentType   contentType   = web.Site.RootWeb.ContentTypes[contentTypeId];

            return(contentType);
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
0
        public SPContentTypeInstance EnsureContentType(object contentType)
        {
            var contentTypeIdToFind = SPContentTypeId.Empty;

            if (contentType is SPContentTypeIdInstance)
            {
                contentTypeIdToFind = (contentType as SPContentTypeIdInstance).ContentTypeId;
            }
            else if (contentType is SPContentTypeInstance)
            {
                contentTypeIdToFind = (contentType as SPContentTypeInstance).ContentType.Id;
            }
            else if (TypeUtilities.IsString(contentType))
            {
                contentTypeIdToFind = new SPContentTypeId(TypeConverter.ToString(contentType));
            }

            if (contentTypeIdToFind == SPContentTypeId.Empty)
            {
                return(null);
            }

            var spContentType = m_list.ContentTypes.OfType <SPContentType>().FirstOrDefault(ct => contentTypeIdToFind.IsParentOf(ct.Id));

            if (spContentType == null)
            {
                var bestMatch = m_list.ParentWeb.AvailableContentTypes.BestMatch(contentTypeIdToFind);

                spContentType = m_list.ContentTypes.Add(m_list.ParentWeb.AvailableContentTypes[bestMatch]);
            }

            return(new SPContentTypeInstance(Engine.Object.InstancePrototype, spContentType));
        }
        protected override void DeployModelInternal(object modelHost, DefinitionBase model)
        {
            var spList = modelHost.WithAssertAndCast<SPList>("modelHost", value => value.RequireNotNull());
            var contentTypeLinkModel = model.WithAssertAndCast<ContentTypeLinkDefinition>("model", value => value.RequireNotNull());

            TraceUtils.WithScope(traceScope =>
            {
                Trace.WriteLine(string.Format("Validate model: {0} ContentTypeLink:{1}", spList, contentTypeLinkModel));

                // assert base properties
                traceScope.WithTraceIndent(trace =>
                {
                    if (spList.ContentTypesEnabled)
                    {
                        var contentTypeId = new SPContentTypeId(contentTypeLinkModel.ContentTypeId);
                        var targetContentType = spList.ParentWeb.ContentTypes[contentTypeId];

                        var listContentType = spList.ContentTypes[targetContentType.Name];

                        // presence
                        trace.WriteLine(string.Format("Validate list content type presence (not null): model:[{0}] content type link:[{1}]", contentTypeLinkModel.ContentTypeId, listContentType));
                        Assert.IsNotNull(listContentType);

                        // child of
                        trace.WriteLine(string.Format("Validate ChildOf: model:[{0}] content type link:[{1}]", contentTypeLinkModel.ContentTypeId, listContentType));
                        Assert.IsTrue(listContentType.Id.IsChildOf(new SPContentTypeId(contentTypeLinkModel.ContentTypeId)));
                    }
                    else
                    {
                        trace.WriteLine("Skipping content type link check as List.ContentTypesEnabled is false");
                    }
                });
            });
        }
    public static SPListItem CreateLinkToDocumentFile(SPDocumentLibrary list, SPContentTypeId contentTypeId, string name, SPFieldUrlValue urlVal, string overrideIcon = null)
    {
        SPContentType contentType = list.ContentTypes[contentTypeId];
        string        extension   = "";

        if (urlVal != null && urlVal.Url != null)
        {
            extension = Path.GetExtension((urlVal.Url).Trim()).TrimStart(".".ToCharArray());
        }
        SPFolder         currentFolder = list.RootFolder;
        SPFileCollection files         = currentFolder.Files;
        string           fileUrl       = string.Concat(currentFolder.Url, "/", name, ".aspx");
        string           fileTemplate  = "<%@ Assembly Name='{0}' %>\r\n <%@ Register TagPrefix='SharePoint' Namespace='Microsoft.SharePoint.WebControls' Assembly='Microsoft.SharePoint' %>\r\n <%@ Import Namespace='System.IO' %>\r\n <%@ Import Namespace='Microsoft.SharePoint' %>\r\n <%@ Import Namespace='Microsoft.SharePoint.Utilities' %>\r\n <%@ Import Namespace='Microsoft.SharePoint.WebControls' %>\r\n <html>\r\n <head> <meta name='progid' content='SharePoint.Link' /> </head>\r\n <body>\r\n <form id='Form1' runat='server'>\r\n <SharePoint:UrlRedirector id='Redirector1' runat='server' />\r\n </form>\r\n </body>\r\n </html>";
        StringBuilder    fileContent   = new StringBuilder(fileTemplate.Length + 400);

        fileContent.AppendFormat(fileTemplate, typeof(SPDocumentLibrary).Assembly.FullName);
        Hashtable       properties = new Hashtable();
        SPContentTypeId ctId       = contentType.Id;

        properties["ContentTypeId"] = ctId.ToString();
        SPFile     file = files.Add(fileUrl, new MemoryStream((new UTF8Encoding()).GetBytes(fileContent.ToString())), properties, false, false);
        SPListItem item = file.Item;

        item[FLD_URL] = urlVal;
        if (list.Fields.Contains(g_guidIconOverride))
        {
            item[g_guidIconOverride] = string.Concat("|", overrideIcon ?? extension, "|");
        }
        item.IconOverlay = "linkoverlay.gif";
        item.UpdateOverwriteVersion();
        return(item);
    }
Exemplo n.º 21
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);
        }
        /// <summary>
        /// Builds a valid child content type ID from a parent and a unique identifier
        /// </summary>
        /// <param name="parentContentTypeId">The parent content type's ID</param>
        /// <param name="childContentTypeIdValue">The child CT's unique identifier</param>
        /// <returns>A correctly formatted child CT ID string</returns>
        public static string ConcatAsContentTypeId(SPContentTypeId parentContentTypeId, Guid childContentTypeIdValue)
        {
            const string Format = "{0}00{1}";
            var cleanedUpGuidString = childContentTypeIdValue.ToString().Replace("{", string.Empty).Replace("}", string.Empty).Replace("-", string.Empty);

            return string.Format(CultureInfo.InvariantCulture, Format, parentContentTypeId.ToString(), cleanedUpGuidString);
        }
Exemplo n.º 23
0
        public ArtDevContentType CreateContentType(string Name, SPContentTypeId parent)
        {
            SPContentType     type       = NewOrRefContentType(Name, parent);
            ArtDevContentType ArtDevType = new ArtDevContentType(type);

            return(ArtDevType);
        }
Exemplo n.º 24
0
        private void GetListContentTypes(SPList list)
        {
            SPContentTypeId picture = new SPContentTypeId("0x010102");

            foreach (SPContentType ct in list.ContentTypes)
            {
                if (ct.Id == picture || ct.Id.IsChildOf(picture))
                {
                    ListItem item = new ListItem(ct.Name, ct.Id.ToString());

                    if (!this.ddl_contenttype.Items.Contains(item))
                    {
                        this.ddl_contenttype.Items.Add(item);
                    }
                }
            }

            if (this.ddl_contenttype.Items.Count > 0)
            {
                this.ddl_contenttype.SelectedValue = this.ddl_contenttype.Items[0].Value;
                Btn_Save.Enabled = true;
            }
            else
            {
                Btn_Save.Enabled = false;
            }
        }
Exemplo n.º 25
0
        public List <PageLayout> GetPageLayouts(SPContentTypeId contentTypeId)
        {
            List <PageLayout>  pagelayouts = new List <PageLayout>();
            PageLayout         _found      = PageLayout.CreatePageLayout();
            IList <PageLayout> layouts     = GetPageLayouts();

            if (layouts == null)
            {
                //return _found;
                return(pagelayouts);
            }

            rrLock.EnterReadLock();

            try
            {
                foreach (PageLayout layout in layouts)
                {
                    if (layout.ContenTypeId.Equals(contentTypeId))
                    {
                        pagelayouts.Add(layout);
                        //_found = layout;
                        //break;
                    }
                }

                return(pagelayouts);// _found;
            }
            finally
            {
                rrLock.ExitReadLock();
            }
        }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
0
        protected override void DeployModelInternal(object modelHost, DefinitionBase model)
        {
            var spList = modelHost.WithAssertAndCast <SPList>("modelHost", value => value.RequireNotNull());
            var contentTypeLinkModel = model.WithAssertAndCast <ContentTypeLinkDefinition>("model", value => value.RequireNotNull());

            TraceUtils.WithScope(traceScope =>
            {
                Trace.WriteLine(string.Format("Validate model: {0} ContentTypeLink:{1}", spList, contentTypeLinkModel));

                // assert base properties
                traceScope.WithTraceIndent(trace =>
                {
                    if (spList.ContentTypesEnabled)
                    {
                        var contentTypeId     = new SPContentTypeId(contentTypeLinkModel.ContentTypeId);
                        var targetContentType = spList.ParentWeb.ContentTypes[contentTypeId];

                        var listContentType = spList.ContentTypes[targetContentType.Name];

                        // presence
                        trace.WriteLine(string.Format("Validate list content type presence (not null): model:[{0}] content type link:[{1}]", contentTypeLinkModel.ContentTypeId, listContentType));
                        Assert.IsNotNull(listContentType);

                        // child of
                        trace.WriteLine(string.Format("Validate ChildOf: model:[{0}] content type link:[{1}]", contentTypeLinkModel.ContentTypeId, listContentType));
                        Assert.IsTrue(listContentType.Id.IsChildOf(new SPContentTypeId(contentTypeLinkModel.ContentTypeId)));
                    }
                    else
                    {
                        trace.WriteLine("Skipping content type link check as List.ContentTypesEnabled is false");
                    }
                });
            });
        }
Exemplo n.º 28
0
        /// <summary>Creates a package reader for a package without accessing the store.</summary>
        /// <param name="file">The package.</param>
        /// <param name="location">The package location.</param>
        /// <param name="runWithElevatedPrivileges">Whether to run with elevated privileges or not.</param>
        public PackageReader CreatePackageReader(SPFile file, SharePointFileLocation location, bool runWithElevatedPrivileges)
        {
            if (SPContentTypeId.FindCommonParent(file.Item.ContentType.Id, permanentCacheContentType) == permanentCacheContentType)
            {
                object directoryValue = file.Item[new Guid("a76de874-b256-4fd6-8933-813aa8587163")];
                if (directoryValue == null)
                {
                    throw new CacheException(Resources.PermanentCacheNoDirectory);
                }
                else
                {
                    DirectoryInfo directory;
                    try
                    {
                        directory = new DirectoryInfo(directoryValue.ToString());
                    }
                    catch (ArgumentException)
                    {
                        throw new CacheException(Resources.PermanentCacheInvalidDirectory);
                    }
                    catch (PathTooLongException)
                    {
                        throw new CacheException(Resources.PermanentCacheInvalidDirectory);
                    }

                    return(new PermanentCacheSharePointPackageReader(directory, location));
                }
            }
            else
            {
                return(new SharePointPackageReader(CacheSettings, location, file, runWithElevatedPrivileges));
            }
        }
Exemplo n.º 29
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);
            }
        }
        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();
                }
            }
        }
        private static void UpdateListItemEventReceivers(SPSite site)
        {
            //Upgrade All Lists Instances with new Event Receiver Assembly for
            //Lists based on the Training Course Content Type

            string          newAssembly   = "Contoso.TrainingManagement, Version=2.0.0.0, Culture=neutral, PublicKeyToken=9f4da00116c38ec5"; //our new assembly info
            string          newClass      = "Contoso.TrainingManagement.TrainingCourseItemEventReceiver";
            SPContentTypeId contentTypeId = new SPContentTypeId(ContentTypes.TrainingCourse);                                                //our custom ctype

            foreach (SPWeb web in site.AllWebs)
            {
                using ( web )
                {
                    for (int i = 0; i < web.Lists.Count; i++)
                    {
                        SPList          list      = web.Lists[i];
                        SPContentTypeId bestMatch = list.ContentTypes.BestMatch(contentTypeId);
                        if (bestMatch.IsChildOf(contentTypeId))
                        {
                            for (int j = 0; j < list.EventReceivers.Count; j++)
                            {
                                SPEventReceiverDefinition eventReceiverDefinition = list.EventReceivers[j];
                                if (String.Compare(eventReceiverDefinition.Assembly, newAssembly, true) != 0)
                                {
                                    list.EventReceivers.Add(eventReceiverDefinition.Type, newAssembly, newClass);
                                    eventReceiverDefinition.Delete();
                                    list.Update();
                                }
                            }
                        }
                    }
                }
            }
        }
Exemplo n.º 32
0
        public SPContentTypeInstance AddContentType(object contentType)
        {
            SPContentTypeId bestMatch = SPContentTypeId.Empty;


            if (contentType is SPContentTypeIdInstance)
            {
                bestMatch = m_list.ParentWeb.AvailableContentTypes.BestMatch((contentType as SPContentTypeIdInstance).ContentTypeId);
            }
            else if (contentType is SPContentTypeInstance)
            {
                bestMatch = m_list.ParentWeb.AvailableContentTypes.BestMatch((contentType as SPContentTypeInstance).ContentType.Id);
            }
            else if (TypeUtilities.IsString(contentType))
            {
                bestMatch =
                    m_list.ParentWeb.AvailableContentTypes.BestMatch(
                        new SPContentTypeId(TypeConverter.ToString(contentType)));
            }

            if (bestMatch == SPContentTypeId.Empty)
            {
                return(null);
            }

            var spContentType = m_list.ContentTypes.Add(m_list.ParentWeb.AvailableContentTypes[bestMatch]);

            return(new SPContentTypeInstance(Engine.Object.InstancePrototype, spContentType));
        }
Exemplo n.º 33
0
        public SPContentTypeInstance Construct(object contentTypeId)
        {
            if (contentTypeId == null || contentTypeId == Null.Value || contentTypeId == Undefined.Value)
            {
                throw new JavaScriptException(this.Engine, "Error", "When creating a new instance of a SPContentType, a content type id must be specified which is either a string or an instance of a SPContentTypeId.");
            }

            SPContentType contentType;

            if (contentTypeId is SPContentTypeIdInstance)
            {
                var spContentTypeId        = (contentTypeId as SPContentTypeIdInstance).ContentTypeId;
                var bestSPContentTypeMatch = SPBaristaContext.Current.Web.AvailableContentTypes.BestMatch(spContentTypeId);
                contentType = SPBaristaContext.Current.Web.AvailableContentTypes[bestSPContentTypeMatch];
            }
            else
            {
                var strContentTypeId       = TypeConverter.ToString(contentTypeId);
                var spContentTypeId        = new SPContentTypeId(strContentTypeId);
                var bestSPContentTypeMatch = SPBaristaContext.Current.Web.AvailableContentTypes.BestMatch(spContentTypeId);
                contentType = SPBaristaContext.Current.Web.AvailableContentTypes[bestSPContentTypeMatch];
            }

            if (contentType == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "A match for the specified content type could not be found in the current web.");
            }

            return(new SPContentTypeInstance(this.InstancePrototype, contentType));
        }
        /// <summary>
        /// Lists the attachments associated with the specified entity.
        /// </summary>
        /// <param name="containerTitle">The container title.</param>
        /// <param name="entityId">The entity id.</param>
        /// <returns></returns>
        public virtual IList <Attachment> ListAttachments(string containerTitle, Guid entityId)
        {
            SPSite site;
            var    web = GetDocumentStoreWeb(out site);

            SPList   list;
            SPFolder folder;

            if (SPDocumentStoreHelper.TryGetFolderFromPath(web, containerTitle, out list, out folder, String.Empty) == false)
            {
                return(null);
            }

            DocumentSet documentSet;

            if (SPDocumentStoreHelper.TryGetDocumentStoreEntityDocumentSet(list, folder, entityId, out documentSet) == false)
            {
                return(null);
            }

            var attachmentContentTypeId     = new SPContentTypeId(Constants.DocumentStoreEntityAttachmentContentTypeId);
            var listAttachmentContentTypeId = list.ContentTypes.BestMatch(attachmentContentTypeId);
            var attachmentContentType       = list.ContentTypes[listAttachmentContentTypeId];

            return(documentSet.Folder.Files.OfType <SPFile>()
                   .Where(f => attachmentContentType != null && f.Item.ContentTypeId == attachmentContentType.Id)
                   .Select(SPDocumentStoreHelper.MapAttachmentFromSPFile)
                   .ToList());
        }
Exemplo n.º 35
0
        public ArtDevList addContentType(SPContentTypeId typeID)
        {
            SPContentType CType = this.list.ParentWeb.AvailableContentTypes[typeID];

            CType = this.list.ContentTypes.Cast <SPContentType>().FirstOrDefault(c => c.Name.Equals(CType.Name)) ?? this.list.ContentTypes.Add(CType);
            this.list.Update();
            return(this);
        }
Exemplo n.º 36
0
        /// <summary>
        /// Gets an <see cref="Microsoft.SharePoint.SPContentType"/> object representing list content type of the specified content type ID under the specified list.
        /// </summary>
        /// <param name="listUrl">Server-relative URL of the list.</param>
        /// <param name="contentTypeId">List content type ID.</param>
        /// <returns>An <see cref="Microsoft.SharePoint.SPContentType"/> object in cache. NULL if list content type of given content type ID does not exist, or the specified list does not exist.</returns>
        /// <exception cref="System.ArgumentNullException">Throws when input parameter <paramref name="listUrl"/> is null.</exception>
        public SPContentType GetContentType(string listUrl, SPContentTypeId contentTypeId)
        {
            CommonHelper.ConfirmNotNull(listUrl, "listUrl");
            SPListLookupKey        listInfo  = hashtable.EnsureKeyValue(listUrl, () => GetListInfoFromUrl(listUrl));
            SPContentTypeLookupKey lookupKey = new SPContentTypeLookupKey(listInfo.ListId, contentTypeId);

            return(GetOrAdd(lookupKey, () => GetList(listInfo.WebId, listInfo.ListId).ContentTypes[contentTypeId]));
        }
 /// <summary>
 /// Creates a content type metadata encapsulation
 /// </summary>
 /// <param name="contentTypeId">The content type ID</param>
 /// <param name="fields">A list of field information to document the structure of the content type</param>
 /// <param name="titleResourceKey">The resource key to use for the title</param>
 /// <param name="descriptionResourceKey">The resource key to use for the description</param>
 /// <param name="contentGroupResourceKey">The resource key to use for the content group</param>
 /// <param name="resourceFileName">The resource file where all the resources can be found</param>
 public ContentTypeInfo(SPContentTypeId contentTypeId, IList<FieldInfo> fields, string titleResourceKey, string descriptionResourceKey, string contentGroupResourceKey, string resourceFileName)
 {
     this.ContentTypeId = contentTypeId;
     this.TitleResourceKey = titleResourceKey;
     this.DescriptionResourceKey = descriptionResourceKey;
     this.ContentGroupResourceKey = contentGroupResourceKey;
     this.Fields = fields;
     this.resourceFileName = resourceFileName;
 }
Exemplo n.º 38
0
 public static void RemoveInheritedContentTypeFromList(SPWeb web, SPList list, SPContentTypeId contentTypeId)
 {
     SPContentType ctWeb = web.ContentTypes[contentTypeId];
     SPContentType ctList = list.ContentTypes[ctWeb.Name];
     if (ctList != null)
     {
         list.ContentTypes.Delete(ctList.Id);
     }
 }
Exemplo n.º 39
0
        protected override void DeployModelInternal(object modelHost, DefinitionBase model)
        {
            var siteModelHost = modelHost.WithAssertAndCast<SiteModelHost>("modelHost", value => value.RequireNotNull());
            var contentTypeModel = model.WithAssertAndCast<ContentTypeDefinition>("model", value => value.RequireNotNull());

            var site = siteModelHost.HostSite;
            var rootWeb = site.RootWeb;

            // SPBug, it has to be new SPWen for every content type operation inside feature event handler
            using (var tmpRootWeb = site.OpenWeb(rootWeb.ID))
            {
                var contentTypeId = new SPContentTypeId(contentTypeModel.GetContentTypeId());

                var targetContentType = tmpRootWeb.ContentTypes[contentTypeId];

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

                if (targetContentType == null)
                    targetContentType = tmpRootWeb
                                            .ContentTypes
                                            .Add(new SPContentType(contentTypeId, tmpRootWeb.ContentTypes, contentTypeModel.Name));

                targetContentType.Name = contentTypeModel.Name;
                targetContentType.Group = contentTypeModel.Group;

                // SPBug, description cannot be null
                targetContentType.Description = contentTypeModel.Description ?? string.Empty;

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

                targetContentType.Update();

                tmpRootWeb.Update();
            }
        }
        /// <summary>
        /// Adds the list item to the list and sets the field values
        /// </summary>
        protected virtual void AddListItem()
        {
            SPContentTypeId listItemContentTypeId = new SPContentTypeId(_ContentTypeId);

            _ListItem = _List.AddItem();
            _ListItem[SPBuiltInFieldId.ContentTypeId] = listItemContentTypeId;
            foreach (KeyValuePair<string, object> listItemProperty in _ListItemProperties)            
            {
                _ListItem[listItemProperty.Key] = listItemProperty.Value;
            }
            _ListItem.Update();
        }
Exemplo n.º 41
0
 public virtual void EnsureCollectionIsUpdateble(SPWeb web, SPContentTypeId contentTypeId)
 {
     if (web.ContentTypes[contentTypeId] == null)
     {
         if (web.AvailableContentTypes[contentTypeId] != null)
         {
             throw new SPGENGeneralException("The content type '" + contentTypeId.ToString() + "' doesn't exist in the updateble content type collection on this web but is a member of an ancestor web.");
         }
         else
         {
             throw new SPGENGeneralException("The content type '" + contentTypeId.ToString() + "' doesn't exist in the updateble content type collection on this web.");
         }
     }
 }
        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 linkContenType = new SPContentTypeId(definition.ContentTypeId);
                var bestMatch = list.ContentTypes.BestMatch(linkContenType);

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

            return result;
        }
Exemplo n.º 43
0
        public override void WithResolvingModelHost(ModelHostResolveContext modelHostContext)
        {
            var modelHost = modelHostContext.ModelHost;
            var model = modelHostContext.Model;
            var childModelType = modelHostContext.ChildModelType;
            var action = modelHostContext.Action;


            var web = ExtractWeb(modelHost);

            var site = web.Site;
            var contentTypeDefinition = model as ContentTypeDefinition;

            if (site != null && contentTypeDefinition != null)
            {
                var contentTypeId = new SPContentTypeId(contentTypeDefinition.GetContentTypeId());

                // SPBug, it has to be new SPWen for every content type operation inside feature event handler
                using (var tmpRootWeb = site.OpenWeb(web.ID))
                {
                    var targetContentType = tmpRootWeb.ContentTypes[contentTypeId];

                    if (childModelType == typeof(ModuleFileDefinition))
                    {
                        action(new FolderModelHost()
                        {
                            CurrentContentType = targetContentType,
                            CurrentContentTypeFolder = targetContentType.ResourceFolder
                        });
                    }
                    else
                    {
                        action(targetContentType);
                    }

                    targetContentType.Update(true);
                    tmpRootWeb.Update();
                }
            }
            else
            {
                action(modelHost);
            }
        }
        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();
            }
        }
Exemplo n.º 45
0
        public void EnsureContentType_WhenAlreadyExists_ShouldReturnSameContentType()
        {
            using (var testScope = SiteTestScope.BlankSite())
            {
                // Arrange
                var contentTypeId = string.Format(
                    CultureInfo.InvariantCulture,
                    "0x0100{0:N}",
                    new Guid("{F8B6FF55-2C9E-4FA2-A705-F55FE3D18777}"));

                var contentTypeInfo = new ContentTypeInfo(contentTypeId, "NameKey", "DescriptionKey", "GroupKey");

                using (var injectionScope = IntegrationTestServiceLocator.BeginLifetimeScope())
                {
                    var contentTypeHelper = injectionScope.Resolve<IContentTypeHelper>();
                    var contentTypeCollection = testScope.SiteCollection.RootWeb.ContentTypes;
                    var expectedNumberOfContentTypes = contentTypeCollection.Count + 1;
                    var expectedContentTypeId = new SPContentTypeId(contentTypeId);
                    var expectedDisplayName = contentTypeInfo.DisplayNameResourceKey;
                    var expectedDescription = contentTypeInfo.DescriptionResourceKey;
                    var expectedGroup = contentTypeInfo.GroupResourceKey;

                    // Act
                    contentTypeHelper.EnsureContentType(contentTypeCollection, contentTypeInfo);
                    var actualContentType = contentTypeHelper.EnsureContentType(contentTypeCollection, contentTypeInfo);
                    var actualNumberOfContentTypes = contentTypeCollection.Count;

                    // Assert
                    Assert.AreEqual(expectedNumberOfContentTypes, actualNumberOfContentTypes);
                    Assert.IsNotNull(actualContentType);
                    Assert.AreEqual(expectedContentTypeId, actualContentType.Id);
                    Assert.AreEqual(expectedDisplayName, actualContentType.NameResource.Value);
                    Assert.AreEqual(expectedDescription, actualContentType.DescriptionResource.Value);
                    Assert.AreEqual(expectedGroup, actualContentType.Group);

                    var contentTypeRefetched = testScope.SiteCollection.RootWeb.ContentTypes["NameKey"];
                    Assert.IsNotNull(contentTypeRefetched);
                    Assert.AreEqual(expectedContentTypeId, contentTypeRefetched.Id);
                    Assert.AreEqual(expectedDisplayName, contentTypeRefetched.NameResource.Value);
                    Assert.AreEqual(expectedDescription, contentTypeRefetched.DescriptionResource.Value);
                    Assert.AreEqual(expectedGroup, contentTypeRefetched.Group);
                }
            }
        }
Exemplo n.º 46
0
        /// <summary>
        /// Creates a page in the Pages library
        /// </summary>
        /// <param name="currentWeb">The current web</param>
        /// <param name="folderId">The folder in which to add the item</param>
        /// <param name="contentTypeId">Id of Content Type to create</param>
        /// <param name="pageLayoutName">Name (filename) of Page Layout to apply</param>
        /// <param name="pageTitle">The human-readable title of the page</param>
        /// <param name="pageName">The url/name of the page relative to its parent folder</param>
        /// <returns>The newly created publishing page</returns>
        public PublishingPage Create(SPWeb currentWeb, int folderId, SPContentTypeId contentTypeId, string pageLayoutName, string pageTitle, string pageName)
        {
            PublishingPage newPage = null;

            var folder = this._folderRepository.GetFolderByIdForWeb(currentWeb, folderId);

            if (folder.Item.DoesUserHavePermissions(SPBasePermissions.AddListItems))
            {
                using (new Unsafe(currentWeb))
                {
                    SPContentType pubPageBaseContentType = currentWeb.AvailableContentTypes[ContentTypeId.ArticlePage];

                    var requestedContentType = currentWeb.AvailableContentTypes[contentTypeId];
                    if (null != requestedContentType && requestedContentType.Id.IsChildOf(pubPageBaseContentType.Id))
                    {
                        var publishingSite = new PublishingSite(currentWeb.Site);
                        PageLayoutCollection pageLayoutsForCT = publishingSite.GetPageLayouts(requestedContentType, false);

                        var requestedPageLayout = pageLayoutsForCT.Cast<PageLayout>().FirstOrDefault(layout => layout.Name == pageLayoutName);

                        if (requestedPageLayout != null)
                        {
                            PublishingWeb publishingWeb = PublishingWeb.GetPublishingWeb(currentWeb);

                            if (!pageName.EndsWith(".aspx", StringComparison.OrdinalIgnoreCase))
                            {
                                pageName += ".aspx";
                            }

                            newPage = publishingWeb.GetPublishingPages().Add(folder.ServerRelativeUrl + "/" + pageName, requestedPageLayout);
                            newPage.ListItem[BuiltInFields.Title.InternalName] = pageTitle;
                            newPage.ListItem[BuiltInFields.ContentType.InternalName] = requestedContentType.Name;
                            newPage.ListItem[BuiltInFields.ContentTypeId.InternalName] = requestedContentType.Id;
                            newPage.ListItem.Update();
                        }
                    }
                }
            }

            return newPage;
        }
Exemplo n.º 47
0
        /// <summary>
        /// Create publishing page in Pages Library
        /// </summary>
        /// <param name="web">the current web</param>
        /// <param name="folderId">the current folder id</param>
        /// <param name="contentTypeId">the current content type id</param>
        /// <param name="pageLayoutName">the page layout name</param>
        /// <param name="pageTitle">the page title</param>
        /// <param name="pageName">the page name</param>
        /// <returns>the created publishing page</returns>
        public PublishingPage Create(SPWeb web, int folderId, SPContentTypeId contentTypeId, string pageLayoutName, string pageTitle, string pageName)
        {
            var publishingSite = new PublishingSite(web.Site);
            var pageLayout = this.GetPageLayout(publishingSite, pageLayoutName, false);
            var page = new PageInfo()
            {
                Name = pageName,
                ContentTypeId = contentTypeId,
                PageLayout = pageLayout,
                Values = new List<IFieldValueInfo>()
                {
                    new FieldValueInfo()
                    {
                        FieldName = BuiltInFields.Title.InternalName,
                        Value = pageTitle
                    }
                }
            };

            return this.Create(web, folderId, page);
        }
Exemplo n.º 48
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;
            }
        }
        public void DeleteContentTypeIfNotUsed(SPContentTypeCollection collection, SPContentTypeId contentTypeId)
        {
            if (contentTypeId == null)
            {
                throw new ArgumentNullException("contentTypeId");
            }

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

            // Get the content type from the web.
            SPContentType contentType = collection[collection.BestMatch(contentTypeId)];

            // return false if the content type does not exist.
            if (contentType != null)
            {
                // Delete the content type if not used.
                this.DeleteContentTypeIfNotUsed(contentType);
            }
        }
Exemplo n.º 50
0
        /// <summary>
        /// Adds the content type id.
        /// </summary>
        /// <param name="list">The list.</param>
        /// <param name="contentTypeId">The content type id.</param>
        /// <exception cref="System.ArgumentNullException">Any null parameters.</exception>
        /// <exception cref="System.ArgumentOutOfRangeException">contentTypeId;Content Type not available in the lists parent web.</exception>
        public void AddContentType(SPList list, SPContentTypeId contentTypeId)
        {
            if (list == null)
            {
                throw new ArgumentNullException("list");
            }

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

            SPContentType contentType = list.ParentWeb.AvailableContentTypes[contentTypeId];

            if (contentType != null)
            {
                this.AddContentType(list, contentType);
            }
            else
            {
                throw new ArgumentOutOfRangeException("contentTypeId", "Content Type not available in the lists parent web.");
            }
        }
Exemplo n.º 51
0
        /// <summary>
        /// Creates a new child content type ID
        /// </summary>
        /// <param name="parentContentTypeId">The parent CT ID</param>
        /// <param name="childContentTypeUniqueId">The unique ID for the new child CT</param>
        /// <returns>The new content type ID</returns>
        public static SPContentTypeId CreateChild(SPContentTypeId parentContentTypeId, Guid childContentTypeUniqueId)
        {
            if (parentContentTypeId == null)
            {
                throw new ArgumentNullException("parentContentTypeId");
            }

            if (childContentTypeUniqueId == null || childContentTypeUniqueId == Guid.Empty)
            {
                throw new ArgumentNullException("childContentTypeUniqueId");
            }

            string childGuidString = childContentTypeUniqueId.ToString("N", CultureInfo.InvariantCulture).ToUpperInvariant();
            string parentId = parentContentTypeId.ToString();

            string newContentTypeIdString = string.Format(
                CultureInfo.InvariantCulture,
                "{0}00{1}",     // "00" as separator between CT Guids
                parentId,
                childGuidString);

            return new SPContentTypeId(newContentTypeIdString);
        }
Exemplo n.º 52
0
        /// <summary>
        /// Creates a new child content type ID
        /// </summary>
        /// <param name="parentContentTypeId">The parent CT ID</param>
        /// <param name="childContentTypeUniqueId">The unique ID for the new child CT</param>
        /// <returns>The new content type ID</returns>
        public static SPContentTypeId CreateChild(SPContentTypeId parentContentTypeId, int childContentTypeUniqueId)
        {
            if (parentContentTypeId == null)
            {
                throw new ArgumentNullException("parentContentTypeId");
            }

            if (childContentTypeUniqueId <= 0)
            {
                throw new ArgumentOutOfRangeException("childContentTypeUniqueId", "Child content type discriminator integer should be larger than 0.");
            }

            string childIdString = childContentTypeUniqueId.ToString(CultureInfo.InvariantCulture);
            string parentId = parentContentTypeId.ToString();

            string newContentTypeIdString = string.Format(
                CultureInfo.InvariantCulture,
                "{0}0{1}",      // "0" as separator between CT int IDs
                parentId,
                childIdString);

            return new SPContentTypeId(newContentTypeIdString);
        }
Exemplo n.º 53
0
        /// <summary>
        /// Creates a new child content type ID
        /// </summary>
        /// <param name="parentContentTypeId">The parent CT ID</param>
        /// <param name="childContentTypeUniqueId">The unique ID for the new child CT</param>
        /// <returns>The new content type ID</returns>
        public static SPContentTypeId CreateChild(SPContentTypeId parentContentTypeId, string childContentTypeUniqueId)
        {
            if (parentContentTypeId == null)
            {
                throw new ArgumentNullException("parentContentTypeId");
            }

            if (!string.IsNullOrEmpty(childContentTypeUniqueId))
            {
                throw new ArgumentNullException("childContentTypeUniqueId");
            }

            string childIdString = childContentTypeUniqueId.ToString(CultureInfo.InvariantCulture);
            string parentId = parentContentTypeId.ToString();

            string newContentTypeIdString = string.Format(
                CultureInfo.InvariantCulture,
                "{0}{1}",       // use no separator when you use a dirty string-based CT discriminator: at this point, your loss your CTID logic is messed up. 
                parentId,
                childIdString);

            return new SPContentTypeId(newContentTypeIdString);
        }
Exemplo n.º 54
0
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var web = ExtractWeb(modelHost);
            var contentTypeModel = model.WithAssertAndCast<ContentTypeDefinition>("model", value => value.RequireNotNull());

            var site = web.Site;
            var targetWeb = web;

            // SPBug, it has to be new SPWen for every content type operation inside feature event handler
            using (var tmpWeb = site.OpenWeb(targetWeb.ID))
            {
                var contentTypeId = new SPContentTypeId(contentTypeModel.GetContentTypeId());

                // by ID, by Name
                var targetContentType = tmpWeb.ContentTypes[contentTypeId];

                if (targetContentType == null)
                {
                    targetContentType = tmpWeb.ContentTypes
                                                  .OfType<SPContentType>()
                                                  .FirstOrDefault(f => f.Name.ToUpper() == contentTypeModel.Name.ToUpper());
                }

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

                if (targetContentType == null)
                {
                    TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject, "Processing new content type");

                    targetContentType = tmpWeb
                        .ContentTypes
                        .Add(new SPContentType(contentTypeId, tmpWeb.ContentTypes, contentTypeModel.Name));
                }
                else
                {
                    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject, "Processing existing content type");
                }

                targetContentType.Hidden = contentTypeModel.Hidden;

                targetContentType.Name = contentTypeModel.Name;
                targetContentType.Group = contentTypeModel.Group;

                if (contentTypeModel.Sealed.HasValue)
                    targetContentType.Sealed = contentTypeModel.Sealed.Value;

                if (contentTypeModel.ReadOnly.HasValue)
                    targetContentType.ReadOnly = contentTypeModel.ReadOnly.Value;

                // SPBug, description cannot be null
                targetContentType.Description = contentTypeModel.Description ?? string.Empty;

#if !NET35
                if (!string.IsNullOrEmpty(contentTypeModel.JSLink))
                    targetContentType.JSLink = contentTypeModel.JSLink;
#endif

                if (!string.IsNullOrEmpty(contentTypeModel.DocumentTemplate))
                {
                    var processedDocumentTemplateUrl = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                    {
                        Value = contentTypeModel.DocumentTemplate,
                        Context = tmpWeb
                    }).Value;

                    // resource related path
                    if (!processedDocumentTemplateUrl.Contains('/')
                        && !processedDocumentTemplateUrl.Contains('\\'))
                    {
                        processedDocumentTemplateUrl = UrlUtility.CombineUrl(new string[] { 
                            targetContentType.ResourceFolder.ServerRelativeUrl,
                            processedDocumentTemplateUrl
                        });
                    }

                    targetContentType.DocumentTemplate = processedDocumentTemplateUrl;
                }

                ProcessLocalization(targetContentType, contentTypeModel);

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

                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Calling currentContentType.Update(true)");
                targetContentType.UpdateIncludingSealedAndReadOnly(true);

                tmpWeb.Update();
            }
        }
Exemplo n.º 55
0
 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];
 }
Exemplo n.º 56
0
 public static void AddFieldToContentType(SPWeb web, SPContentTypeId contentTypeId, SPField field)
 {
     SPContentType contentType = web.ContentTypes[contentTypeId];
     if (contentType == null) return;
     if (contentType.Fields.ContainsField(field.Title)) return;
     SPFieldLink fieldLink = new SPFieldLink(field);
     contentType.FieldLinks.Add(fieldLink);
     contentType.Update();
 }
        /// <summary>
        /// Provisions the document set.
        /// </summary>
        /// <param name="contentTypeId">The content type id.</param>
        private void ProvisionDocumentSet(SPContentTypeId contentTypeId)
        {
            SPContentType contentType = this.Site.RootWeb.ContentTypes[contentTypeId];
            if (this.Deployed(contentType))
            {
                return;
            }

            this.ProvisionDocumentSet(contentType);
        }
Exemplo n.º 58
0
 /// <summary>
 /// Initializes a new <see cref="PageLayoutInfo"/> instance
 /// </summary>
 /// <param name="name">Page layout file name (including the .aspx)</param>
 /// <param name="associatedContentTypeId">Associated page content type ID</param>
 public PageLayoutInfo(string name, SPContentTypeId associatedContentTypeId)
     : this()
 {
     this.Name = name;
     this.AssociatedContentTypeId = associatedContentTypeId;
 }
        public override void DeployModel(object modelHost, DefinitionBase model)
        {
            var listModelHost = modelHost.WithAssertAndCast<ListModelHost>("modelHost", value => value.RequireNotNull());
            var contentTypeLinkModel = model.WithAssertAndCast<ContentTypeLinkDefinition>("model", value => value.RequireNotNull());

            var list = listModelHost.HostList;

            if (list.ContentTypesEnabled)
            {
                var web = list.ParentWeb;

                var contentTypeId = new SPContentTypeId(contentTypeLinkModel.ContentTypeId);
                var targetContentType = web.AvailableContentTypes[contentTypeId];

                if (targetContentType == null)
                {
                    TraceService.ErrorFormat((int)LogEventId.ModelProvisionCoreCall,
                        "Cannot find site content type by ID: [{0}]. Throwing SPMeta2Exception.",
                        contentTypeId);

                    throw new SPMeta2Exception(string.Format("Cannot find site content type with ID [{0}].",
                        contentTypeId));
                }

                var currentListContentType = GetListContentType(list, contentTypeLinkModel);

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

                if (currentListContentType == null)
                {
                    TraceService.Information((int)LogEventId.ModelProvisionProcessingNewObject,
                        "Processing new list content type link");

                    var listCt = list.ContentTypes.Add(targetContentType);

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

                    //list.Update();
                }
                else
                {
                    TraceService.Information((int)LogEventId.ModelProvisionProcessingExistingObject,
                        "Processing existing list content type link");

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

                }
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "ContentTypesEnabled is FALSE. Provision might break.");
            }
        }
 /// <summary>
 /// Gets the content type from the ContentTypes property where the id of that content type is passed by parameter.
 /// </summary>
 /// <param name="contentTypeId">The unique identifier of the content type we are looking for.</param>
 /// <returns>
 /// The content type information.
 /// </returns>
 public ContentTypeInfo GetContentTypeById(SPContentTypeId contentTypeId)
 {
     return this.ContentTypes.Single(c => c.ContentTypeId.Equals(contentTypeId));
 }