示例#1
0
        public void TestFieldNumberConstructor()
        {
            var field = new FieldNumber(null);

            Assert.AreEqual("0", field.GetValue());

            //numeric values
            field = new FieldNumber(null, new Number(1), Number.NaN, Number.NaN);
            Assert.AreEqual(field.GetValue(), "1");
            field = new FieldNumber(null, new Number(1.5f), Number.NaN, Number.NaN);
            Assert.AreEqual(field.GetValue(), "1.5");

            //string values
            field = new FieldNumber(null, "2");
            Assert.AreEqual(field.GetValue(), "2");
            field = new FieldNumber(null, "2.5");
            Assert.AreEqual(field.GetValue(), "2.5");

            field = new FieldNumber(null, new Number(0), new Number(-128), new Number(127));
            Assert.AreEqual(field.GetValue(), "0");
            Assert.AreEqual(field.Min.Value, -128);
            Assert.AreEqual(field.Max.Value, 127);

            field = new FieldNumber(null, "bad");
            Assert.AreEqual(field.GetValue(), "0");
        }
示例#2
0
        /// <summary>
        /// Creates choice field for contextual help list
        /// </summary>
        /// <param name="clientcontext">Client Context</param>
        private static void AddValuesToChoiceColumn(ClientContext clientcontext)
        {
            // Basic code to load the list
            Web myWeb = clientcontext.Web;

            clientcontext.Load(myWeb);
            List            myList    = myWeb.Lists.GetByTitle(ConfigurationManager.AppSettings["ContextualHelpSectionListName"]);
            FieldCollection allFields = myList.Fields;

            clientcontext.Load(allFields);
            clientcontext.ExecuteQuery();
            //The field must be cast to a FieldChoice using context.CastTo

            for (int iIterator = 0; iIterator < Convert.ToInt32(ConfigurationManager.AppSettings["NumberOfColumns"], CultureInfo.InvariantCulture); iIterator++)   // For each list
            {
                string columnName       = ConfigurationManager.AppSettings["ChoiceFieldColumnName" + iIterator];
                string choiceFields     = ConfigurationManager.AppSettings["ChoiceFieldValues" + iIterator];
                string choiceFieldValue = string.Empty;

                string[] listChioceFields = choiceFields.Split(new string[] { "$|$" }, StringSplitOptions.RemoveEmptyEntries);
                for (int iCount = 0; iCount < listChioceFields.Length; iCount++) // Create columns inside list
                {
                    choiceFieldValue = string.Format(CultureInfo.InvariantCulture, "{0}<CHOICE>{1}</CHOICE>", choiceFieldValue, listChioceFields[iCount]);
                }
                choiceFieldValue = string.Format(CultureInfo.InvariantCulture, "<CHOICES>{0}</CHOICES>", choiceFieldValue);

                string      choiceFieldDefaultvalue = string.Format(CultureInfo.InvariantCulture, "<Default>{0}</Default>", ConfigurationManager.AppSettings["DefaultChoiceField" + iIterator]);
                string      choicefieldXml          = "<Field Type='Choice' DisplayName='{0}' Required='FALSE' EnforceUniqueValues='FALSE' Format='Dropdown' FillInChoice='FALSE'> {1}{2}</Field>";
                Field       choiceField             = myList.Fields.AddFieldAsXml(string.Format(CultureInfo.InvariantCulture, choicefieldXml, columnName, choiceFieldDefaultvalue, choiceFieldValue), true, AddFieldOptions.DefaultValue);
                FieldNumber fldNumberTaskStatus     = clientcontext.CastTo <FieldNumber>(choiceField);
                fldNumberTaskStatus.Update();
                clientcontext.ExecuteQuery();
            }
        }
        private void AddTextField(List list, string displayName, string fieldName, ClientContext context)
        {
            Field field = list.Fields.AddFieldAsXml($"<Field DisplayName='{displayName}' Name='{fieldName}' Title='{fieldName}' Type='Text' />",
                                                    true,
                                                    AddFieldOptions.DefaultValue);
            FieldNumber fldNumber = context.CastTo <FieldNumber>(field);

            fldNumber.Update();
        }
示例#4
0
        public override int GetHashCode()
        {
            int hash = 17;

            hash = hash * 23 + FieldState.GetHashCode();
            hash = hash * 23 + FieldValue.GetHashCode();
            hash = hash * 23 + RequiredStatus.GetHashCode();
            hash = hash * 23 + EnabledStatus.GetHashCode();
            hash = hash * 23 + FieldNumber.GetHashCode();
            hash = hash * 23 + LockedStatus.GetHashCode();
            return(hash);
        }
示例#5
0
        public FormDialog AddFieldNumber(string title, string dataname, Predicate <int> condition, bool hide = false)
        {
            FieldNumber field = new FieldNumber();

            field.Title     = title;
            field.Dataname  = dataname;
            field.Condition = condition;
            field.Hidden    = hide;

            fields.Add(field);

            return(this);
        }
        protected override void Execute(CodeActivityContext context)
        {
            var chID         = Channel__ID.Get(context);
            var readKey      = Read_API_Key.Get(context) == null ? "" : "api_key=" + Read_API_Key.Get(context);
            var chosenFormat = Format.ToString();
            var chosenField  = (FieldNumber.GetHashCode() + 1).ToString();

            var results   = Results.Get(context) == 0 ? "" : "&results=" + Results.Get(context).ToString();
            var days      = Days.Get(context) == 0 ? "" : "&days=" + Days.Get(context).ToString();
            var minutes   = Minutes.Get(context) == 0 ? "" : "&minutes=" + Minutes.Get(context).ToString();
            var start     = Start.Get(context) == null ? "" : "&start=" + Start.Get(context);
            var end       = End.Get(context) == null ? "" : "&end=" + End.Get(context);
            var timezone  = Timezone.Get(context) == null ? "" : "&timezone=" + Timezone.Get(context);
            var offset    = Offset.Get(context) == 0 ? "" : "&offset=" + Offset.Get(context).ToString();
            var status    = Status.Get(context) == true ? "&status=true" : "";
            var metadata  = Metadata.Get(context) == true ? "&metadata=true" : "";
            var location  = Location.Get(context) == true ? "&location=true" : "";
            var min       = Min.Get(context) == 0 ? "" : "&min=" + Min.Get(context).ToString();
            var max       = Max.Get(context) == 0 ? "" : "&max=" + Max.Get(context).ToString();
            var round     = Round.Get(context) == 0 ? "" : "&round=" + Round.Get(context).ToString();
            var timescale = Timescale.Get(context) == null ? "" : "&timescale=" + Timescale.Get(context);
            var sum       = Sum.Get(context) == null ? "" : "&sum=" + Sum.Get(context);
            var average   = Average.Get(context) == null ? "" : "&average=" + Average.Get(context);
            var median    = Median.Get(context) == null ? "" : "&median=" + Median.Get(context);
            var callback  = Callback.Get(context) == null ? "" : "&callback=" + Callback.Get(context);


            string URL = "https://api.thingspeak.com/channels/" + chID + "/fields/" + chosenField + "." + chosenFormat + "?";

            URL = URL + readKey + results + days + minutes + start + end + timezone + offset + status + metadata + location
                  + min + max + round + timescale + sum + average + median + callback;

            WebRequest   wrGETURL  = WebRequest.Create(URL);
            Stream       objStream = wrGETURL.GetResponse().GetResponseStream();
            StreamReader objReader = new StreamReader(objStream);

            string sLine        = "";
            string httpResponse = "";

            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    httpResponse = httpResponse + sLine + "\n";
                }
            }
            objStream.Close();
            //objReader.Close();
            Response.Set(context, httpResponse);
        }
