Exemplo n.º 1
0
        public void EnsureContentTypes()
        {
            Web web = ClientContext.Web;
            ContentTypeCollection existingContentTypes = web.ContentTypes;

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

            foreach (ShContentType contentType in ContentTypes)
            {
                var existingContentType = existingContentTypes.SingleOrDefault(
                    item => item.Id.ToString().Equals(contentType.ID.ToString(CultureInfo.InvariantCulture)));
                if (existingContentType != null)
                {
                    if (existingContentType.Group != contentType.Group)
                    {
                        Log.Debug("Updating group of content type " + contentType.DisplayName);
                        existingContentType.Group = contentType.Group;
                        existingContentType.Update(true);
                        ClientContext.ExecuteQuery();
                    }
                    if (existingContentType.Name != contentType.DisplayName)
                    {
                        Log.Debug("Updating display name of content type " + contentType.DisplayName);
                        existingContentType.Name = contentType.DisplayName;
                        existingContentType.Update(true);
                        ClientContext.ExecuteQuery();
                    }
                    var template = contentType.Template;
                    if (template != null)
                    {
                        AddTemplateToContentType(contentType);
                    }
                }
                else
                {
                    Log.Debug("Creating content type " + contentType.DisplayName);
                    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();
                    var template = contentType.Template;
                    if (template != null)
                    {
                        AddTemplateToContentType(contentType);
                    }
                }
                Log.Debug("Adding fields to existing content type " + contentType.DisplayName);
                // We want to add fields even if the content type exists
                AddSiteColumnsToContentType(contentType);
            }
        }