Example #1
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
		}
        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;
            }
        }
        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 #4
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 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-SPOField",
                        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);

            }
        }
		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.ExecuteQueryRetry();

				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.");
			}
		}
		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);
			}
		}
		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));
			}
		}
		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 #10
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 #11
0
        protected void btnScenario4_Click(object sender, EventArgs e)
        {
            // Localize content type and site column
            var spContext = SharePointContextProvider.Current.GetSharePointContext(Context);

            using (var ctx = spContext.CreateUserClientContextForSPHost())
            {
                // Create a document content type inherited from Document
                string contentTypeId = "0x0101001f11771d89214705b6c4baf77b0f219c";
                Guid fieldId = new Guid("92faab58-65ed-4035-8e16-446a6c575f4d");

                // Notice that followign line does break if the content type already exists
                if (!ctx.Web.ContentTypeExistsById(contentTypeId))
                {
                    ctx.Web.CreateContentType("LitwareDoc2", contentTypeId, "Contoso Content Types");
                }
                // Add site colummn to the content type, create column if it does not exist
                if (!ctx.Web.FieldExistsByName("LitwareFieldText"))
                {
                    FieldCreationInformation field = new FieldCreationInformation(FieldType.Text)
                    {
                        Id = fieldId,
                        InternalName = "LitwareFieldText",
                        DisplayName = "Litware Field Text",
                        Group = "Contoso Fields"
                    };
                    ctx.Web.CreateField(field);
                }
                // Add field to content type
                //ctx.Web.AddFieldToContentTypeById(contentTypeId, fieldId);
                // Create list and associate document to the list
                if (!ctx.Web.ListExists(txtListName.Text))
                {
                    ctx.Web.CreateList(ListTemplateType.DocumentLibrary, txtListName.Text, false);
                    // Enable content types in list
                    List list = ctx.Web.GetListByTitle(txtListName.Text);
                    list.ContentTypesEnabled = true;
                    list.Update();
                    ctx.Web.Context.ExecuteQuery();
                }
                // Create list and associate document to the list
                if (!ctx.Web.ContentTypeExistsByName(txtListName.Text, "LitwareDoc2"))
                {
                    ctx.Web.AddContentTypeToListByName(txtListName.Text, "LitwareDoc2");
                }

                // Set the content type as default content type to the TestLib list
                ctx.Web.SetDefaultContentTypeToList(txtListName.Text, contentTypeId);

                //Set translations to content type
                ctx.Web.SetLocalizationForContentType("LitwareDoc2", "fi-fi", "Litware Dokumentti", "Litware  dokumentti on tässä");
                ctx.Web.SetLocalizationForContentType("LitwareDoc2", "es-es", "Litware documento", "Litware  documento");
                
                //Set translations to site columns
                ctx.Web.SetLocalizationForField(fieldId, "fi-fi", "Litware Teksti kenttä", "Litware Teksti kenttä");
                ctx.Web.SetLocalizationForField(fieldId, "es-es", "Field Name (es)", "Field Name (es)");

                //Set translations to list - Seems to have issues right now, so commented
                // ctx.Web.SetLocalizationLabelsForList(txtListName.Text, "fi-fi", "Listan nimi suomeksi", "Listan nimi suomeksi.");
                // ctx.Web.SetLocalizationLabelsForList(txtListName.Text, "es-es", "List name (es)", "List description (es)");

                lblStatus4.Text = "Created new content type and list with translations. Check the blog posts for requirements for end users to see translations in practice.";
                
            }
        }
Example #12
0
        protected override void ExecuteCmdlet()
        {

            if (Id.Id == Guid.Empty)
            {
                Id = new GuidPipeBind(Guid.NewGuid());
            }

            if (List != null)
            {
                var list = SelectedWeb.GetList(List);
                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 = 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 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 #13
0
        /// <summary>
        /// Creates a custom document library and IT Document Content Type
        /// </summary>
        /// <param name="ctx">The client context that has be authenticated</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)){
                FieldCreationInformation field = 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(field);
            }
            //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.AddFieldToContentTypeByName(ITDOCUMENT_CT_NAME, FLD_BUSINESS_UNIT_ID);
            }
            CreateLibrary(ctx, library, ITDOCUMENT_CT_ID);
        }