示例#7
0
        //Add a field to a SharePoint list
        static void _AddField()
        {
            // Starting with ClientContext, the constructor requires a URL to the
            // server running SharePoint.
            ClientContext context = new ClientContext(_url);
            List          list    = context.Web.Lists.GetByTitle("My List");
            Field         field   = list.Fields.AddFieldAsXml("<Field DisplayName='MyField2' Type='Number' />",
                                                              true,
                                                              AddFieldOptions.DefaultValue);
            FieldNumber fldNumber = context.CastTo <FieldNumber>(field);

            fldNumber.MaximumValue = 100;
            fldNumber.MinimumValue = 35;
            fldNumber.Update();
            context.ExecuteQuery();
        }
        static void CreateWingtipSiteColumns()
        {
            Console.WriteLine();

            fieldProductCode = CreateSiteColumn("ProductCode", "Product Code", "Text");
            fieldProductCode.EnforceUniqueValues = true;
            fieldProductCode.Indexed             = true;
            fieldProductCode.Required            = true;
            fieldProductCode.Update();
            clientContext.ExecuteQuery();
            clientContext.Load(fieldProductCode);
            clientContext.ExecuteQuery();

            fieldProductDescription = clientContext.CastTo <FieldMultiLineText>(CreateSiteColumn("ProductDescription", "Product Description", "Note"));
            fieldProductDescription.NumberOfLines = 4;
            fieldProductDescription.RichText      = false;
            fieldProductDescription.Update();
            clientContext.ExecuteQuery();

            fieldProductListPrice = clientContext.CastTo <FieldCurrency>(CreateSiteColumn("ProductListPrice", "List Price", "Currency"));
            fieldProductListPrice.MinimumValue = 0;
            fieldProductListPrice.Update();
            clientContext.ExecuteQuery();

            fieldProductColor = clientContext.CastTo <FieldMultiChoice>(CreateSiteColumn("ProductColor", "Product Color", "MultiChoice"));
            string[] choicesProductColor = { "White", "Black", "Grey", "Blue", "Red", "Green", "Yellow" };
            fieldProductColor.Choices = choicesProductColor;
            fieldProductColor.Update();
            clientContext.ExecuteQuery();

            fieldMinimumAge = clientContext.CastTo <FieldNumber>(CreateSiteColumn("MinimumAge", "Minimum Age", "Number"));
            fieldMinimumAge.MinimumValue = 1;
            fieldMinimumAge.MaximumValue = 100;
            fieldMinimumAge.Update();
            clientContext.ExecuteQuery();

            fieldMaximumAge = clientContext.CastTo <FieldNumber>(CreateSiteColumn("MaximumAge", "Maximum Age", "Number"));
            fieldMaximumAge.MinimumValue = 1;
            fieldMaximumAge.MaximumValue = 100;
            fieldMaximumAge.Update();
            clientContext.ExecuteQuery();

            fieldProductImageUrl = clientContext.CastTo <FieldUrl>(CreateSiteColumn("ProductImageUrl", "Product Image Url", "URL"));
            fieldProductImageUrl.DisplayFormat = UrlFieldFormatType.Image;
            fieldProductImageUrl.Update();
            clientContext.ExecuteQuery();
        }
示例#9
0
        protected override void Execute(CodeActivityContext context)
        {
            var chID         = Channel__ID.Get(context);
            var readKey      = Read_API_Key.Get(context) == null ? "" : "api_key=" + Read_API_Key.Get(context);
            var chosenField  = (FieldNumber.GetHashCode() + 1).ToString();
            var chosenFormat = Format.GetHashCode() == 0 ? "" : "." + Format.ToString();

            var timezone = Timezone.Get(context) == null ? "" : "&timezone=" + Timezone.Get(context);
            var offset   = Offset.Get(context) == 0 ? "" : "&offset=" + Offset.Get(context).ToString();
            var status   = Status.Get(context) == true ? "&status=true" : "";
            var location = Location.Get(context) == true ? "&location=true" : "";
            var callback = Callback.Get(context) == null ? "" : "&callback=" + Callback.Get(context);
            var prepend  = Prepend.Get(context) == null ? "" : "&prepend=" + Prepend.Get(context);
            var append   = Append.Get(context) == null ? "" : "&append=" + Append.Get(context);

            string URL = "https://api.thingspeak.com/channels/" + chID + "/fields/" + chosenField + "/last" + chosenFormat + "?";

            URL = URL + readKey + timezone + offset + status + location + callback + prepend + append;

            WebRequest   wrGETURL  = WebRequest.Create(URL);
            Stream       objStream = wrGETURL.GetResponse().GetResponseStream();
            StreamReader objReader = new StreamReader(objStream);

            string sLine        = "";
            string httpResponse = "";

            while (sLine != null)
            {
                sLine = objReader.ReadLine();
                if (sLine != null)
                {
                    httpResponse = httpResponse + sLine + "\n";
                }
            }
            objStream.Close();
            //objReader.Close();
            Response.Set(context, httpResponse);
        }
示例#10
0
 public FieldNumberInformation(FieldNumber field) : base(field)
 {
     MinimumValue = field.MinimumValue;
     MaximumValue = field.MaximumValue;
 }
