Example #1
0
        public void CreateFieldTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var fieldName = "Test_" + DateTime.Now.ToFileTime();
                var fieldId   = Guid.NewGuid();

                var fieldCI = new FieldCreationInformation(FieldType.Choice)
                {
                    Id               = fieldId,
                    InternalName     = fieldName,
                    DisplayName      = fieldName,
                    AddToDefaultView = true,
                    Group            = "Test fields group"
                };
                var fieldChoice = clientContext.Web.CreateField <FieldChoice>(fieldCI);

                var field = clientContext.Web.Fields.GetByTitle(fieldName);
                clientContext.Load(field);
                clientContext.ExecuteQuery();

                Assert.AreEqual(fieldId, field.Id, "Field IDs do not match.");
                Assert.AreEqual(fieldName, field.InternalName, "Field internal names do not match.");
                Assert.AreEqual("Choice", fieldChoice.TypeAsString, "Failed to create a FieldChoice object.");
            }
        }
Example #2
0
        public static void AddAddBirthdayAction(ClientContext ctx)
        {
            if (!ctx.Web.ListExists("Person"))
            {
                ctx.Web.CreateList(ListTemplateType.GenericList, "Person", false);
            }

            List list = ctx.Web.GetListByTitle("Person");

            if (!list.FieldExistsById("{A7A83D5A-06C4-4EA0-94D4-831B74B2E077}"))
            {
                FieldCreationInformation fieldInfo = new FieldCreationInformation(FieldType.Number);
                fieldInfo.Id           = "{A7A83D5A-06C4-4EA0-94D4-831B74B2E077}".ToGuid();
                fieldInfo.InternalName = "CUSTOM_AGE";
                fieldInfo.DisplayName  = "Current Age";

                list.CreateField(fieldInfo);
            }

            DelectCustomActionFromList(ctx, "AddAge", list);

            ctx.Load(ctx.Web, w => w.Url);
            ctx.ExecuteQuery();

            UserCustomAction customAction = list.UserCustomActions.Add();

            customAction.Name     = "AddAge";
            customAction.Location = "EditControlBlock";
            customAction.Title    = "Have birthday";
            customAction.Url      = "javascript:window.location = 'https://localhost:44363/home/HaveBirthday?SPHostUrl=" + ctx.Web.Url + "&listId={ListId}&itemid={ItemId}'";
            customAction.Update();

            ctx.ExecuteQuery();
        }
Example #3
0
        private static Field CreateChoiceField(FieldType fType, string displayName, string internalName, string fieldGroup, IEnumerable <KeyValuePair <string, string> > additionalAttributes, bool addToDefaultView, bool required, string[] choices)
        {
            Field field = null;

            if (web.FieldExistsByName(internalName))
            {
                field = web.Fields.GetByInternalNameOrTitle(internalName);
                field.DeleteObject();
                context.ExecuteQuery();
            }
            FieldCreationInformation fieldCi = new FieldCreationInformation(FieldType.Choice)
            {
                DisplayName      = displayName,
                InternalName     = internalName,
                AddToDefaultView = addToDefaultView,
                Required         = required,
                Id    = Guid.NewGuid(),
                Group = fieldGroup,
                AdditionalAttributes = additionalAttributes,
            };

            field = web.CreateField(fieldCi);

            FieldChoice fieldChoice = context.CastTo <FieldChoice>(web.Fields.GetByTitle(displayName));

            context.Load(fieldChoice);
            context.ExecuteQuery();

            fieldChoice.Choices = choices;
            fieldChoice.Update();
            context.Load(fieldChoice);
            context.ExecuteQuery();

            return(fieldChoice);
        }
Example #4
0
        public void Initialize()
        {
            /*** Make sure that the user defined in the App.config has permissions to Manage Terms ***/

            // Create some taxonomy groups and terms
            using (var clientContext = TestCommon.CreateClientContext())
            {
                _termGroupName = "Test_Group_" + DateTime.Now.ToFileTime();
                _termSetName   = "Test_Termset_" + DateTime.Now.ToFileTime();
                _termName      = "Test_Term_" + DateTime.Now.ToFileTime();
                _textFieldName = "Test_Text_Field_" + DateTime.Now.ToFileTime();

                _termGroupId = Guid.NewGuid();
                _termSetId   = Guid.NewGuid();
                _termId      = Guid.NewGuid();

                // Termgroup
                var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore  = taxSession.GetDefaultSiteCollectionTermStore();
                var termGroup  = termStore.CreateGroup(_termGroupName, _termGroupId);
                clientContext.Load(termGroup);
                clientContext.ExecuteQuery();

                // Termset
                var termSet = termGroup.CreateTermSet(_termSetName, _termSetId, 1033);
                clientContext.Load(termSet);
                clientContext.ExecuteQuery();

                // Term
                termSet.CreateTerm(_termName, 1033, _termId);
                clientContext.ExecuteQuery();

                // List

                _textFieldId = Guid.NewGuid();

                var fieldCI = new FieldCreationInformation(FieldType.Text)
                {
                    Id           = _textFieldId,
                    InternalName = _textFieldName,
                    DisplayName  = "Test Text Field",
                    Group        = "Test Group"
                };

                var textfield = clientContext.Web.CreateField(fieldCI);

                var list = clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, "Test_list_" + DateTime.Now.ToFileTime(), false);

                var field = clientContext.Web.Fields.GetByInternalNameOrTitle("TaxKeyword"); // Enterprise Metadata

                list.Fields.Add(field);
                list.Fields.Add(textfield);

                list.Update();
                clientContext.Load(list);
                clientContext.ExecuteQuery();

                _listId = list.Id;
            }
        }
        /// <summary>
        /// Creates a custom document library and IT Document Content Type
        /// </summary>
        /// <param name="ctx">The authenticated ClientContext</param>
        /// <param name="library">The Library  to create</param>
        public void CreateITDocumentLibrary(ClientContext ctx, Library library)
        {
            //Check the fields
            if (!ctx.Web.FieldExistsById(FLD_BUSINESS_UNIT_ID))
            {
                //ctx.Web.CreateField(FLD_BUSINESS_UNIT_ID,
                //                    FLD_BUSINESS_UNIT_INTERNAL_NAME,
                //                    FieldType.Text,
                //                    FLD_BUSINESS_UNIT_DISPLAY_NAME,
                //                    FIELDS_GROUP_NAME);
                FieldCreationInformation fldCreate = new FieldCreationInformation(FieldType.Text)
                {
                    Id           = FLD_BUSINESS_UNIT_ID,
                    InternalName = FLD_BUSINESS_UNIT_INTERNAL_NAME,
                    DisplayName  = FLD_BUSINESS_UNIT_DISPLAY_NAME,
                    Group        = FIELDS_GROUP_NAME
                };
                ctx.Web.CreateField(fldCreate);
            }
            //check the content type
            if (!ctx.Web.ContentTypeExistsById(ITDOCUMENT_CT_ID))
            {
                ctx.Web.CreateContentType(ITDOCUMENT_CT_NAME, CT_DESC, ITDOCUMENT_CT_ID, CT_GROUP);
            }

            //associate fields to content types
            if (!ctx.Web.FieldExistsByNameInContentType(ITDOCUMENT_CT_NAME, FLD_BUSINESS_UNIT_INTERNAL_NAME))
            {
                ctx.Web.AddFieldToContentTypeById(ITDOCUMENT_CT_ID, FLD_BUSINESS_UNIT_ID.ToString(), false);
            }

            CreateLibrary(ctx, library, ITDOCUMENT_CT_ID);
        }
        public void AddFieldToContentTypeMakeRequiredTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                clientContext.Web.CreateContentType(TEST_CT_PNP, TEST_CT_PNP_ID, TEST_CATEGORY);

                var fieldName = "Test_" + DateTime.Now.ToFileTime();
                var fieldId = Guid.NewGuid();

                var fieldCI = new FieldCreationInformation(FieldType.Text)
                {
                    Id = fieldId,
                    InternalName = fieldName,
                    DisplayName = fieldName,
                    AddToDefaultView = true,
                    Group = "Test fields group"
                };
                var fieldText = clientContext.Web.CreateField<FieldText>(fieldCI);

                // simply add the field to the content type
                clientContext.Web.AddFieldToContentTypeByName(TEST_CT_PNP, fieldId);

                // add the same field, but now with required setting to true and hidden to true
                clientContext.Web.AddFieldToContentTypeByName(TEST_CT_PNP, fieldId, true);

                // Fetch the created field and verify the state of the hidden and required properties
                ContentType ct = clientContext.Web.GetContentTypeByName(TEST_CT_PNP);
                FieldCollection fields = ct.Fields;
                IEnumerable<Field> results = ct.Context.LoadQuery<Field>(fields.Where(item => item.Id == fieldId));
                ct.Context.ExecuteQueryRetry();
                Assert.IsTrue(results.FirstOrDefault().Required);
            }
        }
