private void AddContentTypeToList(Web web, string contentTypeId, string listName, IEnumerable <Field> fields)
        {
            Debug.WriteLine("CType: {0}, List: {1}", contentTypeId, listName);
            var list = web.GetListByTitle(listName);

            if (!list.ContentTypeExistsById(contentTypeId))
            {
                web.AddContentTypeToListById(listName, contentTypeId);
            }

            list.ContentTypesEnabled = true;
            list.Update();
            list.RefreshLoad();

            var contentType = web.ContentTypes.GetById(contentTypeId);
            var defaultView = list.DefaultView;

            web.Context.Load(contentType);
            web.Context.Load(defaultView);
            web.Context.Load(defaultView.ViewFields);
            web.Context.ExecuteQuery();

            foreach (var field in fields)
            {
                // add the fields to the default view
                if (field.FieldTypeKind != FieldType.Note &&
                    !defaultView.ViewFields.Contains(field.InternalName))
                {
                    defaultView.ViewFields.Add(field.InternalName);
                    Debug.WriteLine("  added to default view");
                }

                defaultView.Update();
            }
            web.Context.ExecuteQuery();

            // Item content type
            DeleteContentTypeFromList(web, list, "Item");
        }
Example #2
0
        private void AddContentTypeToList(Web web, string contentTypeId, string listName, IEnumerable<Field> fields) {
            Debug.WriteLine("CType: {0}, List: {1}", contentTypeId, listName);
            var list = web.GetListByTitle(listName);

            if (!list.ContentTypeExistsById(contentTypeId))
                web.AddContentTypeToListById(listName, contentTypeId);

            list.ContentTypesEnabled = true;
            list.Update();
            list.RefreshLoad();

            var contentType = web.ContentTypes.GetById(contentTypeId);
            var defaultView = list.DefaultView;
            web.Context.Load(contentType);
            web.Context.Load(defaultView);
            web.Context.Load(defaultView.ViewFields);
            web.Context.ExecuteQuery();

            foreach (var field in fields) {
                // add the fields to the default view
                if (field.FieldTypeKind != FieldType.Note &&
                    !defaultView.ViewFields.Contains(field.InternalName)) {
                    defaultView.ViewFields.Add(field.InternalName);
                    Debug.WriteLine("  added to default view");
                }

                defaultView.Update();
            }
            web.Context.ExecuteQuery();

            // Item content type
            DeleteContentTypeFromList(web, list, "Item");
        }