示例#11
0
        static void CreateWingtipSiteColumns()
        {
            Console.WriteLine();

              fieldProductCode = CreateSiteColumn("ProductCode", "Product Code", "Text");
              fieldProductCode.EnforceUniqueValues = true;
              fieldProductCode.Indexed = true;
              fieldProductCode.Required = true;
              fieldProductCode.Update();
              clientContext.ExecuteQuery();
              clientContext.Load(fieldProductCode);
              clientContext.ExecuteQuery();

              fieldProductDescription = clientContext.CastTo<FieldMultiLineText>(CreateSiteColumn("ProductDescription", "Product Description", "Note"));
              fieldProductDescription.NumberOfLines = 4;
              fieldProductDescription.RichText = false;
              fieldProductDescription.Update();
              clientContext.ExecuteQuery();

              fieldProductListPrice = clientContext.CastTo<FieldCurrency>(CreateSiteColumn("ProductListPrice", "Product List Price", "Currency"));
              fieldProductListPrice.MinimumValue = 0;
              fieldProductListPrice.Update();
              clientContext.ExecuteQuery();

              fieldProductColor = clientContext.CastTo<FieldMultiChoice>(CreateSiteColumn("ProductColor", "Product Color", "MultiChoice"));
              string[] choicesProductColor = { "White", "Black", "Grey", "Blue", "Red", "Green", "Yellow" };
              fieldProductColor.Choices = choicesProductColor;
              fieldProductColor.Update();
              clientContext.ExecuteQuery();

              fieldMinimumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MinimumAge", "Minimum Age", "Number"));
              fieldMinimumAge.MinimumValue = 1;
              fieldMinimumAge.MaximumValue = 100;
              fieldMinimumAge.Update();
              clientContext.ExecuteQuery();

              fieldMaximumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MaximumAge", "Maximum Age", "Number"));
              fieldMaximumAge.MinimumValue = 1;
              fieldMaximumAge.MaximumValue = 100;
              fieldMaximumAge.Update();
              clientContext.ExecuteQuery();
        }