Example #7
0
        public void AddFieldToContentTypeMakeRequiredTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                clientContext.Web.CreateContentType(TEST_CT_PNP, TEST_CT_PNP_ID, TEST_CATEGORY);

                var fieldName = "Test_" + DateTime.Now.ToFileTime();
                var fieldId   = Guid.NewGuid();

                var fieldCI = new FieldCreationInformation(FieldType.Text)
                {
                    Id               = fieldId,
                    InternalName     = fieldName,
                    DisplayName      = fieldName,
                    AddToDefaultView = true,
                    Group            = "Test fields group"
                };
                var fieldText = clientContext.Web.CreateField <FieldText>(fieldCI);

                // simply add the field to the content type
                clientContext.Web.AddFieldToContentTypeByName(TEST_CT_PNP, fieldId);

                // add the same field, but now with required setting to true and hidden to true
                clientContext.Web.AddFieldToContentTypeByName(TEST_CT_PNP, fieldId, true);

                // Fetch the created field and verify the state of the hidden and required properties
                ContentType         ct      = clientContext.Web.GetContentTypeByName(TEST_CT_PNP);
                FieldCollection     fields  = ct.Fields;
                IEnumerable <Field> results = ct.Context.LoadQuery <Field>(fields.Where(item => item.Id == fieldId));
                ct.Context.ExecuteQueryRetry();
                Assert.IsTrue(results.FirstOrDefault().Required);
            }
        }
Example #8
0
        public void RemoveFieldTest()
        {
            using (var ctx = TestCommon.CreateClientContext())
            {
                FieldCreationInformation fieldCI = new FieldCreationInformation(FieldType.Text)
                {
                    DisplayName  = "PnPTestTextField",
                    Group        = "PnP",
                    InternalName = "PnPTestTextField",
                    Required     = false
                };

                ctx.Web.CreateField(fieldCI);

                using (var scope = new PSTestScope(true))
                {
                    scope.ExecuteCommand("Remove-PnPField",
                                         new CommandParameter("Identity", "PnPTestTextField"),
                                         new CommandParameter("Force"));
                }

                var succeeded = false;
                try
                {
                    var field = ctx.Web.Fields.GetByInternalNameOrTitle("PnPTestTextField");
                    ctx.ExecuteQueryRetry();
                }
                catch {
                    succeeded = true;
                }

                Assert.IsTrue(succeeded);
            }
        }
        static TField CreateField <TField>(Web web, Guid fieldId, string internalName, FieldType fieldType, string displayName, string groupName, string attributes, bool executeQuery = true) where TField : Field
        {
            if (!web.Fields.ServerObjectIsNull.HasValue ||
                web.Fields.ServerObjectIsNull.Value)
            {
                web.Context.Load(web.Fields);
                web.Context.ExecuteQuery();
            }

            var fieldCI = new FieldCreationInformation(fieldType)
            {
                Id               = fieldId,
                InternalName     = internalName,
                DisplayName      = displayName,
                AddToDefaultView = true,
                Group            = groupName
            };

            var field = web.Fields.FirstOrDefault(f => f != null && f.StaticName == internalName);

            if (field == null)
            {
                field = web.CreateField <TField>(fieldCI, executeQuery);
            }

            return(web.Context.CastTo <TField>(field));
        }
        //Generic method for all column types
        private static CSOMOperation AddField(this CSOMOperation operation, string name, FieldType type, string displayName = "", bool required = false, bool uniqueValues = false, string defaultValue = "", string group = "", int?maxLength = null, bool percentage = false, int decimals = 2, int?min = null, int?max = null, List <string> choices = null, ChoiceTypes choiceType = ChoiceTypes.Default, string lookupList = "", string lookupField = "")
        {
            operation.LogInfo($"Adding column {name}");

            FieldCreationInformation fieldInformation = new FieldCreationInformation
            {
                InternalName = name,
                DisplayName  = String.IsNullOrEmpty(displayName) ? name : displayName,
                FieldType    = type,
                Required     = required,
                UniqueValues = uniqueValues,
                Group        = group,
                Default      = defaultValue,
                Percentage   = percentage,
                Decimals     = decimals,
                Min          = min,
                Max          = max,
                Choices      = choices,
                Format       = choiceType,
                List         = lookupList,
                ShowField    = lookupField,
                MaxLegth     = maxLength
            };

            DecideFieldSource(operation).AddFieldAsXml(fieldInformation.ToXml(), true, AddFieldOptions.AddFieldInternalNameHint);

            return(operation);
        }
Example #11
0
        static string FormatField(Guid fieldId, string internalName, FieldType fieldType, string displayName, string groupName, string attributes)
        {
            var fieldCI = new FieldCreationInformation(fieldType)
            {
                Id               = fieldId,
                InternalName     = internalName,
                DisplayName      = displayName,
                AddToDefaultView = true,
                Group            = groupName
            };

            return(FieldAndContentTypeExtensions.FormatFieldXml(fieldCI));
        }
        /// <summary>
        /// Project the field defintion into the expected provisioning CSOM object
        /// </summary>
        /// <returns></returns>
        public FieldCreationInformation ToCreationObject()
        {
            var finfo = new FieldCreationInformation(this.fieldType);

            finfo.Id                   = this.FieldGuid;
            finfo.InternalName         = this.InternalName;
            finfo.DisplayName          = this.DisplayName;
            finfo.Group                = this.GroupName;
            finfo.AddToDefaultView     = this.AddToDefaultView;
            finfo.Required             = this.Required;
            finfo.AdditionalAttributes = new List <KeyValuePair <string, string> >();

            return(finfo);
        }