Example #14
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 #15
0
        protected override void ExecuteCmdlet()
        {

            if (Id.Id == Guid.Empty)
            {
                Id = new GuidPipeBind(Guid.NewGuid());
            }

            if (List != null)
            {
                var list = SelectedWeb.GetList(List);
                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 #16
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);
                            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 (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();
                }
                switch (f.FieldTypeKind)
                {
                    case FieldType.DateTime:
                        {
                            WriteObject(ClientContext.CastTo<FieldDateTime>(f));
                            break;
                        }
                    case FieldType.Choice:
                        {
                            WriteObject(ClientContext.CastTo<FieldChoice>(f));
                            break;
                        }
                    case FieldType.Calculated:
                        {
                            WriteObject(ClientContext.CastTo<FieldCalculated>(f));
                            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 #17
0
        private void CreateSiteClassificationList(ClientContext ctx)
        {
            var _newList = new ListCreationInformation()
            {
                Title = SiteClassificationList.SiteClassificationListTitle,
                Description = SiteClassificationList.SiteClassificationDesc,
                TemplateType = (int)ListTemplateType.GenericList,
                Url = SiteClassificationList.SiteClassificationUrl,
                QuickLaunchOption = QuickLaunchOptions.Off
            };

            if(!ctx.Web.ContentTypeExistsById(SiteClassificationContentType.SITEINFORMATION_CT_ID))
            {
                //ct
                ContentType _contentType = ctx.Web.CreateContentType(SiteClassificationContentType.SITEINFORMATION_CT_NAME,
                    SiteClassificationContentType.SITEINFORMATION_CT_DESC,
                    SiteClassificationContentType.SITEINFORMATION_CT_ID,
                    SiteClassificationContentType.SITEINFORMATION_CT_GROUP);

                FieldLink _titleFieldLink = _contentType.FieldLinks.GetById(new Guid("fa564e0f-0c70-4ab9-b863-0177e6ddd247"));
                _titleFieldLink.Required = false;
                _contentType.Update(false);

                //Key Field
                FieldCreationInformation fldCreate = new FieldCreationInformation(FieldType.Text)
                {
                    Id = SiteClassificationFields.FLD_KEY_ID,
                    InternalName = SiteClassificationFields.FLD_KEY_INTERNAL_NAME,
                    DisplayName = SiteClassificationFields.FLD_KEY_DISPLAY_NAME,
                    Group = SiteClassificationFields.FIELDS_GROUPNAME,
                };
                ctx.Web.CreateField(fldCreate);

                //value field
                fldCreate = new FieldCreationInformation(FieldType.Text)
                {
                    Id = SiteClassificationFields.FLD_VALUE_ID,
                    InternalName = SiteClassificationFields.FLD_VALUE_INTERNAL_NAME,
                    DisplayName = SiteClassificationFields.FLD_VALUE_DISPLAY_NAME,
                    Group = SiteClassificationFields.FIELDS_GROUPNAME,
                };
                ctx.Web.CreateField(fldCreate);

                //Add Key Field to content type
                ctx.Web.AddFieldToContentTypeById(SiteClassificationContentType.SITEINFORMATION_CT_ID, 
                    SiteClassificationFields.FLD_KEY_ID.ToString(), 
                    true);
                //Add Value Field to content type
                ctx.Web.AddFieldToContentTypeById(SiteClassificationContentType.SITEINFORMATION_CT_ID,
                    SiteClassificationFields.FLD_VALUE_ID.ToString(),
                    true);
            }
            var _list = ctx.Web.Lists.Add(_newList);
            _list.Hidden = true;
            _list.ContentTypesEnabled = true;
            _list.Update();
            ctx.Web.AddContentTypeToListById(SiteClassificationList.SiteClassificationListTitle, SiteClassificationContentType.SITEINFORMATION_CT_ID, true);
            this.CreateCustomPropertiesInList(_list);
            ctx.ExecuteQuery();
            this.RemoveFromQuickLaunch(ctx, SiteClassificationList.SiteClassificationListTitle);

        }