示例#12
0
        public ActionResult Index()
        {
            var model     = new IndexAdvertisementViewModel();
            var spContext = SharePointContextProvider.Current.GetSharePointContext(HttpContext);

            if (spContext != null)
            {
                Session["SpContext"] = spContext;
                Session["SpHostUrl"] = spContext.SPHostUrl;
            }
            else
            {
                spContext = Session["SpContext"] as SharePointContext;
            }
            using (var clientContext = spContext.CreateUserClientContextForSPHost())
            {
                if (clientContext != null)
                {
                    ListCollection  listCol         = clientContext.Web.Lists;
                    TaxonomySession taxonomySession = TaxonomySession.GetTaxonomySession(clientContext);
                    User            currentUser     = clientContext.Web.CurrentUser;
                    clientContext.Load(taxonomySession);
                    clientContext.Load(listCol, y => y.Where(x => x.Title == "Annonser"));
                    clientContext.Load(currentUser);
                    clientContext.ExecuteQuery();
                    //List list = clientContext.Web.Lists.GetByTitle("Annonser");     Fungerar utan lista??

                    if (taxonomySession != null)
                    {
                        #region Create Category Taxonomy
                        Session["TaxSession"] = taxonomySession;
                        TermStore           termStore    = taxonomySession.GetDefaultSiteCollectionTermStore();
                        TermGroupCollection termGroupCol = termStore.Groups;
                        clientContext.Load(termGroupCol, t => t.Where(y => y.Name == "Advertisements"));
                        clientContext.ExecuteQuery();

                        var termGroup = termGroupCol.FirstOrDefault();
                        if (termGroup == null)
                        {
                            TermGroup annonsKategorierGroup = termStore.CreateGroup("Advertisements", Guid.NewGuid());
                            clientContext.ExecuteQuery();
                            TermSet annonsKateGorierTermSet = annonsKategorierGroup.CreateTermSet("Categories", Guid.NewGuid(), 1033);
                            clientContext.ExecuteQuery();

                            annonsKateGorierTermSet.CreateTerm("Electronics", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Appliances", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Clothing", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Books", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Office", 1033, Guid.NewGuid());
                            annonsKateGorierTermSet.CreateTerm("Other", 1033, Guid.NewGuid());
                            clientContext.ExecuteQuery();
                            termGroup = annonsKategorierGroup;
                        }
                        #endregion

                        if (termGroup != null)
                        {
                            TermSet        termSet = termGroup.TermSets.GetByName("Categories");
                            TermCollection terms   = termSet.GetAllTerms();
                            clientContext.Load(termSet);
                            clientContext.Load(terms);
                            clientContext.ExecuteQuery();

                            foreach (Term term in terms)
                            {
                                SelectListItem newItem = new SelectListItem {
                                    Value = term.Id.ToString(), Text = term.Name
                                };
                                model.Categories.Add(newItem);
                            }
                        }
                    }

                    var list = listCol.FirstOrDefault();

                    if (list == null)
                    {
                        #region Create Advertisement List
                        ListCreationInformation listCreationInfo = new ListCreationInformation();
                        listCreationInfo.Title        = "Annonser";
                        listCreationInfo.TemplateType = (int)ListTemplateType.GenericList;

                        var             newList  = clientContext.Web.Lists.Add(listCreationInfo);
                        FieldCollection fieldCol = newList.Fields;


                        Field defaultTitleField = fieldCol.GetByTitle("Title");
                        clientContext.Load(fieldCol);
                        clientContext.Load(defaultTitleField);
                        clientContext.ExecuteQuery();
                        defaultTitleField.Hidden = true;
                        defaultTitleField.SetShowInDisplayForm(false);
                        defaultTitleField.SetShowInEditForm(false);
                        defaultTitleField.SetShowInNewForm(false);
                        defaultTitleField.Required = false;
                        defaultTitleField.Update();

                        Field rubrikField = newList.Fields.AddFieldAsXml("<Field DisplayName='Rubrik' Type='Text' Name='Rubrik' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field textField   = newList.Fields.AddFieldAsXml("<Field DisplayName='Text' Type='Text' Name='Text' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field prisField   = newList.Fields.AddFieldAsXml("<Field DisplayName='Pris' Type='Number' Name='Pris' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field datumField  = newList.Fields.AddFieldAsXml("<Field DisplayName='Datum' Type='DateTime' Name='Datum' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        //Field anvandareField = newList.Fields.AddFieldAsXml("<Field DisplayName='Användare' Type='User' Name='Anvandare' StaticName='Anvandare' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);
                        Field kategoriField = newList.Fields.AddFieldAsXml("<Field DisplayName='Kategori' Type='TaxonomyFieldType' Name='Kategori' Required='TRUE' />", true, AddFieldOptions.AddFieldToDefaultView);

                        FieldNumber rubrikFieldNumber = clientContext.CastTo <FieldNumber>(rubrikField);
                        FieldNumber textFieldNumber   = clientContext.CastTo <FieldNumber>(textField);
                        FieldNumber prisFieldNumber   = clientContext.CastTo <FieldNumber>(prisField);
                        FieldNumber datumFieldNumber  = clientContext.CastTo <FieldNumber>(datumField);
                        //FieldNumber anvandareFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField);
                        //FieldNumber kategoryFieldNumber = clientContext.CastTo<FieldNumber>(anvandareField);
                        Guid termStoreId = Guid.Empty;
                        Guid termSetId   = Guid.Empty;
                        GetTaxonomyFieldInfo(clientContext, out termStoreId, out termSetId, "Categories");
                        TaxonomyField kategoryFieldNumber = clientContext.CastTo <TaxonomyField>(kategoriField);
                        kategoryFieldNumber.SspId          = termStoreId;
                        kategoryFieldNumber.TermSetId      = termSetId;
                        kategoryFieldNumber.TargetTemplate = String.Empty;
                        kategoryFieldNumber.AnchorId       = Guid.Empty;

                        rubrikFieldNumber.Update();
                        textFieldNumber.Update();
                        prisFieldNumber.Update();
                        datumFieldNumber.Update();
                        //anvandareFieldNumber.Update();
                        kategoryFieldNumber.Update();

                        View view = newList.Views.GetByTitle("All Items");
                        clientContext.Load(view);
                        clientContext.ExecuteQuery();
                        ViewFieldCollection viewFields = view.ViewFields;
                        viewFields.Remove("LinkTitle");
                        view.Update();

                        clientContext.ExecuteQuery();

                        list = newList;
                        #endregion
                    }
                    CamlQuery cQuery = new CamlQuery();
                    cQuery.ViewXml = @"<View>
                                        <Query>
                                        <Where>
                                        <Eq>
                                        <FieldRef Name='Author' LookupId='True'/>
                                        <Value Type='Lookup'>" + currentUser.Id + @"</Value>
                                        </Eq>
                                        </Where>
                                        </Query>
                                        </View>";
                    var listItems = list.GetItems(cQuery);
                    clientContext.Load(listItems);
                    clientContext.ExecuteQuery();

                    foreach (ListItem listItem in listItems)
                    {
                        AdvertisementViewModel tempObj = new AdvertisementViewModel
                        {
                            Title      = listItem["Rubrik"].ToString(),
                            Text       = listItem["Text"].ToString(),
                            Price      = int.Parse(listItem["Pris"].ToString()),
                            Date       = DateTime.Parse(listItem["Datum"].ToString()),
                            User       = listItem["Author"] as FieldUserValue,
                            Category   = listItem["Kategori"] as TaxonomyFieldValue,
                            ListItemId = listItem["ID"].ToString()
                        };
                        model.Advertisements.Add(tempObj);
                    }
                }
                return(View(model));
            }
        }
 public int CompareTo(IFieldDescriptorLite other)
 {
     return(FieldNumber.CompareTo(other.FieldNumber));
 }
示例#14
0
        /// <summary>
        /// Lanza el proceso de creación de nuevas columnas
        /// </summary>
        /// <returns></returns>
        public bool CreateColumns()
        {
            bool result          = true;
            List list            = null;
            bool continueProcess = true;

            if (ConectionSiteOK)
            {
                if (SPFields.Count > 0)
                {
                    foreach (SPFields infoField in SPFields)
                    {
                        continueProcess = true;
                        try
                        {
                            list = site.Web.Lists.GetByTitle(infoField.ListName);
                        }
                        catch (Exception ex)
                        {
                            SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Error));
                            continueProcess = false;
                        }

                        if (continueProcess)
                        {
                            //Configuramos...
                            switch (infoField.Column)
                            {
                            case TypeColumn.LineOfText:
                                //Linea de texto
                                Field newField1 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField1.StaticName  = infoField.ColumnName;
                                newField1.Description = infoField.Description;

                                if (infoField.FieldText != null)
                                {
                                    FieldText fldText = site.CastTo <FieldText>(newField1);
                                    fldText.Required            = infoField.FieldText.ContainInformation;
                                    fldText.EnforceUniqueValues = infoField.FieldText.UniqueValues;
                                    fldText.MaxLength           = infoField.FieldText.MaxLength;
                                    fldText.DefaultValue        = infoField.FieldText.DefaultValue;
                                    if (infoField.FieldText.UniqueValues)
                                    {
                                        fldText.Indexed = true;
                                    }
                                    fldText.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Multiline:
                                //Varias líneas de texto
                                Field newField2 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField2.StaticName  = infoField.ColumnName;
                                newField2.Description = infoField.Description;

                                if (infoField.FieldMultiText != null)
                                {
                                    FieldMultiLineText fldMultiLine = site.CastTo <FieldMultiLineText>(newField2);
                                    fldMultiLine.Required      = infoField.FieldMultiText.ContainInformation;
                                    fldMultiLine.NumberOfLines = infoField.FieldMultiText.NumLines;
                                    fldMultiLine.RichText      = infoField.FieldMultiText.RichText;
                                    fldMultiLine.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Choice:
                                //Eleccion
                                Field newField3 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField3.StaticName  = infoField.ColumnName;
                                newField3.Description = infoField.Description;

                                if (infoField.FieldChoice != null)
                                {
                                    FieldMultiChoice fldChoice = site.CastTo <FieldMultiChoice>(newField3);
                                    fldChoice.Required            = infoField.FieldChoice.ContainInformation;
                                    fldChoice.EnforceUniqueValues = infoField.FieldChoice.UniqueValues;
                                    fldChoice.DefaultValue        = infoField.FieldChoice.DefaultValue;
                                    if (infoField.FieldChoice.UniqueValues)
                                    {
                                        fldChoice.Indexed = true;
                                    }
                                    fldChoice.Choices = infoField.FieldChoice.Options;
                                    fldChoice.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Number:
                                //Numero
                                Field newField4 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField4.StaticName  = infoField.ColumnName;
                                newField4.Description = infoField.Description;

                                if (infoField.FieldNumber != null)
                                {
                                    FieldNumber fldNumber = site.CastTo <FieldNumber>(newField4);
                                    fldNumber.ShowAsPercentage = infoField.FieldNumber.ShowAsPercentaje;
                                    if (infoField.FieldNumber.MinValue != 0)
                                    {
                                        fldNumber.MinimumValue = infoField.FieldNumber.MinValue;
                                    }
                                    if (infoField.FieldNumber.MaxValue != 0)
                                    {
                                        fldNumber.MaximumValue = infoField.FieldNumber.MaxValue;
                                    }

                                    fldNumber.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.Lookup:
                                if (infoField.FieldLookup != null)
                                {
                                    string required = "FALSE";
                                    if (infoField.FieldLookup.ContainInformation)
                                    {
                                        required = "TRUE";
                                    }

                                    try
                                    {
                                        List sourceList = site.Web.Lists.GetByTitle(infoField.FieldLookup.LookupList);
                                        site.Load(sourceList);

                                        List destinationList = site.Web.Lists.GetByTitle(infoField.ListName);
                                        site.Load(destinationList);

                                        site.ExecuteQuery();

                                        Field LookUpField = destinationList.Fields.AddFieldAsXml(string.Format(schemaXMLLookUp, infoField.Type, infoField.ColumnName, required, sourceList.Id, infoField.FieldLookup.LookupField), true, AddFieldOptions.DefaultValue);
                                        LookUpField.Description = infoField.Description;
                                        LookUpField.Update();
                                    }
                                    catch (Exception ex)
                                    {
                                        SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Error));
                                        continueProcess = false;
                                    }
                                }
                                else
                                {
                                    continueProcess = false;
                                }
                                break;

                            case TypeColumn.UsersAndGroups:
                                Field newField5 = list.Fields.AddFieldAsXml(string.Format(schemaXML, infoField.Type, infoField.ColumnName), true, AddFieldOptions.AddToDefaultContentType);
                                newField5.StaticName  = infoField.ColumnName;
                                newField5.Description = infoField.Description;

                                if (infoField.FieldUserGroup != null)
                                {
                                    FieldUser fldUser = site.CastTo <FieldUser>(newField5);
                                    fldUser.Required = infoField.FieldUserGroup.ContainInformation;
                                    switch (infoField.FieldUserGroup.UserSelectionMode)
                                    {
                                    case TypeUserSelectionMode.PeopleOnly:
                                        fldUser.SelectionMode = FieldUserSelectionMode.PeopleOnly;
                                        break;

                                    case TypeUserSelectionMode.PeopleAndGroups:
                                        fldUser.SelectionMode = FieldUserSelectionMode.PeopleAndGroups;
                                        break;
                                    }

                                    if (infoField.FieldUserGroup.MultiUser)
                                    {
                                        fldUser.AllowMultipleValues = true;
                                    }

                                    if (!string.IsNullOrEmpty(infoField.FieldUserGroup.UsersFromGroup))
                                    {
                                        Group group = site.Web.SiteGroups.GetByName(infoField.FieldUserGroup.UsersFromGroup);

                                        try
                                        {
                                            site.Load(group);
                                            site.ExecuteQuery();
                                        }
                                        catch (Exception ex)
                                        {
                                            SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Warning));
                                            group = null;
                                        }

                                        if (group != null)
                                        {
                                            fldUser.SelectionGroup = group.Id;
                                        }
                                    }

                                    fldUser.Update();
                                }
                                else
                                {
                                    continueProcess = false;
                                }

                                break;
                            }

                            //Añadimos...
                            if (continueProcess)
                            {
                                try
                                {
                                    site.ExecuteQuery();
                                }
                                catch (Exception ex)
                                {
                                    SHPExecOperationsErrors.Add(GetInfoError(ex, string.Format("Alta de nuevo campo {0}", infoField.ColumnName), TypeError.Error));
                                }
                            }
                        }

                        list = null;
                    }
                }
                else
                {
                    SHPExecOperationsErrors.Add(GetInfoError("Creación de columnas (CreateColumns)", "No se han indicado campos a crear", "", TypeError.Warning));
                    result = false;
                }
            }
            else
            {
                SHPExecOperationsErrors.Add(GetInfoError("Creación de columnas (CreateColumns)", "No se ha establecido conexión con el site", "", TypeError.Warning));
                result = false;
            }

            SPFields.Clear();

            return(result);
        }
