Esempio n. 1
0
        /// <summary>
        /// Returns content type associated with the list.
        /// </summary>
        /// <param name="list">List object</param>
        /// <param name="clientContext">Client Context object</param>
        /// <returns>Content type object</returns>
        internal static ContentType GetContentType(List list, ClientContext clientContext)
        {
            ContentType           targetDocumentSetContentType = null;
            ContentTypeCollection listContentTypes             = null;

            try
            {
                listContentTypes = list.ContentTypes;
                clientContext.Load(
                    listContentTypes,
                    types => types.Include(
                        type => type.Id,
                        type => type.Name,
                        type => type.Parent));

                var result = clientContext.LoadQuery(listContentTypes.Where(c => c.Name == ConstantStrings.OneDriveDocumentContentType));
                clientContext.ExecuteQuery();
                targetDocumentSetContentType = result.FirstOrDefault();
            }
            catch (Exception exception)
            {
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return(targetDocumentSetContentType);
        }
Esempio n. 2
0
        /// <summary>
        /// Creates the type of the content.
        /// </summary>
        /// <param name="clientContext">The client context.</param>
        /// <param name="web">Object of site</param>
        /// <param name="siteColumns">The site columns.</param>
        /// <param name="contentTypeName">Name of Content Type</param>
        internal static bool CreateContentType(ClientContext clientContext, Microsoft.SharePoint.Client.Web web, List <string> siteColumns, string contentTypeName, string contentTypegroup)
        {
            bool        status            = true;
            ContentType parentContentType = null;

            try
            {
                ContentTypeCollection contentTypeCollection = web.ContentTypes;
                clientContext.Load(contentTypeCollection);
                clientContext.Load(web.Fields);
                clientContext.ExecuteQuery();
                parentContentType = (from ct in contentTypeCollection
                                     where ct.Name == ServiceConstantStrings.OneDriveParentContentType
                                     select ct).FirstOrDefault();
                ContentTypeCreationInformation contentType = new ContentTypeCreationInformation();
                contentType.Name  = contentTypeName;
                contentType.Group = contentTypegroup;
                ///// contentType.Id = "0x010100B1ED198475FB3A4AABC59AAAD89B7EAD";
                if (parentContentType != null)
                {
                    contentType.ParentContentType = parentContentType;
                }
                ContentType finalObj = web.ContentTypes.Add(contentType);
                AddColumnsToContentType(web, siteColumns, finalObj);
                web.Update();
                clientContext.ExecuteQuery();
            }
            catch (Exception exception)
            {
                status = false;
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return(status);
        }
Esempio n. 3
0
        public static void SetDefaultContentTypeToList(List list, string contentTypeId)
        {
            ContentTypeCollection ctCol = list.ContentTypes;

            list.Context.Load(ctCol);
            list.Context.ExecuteQuery();

            var ctIds = new List <ContentTypeId>();

            foreach (ContentType ct in ctCol)
            {
                ctIds.Add(ct.Id);
            }

            var newOrder = ctIds.Except(
                // remove the folder content type
                ctIds.Where(id => id.StringValue.StartsWith("0x012000"))
                )
                           .OrderBy(x => !x.StringValue.StartsWith(contentTypeId, StringComparison.OrdinalIgnoreCase))
                           .ToArray();

            list.RootFolder.UniqueContentTypeOrder = newOrder;

            list.RootFolder.Update();
            list.Update();
            list.Context.ExecuteQuery();
        }
Esempio n. 4
0
        /// <summary>
        /// Determines whether the content type exists in the content type group under the specified client context.
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="web">Object of site</param>
        /// <param name="receivedContentType">Type of the received content</param>
        /// <param name="contentTypeGroup">The content type group</param>
        /// <param name="siteColumns">List of site columns</param>
        internal static bool IsContentTypePresentCheck(ClientContext clientContext, Microsoft.SharePoint.Client.Web web, string receivedContentType, string contentTypeGroup, List <string> siteColumns)
        {
            bool status = true;

            try
            {
                ContentTypeCollection contentTypeCollection = web.ContentTypes;
                clientContext.Load(contentTypeCollection, contentTypes => contentTypes.Include(contentTypeProperties => contentTypeProperties.Group, contentTypeProperties => contentTypeProperties.Name).Where(contentTypeValues => (contentTypeValues.Group == ServiceConstantStrings.OneDriveContentTypeGroup) && (contentTypeValues.Name == ServiceConstantStrings.OneDriveContentTypeName)));
                clientContext.ExecuteQuery();

                if (0 < contentTypeCollection.Count)
                {
                    FieldCollection fields = contentTypeCollection[0].Fields;
                    clientContext.Load(fields, field => field.Include(fieldType => fieldType.Title).Where(column => column.Title == ServiceConstantStrings.OneDriveSiteColumn));
                    clientContext.ExecuteQuery();
                    if (0 == fields.Count)
                    {
                        BriefcaseContentTypeHelperFunctions.AddColumnsToContentType(web, siteColumns, contentTypeCollection[0]);
                        web.Update();
                        clientContext.ExecuteQuery();
                    }
                }
                else
                {
                    status = BriefcaseContentTypeHelperFunctions.CreateContentType(clientContext, web, siteColumns, receivedContentType, contentTypeGroup);
                }
            }
            catch (Exception exception)
            {
                status = false;
                Logger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, ServiceConstantStrings.LogTableName);
            }
            return(status);
        }
        public void AddFieldToContentType(string contentTypeName, string[] fields)
        {
            // Get all the content types from current site
            ContentTypeCollection collection = _context.Site.RootWeb.ContentTypes;

            _context.Load(collection);
            _context.ExecuteQuery();

            ContentType contentType = (from c in collection
                                       where c.Name == contentTypeName
                                       select c).FirstOrDefault();

            foreach (var item in fields)
            {
                if (item.Contains("Leader") || item.Contains("Members"))
                {
                    continue;
                }
                Field targetField = _context.Web.AvailableFields.GetByInternalNameOrTitle(item);
                FieldLinkCreationInformation fldLink = new FieldLinkCreationInformation
                {
                    Field = targetField
                };
                fldLink.Field.Required = false;
                fldLink.Field.Hidden   = false;

                contentType.FieldLinks.Add(fldLink);
                contentType.Update(false);
            }
        }
        public void GetFolderContentTypes(string nomListe)
        {
            // Get the content type collection for the list nomListe

            NomDossier = nomListe;
            ContentTypeCollection contentTypeColl = ClientCtx.Web.Lists.GetByTitle(NomDossier).ContentTypes;

            //Execute the reques
            ClientCtx.Load(contentTypeColl);

            //try
            //{
            ClientCtx.ExecuteQuery();
            //}
            //catch
            //{
            //  Console.WriteLine("Quelquechose s'est mal passé dans la récupération des content types veuillez verifier le nom du dossier");
            //Console.Read();
            //System.Environment.Exit(-3);
            // }

            foreach (ContentType c in contentTypeColl)
            {
                ListDesContentType.Add(c);
            }
        }
Esempio n. 7
0
        public ContentType Create()
        {
            ContentTypeCollection cntTypeList = context.Web.ContentTypes;

            context.Load(cntTypeList);
            context.ExecuteQuery();

            var targetContentType = GetContentType(cntTypeList);

            // not exist content type yet
            if (targetContentType == null)
            {
                var parentContentType = GetContentType(cntTypeList, ParentType);
                // Create content Type
                ContentTypeCreationInformation newCntType = new ContentTypeCreationInformation
                {
                    Name              = Name,
                    Description       = Description,
                    Group             = Group,
                    ParentContentType = parentContentType
                };

                targetContentType = cntTypeList.Add(newCntType);

                LoadSiteColumn(targetContentType);
                context.Load(targetContentType);
                context.ExecuteQuery();
            }
            return(targetContentType);
        }
Esempio n. 8
0
        public static void CreateContentType(Web web)
        {
            ClientContext context = (ClientContext)web.Context;

            context.Load(web, w => w.ContentTypes);
            ContentTypeCollection contentTypes = web.ContentTypes;
            var itemContentType = contentTypes.GetById("0x01");

            ContentTypeCreationInformation lessonsLearnedInfo = new ContentTypeCreationInformation();

            lessonsLearnedInfo.ParentContentType = itemContentType;
            lessonsLearnedInfo.Name  = "Lessons Learned";
            lessonsLearnedInfo.Group = "Webcor Custom";


            ContentType lessonsLearnedContentType = contentTypes.Add(lessonsLearnedInfo);

            //add Projects Column (using Term Set)
            //add Keywords Column (using Term Set)
            //add Lessons Learned Field
            //add Date-Time Field
            //add Innovator Field
            //add Issue Field
            //add Resolution Field
            //add Status Field
        }
Esempio n. 9
0
        /// <summary>
        /// Gets content type data
        /// </summary>
        /// <param name="clientContext">Client context</param>
        /// <param name="contentTypeNames">Content type names</param>
        /// <returns>IList object</returns>
        internal static IList <ContentType> GetContentTypeData(ClientContext clientContext, IList <string> contentTypeNames)
        {
            ContentTypeCollection contentTypeCollection         = null;
            IList <ContentType>   selectedContentTypeCollection = null;

            if (null != clientContext && null != contentTypeNames)
            {
                Microsoft.SharePoint.Client.Web web = clientContext.Web;
                contentTypeCollection = web.ContentTypes;
                clientContext.Load(contentTypeCollection);
                clientContext.ExecuteQuery();
                selectedContentTypeCollection = new List <ContentType>();
                foreach (string contentTypeName in contentTypeNames)
                {
                    foreach (ContentType contentType in contentTypeCollection)
                    {
                        if (string.Equals(contentTypeName, contentType.Name))
                        {
                            selectedContentTypeCollection.Add(contentType);
                        }
                    }
                }
            }
            return(selectedContentTypeCollection);
        }
Esempio n. 10
0
        private void CreateContentType(ClientContext context)
        {
            //Reference -
            //http://www.srinisistla.com/blog/Lists/Posts/Post.aspx?ID=100
            //https://msdn.microsoft.com/library/office/microsoft.sharepoint.client.contenttypecollection.add.aspx
            try
            {
                //ContentTypeCollection cTCollection = context.Site.RootWeb.AvailableContentTypes;  // AvailableContentTypes is read only. It returns all the CT from web as well as root site
                ContentTypeCollection cTCollection = context.Site.RootWeb.ContentTypes;  // ContentTypes returns all the CT from current web site only
                //context.Load(cTCollection);
                //context.ExecuteQuery();
                //foreach (ContentType ct in cTCollection)
                //{
                //    Console.WriteLine(ct.Name + "   :   " + ct.Parent);
                //}

                ContentTypeCreationInformation cti = new ContentTypeCreationInformation();
                cti.Description = "this is a test Content Type";
                cti.Name        = "TestContentTypeRohit";
                cti.Group       = "RohitCTGroup";
                ContentType ct = cTCollection.Add(cti);
                context.Load(cTCollection);
                context.ExecuteQuery();
            }
            catch (Exception ex)
            {
                Console.WriteLine("Exception in CreateContent Type :  " + ex.Message.ToString());
            }
        }
Esempio n. 11
0
        void createList()
        {
            ListCreationInformation listCreationInformation = new ListCreationInformation();

            listCreationInformation.Title        = "Employee";
            listCreationInformation.TemplateType = (int)ListTemplateType.GenericList;

            List newList = web.Lists.Add(listCreationInformation);

            context.Load(newList);
            context.ExecuteQuery();

            ContentTypeCollection contentTypes = web.ContentTypes;

            context.Load(contentTypes);
            context.ExecuteQuery();

            ContentType EmployeeContentType = (from contentType in contentTypes where contentType.Name == "Employee" select contentType).FirstOrDefault();

            List EmployeeList = web.Lists.GetByTitle("Employee");

            EmployeeList.ContentTypes.AddExistingContentType(EmployeeContentType);
            EmployeeList.Update();
            context.Web.Update();
            context.ExecuteQuery();

            Console.WriteLine("Success create list");
        }
Esempio n. 12
0
        public override object GetRealSPObject()
        {
            if (realObject != null)
            {
                return(realObject);
            }

            object parentObj = base.ParentNode.SPObject;

            if (parentObj != null)
            {
                if (parentObj is ContentTypeCollection)
                {
                    ContentTypeCollection contentTypes = parentObj as ContentTypeCollection;

                    if (contentTypes.Any(c => c.Name == this.Title))
                    {
                        realObject = contentTypes.FirstOrDefault(c => c.Name == this.Title);
                        return(realObject);
                    }
                }
            }

            return(null);
        }
Esempio n. 13
0
 /// <summary>
 /// Method to revert creation of site column and Content Type
 /// </summary>
 /// <param name="clientContext">Client Context</param>
 /// <param name="siteColumns">List of site columns</param>
 /// <param name="contentType">Name of Content Type</param>
 /// <param name="contentTypegroup">Name of Content Type group</param>
 /// <returns>Success or Message</returns>
 internal static void RevertSiteColumns(ClientContext clientContext, List <string> siteColumns, string contentType, string contentTypegroup)
 {
     try
     {
         Console.WriteLine("Deleting existing site columns and content type");
         Web web = clientContext.Web;
         ContentTypeCollection contentTypeCollection = web.ContentTypes;
         ContentType           parentContentType     = null;
         clientContext.Load(contentTypeCollection, contentTypeItem => contentTypeItem.Include(type => type.Group, type => type.Name).Where(f => f.Group == contentTypegroup));
         FieldCollection fieldCollection = web.Fields;
         clientContext.Load(fieldCollection, field => field.Include(attribute => attribute.Group, attribute => attribute.Title).Where(p => p.Group == contentTypegroup));
         clientContext.ExecuteQuery();
         parentContentType = (from contentTypes in contentTypeCollection where contentTypes.Name == contentType select contentTypes).FirstOrDefault();
         if (null != parentContentType)
         {
             parentContentType.DeleteObject();
         }
         foreach (string columns in siteColumns)
         {
             Field revertColumn = (from field in fieldCollection where field.Title == columns select field).FirstOrDefault();
             if (null != revertColumn)
             {
                 revertColumn.DeleteObject();
             }
         }
         web.Update();
         clientContext.ExecuteQuery();
         Console.WriteLine("Deleted existing site columns and content type");
     }
     catch (Exception exception)
     {
         Console.WriteLine("Failed to delete existing site columns.");
         ErrorLogger.LogErrorToTextFile(errorFilePath, "Message: " + exception.Message + "\nStacktrace: " + exception.StackTrace);
     }
 }
        protected override void ProcessRecord()
        {
            base.ProcessRecord();
            var ctx = base.Context;

            string surl = Web.Read();
            Web    web  = ctx.Site.OpenWeb(surl);

            ContentTypeCollection contentTypes = null;

            if (ParameterSetName == "Web")
            {
                contentTypes = web.ContentTypes;
            }
            else if (ParameterSetName == "List")
            {
                SPOList list = List.Read(web, false);
                contentTypes = list.List.ContentTypes;
            }
            ctx.Load(contentTypes);
            ctx.ExecuteQuery();

            foreach (ContentType ct in contentTypes)
            {
                if (string.IsNullOrEmpty(Identity) || ct.Name.ToLower() == Identity.ToLower() || ct.Id.StringValue.ToLower() == Identity.ToLower())
                {
                    SPOContentType.LoadContentType(ctx, ct);
                    WriteObject(new SPOContentType(ct));
                }
            }
        }
Esempio n. 15
0
        public void CreateContentTypes()
        {
            Web web = ClientContext.Web;
            ContentTypeCollection existingContentTypes = web.ContentTypes;

            ClientContext.Load(existingContentTypes);
            ClientContext.ExecuteQuery();

            foreach (GtContentType contentType in ContentTypes)
            {
                if (existingContentTypes.Any(item => item.Id.ToString().Equals(contentType.ID.ToString(CultureInfo.InvariantCulture))))
                {
                    // We want to add fields even if the content type exists (?)
                    AddSiteColumnsToContentType(contentType);
                }
                else
                {
                    var contentTypeCreationInformation = contentType.GetContentTypeCreationInformation();
                    var newContentType = existingContentTypes.Add(contentTypeCreationInformation);
                    ClientContext.ExecuteQuery();

                    // Update display name (internal name will not be changed)
                    newContentType.Name = contentType.DisplayName;
                    newContentType.Update(true);
                    ClientContext.ExecuteQuery();

                    AddSiteColumnsToContentType(contentType);
                }
            }
        }
Esempio n. 16
0
        /// <summary>
        /// Create Content Type
        /// </summary>
        public static void CreateContentType(ClientContext clientContext, string ContentTypeName, string ContentTypeDescription, string ContentTypeId, string[] filedNames)
        {
            var contentType = CSOMUtil.GetContentTypeById(clientContext, ContentTypeId);

            // check if the content type exists
            if (contentType == null)
            {
                ContentTypeCollection contentTypeColl = clientContext.Web.ContentTypes;
                clientContext.Load(contentTypeColl);
                clientContext.ExecuteQuery();

                // Specifies properties that are used as parameters to initialize a new content type.
                ContentTypeCreationInformation contentTypeCreation = new ContentTypeCreationInformation();
                contentTypeCreation.Name        = ContentTypeName;
                contentTypeCreation.Description = ContentTypeDescription;
                contentTypeCreation.Group       = "Property Manager My App Content Types";
                contentTypeCreation.Id          = ContentTypeId;

                //// Add the new content type to the collection
                contentType = contentTypeColl.Add(contentTypeCreation);
                clientContext.Load(contentType);
                clientContext.ExecuteQuery();

                CSOMUtil.BindFieldsToContentType(clientContext, contentType, filedNames);
            }
        }
Esempio n. 17
0
        private static void CreateContentTypeIfDoesNotExist(ClientContext cc, Web web)
        {
            ContentTypeCollection contentTypes = web.ContentTypes;

            cc.Load(contentTypes);
            cc.ExecuteQuery();

            foreach (var item in contentTypes)
            {
                if (item.StringId == "0x0101009189AB5D3D2647B580F011DA2F356FB3")
                {
                    return;
                }
            }

            // Create a Content Type Information object
            ContentTypeCreationInformation newCt = new ContentTypeCreationInformation();

            // Set the name for the content type
            newCt.Name = "Contoso Sample Document";
            //Inherit from oob document - 0x0101 and assign
            newCt.Id = "0x0101009189AB5D3D2647B580F011DA2F356FB3";
            // Set content type to be avaialble from specific group
            newCt.Group = "Contoso Content Types";
            // Create the content type
            ContentType myContentType = contentTypes.Add(newCt);

            cc.ExecuteQuery();

            Console.WriteLine("Content type created.");
        }
        private SPOContentType Read(ContentTypeCollection contentTypes)
        {
            var ctx = SPOSiteContext.CurrentSiteContext.Context;
            ContentType contentType = null;
            if (_contentTypeId != null)
            {
                contentType = contentTypes.GetById(_contentTypeId);
            }
            else if (!string.IsNullOrEmpty(_name))
            {
                ctx.Load(contentTypes);
                ctx.ExecuteQuery();

                foreach (ContentType ct in contentTypes)
                {
                    if (ct.Name.ToLower() == _name.ToLower())
                    {
                        contentType = ct;
                        break;
                    }
                }

            }
            if (contentType != null)
            {
                SPOContentType.LoadContentType(ctx, contentType);
                if (contentType.ServerObjectIsNull.Value)
                    return null;

                return new SPOContentType(contentType);
            }

            return null;
        }
        public bool Validate(ContentTypeCollection sourceCollection, ContentTypeCollection targetCollection, TokenParser tokenParser)
        {
            // Convert object collections to XML 
            List<SerializedContentType> sourceContentTypes = new List<SerializedContentType>();
            List<SerializedContentType> targetContentTypes = new List<SerializedContentType>();

            foreach (ContentType ct in sourceCollection)
            {
                ProvisioningTemplate pt = new ProvisioningTemplate();
                pt.ContentTypes.Add(ct);

                sourceContentTypes.Add(new SerializedContentType() { SchemaXml = ExtractElementXml(pt) });                
            }

            foreach (ContentType ct in targetCollection)
            {
                ProvisioningTemplate pt = new ProvisioningTemplate();
                pt.ContentTypes.Add(ct);

                targetContentTypes.Add(new SerializedContentType() { SchemaXml = ExtractElementXml(pt) });
            }

            // Use XML validation logic to compare source and target
            Dictionary<string, string[]> parserSettings = new Dictionary<string, string[]>();
            parserSettings.Add("SchemaXml", null);
            bool isContentTypeMatch = ValidateObjectsXML(sourceContentTypes, targetContentTypes, "SchemaXml", new List<string> { "ID" }, tokenParser, parserSettings);
            Console.WriteLine("-- Content type validation " + isContentTypeMatch);
            return isContentTypeMatch;
        }
        /// <summary>
        /// Add content type to list
        /// </summary>
        /// <param name="list"></param>
        /// <param name="contentType"></param>
        /// <param name="defaultContent"></param>
        public static void AddContentTypeToList(this List list, ContentType contentType, bool defaultContent = false)
        {
            list.ContentTypesEnabled = true;
            list.Update();
            list.Context.ExecuteQuery();
            ContentTypeCollection contentTypes = list.ContentTypes;

            list.Context.Load(contentTypes);
            list.Context.ExecuteQuery();


            foreach (ContentType ct in contentTypes)
            {
                if (ct.Name.ToLowerInvariant() == contentType.Name.ToString().ToLowerInvariant())
                {
                    // Already there, abort
                    return;
                }
            }

            contentTypes.AddExistingContentType(contentType);
            list.Context.ExecuteQuery();
            //set the default contenttype
            if (defaultContent)
            {
                SetDefaultContentTypeToList(list, contentType);
            }
        }
Esempio n. 21
0
        public void DeleteAllCustomContentTypes()
        {
            Web web = ClientContext.Web;
            ContentTypeCollection existingContentTypes = web.ContentTypes;

            ClientContext.Load(existingContentTypes);
            ClientContext.ExecuteQuery();

            var contentTypeGroups = new List <string>();

            foreach (
                ShContentType contentType in
                ContentTypes.Where(contentType => !contentTypeGroups.Contains(contentType.Group)))
            {
                contentTypeGroups.Add(contentType.Group);
            }
            List <ContentType> contentTypes =
                existingContentTypes.ToList()
                .OrderBy(ct => ct.Id.ToString())
                .Where(ct => contentTypeGroups.Contains(ct.Group))
                .ToList();

            for (int i = contentTypes.Count - 1; i >= 0; i--)
            {
                contentTypes[i].DeleteObject();
                try
                {
                    ClientContext.ExecuteQuery();
                }
                catch
                {
                    Console.WriteLine("Could not delete content type '" + contentTypes[i].Name + "'");
                }
            }
        }
Esempio n. 22
0
        /// <summary>
        /// This method will get all content types from the specified content type group and will filter out the content types that user has selected
        /// when creating the matter
        /// </summary>
        /// <param name="clientContext">The sharepoint context object</param>
        /// <param name="contentTypesNames">Content Type Names that user selected in the create matter screen</param>
        /// <param name="client">The client object which contains information for which client the matter is getting created and the url of the client</param>
        /// <param name="matter">The matter information that is getting created</param>
        /// <returns></returns>
        public IList <ContentType> GetContentTypeData(ClientContext clientContext, IList <string> contentTypesNames, Client client, Matter matter)
        {
            ContentTypeCollection contentTypeCollection         = null;
            IList <ContentType>   selectedContentTypeCollection = new List <ContentType>();

            try
            {
                if (null != clientContext && null != contentTypesNames)
                {
                    Web    web             = clientContext.Web;
                    string contentTypeName = contentTypesConfig.OneDriveContentTypeGroup.Trim();
                    contentTypeCollection = web.ContentTypes;
                    clientContext.Load(contentTypeCollection, contentType => contentType.Include(thisContentType => thisContentType.Name).Where(currContentType => currContentType.Group == contentTypeName));
                    clientContext.ExecuteQuery();
                    selectedContentTypeCollection = GetContentTypeList(contentTypesNames, contentTypeCollection.ToList());
                }
            }
            catch (Exception exception)
            {
                customLogger.LogError(exception, MethodBase.GetCurrentMethod().DeclaringType.Name, MethodBase.GetCurrentMethod().Name, logTables.SPOLogTable);
                throw;
            }

            return(selectedContentTypeCollection);
        }
Esempio n. 23
0
        private static void LocalizeContentTypeAndField(ClientContext cc, Web web)
        {
            ContentTypeCollection contentTypes  = web.ContentTypes;
            ContentType           myContentType = contentTypes.GetById("0x0101009189AB5D3D2647B580F011DA2F356FB2");

            cc.Load(contentTypes);
            cc.Load(myContentType);
            cc.ExecuteQuery();
            // Title of the content type
            myContentType.NameResource.SetValueForUICulture("en-US", "Contoso Document");
            myContentType.NameResource.SetValueForUICulture("fi-FI", "Contoso Dokumentti");
            myContentType.NameResource.SetValueForUICulture("fr-FR", "Contoso Document (FR)");
            // Description of the content type
            myContentType.DescriptionResource.SetValueForUICulture("en-US", "This is the Contoso Document.");
            myContentType.DescriptionResource.SetValueForUICulture("fi-FI", "Tämä on geneerinen Contoso dokumentti.");
            myContentType.DescriptionResource.SetValueForUICulture("fr-FR", "French Contoso document.");
            myContentType.Update(true);
            cc.ExecuteQuery();

            // Do localization also for the site column
            FieldCollection fields = web.Fields;
            Field           fld    = fields.GetByInternalNameOrTitle("ContosoString");

            fld.TitleResource.SetValueForUICulture("en-US", "Contoso String");
            fld.TitleResource.SetValueForUICulture("fi-FI", "Contoso Teksti");
            fld.TitleResource.SetValueForUICulture("fr-FR", "Contoso French String");
            // Description entry
            fld.DescriptionResource.SetValueForUICulture("en-US", "Used to store Contoso specific metadata.");
            fld.DescriptionResource.SetValueForUICulture("fi-FI", "Tää on niiku Contoso metadatalle.");
            fld.DescriptionResource.SetValueForUICulture("fr-FR", "French Description Goes here");
            fld.UpdateAndPushChanges(true);
            cc.ExecuteQuery();
        }
Esempio n. 24
0
        private static void AddContentTypeToList()
        {
            string contentTypename;
            Console.Write("Enter content type - \n");
            contentTypename = Console.ReadLine();
            Console.WriteLine("You entered", contentTypename);

            string contentdescription;
            Console.Write("Enter a description for content type - \n");
            contentdescription = Console.ReadLine();
            Console.WriteLine("You entered ", contentdescription);

            string groupName;
            Console.Write("Enter group name - \n");
            groupName = Console.ReadLine();
            Console.WriteLine("You entered ", groupName);

            ContentTypeCollection contentTypeColl = globalctx.Web.ContentTypes;

            ContentTypeCreationInformation contentTypeCreation = new ContentTypeCreationInformation();
            contentTypeCreation.Name = contentTypename;
            contentTypeCreation.Description = contentdescription;
            contentTypeCreation.Group = groupName;

            ContentType ct = contentTypeColl.Add(contentTypeCreation);
            globalctx.Load(ct);
            globalctx.ExecuteQuery();

            Console.WriteLine(ct.Name + " content type is created successfully");

        }
Esempio n. 25
0
        void createList()
        {
            ListCreationInformation listCreationInformation = new ListCreationInformation();

            listCreationInformation.Title        = "Project documents";
            listCreationInformation.TemplateType = (int)ListTemplateType.DocumentLibrary;

            List newList = web.Lists.Add(listCreationInformation);

            context.Load(newList);
            context.ExecuteQuery();

            ContentTypeCollection contentTypes = web.ContentTypes;

            context.Load(contentTypes);
            context.ExecuteQuery();

            ContentType ProjectDocumentsContentType = (from contentType in contentTypes where contentType.Name == "Project documents" select contentType).FirstOrDefault();

            List ProjectDocumentsList = web.Lists.GetByTitle("Project documents");

            ProjectDocumentsList.ContentTypes.AddExistingContentType(ProjectDocumentsContentType);
            ProjectDocumentsList.Update();
            context.Web.Update();
            context.ExecuteQuery();

            Console.WriteLine("Success create list");
        }
        public virtual ContentType Create()
        {
            ContentTypeCollection contentTypeColl = _context.Web.ContentTypes;

            _context.Load(contentTypeColl);
            _context.ExecuteQuery();

            var targetContentType = GetContentType(contentTypeColl);

            if (targetContentType != null)
            {
                throw new Exception("Content type already Exists");
            }
            else
            {
                var parentContentType = GetContentType(contentTypeColl, ParentTypeTitle);
                // Create content Type
                ContentTypeCreationInformation contentTypeCreationInformation = new ContentTypeCreationInformation
                {
                    Name              = Name,
                    Description       = Description,
                    Group             = Group,
                    ParentContentType = parentContentType
                };

                targetContentType = contentTypeColl.Add(contentTypeCreationInformation);

                _context.Load(targetContentType);
                _context.ExecuteQuery();
                return(targetContentType);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Removes a content type from a list/library by name
        /// </summary>
        /// <param name="list">The list</param>
        /// <param name="contentTypeName">The content type name to remove from the list</param>
        /// <exception cref="System.ArgumentException">Thrown when a arguement is null or <see cref="String.Empty"/></exception>
        public static void RemoveContentTypeByName(this List list, string contentTypeName)
        {
            if (string.IsNullOrEmpty(contentTypeName))
            {
                var message = string.Format(Constants.EXCEPTION_MSG_INVALID_ARG, "contentTypeName");
                throw new ArgumentNullException("contentTypeName", message);
            }

            ContentTypeCollection _cts = list.ContentTypes;

            list.Context.Load(_cts);

            IEnumerable <ContentType> _results = list.Context.LoadQuery <ContentType>(_cts.Where(item => item.Name == contentTypeName));

            list.Context.ExecuteQuery();

            ContentType _ct = _results.FirstOrDefault();

            if (_ct != null)
            {
                _ct.DeleteObject();
                list.Update();
                list.Context.ExecuteQuery();
            }
        }
Esempio n. 28
0
 // Create SharePoint site context
 public static string GetAllContentTypesBySiteUrl(SharepointRequest request)
 {
     try
     {
         using (ClientContext context = GetClientContext(request))
         {
             ContentTypeCollection contentTypeColl = context.Web.ContentTypes;
             context.Load(contentTypeColl);
             context.ExecuteQuery();
             List <SPContentType> contentTypes = new List <SPContentType>();
             foreach (ContentType contentType in contentTypeColl)
             {
                 string id = contentType.Id.ToString();
                 if (contentType.Group != "_Hidden" && !contentType.Hidden && (id.StartsWith(SPDocumentContentType.DocumentContentType) || id.StartsWith(SPDocumentContentType.DocumentSetContentType)))
                 {
                     contentTypes.Add(new SPContentType()
                     {
                         Id       = id,
                         Name     = contentType.Name,
                         Selected = false
                     });
                 }
             }
             return(JsonHelper.ConvertToJson(contentTypes));
         }
     }
     catch
     {
         throw;
     }
 }
Esempio n. 29
0
        public void CreateListAndLib(string listName, int templateType, string contentTypeName)
        {
            ContentTypeCollection contentTypeCollection = _context.Site.RootWeb.ContentTypes;

            _context.Load(contentTypeCollection);
            _context.ExecuteQuery();

            //Create list
            ListCreationInformation lci = new ListCreationInformation
            {
                Title        = listName,
                TemplateType = templateType,
            };
            List itList = _context.Web.Lists.Add(lci);

            itList.ContentTypesEnabled = true;
            itList.Update();

            //Add Content type to list
            ContentType contentType = (from c in contentTypeCollection
                                       where c.Name == contentTypeName
                                       select c).FirstOrDefault();

            List targetList = _context.Web.Lists.GetByTitle(listName);

            targetList.ContentTypes.AddExistingContentType(contentType);
            targetList.Update();

            _context.Web.Update();
        }
Esempio n. 30
0
        public static dynamic IsExist_Helper(ClientContext context, String fieldToCheck, String type)
        {
            var                   isExist        = 0;
            Web                   oWeb           = context.Web;
            ListCollection        listCollection = oWeb.Lists;
            ContentTypeCollection cntCollection  = oWeb.ContentTypes;
            FieldCollection       fldCollection  = oWeb.Fields;

            switch (type)
            {
            case "list":
                context.Load(listCollection, lsts => lsts.Include(list => list.Title).Where(list => list.Title == fieldToCheck));
                context.ExecuteQuery();
                isExist = listCollection.Count;
                break;

            case "contenttype":
                context.Load(cntCollection, cntyp => cntyp.Include(ct => ct.Name).Where(ct => ct.Name == fieldToCheck));
                context.ExecuteQuery();
                isExist = cntCollection.Count;
                break;

            case "contenttypeName":
                context.Load(cntCollection, cntyp => cntyp.Include(ct => ct.Name, ct => ct.Id).Where(ct => ct.Name == fieldToCheck));
                context.ExecuteQuery();
                foreach (ContentType ct in cntCollection)
                {
                    return(ct.Id.ToString());
                }
                break;

            case "field":
                FieldCollection fieldColl = oWeb.Fields;

                var siteColumnDetails = context.LoadQuery(fieldColl.Where(ct => ct.InternalName == fieldToCheck));
                context.ExecuteQuery();

                var siteColumn = siteColumnDetails.FirstOrDefault();

                if (siteColumn != null && !String.IsNullOrEmpty(siteColumn.InternalName))
                {
                    isExist = 1;
                }
                else
                {
                    isExist = 0;
                }
                break;

            case "listcntype":
                List lst = context.Web.Lists.GetByTitle(fieldToCheck);
                ContentTypeCollection lstcntype = lst.ContentTypes;
                context.Load(lstcntype, lstc => lstc.Include(lc => lc.Name).Where(lc => lc.Name == fieldToCheck));
                context.ExecuteQuery();
                isExist = lstcntype.Count;
                break;
            }
            return(isExist);
        }
Esempio n. 31
0
 public static List<Model.ContentType> ToContentTypes(ContentTypeCollection contentTypes)
 {
     return contentTypes.Cast<ContentType>().Select(ct => new Model.ContentType
     {
         Id = ct.StringId,
         Name = ct.Name
     }).ToList();
 }
        /// <summary>
        /// Return content type by name
        /// </summary>
        /// <param name="list"></param>
        /// <param name="contentTypeName"></param>
        /// <returns>Conten type object or null if was not found</returns>
        public static ContentType GetContentTypeByName(this List list, string contentTypeName)
        {
            ContentTypeCollection     ctCol   = list.ContentTypes;
            IEnumerable <ContentType> results = list.Context.LoadQuery <ContentType>(ctCol.Where(item => item.Name == contentTypeName));

            list.Context.ExecuteQuery();
            return(results.FirstOrDefault());
        }
Esempio n. 33
0
 public static List <Model.ContentType> ToContentTypes(ContentTypeCollection contentTypes)
 {
     return(contentTypes.Cast <ContentType>().Select(ct => new Model.ContentType
     {
         Id = ct.StringId,
         Name = ct.Name
     }).ToList());
 }
        protected ContentType FindByName(ContentTypeCollection contentTypes, string name)
        {
            foreach (var ct in contentTypes)
            {
                if (String.Compare(ct.Name, name, System.StringComparison.OrdinalIgnoreCase) == 0)
                    return ct;
            }

            return null;
        }
        public bool ValidateContentTypes(ContentTypeCollection sElements, ContentTypeCollection tElements, TokenParser sParser, TokenParser tParser)
        {
            List<Localization> sColl = LoadContentTypes(sElements);
            List<Localization> tColl = LoadContentTypes(tElements);

            if (sColl.Count > 0)
            {
                if (!Validatelocalization(sColl, tColl, sParser, tParser)) { return false; }
            }

            return true;
        }
        internal static SPOContentType GetContentType(CmdletContext ctx, ContentTypeCollection contentTypes, string name)
        {
            ctx.Load(contentTypes);
            ctx.ExecuteQuery();

            foreach (ContentType ct in contentTypes)
            {
                if (ct.Name.ToLower() == name.ToLower())
                {
                    SPOContentType.LoadContentType(ctx, ct);
                    return new SPOContentType(ct);
                }
            }
            return null;
        }
Esempio n. 37
0
        /// <summary>
        /// Gets the content types (explicitly declared) from the 
        /// site collection that is currently being processed
        /// </summary>
        private void RetreiveContentTypes()
        {
            _siteFields = _ctx.Site.RootWeb.Fields;
            _ctx.Load(_siteFields);
            _cts = _ctx.Site.RootWeb.ContentTypes;
            _ctx.Load(_cts);
            _ctx.ExecuteQuery();

            foreach (var contentType in _cts)
            {
                _ctx.Load(contentType,
                    ct => ct.Parent.Name,
                    ct => ct.Parent.Id,
                    ct => ct.Sealed,
                    ct => ct.Hidden,
                    ct => ct.Id, ct => ct.FieldLinks);
            }
            _ctx.ExecuteQuery();
        }
        private List<Localization> LoadContentTypes(ContentTypeCollection coll)
        {
            List<Localization> loc = new List<Localization>();

            foreach (ContentType item in coll)
            {
                loc.Add(new Localization(item.Id, item.Name, item.Description));
            }           

            return loc;
        }