Example #13
0
        static string FormatField(Guid fieldId, string internalName, FieldType fieldType, string displayName, string groupName, bool required, IEnumerable <KeyValuePair <string, string> > attributes)
        {
            FieldCreationInformation fldCreate = new FieldCreationInformation(fieldType)
            {
                Id                   = fieldId,
                InternalName         = internalName,
                DisplayName          = displayName,
                Group                = groupName,
                AdditionalAttributes = attributes,
                Required             = required,
            };

            return(FieldAndContentTypeExtensions.FormatFieldXml(fldCreate));
        }
Example #14
0
        public static Field CreateField(this List list, Guid id, string internalName, string fieldType, bool addToDefaultView, string displayName, string group, string additionalXmlAttributes = "", bool executeQuery = true)
        {
            var additionalAttributes = ParseAdditionalAttributes(additionalXmlAttributes);
            FieldCreationInformation fieldCreationInformation = new FieldCreationInformation(fieldType)
            {
                Id = id,
                AddToDefaultView     = false,
                DisplayName          = displayName,
                Group                = group,
                InternalName         = internalName,
                AdditionalAttributes = additionalAttributes
            };

            return(CreateField(list, fieldCreationInformation, executeQuery));
        }
Example #15
0
        public static Field CreateField(this Web web, Guid id, string internalName, FieldType fieldType, string displayName, string group, string additionalXmlAttributes = "", bool executeQuery = true)
        {
            var additionalAttributes = ParseAdditionalAttributes(additionalXmlAttributes);

            FieldCreationInformation fieldCreationInformation = new FieldCreationInformation(fieldType)
            {
                Id                   = id,
                InternalName         = internalName,
                DisplayName          = displayName,
                Group                = group,
                AdditionalAttributes = additionalAttributes
            };

            return(CreateField(web, fieldCreationInformation, executeQuery));
        }
Example #16
0
        static TField CreateFieldBase <TField>(FieldCollection fields, Guid id, string internalName, string fieldType, bool addToDefaultView, string displayName, string group, string additionalXmlAttributes = "", bool executeQuery = true) where TField : Field
        {
            var additionalAttributes = ParseAdditionalAttributes(additionalXmlAttributes);
            FieldCreationInformation fieldCreationInformation = new FieldCreationInformation(fieldType)
            {
                Id                   = id,
                InternalName         = internalName,
                AddToDefaultView     = addToDefaultView,
                Group                = group,
                AdditionalAttributes = additionalAttributes,
                DisplayName          = displayName
            };

            return(CreateFieldBase <TField>(fields, fieldCreationInformation, executeQuery));
        }
Example #17
0
        private static Field CreateTaxonomyFieldInternal(this List list, Guid id, string internalName, string displayName, string group, TaxonomyItem taxonomyItem, bool multiValue)
        {
            internalName.ValidateNotNullOrEmpty("internalName");
            displayName.ValidateNotNullOrEmpty("displayName");
            taxonomyItem.ValidateNotNullOrEmpty("taxonomyItem");

            try
            {
                List <KeyValuePair <string, string> > additionalAttributes = new List <KeyValuePair <string, string> >();
                additionalAttributes.Add(new KeyValuePair <string, string>("ShowField", "Term1033"));

                FieldCreationInformation fieldCI = new FieldCreationInformation(multiValue ? "TaxonomyFieldTypeMulti" : "TaxonomyFieldType")
                {
                    Id                   = id,
                    InternalName         = internalName,
                    AddToDefaultView     = true,
                    DisplayName          = displayName,
                    Group                = group,
                    AdditionalAttributes = additionalAttributes
                };
                var _field = list.CreateField(fieldCI);

                WireUpTaxonomyFieldInternal(_field, taxonomyItem, multiValue);
                _field.Update();

                list.Context.ExecuteQuery();

                return(_field);
            }
            catch (Exception)
            {
                ///If there is an exception the hidden field might be present
                FieldCollection _fields = list.Fields;
                list.Context.Load(_fields, fc => fc.Include(f => f.Id, f => f.InternalName));
                list.Context.ExecuteQuery();
                var _hiddenField = id.ToString().Replace("-", "");

                var _field = _fields.FirstOrDefault(f => f.InternalName == _hiddenField);
                if (_field != null)
                {
                    _field.Hidden = false; // Cannot delete a hidden column
                    _field.Update();
                    _field.DeleteObject();
                    list.Context.ExecuteQuery();
                }
                throw;
            }
        }
Example #18
0
        public static TField CreateField <TField>(this Web web, Guid id, string internalName, FieldType fieldType, bool addToDefaultView, string displayName, string group, string additionalXmlAttributes = "", bool executeQuery = true) where TField : Field
        {
            var additionalAttributes = ParseAdditionalAttributes(additionalXmlAttributes);

            var fieldCreationInformation = new FieldCreationInformation(fieldType)
            {
                Id                   = id,
                InternalName         = internalName,
                AddToDefaultView     = addToDefaultView,
                Group                = group,
                DisplayName          = displayName,
                AdditionalAttributes = additionalAttributes
            };

            return(CreateField <TField>(web, fieldCreationInformation, executeQuery));
        }
Example #19
0
        protected void btnScenario1_Click(object sender, EventArgs e)
        {
            // Create New Content Type
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var ctx = spContext.CreateUserClientContextForSPHost())
            {
                // Call the custom web object extension
                Guid   fieldId = new Guid("439c9788-ea39-4e74-941d-ed29b22f9b6b");
                string ctId    = string.Format("{0}00{1}", drpContentTypes.SelectedValue, txtContentTypeExtension.Text);

                // Do not re-create it
                if (!ctx.Web.ContentTypeExistsByName(txtContentTypeName.Text))
                {
                    ctx.Web.CreateContentType(txtContentTypeName.Text, ctId, "Contoso Content Types");
                }
                else
                {
                    lblStatus1.Text = string.Format("Content type with given name and/or ID already existed. Name -  {0} ID - {1}",
                                                    txtContentTypeName.Text, ctId);
                    return;
                }
                if (!ctx.Web.FieldExistsByName("ContosoFieldText"))
                {
                    FieldCreationInformation field = new FieldCreationInformation(FieldType.Text)
                    {
                        Id           = fieldId,
                        InternalName = "ContosoFieldText",
                        DisplayName  = "Contoso Field Text",
                        Group        = "Contoso Fields"
                    };
                    ctx.Web.CreateField(field);
                }
                // This will never be true for this sample, but shows the pattern
                if (!ctx.Web.FieldExistsByNameInContentType(txtContentTypeName.Text, "ContosoFieldText"))
                {
                    ctx.Web.AddFieldToContentTypeByName(txtContentTypeName.Text, fieldId);
                }

                // Done - all good to go.
                lblStatus1.Text = string.Format("Created new content type to host web with name {0} and ID {1}",
                                                txtContentTypeName.Text, ctId);
            }
        }
        public void Create(ClientContext ctx, bool execute)
        {
            if (FieldInformation == null)
            {
                throw new Exception("Field Information Cannot be null");
            }
            OfficeDevPnP.Core.Entities.FieldCreationInformation fld = new FieldCreationInformation(FieldInformation.FieldType)
            {
                AdditionalAttributes          = this.FieldInformation.AdditionalAttributes,
                AddToDefaultView              = this.FieldInformation.AddToDefaultView,
                ClientSideComponentId         = this.FieldInformation.ClientSideComponentId,
                ClientSideComponentProperties = this.FieldInformation.ClientSideComponentProperties,
                DisplayName  = this.FieldInformation.DisplayName,
                Group        = this.FieldInformation.Group,
                Id           = this.FieldInformation.Id,
                InternalName = this.FieldInformation.InternalName,
                Required     = this.FieldInformation.Required
            };

            this.AssociatedField = ctx.Web.CreateField(fld, execute);
        }