示例#15
0
        static void CreateWingtipSiteColumns()
        {
            Console.WriteLine();
              Console.WriteLine("Creating site columns");

              fieldProductCode = CreateSiteColumn("ProductCode", "Product Code", "Text");
              fieldProductCode.EnforceUniqueValues = true;
              fieldProductCode.Indexed = true;
              fieldProductCode.Required = true;
              fieldProductCode.Update();
              clientContext.ExecuteQuery();
              clientContext.Load(fieldProductCode);
              clientContext.ExecuteQuery();

              fieldProductListPrice = clientContext.CastTo<FieldCurrency>(CreateSiteColumn("ProductListPrice", "List Price", "Currency"));

              fieldProductCategory = clientContext.CastTo<FieldChoice>(CreateSiteColumn("ProductCategory", "Product Category", "Choice"));
              string[] choicesProductCategory = { "Action Figures", "Arts and Crafts", "Vehicles and Remote Control" };
              fieldProductCategory.Choices = choicesProductCategory;
              fieldProductCategory.Update();
              clientContext.ExecuteQuery();

              fieldProductColor = clientContext.CastTo<FieldChoice>(CreateSiteColumn("ProductColor", "Product Color", "Choice"));
              string[] choicesProductColor = { "White", "Black", "Grey", "Blue", "Red", "Green", "Yellow" };
              fieldProductColor.Choices = choicesProductColor;
              fieldProductColor.Update();
              clientContext.ExecuteQuery();

              fieldMinimumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MinimumAge", "Minimum Age", "Number"));

              fieldMaximumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MaximumAge", "Maximum Age", "Number"));
        }
        public static void CreateOrderDetailsList()
        {
            Console.WriteLine("Creating order details list...");

            if (OrdersListExists())
            {
                ListCreationInformation listInformationOrderDetails = new ListCreationInformation();
                listInformationOrderDetails.Title             = "OrderDetails";
                listInformationOrderDetails.Url               = "Lists/OrderDetails";
                listInformationOrderDetails.QuickLaunchOption = QuickLaunchOptions.On;
                listInformationOrderDetails.TemplateType      = (int)ListTemplateType.GenericList;
                listOrderDetails = site.Lists.Add(listInformationOrderDetails);
                listOrderDetails.OnQuickLaunch     = true;
                listOrderDetails.EnableAttachments = false;
                listOrderDetails.Update();
                clientContext.ExecuteQuery();

                listOrderDetails.DefaultView.ViewFields.RemoveAll();
                listOrderDetails.DefaultView.ViewFields.Add("ID");
                listOrderDetails.DefaultView.Update();
                clientContext.ExecuteQuery();

                var fldTitle = listOrderDetails.Fields.GetByInternalNameOrTitle("Title");
                fldTitle.Required = false;
                fldTitle.Update();
                clientContext.ExecuteQuery();

                string      fldOrderLookupXml = @"<Field Name='OrderId' DisplayName='Order' Type='Lookup' ></Field>";
                FieldLookup fldOrderLookup    =
                    clientContext.CastTo <FieldLookup>(listOrderDetails.Fields.AddFieldAsXml(fldOrderLookupXml,
                                                                                             true,
                                                                                             AddFieldOptions.AddFieldInternalNameHint));

                // add cusotmer lookup field
                fldOrderLookup.LookupField = "ID";
                fldOrderLookup.LookupList  = listOrders.Id.ToString();
                fldOrderLookup.Indexed     = true;
                fldOrderLookup.RelationshipDeleteBehavior = RelationshipDeleteBehaviorType.Cascade;
                fldOrderLookup.Update();

                // add quantity field
                string      fldQuantityXml = @"<Field Name='Quantity' DisplayName='Quantity' Type='Number' ></Field>";
                FieldNumber fldQuantity    =
                    clientContext.CastTo <FieldNumber>(listOrderDetails.Fields.AddFieldAsXml(fldQuantityXml,
                                                                                             true,
                                                                                             AddFieldOptions.DefaultValue));
                fldQuantity.Update();

                // add product field
                string    fldProductXml = @"<Field Name='Product' DisplayName='Product' Type='Text' ></Field>";
                FieldText fldProduct    =
                    clientContext.CastTo <FieldText>(listOrderDetails.Fields.AddFieldAsXml(fldProductXml,
                                                                                           true,
                                                                                           AddFieldOptions.DefaultValue));
                fldProduct.Update();

                string        fldSalesAmountXml = @"<Field Name='SalesAmount' DisplayName='SalesAmount' Type='Currency' ></Field>";
                FieldCurrency fldSalesAmount    =
                    clientContext.CastTo <FieldCurrency>(listOrderDetails.Fields.AddFieldAsXml(fldSalesAmountXml,
                                                                                               true,
                                                                                               AddFieldOptions.DefaultValue));
                fldSalesAmount.Update();

                clientContext.ExecuteQuery();

                //listOrderDetails.DefaultView.ViewFields.Remove("Title");
                listOrderDetails.DefaultView.Update();
                clientContext.ExecuteQuery();
            }
            else
            {
                Console.WriteLine("Cannot create OrderDetails list because Orders list does not exist.");
            }
        }
        public static void CreateListColumn()
        {
            var clientContext = Helper.GetClientContext();

            List oList = clientContext.Web.Lists.GetByTitle(listName);

            //Number DataType Column
            Field       numberField = oList.Fields.AddFieldAsXml("<Field DisplayName='Age' Type='Number' />", true, AddFieldOptions.DefaultValue);
            FieldNumber fieldNumber = clientContext.CastTo <FieldNumber>(numberField);

            fieldNumber.MaximumValue = 100;
            fieldNumber.MinimumValue = 35;
            fieldNumber.Update();
            clientContext.Load(fieldNumber);

            // //Single Line Of Text DataType Column
            Field     textField = oList.Fields.AddFieldAsXml("<Field DisplayName='SingleLine' Type='Text' />", true, AddFieldOptions.DefaultValue);
            FieldText fieldText = clientContext.CastTo <FieldText>(textField);

            fieldText.Update();
            clientContext.Load(fieldText);

            //Multi Line Of Text DataType Column
            Field multiLineField = oList.Fields.AddFieldAsXml("<Field DisplayName='MultiLine' Type='Note' />", true, AddFieldOptions.DefaultValue);
            FieldMultiLineText fieldmultiLineText = clientContext.CastTo <FieldMultiLineText>(multiLineField);

            fieldmultiLineText.Update();
            clientContext.Load(fieldmultiLineText);

            //Multi Line Rich Text DataType Column
            Field multiLineRichTextField = oList.Fields.AddFieldAsXml("<Field DisplayName='Multi Line RichText' Type='Note' />", true, AddFieldOptions.DefaultValue);
            FieldMultiLineText fieldmultiLineRichText = clientContext.CastTo <FieldMultiLineText>(multiLineRichTextField);

            fieldmultiLineRichText.AllowHyperlink = true;
            fieldmultiLineRichText.RichText       = true;
            fieldmultiLineRichText.Update();
            fieldmultiLineRichText.UpdateAndPushChanges(true);
            clientContext.Load(fieldmultiLineRichText);

            //An enhanced multi line text field
            string schemaRichTextField        = "<Field Type='Note' Name='EnhancedmultiLine' StaticName='EnhancedmultiLine' DisplayName = 'Enhanced multiLine' NumLines = '6' RichText = 'TRUE' RichTextMode = 'FullHtml' IsolateStyles = 'TRUE' Sortable = 'FALSE' /> ";
            Field  multilineenhancedTextField = oList.Fields.AddFieldAsXml(schemaRichTextField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(multilineenhancedTextField);

            // DropDown Choice
            string schemaChoiceFieldDDL = "<Field Type='Choice' DisplayName='ChoiceDDL' Name='ChoiceDDL' StaticName='ChoiceDDL' Format = 'Dropdown' >"
                                          + "<Default>Option 2</Default>"
                                          + "<CHOICES>"
                                          + "    <CHOICE>Option 2</CHOICE>"
                                          + "    <CHOICE>Option 3</CHOICE>"
                                          + "</CHOICES>"
                                          + "</Field>";

            Field       choiceDDLField = oList.Fields.AddFieldAsXml(schemaChoiceFieldDDL, true, AddFieldOptions.AddFieldInternalNameHint);
            FieldChoice fieldChoice    = clientContext.CastTo <FieldChoice>(choiceDDLField);

            fieldChoice.Required = true;
            fieldChoice.Update();
            clientContext.Load(fieldChoice);


            //Radio buttons
            string schemaRadioChoiceField = "<Field Type='Choice' Name='ChoiceRadio' StaticName='ChoiceRadio' DisplayName = 'Choice Radio' Format = 'RadioButtons' > "
                                            + "<Default>Opt Radio 3</Default>"
                                            + "<CHOICES>"
                                            + "    <CHOICE>Opt Radio 1</CHOICE>"
                                            + "    <CHOICE>Opt Radio 2</CHOICE>"
                                            + "    <CHOICE>Opt Radio 3</CHOICE>"
                                            + "</CHOICES>"
                                            + "</Field>";
            Field choiceField = oList.Fields.AddFieldAsXml(schemaRadioChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(choiceField);

            //Checkboxes
            string schemaMultiChoiceField = "<Field Type='MultiChoice' Name='ChoiceMulti' StaticName='ChoiceMulti' DisplayName = 'Choice Multi' > "
                                            + "<Default>MultiChoice 2</Default>"
                                            + "<CHOICES>"
                                            + "    <CHOICE>MultiChoice 1</CHOICE>"
                                            + "    <CHOICE>MultiChoice 2</CHOICE>"
                                            + "    <CHOICE>MultiChoice 3</CHOICE>"
                                            + "</CHOICES>"
                                            + "</Field>";
            Field choiceMultiChoiceField = oList.Fields.AddFieldAsXml(schemaMultiChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(choiceMultiChoiceField);

            //Fill In option
            string schemaFillInChoiceField = "<Field Type='Choice' DisplayName='Fill In Choice' Name='FillInChoice' StaticName='FillInChoice' Format = 'Dropdown' FillInChoice = 'TRUE' > "
                                             + "<Default>My Choices Data will come here</Default>"
                                             + "<CHOICES>"
                                             + "    <CHOICE>FillInChoice 1</CHOICE>"
                                             + "    <CHOICE>FillInChoice 2</CHOICE>"
                                             + "    <CHOICE>FillInChoice 3</CHOICE>"
                                             + "</CHOICES>"
                                             + "</Field>";
            Field choiceFillInChoiceField = oList.Fields.AddFieldAsXml(schemaFillInChoiceField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(choiceFillInChoiceField);

            //Picture field

            string schemaPictureField = "<Field Type='URL' Name='EmployeePicture' StaticName='EmployeePicture' DisplayName = 'Employee Picture' Format = 'Image' /> ";
            Field  pictureField       = oList.Fields.AddFieldAsXml(schemaPictureField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(pictureField);

            //URL field

            string schemaUrlField = "<Field Type='URL' Name='BlogUrl' StaticName='BlogUrl' DisplayName='Blog URL' Format='Hyperlink'/>";
            Field  urlField       = oList.Fields.AddFieldAsXml(schemaUrlField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(urlField);
            clientContext.ExecuteQuery();

            // Lookup field

            List countryList = clientContext.Web.Lists.GetByTitle("Countries");

            clientContext.Load(countryList, c => c.Id);
            clientContext.ExecuteQuery();


            // //define the relationship with the lookup field, in that case the field needs to be indexed:
            // string schemaLookupField = "<Field Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country Name' List = '{B5E2D800F-E739-401F-983F-B40984B70273}' ShowField = 'Title' RelationshipDeleteBehavior = 'Restrict' Indexed = 'TRUE' /> ";
            //string schemaLookupField = "<Field Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country Name' List = 'Countries' ShowField = 'Title' RelationshipDeleteBehavior = 'Restrict' Indexed = 'TRUE' /> ";
            string schemaLookupField = "<Field Type='Lookup' Name='Country' StaticName='Country' DisplayName='Country Name' List = '" + countryList.Id + "' ShowField = 'Title' /> ";
            Field  lookupField       = oList.Fields.AddFieldAsXml(schemaLookupField, true, AddFieldOptions.AddFieldInternalNameHint);

            lookupField.Update();
            clientContext.Load(lookupField);

            //// multi-select lookup field
            string schemaMultiLookupField = "<Field Type='LookupMulti' Name='Country' StaticName='Country' DisplayName='Country' List = '" + countryList.Id + "' ShowField = 'Title' Mult = 'TRUE' /> ";
            //string schemaMultiLookupField = "<Field Type='LookupMulti' Name='Country' StaticName='Country' DisplayName='Country' List = 'Countries' ShowField = 'Title' Mult = 'TRUE' /> ";
            Field lookupFieldmulti = oList.Fields.AddFieldAsXml(schemaMultiLookupField, true, AddFieldOptions.AddFieldInternalNameHint);

            lookupFieldmulti.Update();
            clientContext.Load(lookupFieldmulti);


            ////Ref: https://karinebosch.wordpress.com/my-articles/creating-fields-using-csom/

            // //User Field
            string schemaUserField = "<Field Type='User' Name='UserName' StaticName='UserName' DisplayName='User Name' />";
            Field  userField       = oList.Fields.AddFieldAsXml(schemaUserField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(userField);

            ////User Field multiple
            //string schemaUserGroupField = "<Field Type='UserMulti' Name='EmployeeName' StaticName='EmployeeName' DisplayName='Employee Name' UserSelectionMode = 'PeopleOnly' UserSelectionScope = '7' Mult = 'TRUE' /> ";
            string schemaUserGroupField = "<Field Type='UserMulti' Name='EmployeeName' StaticName='EmployeeName' DisplayName='Employee Name' UserSelectionMode = 'PeopleAndGroups' UserSelectionScope = '7' Mult = 'TRUE' /> ";
            Field  userGroupField       = oList.Fields.AddFieldAsXml(schemaUserGroupField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(userGroupField);

            ////boolean field

            string schemaBooleanField = "<Field Type='Boolean' Name='Married' StaticName='Married' DisplayName='Married'> <Default>1</Default> </Field>";
            Field  booleanField       = oList.Fields.AddFieldAsXml(schemaBooleanField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(booleanField);

            ////DateTime Field

            //Date only field
            string schemaBirthDate = "<Field Type='DateTime' Name='BirthDate' StaticName='BirthDate' DisplayName = 'Birth date' Format = 'DateOnly'> <Default>[Today]</Default></Field>";
            Field  birthDateField  = oList.Fields.AddFieldAsXml(schemaBirthDate, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(birthDateField);

            ////Date and time field
            string schemaArrivalField = "<Field Type='DateTime' Name='ArrivalDateTime' StaticName='ArrivalDateTime' DisplayName = 'Arrival' Format = 'DateTime'> <Default>[Now]</Default></Field>";
            Field  DateTimeField      = oList.Fields.AddFieldAsXml(schemaArrivalField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(DateTimeField);

            ////hidden field

            string schemaHiddenTextField = "<Field Type='Text' Name='HiddenField' StaticName='HiddenField' DisplayName='Hidden Field' Hidden='TRUE' />";
            Field  hiddenTextField       = oList.Fields.AddFieldAsXml(schemaHiddenTextField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(hiddenTextField);

            //indexed field // Not Working as of now

            //Field f = oList.Fields.GetByInternalNameOrTitle("ID");
            //clientContext.Load(f);
            //clientContext.ExecuteQuery();
            //f.Indexed = true;
            //f.Update();

            //Managed Metadata field

            Guid termStoreId = Guid.Empty;
            Guid termSetId   = Guid.Empty;

            GetTaxonomyFieldInfo(clientContext, out termStoreId, out termSetId);

            // Single selection Taxonomy field
            string schemaTaxonomyField = "<Field Type='TaxonomyFieldType' Name='TaxonomyField' StaticName='TaxonomyField' DisplayName = 'Taxonomy Field' /> ";
            Field  taxonomyFieldSingle = oList.Fields.AddFieldAsXml(schemaTaxonomyField, true, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(taxonomyFieldSingle);

            // Retrieve the field as a Taxonomy Field
            TaxonomyField taxonomyField = clientContext.CastTo <TaxonomyField>(taxonomyFieldSingle);

            taxonomyField.SspId          = termStoreId;
            taxonomyField.TermSetId      = termSetId;
            taxonomyField.TargetTemplate = String.Empty;
            taxonomyField.AnchorId       = Guid.Empty;
            taxonomyField.Update();

            // Multi selection Taxonomy field

            string schemaTaxonomyFieldMulti = "<Field Type='TaxonomyFieldTypeMulti' Name='TaxonomyFieldMulti' StaticName='TaxonomyFieldMulti' DisplayName = 'Taxonomy Field Multi' Mult = 'TRUE' /> ";
            Field  taxonomyFieldMulti       = oList.Fields.AddFieldAsXml(schemaTaxonomyFieldMulti, false, AddFieldOptions.AddFieldInternalNameHint);

            clientContext.Load(taxonomyFieldMulti);

            // Retrieve the field as a Taxonomy Field
            TaxonomyField taxonomyField1 = clientContext.CastTo <TaxonomyField>(taxonomyFieldMulti);

            taxonomyField1.SspId          = termStoreId;
            taxonomyField1.TermSetId      = termSetId;
            taxonomyField1.TargetTemplate = String.Empty;
            taxonomyField1.AnchorId       = Guid.Empty;
            taxonomyField1.Update();


            clientContext.ExecuteQuery();

            //Calculated field

            // Not Working

            //string formula = "<Formula>=Age&amp;\"\"&amp;SingleLine&amp;\"(id:\"&amp;ID&amp;\"\"</Formula>"
            //                  + "<FieldRefs>"
            //                  + "<FieldRef Name='Age' />"
            //                  + "<FieldRef Name='SingleLine' />"
            //                  + "<FieldRef Name='ID' />"
            //                  + "</FieldRefs>";

            //string schemaCalculatedField = "<Field Type='Calculated' Name='CalculatedField' StaticName='CalculatedField' DisplayName = 'Calculated Field' ResultType = 'Text' Required = 'TRUE' ReadOnly = 'TRUE' > " + formula + " </ Field > ";
            //Field fullNameField = oList.Fields.AddFieldAsXml(schemaCalculatedField, true, AddFieldOptions.AddFieldInternalNameHint);
            //clientContext.ExecuteQuery();

            string fieldXml = "<Field Name='CalculatedField_Year' StaticName='CalculatedField_Year' DisplayName='CalculatedField Year' Type='Text' ReadOnly = 'TRUE'>"
                              + "<DefaultFormula>=CONCATENATE(YEAR(Today))</DefaultFormula>"
                              + "</Field>";
            Field field = oList.Fields.AddFieldAsXml(fieldXml, true, AddFieldOptions.DefaultValue);

            clientContext.ExecuteQuery();
        }
        static void CreateWingtipSiteColumns()
        {
            Console.WriteLine();

              fieldProductCode = CreateSiteColumn("ProductCode", "Product Code", "Text");
              fieldProductCode.EnforceUniqueValues = true;
              fieldProductCode.Indexed = true;
              fieldProductCode.Required = true;
              fieldProductCode.Update();
              clientContext.ExecuteQuery();
              clientContext.Load(fieldProductCode);
              clientContext.ExecuteQuery();

              fieldProductDescription = clientContext.CastTo<FieldMultiLineText>(CreateSiteColumn("ProductDescription", "Product Description", "Note"));
              fieldProductDescription.NumberOfLines = 4;
              fieldProductDescription.RichText = false;
              fieldProductDescription.Update();
              clientContext.ExecuteQuery();

              fieldProductListPrice = clientContext.CastTo<FieldCurrency>(CreateSiteColumn("ProductListPrice", "List Price", "Currency"));
              fieldProductListPrice.MinimumValue = 0;
              fieldProductListPrice.Update();
              clientContext.ExecuteQuery();

              fieldProductCategory = clientContext.CastTo<TaxonomyField>(CreateSiteColumn("ProductCategory", "Product Category", "TaxonomyFieldType"));
              fieldProductCategory.SspId = localTermStoreID;
              fieldProductCategory.TermSetId = termSetId;
              fieldProductCategory.AllowMultipleValues = false;
              fieldProductCategory.Update();
              clientContext.ExecuteQuery();

              fieldProductColor = clientContext.CastTo<FieldMultiChoice>(CreateSiteColumn("ProductColor", "Product Color", "MultiChoice"));
              string[] choicesProductColor = { "White", "Black", "Grey", "Blue", "Red", "Green", "Yellow" };
              fieldProductColor.Choices = choicesProductColor;
              fieldProductColor.Update();
              clientContext.ExecuteQuery();

              fieldMinimumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MinimumAge", "Minimum Age", "Number"));
              fieldMinimumAge.MinimumValue = 1;
              fieldMinimumAge.MaximumValue = 100;
              fieldMinimumAge.Update();
              clientContext.ExecuteQuery();

              fieldMaximumAge = clientContext.CastTo<FieldNumber>(CreateSiteColumn("MaximumAge", "Maximum Age", "Number"));
              fieldMaximumAge.MinimumValue = 1;
              fieldMaximumAge.MaximumValue = 100;
              fieldMaximumAge.Update();
              clientContext.ExecuteQuery();

              fieldProductImageUrl = clientContext.CastTo<FieldUrl>(CreateSiteColumn("ProductImageUrl", "Product Image Url", "URL"));
              fieldProductImageUrl.DisplayFormat = UrlFieldFormatType.Image;
              fieldProductImageUrl.Update();
              clientContext.ExecuteQuery();
        }