Example #21
0
        public static void setupComplexListFields(ClientContext ctx)
        {
            Web root = ctx.Site.RootWeb;

            /////////////////////////////////////
            ////////// using xml ///////////////
            ////////////////////////////////////

            string pathToXML = AppDomain.CurrentDomain.BaseDirectory + "complexFields.xml";

            XDocument doc = XDocument.Load(pathToXML);

            List <XElement> LookupElements = doc.Root.Elements("Field").Where(e => e.Attribute("Type").Value == "Lookup").ToList();

            foreach (XElement element in LookupElements)
            {
                string listUrl = element.Attribute("List").Value;
                List   list    = ctx.Web.GetListByUrl(listUrl);
                element.Attribute("List").Value = list.Id.ToString();
            }
            root.CreateFieldsFromXMLString(doc.ToString());

            /////////////////////////////////////
            ////////// Using code ///////////////
            ////////////////////////////////////

            FieldCreationInformation fieldINfo = new FieldCreationInformation(FieldType.Lookup);

            fieldINfo.Id           = "{CC5820F0-60C9-4B9E-9CE9-C739AED70357}".ToGuid();
            fieldINfo.InternalName = "OD1_TryGoodBook2";
            fieldINfo.DisplayName  = "Good book 2";
            fieldINfo.Group        = "Custom Columns";

            FieldLookup lookupField = root.CreateField <FieldLookup>(fieldINfo);

            lookupField.LookupList = root.GetListByUrl("lists/books").Id.ToString();
            lookupField.Update();

            ctx.ExecuteQuery();
        }
Example #22
0
        public void CreateExistingFieldTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var fieldName = "Test_ABC123";
                var fieldId   = Guid.NewGuid();

                FieldCreationInformation fieldCI = new FieldCreationInformation(FieldType.Choice)
                {
                    Id               = fieldId,
                    InternalName     = fieldName,
                    AddToDefaultView = true,
                    DisplayName      = fieldName,
                    Group            = "Test fields group"
                };
                var fieldChoice1 = clientContext.Web.CreateField <FieldChoice>(fieldCI);
                var fieldChoice2 = clientContext.Web.CreateField <FieldChoice>(fieldCI);

                var field = clientContext.Web.Fields.GetByTitle(fieldName);
                clientContext.Load(field);
                clientContext.ExecuteQuery();
            }
        }
        public void AddFieldToContentTypeTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                clientContext.Web.CreateContentType(TEST_CT_PNP, TEST_CT_PNP_ID, TEST_CATEGORY);

                var fieldName = "Test_" + DateTime.Now.ToFileTime();
                var fieldId = Guid.NewGuid();

                var fieldCI = new FieldCreationInformation(FieldType.Text)
                {
                    Id = fieldId,
                    InternalName = fieldName,
                    DisplayName = fieldName,
                    AddToDefaultView = true,
                    Group = "Test fields group"
                };
                var fieldText = clientContext.Web.CreateField<FieldText>(fieldCI);

                clientContext.Web.AddFieldToContentTypeByName(TEST_CT_PNP, fieldId);
                Assert.IsTrue(clientContext.Web.FieldExistsByNameInContentType(TEST_CT_PNP, fieldName));
            }
        }
Example #24
0
        public void AddFieldToContentTypeTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                clientContext.Web.CreateContentType(TEST_CT_PNP, TEST_CT_PNP_ID, TEST_CATEGORY);

                var fieldName = "Test_" + DateTime.Now.ToFileTime();
                var fieldId   = Guid.NewGuid();

                var fieldCI = new FieldCreationInformation(FieldType.Text)
                {
                    Id               = fieldId,
                    InternalName     = fieldName,
                    DisplayName      = fieldName,
                    AddToDefaultView = true,
                    Group            = "Test fields group"
                };
                var fieldText = clientContext.Web.CreateField <FieldText>(fieldCI);

                clientContext.Web.AddFieldToContentTypeByName(TEST_CT_PNP, fieldId);
                Assert.IsTrue(clientContext.Web.FieldExistsByNameInContentType(TEST_CT_PNP, fieldName));
            }
        }
        private void ProvisionFields(List list)
        {
            list.Context.Load(list.Fields, f => f.Include(i => i.InternalName));
            list.Context.ExecuteQueryRetry();

            if (list.Fields.Where(w => w.InternalName == _fieldValueName).Any())
            {
                _logger.LogDebug($"{_fieldValueName} field exists on {list.DefaultViewUrl}");
            }
            else
            {
                _logger.LogDebug($"Creating {_fieldValueName} field on {list.DefaultViewUrl}");

                var fieldCreationInformation = new FieldCreationInformation(FieldType.Note)
                {
                    Id               = Guid.NewGuid(),
                    InternalName     = _fieldValueName,
                    DisplayName      = _fieldValueName,
                    AddToDefaultView = true
                };

                list.CreateField(fieldCreationInformation, true);
            }
        }
Example #26
0
        private static void CreateFields(ClientContext ctx, ContentType orderCT)
        {
            #region Customer
            FieldCreationInformation customer = new FieldCreationInformation(FieldType.Lookup);
            customer.DisplayName  = "Customer";
            customer.InternalName = "Customer";
            customer.Group        = "ODA1";
            customer.Id           = Constants.GUID.OrderCT.CUSTOMER.ToGuid();

            ctx.Web.AddFieldToContentType(orderCT, ctx.Web.CreateField <FieldUrl>(customer, false));
            #endregion
            #region Product
            TaxonomyFieldCreationInformation product = new TaxonomyFieldCreationInformation();

            product.DisplayName  = "Product";
            product.InternalName = "Product_2";
            product.Group        = "ODA1";
            product.TaxonomyItem = GetProductTermSet(ctx);

            product.Id = Constants.GUID.OrderCT.PRODUCT.ToGuid();
            var meh = ctx.Web.CreateTaxonomyField(product);
            ctx.ExecuteQuery();
            ctx.Web.WireUpTaxonomyField(meh, product.TaxonomyItem as TermSet);
            ctx.Web.AddFieldToContentType(orderCT, meh);
            #endregion
            #region Price
            FieldCreationInformation price = new FieldCreationInformation(FieldType.Currency);
            price.DisplayName  = "Price";
            price.InternalName = "Price";
            price.Group        = "ODA1";
            price.Id           = Constants.GUID.OrderCT.PRICE.ToGuid();

            FieldUrl addedPrice = ctx.Web.CreateField <FieldUrl>(price, false);
            ctx.Web.AddFieldToContentType(orderCT, addedPrice);
            #endregion
        }
Example #27
0
        public void Initialize()
        {
            /*** Make sure that the user defined in the App.config has permissions to Manage Terms ***/

            // Create some taxonomy groups and terms
            using (var clientContext = TestCommon.CreateClientContext())
            {
                _termGroupName = "Test_Group_" + DateTime.Now.ToFileTime();
                _termSetName = "Test_Termset_" + DateTime.Now.ToFileTime();
                _termName = "Test_Term_" + DateTime.Now.ToFileTime();
                _textFieldName = "Test_Text_Field_" + DateTime.Now.ToFileTime();

                _termGroupId = Guid.NewGuid();
                _termSetId = Guid.NewGuid();
                _termId = Guid.NewGuid();

                // Termgroup
                var taxSession = TaxonomySession.GetTaxonomySession(clientContext);
                var termStore = taxSession.GetDefaultSiteCollectionTermStore();
                var termGroup = termStore.CreateGroup(_termGroupName,_termGroupId);
                clientContext.Load(termGroup);
                clientContext.ExecuteQueryRetry();

                // Termset
                var termSet = termGroup.CreateTermSet(_termSetName, _termSetId, 1033);
                clientContext.Load(termSet);
                clientContext.ExecuteQueryRetry();

                // Term
                termSet.CreateTerm(_termName, 1033, _termId);
                clientContext.ExecuteQueryRetry();

                // List

                _textFieldId = Guid.NewGuid();

                var fieldCI = new FieldCreationInformation(FieldType.Text)
                {
                    Id = _textFieldId,
                    InternalName = _textFieldName,
                    DisplayName = "Test Text Field",
                    Group = "Test Group"
                };

                var textfield = clientContext.Web.CreateField(fieldCI);

                var list = clientContext.Web.CreateList(ListTemplateType.DocumentLibrary, "Test_list_" + DateTime.Now.ToFileTime(), false);

                var field = clientContext.Web.Fields.GetByInternalNameOrTitle("TaxKeyword"); // Enterprise Metadata

                list.Fields.Add(field);
                list.Fields.Add(textfield);

                list.Update();
                clientContext.Load(list);
                clientContext.ExecuteQueryRetry();

                _listId = list.Id;
            }
        }
Example #28
0
        private static void CreateFields(ClientContext ctx, ContentType customerCT)
        {
            #region Customer logo
            FieldCreationInformation customerLogo = new FieldCreationInformation(FieldType.URL);
            customerLogo.DisplayName  = "Logo";
            customerLogo.InternalName = "DispLogo";
            customerLogo.Group        = "ODA1";
            customerLogo.Id           = Constants.GUID.CustomerCT.CUSTOMER_LOGO.ToGuid();

            FieldUrl AddedCLOGO = ctx.Web.CreateField <FieldUrl>(customerLogo, false);
            //AddedCLOGO.DisplayFormat = UrlFieldFormatType.Image;
            //AddedCLOGO.Update();
            ctx.ExecuteQuery();
            ctx.Web.AddFieldToContentType(customerCT, AddedCLOGO);
            #endregion
            #region Address
            FieldCreationInformation address = new FieldCreationInformation(FieldType.Text);
            address.DisplayName  = "Address";
            address.InternalName = "Address";
            address.Group        = "ODA1";
            address.Id           = Constants.GUID.CustomerCT.ADDRESS.ToGuid();
            ctx.Web.AddFieldToContentType(customerCT, ctx.Web.CreateField(address));
            #endregion
            #region Main Contact Person
            FieldCreationInformation contactPerson = new FieldCreationInformation(FieldType.Text);
            contactPerson.DisplayName  = "Contact Person";
            contactPerson.InternalName = "contactPerson";
            contactPerson.Group        = "ODA1";
            contactPerson.Id           = Constants.GUID.CustomerCT.MAIN_CONTACT_PERSON.ToGuid();

            ctx.Web.AddFieldToContentType(customerCT, ctx.Web.CreateField(contactPerson));
            #endregion
            #region Office Phone
            FieldCreationInformation phoneOffice = new FieldCreationInformation(FieldType.Text);
            phoneOffice.DisplayName  = "Office Phone";
            phoneOffice.InternalName = "phoneOffice";
            phoneOffice.Group        = "ODA1";
            phoneOffice.Id           = Constants.GUID.CustomerCT.PHONE_OFFICE.ToGuid();

            ctx.Web.AddFieldToContentType(customerCT, ctx.Web.CreateField(phoneOffice));
            #endregion
            #region Mobile Phone
            FieldCreationInformation phoneMobile = new FieldCreationInformation(FieldType.Text);
            phoneMobile.DisplayName  = "Mobile";
            phoneMobile.InternalName = "phoneMobile";
            phoneMobile.Group        = "ODA1";
            phoneMobile.Id           = Constants.GUID.CustomerCT.PHONE_MOBILE.ToGuid();

            ctx.Web.AddFieldToContentType(customerCT, ctx.Web.CreateField(phoneMobile));
            #endregion
            #region Email
            FieldCreationInformation email = new FieldCreationInformation(FieldType.Text);
            email.DisplayName  = "E-Mail";
            email.InternalName = "Email";
            email.Group        = "ODA1";
            email.Id           = Constants.GUID.CustomerCT.EMAIL.ToGuid();

            ctx.Web.AddFieldToContentType(customerCT, ctx.Web.CreateField(email));
            #endregion
            #region Last Contacted (Date)
            FieldCreationInformation lastContacted = new FieldCreationInformation(FieldType.DateTime);
            lastContacted.DisplayName  = "Last Contacted";
            lastContacted.InternalName = "LastContacted";
            lastContacted.Group        = "ODA1";
            lastContacted.Id           = Constants.GUID.CustomerCT.LAST_CONTACTED.ToGuid();

            ctx.Web.AddFieldToContentType(customerCT, ctx.Web.CreateField(lastContacted));
            #endregion
            #region Last Order Made(Date, Read Only)
            FieldCreationInformation lastOrderMade = new FieldCreationInformation(FieldType.DateTime);
            lastOrderMade.DisplayName  = "Last order made";
            lastOrderMade.InternalName = "LastOrderMade";
            lastOrderMade.Group        = "ODA1";
            lastOrderMade.Id           = Constants.GUID.CustomerCT.LAST_ORDER_MADE.ToGuid();

            FieldDateTime addedLastOderMade = ctx.Web.CreateField <FieldDateTime>(lastOrderMade, false);
            addedLastOderMade.ReadOnlyField = true;
            addedLastOderMade.Update();
            ctx.ExecuteQuery();

            ctx.Web.AddFieldToContentType(customerCT, addedLastOderMade);
            #endregion
        }
Example #29
0
        protected override void ExecuteCmdlet()
        {
            if (Id.Id == Guid.Empty)
            {
                Id = new GuidPipeBind(Guid.NewGuid());
            }

            if (List != null)
            {
                var   list = List.GetList(SelectedWeb);
                Field f;
                if (ParameterSetName != "FieldRef")
                {
                    var fieldCI = new FieldCreationInformation(Type)
                    {
                        Id               = Id.Id,
                        InternalName     = InternalName,
                        DisplayName      = DisplayName,
                        Group            = Group,
                        AddToDefaultView = AddToDefaultView
                    };

                    if (Type == FieldType.Choice || Type == FieldType.MultiChoice)
                    {
                        f = list.CreateField <FieldChoice>(fieldCI);
                        ((FieldChoice)f).Choices = context.Choices;
                        f.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                    else
                    {
                        f = list.CreateField(fieldCI);
                    }
                    if (Required)
                    {
                        f.Required = true;
                        f.Update();
                        ClientContext.Load(f);
                        ClientContext.ExecuteQueryRetry();
                    }
                    WriteObject(f);
                }
                else
                {
                    Field field = Field.Field;
                    if (field == null)
                    {
                        if (Field.Id != Guid.Empty)
                        {
                            field = SelectedWeb.Fields.GetById(Field.Id);
                        }
                        else if (!string.IsNullOrEmpty(Field.Name))
                        {
                            field = SelectedWeb.Fields.GetByInternalNameOrTitle(Field.Name);
                        }
                        ClientContext.Load(field);
                        ClientContext.ExecuteQueryRetry();
                    }
                    if (field != null)
                    {
                        list.Fields.Add(field);
                        list.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }
            }
            else
            {
                Field f;

                var fieldCI = new FieldCreationInformation(Type)
                {
                    Id               = Id.Id,
                    InternalName     = InternalName,
                    DisplayName      = DisplayName,
                    Group            = Group,
                    AddToDefaultView = AddToDefaultView
                };

                if (Type == FieldType.Choice || Type == FieldType.MultiChoice)
                {
                    f = SelectedWeb.CreateField <FieldChoice>(fieldCI);
                    ((FieldChoice)f).Choices = context.Choices;
                    f.Update();
                    ClientContext.ExecuteQueryRetry();
                }
                else
                {
                    f = SelectedWeb.CreateField(fieldCI);
                }

                if (Required)
                {
                    f.Required = true;
                    f.Update();
                    ClientContext.Load(f);
                    ClientContext.ExecuteQueryRetry();
                }

                WriteObject(f);
            }
        }
Example #30
0
        public static void CreateCarContetType(ClientContext ctx)
        {
            string VehicleContentType = "0x0100567A676ED8534670A79990FADE68DE47";
            string carContentType     = "0x0100567A676ED8534670A79990FADE68DE4700DC042CAC4BCA4EDFB9334B39999E4576";

            if (!ctx.Web.ContentTypeExistsById(VehicleContentType))
            {
                ctx.Web.CreateContentType("Vehicle", VehicleContentType, "Davids Content Types");
            }

            if (!ctx.Web.ContentTypeExistsById(carContentType))
            {
                ctx.Web.CreateContentType("Car", carContentType, "Davids Content Types");
            }

            Guid carModleFieldId = "{6DAD1B3E-A841-4E35-8B00-0E68E269C1F5}".ToGuid();

            if (!ctx.Web.FieldExistsById(carModleFieldId))
            {
                FieldCreationInformation modleFieldInfo = new FieldCreationInformation(FieldType.Text);
                modleFieldInfo.Id           = carModleFieldId;
                modleFieldInfo.InternalName = "F_CarModel";
                modleFieldInfo.DisplayName  = "Car Model";
                modleFieldInfo.Group        = "Davids Fields";

                ctx.Web.CreateField(modleFieldInfo);
            }

            ctx.Web.AddFieldToContentTypeById(carContentType, carModleFieldId.ToString());

            Guid carYearFieldId = "{AB76F05D-FC5F-4456-989D-F435BBF39230}".ToGuid();

            if (!ctx.Web.FieldExistsById(carYearFieldId))
            {
                FieldCreationInformation yearFieldInfo = new FieldCreationInformation(FieldType.Number);
                yearFieldInfo.Id           = carYearFieldId;
                yearFieldInfo.InternalName = "F_CarYear";
                yearFieldInfo.DisplayName  = "Car Year";
                yearFieldInfo.Group        = "Davids Fields";

                ctx.Web.CreateField(yearFieldInfo);
            }

            ctx.Web.AddFieldToContentTypeById(carContentType, carYearFieldId.ToString());

            Guid carColorFieldId = "{3A2B1887-ABBF-4EDB-BCCC-11CF48A279EA}".ToGuid();

            if (!ctx.Web.FieldExistsById(carColorFieldId))
            {
                FieldCreationInformation colorFieldInfo = new FieldCreationInformation(FieldType.Choice);
                colorFieldInfo.Id           = carColorFieldId;
                colorFieldInfo.InternalName = "F_CarColor";
                colorFieldInfo.DisplayName  = "Car Color";
                colorFieldInfo.Group        = "Davids Fields";

                FieldChoice field = ctx.Web.CreateField <FieldChoice>(colorFieldInfo);
                field.Choices      = new string[] { "Green", "Blue", "Red" };
                field.DefaultValue = "Green";
                field.Update();
                ctx.ExecuteQuery();
            }
            ctx.Web.AddFieldToContentTypeById(carContentType, carColorFieldId.ToString());
            ctx.Web.CreateList(ListTemplateType.GenericList, "Cars", false, true, "lists/cars", true);
            ctx.Web.AddContentTypeToListById("Cars", carContentType, true);
        }
        public static void MyFirstContentType(ClientContext ctx)
        {
            Web rootWeb = ctx.Site.RootWeb;

            //string carsID = "0x01001703716880F147E38BD026AA8DDD14D5";

            //if (rootWeb.ContentTypeExistsById(carsID))
            //{
            //    rootWeb.DeleteContentTypeById(carsID);
            //}

            //rootWeb.CreateContentType("Cars", carsID, "Tims Columns");


            //FieldCreationInformation brandField = new FieldCreationInformation(FieldType.Text);
            //brandField.DisplayName = "Brand";
            //brandField.Id = new Guid("{F4D37EFA-3CD5-4426-8F49-D2F48F841653}");
            //brandField.InternalName = "CMS_Brand";
            //brandField.Group = "Tims Columns";

            //if (rootWeb.FieldExistsById(brandField.Id))
            //{
            //    rootWeb.RemoveFieldById(brandField.Id.ToString());
            //}


            //rootWeb.CreateField(brandField);

            //rootWeb.AddFieldToContentTypeById(carsID, "{F4D37EFA-3CD5-4426-8F49-D2F48F841653}", false);

            //FieldCreationInformation yearField = new FieldCreationInformation(FieldType.Number);
            //yearField.DisplayName = "Year";
            //yearField.Id = new Guid("{F1CE6B6C-652B-470B-8299-5081E16A8CB2}");
            //yearField.InternalName = "CMS_Year";
            //yearField.Group = "Tims Columns";

            //if (rootWeb.FieldExistsById(yearField.Id))
            //{
            //    rootWeb.RemoveFieldById(yearField.Id.ToString());
            //}

            //rootWeb.CreateField(yearField);

            //rootWeb.AddFieldToContentTypeById(carsID, "{F1CE6B6C-652B-470B-8299-5081E16A8CB2}", false);



            //FieldCreationInformation colorField = new FieldCreationInformation(FieldType.Choice);
            //colorField.DisplayName = "Color";
            //colorField.Id = new Guid("{9EC39186-A1E6-4DA3-8343-84A7C7137714}");
            //colorField.InternalName = "CMS_Color";
            //colorField.Group = "Tims Columns";

            //if (rootWeb.FieldExistsById(colorField.Id))
            //{
            //    rootWeb.RemoveFieldById(colorField.Id.ToString());

            //}



            //var fc = rootWeb.CreateField<FieldChoice>(colorField);

            //fc.Choices = new string[] { "red", "green", "blue" };

            ////rootWeb.CreateField(colorField);
            //fc.Update();
            //ctx.ExecuteQuery();

            //rootWeb.AddFieldToContentTypeById(carsID, "{9EC39186-A1E6-4DA3-8343-84A7C7137714}", false);


            //List list = rootWeb.GetListByTitle("Tims List From Pnp");
            //list.AddContentTypeToList(rootWeb.GetContentTypeById(carsID), true);

            //for (int i = 0; i < 5; i++)
            //{
            //    list.CreateDocument("dokument " + i, list.RootFolder, DocumentTemplateType.Word);
            //    Console.WriteLine("done"+i);
            //}
            //list.DefaultView.ViewFields.Add("CMS_Brand");
            //list.DefaultView.ViewFields.Add("CMS_Year");
            //list.DefaultView.ViewFields.Add("CMS_Color");
            //list.DefaultView.Update();

            //list.Update();
            //ctx.ExecuteQuery();


            //this is another way to do it using xml
            //rootWeb.Fields.AddFieldAsXml("<field DisplayName = "brand"></fields>)

            string booksID = "0x01003DCFC9B08E1E4DD18AB8BD9053D7F49E";

            if (rootWeb.ContentTypeExistsById(booksID))
            {
                rootWeb.DeleteContentTypeById(booksID);
            }

            rootWeb.CreateContentType("Books", booksID, "Tims Columns");



            FieldCreationInformation bookType = new FieldCreationInformation(FieldType.Choice);

            bookType.DisplayName  = "Book Type";
            bookType.Id           = new Guid("{F0C6D85D-C4DD-48F2-806E-5794ABDCAAB0}");
            bookType.InternalName = "CMS_BookType";
            bookType.Group        = "Tims Columns";

            var fcs = rootWeb.CreateField <FieldChoice>(bookType);

            fcs.Choices = new string[] { "Large", "Medium", "Small" };

            fcs.Update();
            ctx.ExecuteQuery();


            FieldCreationInformation author = new FieldCreationInformation(FieldType.Text);

            author.DisplayName  = "Author";
            author.Id           = new Guid("{A95D3D0B-F076-4675-A99A-7D8EED002481}");
            author.InternalName = "CMS_Author";
            author.Group        = "Tims Columns";

            FieldCreationInformation dateReleased = new FieldCreationInformation(FieldType.DateTime);

            dateReleased.DisplayName  = "Date released";
            dateReleased.Id           = new Guid("{7C81173A-141C-4008-B2E6-A8763F0850DF}");
            dateReleased.InternalName = "CMS_dateReleased";
            dateReleased.Group        = "Tims Columns";

            FieldCreationInformation description = new FieldCreationInformation(FieldType.Note);

            description.DisplayName  = "Description";
            description.Id           = new Guid("{B65E6297-0182-4CA8-A7DE-45E05FE61086}");
            description.InternalName = "CMS_description";
            description.Group        = "Tims Columns";


            //rootWeb.CreateField(bookType);
            rootWeb.CreateField(author);
            rootWeb.CreateField(dateReleased);
            rootWeb.CreateField(description);
            rootWeb.AddFieldToContentTypeById(booksID, "{F0C6D85D-C4DD-48F2-806E-5794ABDCAAB0}", false);
            rootWeb.AddFieldToContentTypeById(booksID, "{A95D3D0B-F076-4675-A99A-7D8EED002481}", false);
            rootWeb.AddFieldToContentTypeById(booksID, "{7C81173A-141C-4008-B2E6-A8763F0850DF}", false);
            rootWeb.AddFieldToContentTypeById(booksID, "{B65E6297-0182-4CA8-A7DE-45E05FE61086}", false);

            List list = rootWeb.CreateList(ListTemplateType.GenericList, "books", false, true, "TimsGenericList", true);

            list.AddContentTypeToListById(booksID, true);
        }
        public void CreateExistingFieldTest()
        {
            using (var clientContext = TestCommon.CreateClientContext())
            {
                var fieldName = "Test_ABC123";
                var fieldId = Guid.NewGuid();

                FieldCreationInformation fieldCI = new FieldCreationInformation(FieldType.Choice)
                {
                    Id = fieldId,
                    InternalName = fieldName,
                    AddToDefaultView = true,
                    DisplayName = fieldName,
                    Group = "Test fields group"
                };
                var fieldChoice1 = clientContext.Web.CreateField<FieldChoice>(fieldCI);
                var fieldChoice2 = clientContext.Web.CreateField<FieldChoice>(fieldCI);

                var field = clientContext.Web.Fields.GetByTitle(fieldName);
                clientContext.Load(field);
                clientContext.ExecuteQueryRetry();
            }
        }
Example #33
0
        protected override void ExecuteCmdlet()
        {
            if (Id.Id == Guid.Empty)
            {
                Id = new GuidPipeBind(Guid.NewGuid());
            }

            if (List != null)
            {
                var list = List.GetList(SelectedWeb);
                if (list == null)
                {
                    throw new PSArgumentException($"No list found with id, title or url '{List}'", "List");
                }
                Field f;
                if (ParameterSetName != ParameterSet_ADDFIELDREFERENCETOLIST)
                {
                    var fieldCI = new FieldCreationInformation(Type)
                    {
                        Id               = Id.Id,
                        InternalName     = InternalName,
                        DisplayName      = DisplayName,
                        Group            = Group,
                        AddToDefaultView = AddToDefaultView
                    };
#if !ONPREMISES
                    if (ClientSideComponentId != null)
                    {
                        fieldCI.ClientSideComponentId = ClientSideComponentId.Id;
                    }
                    if (!string.IsNullOrEmpty(ClientSideComponentProperties))
                    {
                        fieldCI.ClientSideComponentProperties = ClientSideComponentProperties;
                    }
#endif
                    if (Type == FieldType.Choice || Type == FieldType.MultiChoice)
                    {
                        f = list.CreateField <FieldChoice>(fieldCI);
                        ((FieldChoice)f).Choices = choiceFieldParameters.Choices;
                        f.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                    else if (Type == FieldType.Calculated)
                    {
                        f = list.CreateField <FieldCalculated>(fieldCI);
                        ((FieldCalculated)f).Formula = calculatedFieldParameters.Formula;
                        f.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                    else
                    {
                        f = list.CreateField(fieldCI);
                    }
                    if (Required)
                    {
                        f.Required = true;
                        f.Update();
                        ClientContext.Load(f);
                        ClientContext.ExecuteQueryRetry();
                    }
                    WriteObject(f);
                }
                else
                {
                    Field field = Field.Field;
                    if (field == null)
                    {
                        if (Field.Id != Guid.Empty)
                        {
                            field = SelectedWeb.Fields.GetById(Field.Id);
                            ClientContext.Load(field);
                            ClientContext.ExecuteQueryRetry();
                        }
                        else if (!string.IsNullOrEmpty(Field.Name))
                        {
                            try
                            {
                                field = SelectedWeb.Fields.GetByInternalNameOrTitle(Field.Name);
                                ClientContext.Load(field);
                                ClientContext.ExecuteQueryRetry();
                            }
                            catch
                            {
                                // Field might be sitecolumn, swallow exception
                            }
                            if (field != null)
                            {
                                var rootWeb = ClientContext.Site.RootWeb;
                                field = rootWeb.Fields.GetByInternalNameOrTitle(Field.Name);
                                ClientContext.Load(field);
                                ClientContext.ExecuteQueryRetry();
                            }
                        }
                    }
                    if (field != null)
                    {
                        list.Fields.Add(field);
                        list.Update();
                        ClientContext.ExecuteQueryRetry();
                    }
                }
            }
            else
            {
                Field f;

                var fieldCI = new FieldCreationInformation(Type)
                {
                    Id               = Id.Id,
                    InternalName     = InternalName,
                    DisplayName      = DisplayName,
                    Group            = Group,
                    AddToDefaultView = AddToDefaultView
                };

#if !ONPREMISES
                if (ClientSideComponentId != null)
                {
                    fieldCI.ClientSideComponentId = ClientSideComponentId.Id;
                }
                if (!string.IsNullOrEmpty(ClientSideComponentProperties))
                {
                    fieldCI.ClientSideComponentProperties = ClientSideComponentProperties;
                }
#endif

                if (Type == FieldType.Choice || Type == FieldType.MultiChoice)
                {
                    f = SelectedWeb.CreateField <FieldChoice>(fieldCI);
                    ((FieldChoice)f).Choices = choiceFieldParameters.Choices;
                    f.Update();
                    ClientContext.ExecuteQueryRetry();
                }
                else if (Type == FieldType.Calculated)
                {
                    f = SelectedWeb.CreateField <FieldCalculated>(fieldCI);
                    ((FieldCalculated)f).Formula = calculatedFieldParameters.Formula;
                    f.Update();
                    ClientContext.ExecuteQueryRetry();
                }
                else
                {
                    f = SelectedWeb.CreateField(fieldCI);
                }

                if (Required)
                {
                    f.Required = true;
                    f.Update();
                    ClientContext.Load(f);
                    ClientContext.ExecuteQueryRetry();
                }
                switch (f.FieldTypeKind)
                {
                case FieldType.DateTime:
                {
                    WriteObject(ClientContext.CastTo <FieldDateTime>(f));
                    break;
                }

                case FieldType.Choice:
                {
                    WriteObject(ClientContext.CastTo <FieldChoice>(f));
                    break;
                }

                case FieldType.Calculated:
                {
                    var calculatedField = ClientContext.CastTo <FieldCalculated>(f);
                    calculatedField.EnsureProperty(fc => fc.Formula);
                    WriteObject(calculatedField);
                    break;
                }

                case FieldType.Computed:
                {
                    WriteObject(ClientContext.CastTo <FieldComputed>(f));
                    break;
                }

                case FieldType.Geolocation:
                {
                    WriteObject(ClientContext.CastTo <FieldGeolocation>(f));
                    break;
                }

                case FieldType.User:
                {
                    WriteObject(ClientContext.CastTo <FieldUser>(f));
                    break;
                }

                case FieldType.Currency:
                {
                    WriteObject(ClientContext.CastTo <FieldCurrency>(f));
                    break;
                }

                case FieldType.Guid:
                {
                    WriteObject(ClientContext.CastTo <FieldGuid>(f));
                    break;
                }

                case FieldType.URL:
                {
                    WriteObject(ClientContext.CastTo <FieldUrl>(f));
                    break;
                }

                case FieldType.Lookup:
                {
                    WriteObject(ClientContext.CastTo <FieldLookup>(f));
                    break;
                }

                case FieldType.MultiChoice:
                {
                    WriteObject(ClientContext.CastTo <FieldMultiChoice>(f));
                    break;
                }

                case FieldType.Number:
                {
                    WriteObject(ClientContext.CastTo <FieldNumber>(f));
                    break;
                }

                default:
                {
                    WriteObject(f);
                    break;
                }
                }
            }
        }
Example #34
0
        public static void CreateField(ClientContext ctx)
        {
            Web web = ctx.Site.RootWeb;

            // sharepoint client object model way
            //string fieldXml = @"<Field Type='DateTime'
            //                            DisplayName='Important Date2'
            //                            Required='TRUE'
            //                            EnforceUniqueValues='FALSE'
            //                            Indexed='FALSE'
            //                            Format='DateTime'
            //                            Group='Custom Columns'
            //                            ID='{C8DDEC78-F94E-4822-AB10-63FCDCA4AFEB}'
            //                            StaticName='Important_Date2'
            //                            Name='Important_Date2'  >
            //                        <Default>
            //                            [today]
            //                        </Default>
            //                    </Field>";

            //web.Fields.AddFieldAsXml(fieldXml, false, AddFieldOptions.DefaultValue);
            // ctx.ExecuteQuery();


            /// PNP way
            //FieldCreationInformation fieldinfo = new FieldCreationInformation(FieldType.DateTime);
            //fieldinfo.Group = "Custom Columns";
            //fieldinfo.Id = new Guid("{81682584-4E54-4D73-9DF9-E0FE3688833D}");
            //fieldinfo.InternalName = "Important_Date3";
            //fieldinfo.DisplayName = "important date 3";

            //FieldDateTime datetimeField = web.CreateField<FieldDateTime>(fieldinfo);
            //datetimeField.DefaultValue = "[today]";
            //datetimeField.DisplayFormat = DateTimeFieldFormatType.DateTime;
            //datetimeField.UpdateAndPushChanges(true);

            //ctx.ExecuteQuery();


            FieldCreationInformation fieldinfo = new FieldCreationInformation(FieldType.DateTime);

            fieldinfo.Group        = "Custom Columns";
            fieldinfo.Id           = new Guid("{81682584-4E54-4D73-9DF9-E0FE3688833D}");
            fieldinfo.InternalName = "Important_Date3";
            fieldinfo.DisplayName  = "important date 3";

            Field         field         = web.CreateField(fieldinfo);
            FieldDateTime datetimeField = ctx.CastTo <FieldDateTime>(field);

            datetimeField.DefaultValue  = "[today]";
            datetimeField.DisplayFormat = DateTimeFieldFormatType.DateTime;
            datetimeField.UpdateAndPushChanges(true);

            ctx.ExecuteQuery();

            // DeleteFields(ctx);

            string pathToXML = AppDomain.CurrentDomain.BaseDirectory + "fields.xml";

            ctx.Web.CreateFieldsFromXMLFile(pathToXML);
        }