Пример #1
0
        public string GetMultiOwnValue(SP.Field field, string valueAsText)
        {
            if (string.IsNullOrEmpty(valueAsText))
            {
                return(string.Empty);
            }
            string[] values      = valueAsText.Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var      fieldChoice = field as SP.FieldChoice;

            foreach (string value in values)
            {
                bool isOwnValue = true;
                foreach (string key in fieldChoice.Choices)
                {
                    if (key == value)
                    {
                        isOwnValue = false;
                    }
                }
                if (isOwnValue)
                {
                    return(value);
                }
            }
            return(string.Empty);
        }
Пример #2
0
        public bool ShowAsPercentage(SP.Field field)
        {
            bool?_showAsPercentage = null;

            try
            {
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(field.SchemaXml);
                string sPercentage = doc.FirstChild.Attributes["Percentage"].Value;
                bool   p           = false;
                if (bool.TryParse(sPercentage, out p))
                {
                    _showAsPercentage = p;
                }
                else
                {
                    _showAsPercentage = false;
                }
            }
            catch
            {
                _showAsPercentage = false;
            }
            return(_showAsPercentage.Value);
        }
        private void Init(SP.Field Field, string baseurl)
        {
            var xml = Field.SchemaXml;
            XmlReaderSettings readerSettings = new XmlReaderSettings();

            readerSettings.ConformanceLevel = ConformanceLevel.Fragment;
            XmlReader      xmlReader     = XmlReader.Create(new StringReader(xml), readerSettings);
            var            xpathDocument = new XPathDocument(xmlReader);
            XPathNavigator nav           = xpathDocument.CreateNavigator();

            var allowMultipleValuesNode = nav.SelectSingleNode(@"/Field");

            bool.TryParse(allowMultipleValuesNode.GetAttribute("Mult", ""), out allowMultipleValues);

            var sspIdPropertyNode = nav.SelectSingleNode(@"/Field/Customization/ArrayOfProperty/Property[Name='SspId']");

            sspId = sspIdPropertyNode.SelectSingleNode(@"Value").Value;

            var termSetIdPropertyNode = nav.SelectSingleNode(@"/Field/Customization/ArrayOfProperty/Property[Name='TermSetId']");

            termSetId = termSetIdPropertyNode.SelectSingleNode(@"Value").Value;

            using (var tax = new TaxonomyClientService.Taxonomywebservice())
            {
                tax.Url         = baseurl.TrimEnd('/') + "/_vti_bin/TaxonomyClientService.asmx";
                tax.Credentials = credentials.Get(baseurl).Credentials();
                string termsXml = tax.GetChildTermsInTermSet(new Guid(sspId), CultureInfo.CurrentCulture.LCID, new Guid(termSetId));
                Terms = ParseResult(termsXml);
            }
        }
Пример #4
0
        public static Type GetFieldValueType(this Field field)
        {
            var table = new Dictionary <FieldType, Type>();

            table[FieldType.Guid]             = typeof(Guid);
            table[FieldType.Attachments]      = typeof(bool);
            table[FieldType.Boolean]          = typeof(bool);
            table[FieldType.Choice]           = typeof(string);
            table[FieldType.CrossProjectLink] = typeof(bool);
            table[FieldType.DateTime]         = typeof(DateTime);
            table[FieldType.Lookup]           = typeof(FieldLookupValue);
            table[FieldType.ModStat]          = typeof(int);
            table[FieldType.MultiChoice]      = typeof(string[]);
            table[FieldType.Number]           = typeof(double);
            table[FieldType.Recurrence]       = typeof(bool);
            table[FieldType.Text]             = typeof(string);
            table[FieldType.URL]            = typeof(FieldUrlValue);
            table[FieldType.URL]            = typeof(FieldUrlValue);
            table[FieldType.User]           = typeof(FieldUserValue);
            table[FieldType.WorkflowStatus] = typeof(int);
            table[FieldType.ContentTypeId]  = typeof(ContentTypeId);
            table[FieldType.Note]           = typeof(string);
            table[FieldType.Counter]        = typeof(int);
            table[FieldType.Computed]       = typeof(string);
            table[FieldType.Integer]        = typeof(int);
            table[FieldType.File]           = typeof(string);

            if (!table.ContainsKey(field.FieldTypeKind))
            {
                throw new NotSupportedException(string.Format("Unknown field type: {0}", field.FieldTypeKind));
            }
            return(table[field.FieldTypeKind]);
        }
Пример #5
0
        private static void ProcessField(Field field, Guid listGuid, string webId, string relationshipDeleteBehavior)
        {
            var isDirty = false;

            var existingFieldElement = XElement.Parse(field.SchemaXml);

            isDirty = UpdateFieldAttribute(existingFieldElement, "List", listGuid.ToString(), false);

            isDirty = UpdateFieldAttribute(existingFieldElement, "WebId", webId, isDirty);

            isDirty = UpdateFieldAttribute(existingFieldElement, "SourceID", webId, isDirty);

            if (!string.IsNullOrEmpty(relationshipDeleteBehavior))
            {
                isDirty = UpdateFieldAttribute(existingFieldElement, "RelationshipDeleteBehavior", relationshipDeleteBehavior, isDirty);
            }

            if (isDirty)
            {
                field.SchemaXml = existingFieldElement.ToString();

                field.UpdateAndPushChanges(true);
                field.Context.ExecuteQueryRetry();
            }
        }
Пример #6
0
        public static string GetSettingsUrl(this SPClient.Field field, TreeNode selectedNode)
        {
            // <sitecollection|web>/_layouts/FldEditEx.aspx?field=Instructie
            // <sitecollection|web>/_layouts/FldEdit.aspx?List=%7BCEBB8CB0%2DC088%2D4BEE%2DBF17%2DE6A8CD5F6C9F%7D&Field=Title

            if (selectedNode.Parent.Parent.Tag is SPClient.Site)
            {
                // <sitecollection>/_layouts/15/fldedit.aspx?field=%5FEndDate&Source=%2F%5Flayouts%2F15%2Fmngfield%2Easpx%3FFilter%3DAll%2520Groups

                SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
                return(string.Format("{0}/_layouts/fldedit.aspx?field={1}", site.RootWeb.GetUrl(), field.InternalName));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.Web)
            {
                // <sitecollection>/<web>/_layouts/15/fldedit.aspx?field=Sub%5Fx0020%5FSite%5Fx0020%5FColumn&Source=%2Fsub%2F%5Flayouts%2F15%2Fmngfield%2Easpx%3FFilter%3DAll%2520Groups

                SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
                return(string.Format("{0}/_layouts/fldedit.aspx?field={1}", web.GetUrl(), field.InternalName));
            }
            else if (selectedNode.Parent.Parent.Tag is SPClient.List)
            {
                // <sitecollection>/<web>/_layouts/15/FldEditEx.aspx?List=%7B051E4502%2D504E%2D49C8%2DA815%2DF46BFD61911D%7D&Field=Modified

                SPClient.List list = selectedNode.Parent.Parent.Tag as SPClient.List;
                return(string.Format("{0}/_layouts/FldEditEx.aspx?list={1}&field={2}", list.ParentWeb.GetUrl(), list.Id, field.InternalName));
            }
            else
            {
                return(string.Empty);
            }
        }
Пример #7
0
        /// <summary>
        /// Sets the headers/columns for the list view, and populates combo box
        /// and checked list box with field values loaded from SP.
        /// </summary>
        private void InitUI()
        {
            // init listview header
            RecipesListView.Columns.Add("Title", 500);
            RecipesListView.Columns.Add("Time (h)", 50);
            RecipesListView.Columns.Add("Difficulty", 75);
            RecipesListView.Columns.Add("Category", 200);

            // load the choice fields
            SP.Field            difficultyField       = RecipesList.Fields.GetByInternalNameOrTitle("Difficulty");
            SP.FieldChoice      difficultyFieldChoice = Context.CastTo <SP.FieldChoice>(difficultyField);
            SP.Field            categoryField         = RecipesList.Fields.GetByInternalNameOrTitle("Category");
            SP.FieldMultiChoice categoryFieldChoice   = Context.CastTo <SP.FieldMultiChoice>(categoryField);

            Context.Load(difficultyFieldChoice, d => d.Choices);
            Context.Load(categoryFieldChoice, c => c.Choices);
            Context.ExecuteQuery();

            // init combo box items
            foreach (string choice in difficultyFieldChoice.Choices)
            {
                DifficultyComboBox.Items.Add(choice);
            }

            // init checked list box items
            foreach (string choice in categoryFieldChoice.Choices)
            {
                CategoryCheckedListBox.Items.Add(choice);
            }
        }
 public SP.FieldLookupValue[] GetSelectedValues(SPListItem listItem, SP.Field field)
 {
     if (listItem == null)
     {
         return(new SP.FieldLookupValue[0]);
     }
     return((SP.FieldLookupValue[])listItem.Value(field.InternalName));
 }
Пример #9
0
        public string TypeOf(SP.Field field)
        {
            //"TaxonomyFieldTypeMulti"
            //"TaxonomyFieldType"
            string fieldType = GetType(field.SchemaXml);

            return(fieldType);
        }
        public Dictionary <string, string> GetChoices(SP.Field field)
        {
            var fieldChoice = field as SP.FieldMultiChoice;
            Dictionary <string, string> result = new Dictionary <string, string>();

            foreach (string item in fieldChoice.Choices)
            {
                result.Add(item, item);
            }
            return(result);
        }
        private string GetFieldValueAsText(Web web, ListItem listItem, Microsoft.SharePoint.Client.Field field)
        {
            var rawValue = listItem[field.InternalName];

            if (rawValue == null)
            {
                return(null);
            }

            switch (field.FieldTypeKind)
            {
            case FieldType.Geolocation:
                var geoValue = (FieldGeolocationValue)rawValue;
                return($"{geoValue.Altitude},{geoValue.Latitude},{geoValue.Longitude},{geoValue.Measure}");

            case FieldType.URL:
                var urlValue = (FieldUrlValue)rawValue;
                return($"{urlValue.Url},{urlValue.Description}");

            case FieldType.Lookup:
                var strVal = rawValue as string;
                if (strVal != null)
                {
                    return(strVal);
                }
                var singleLookupValue = rawValue as FieldLookupValue;
                if (singleLookupValue != null)
                {
                    return(singleLookupValue.LookupId.ToString());
                }
                var multipleLookupValue = rawValue as FieldLookupValue[];
                if (multipleLookupValue != null)
                {
                    return(string.Join(",", multipleLookupValue.Select(lv => lv.LookupId)));
                }
                throw new Exception("Invalid data in field");

            case FieldType.User:
                var singleUserValue = rawValue as FieldUserValue;
                if (singleUserValue != null)
                {
                    return(GetLoginName(web, singleUserValue.LookupId));
                }
                var multipleUserValue = rawValue as FieldUserValue[];
                if (multipleUserValue != null)
                {
                    return(string.Join(",", multipleUserValue.Select(lv => GetLoginName(web, lv.LookupId))));
                }
                throw new Exception("Invalid data in field");

            default:
                return(Convert.ToString(rawValue));
            }
        }
Пример #12
0
        private void fieldtest()
        {
            List lstDocs = ctx.Web.Lists.GetByTitle("Documents");
            Microsoft.SharePoint.Client.Field fld = lstDocs.Fields.GetByInternalNameOrTitle("Title");
            ctx.Load(lstDocs);
            ctx.Load(fld);
            ctx.ExecuteQuery();
            fld.SetProperty("securedTo", "John");
            ctx.ExecuteQuery();


            
        }
Пример #13
0
        /// <summary>
        /// Replace Field Internal name by Display Name in the Validation formula
        /// (due to a SP issue that when provisioning the field, is expecting the Display name)
        /// https://github.com/SharePoint/PnP-Sites-Core/issues/849
        /// </summary>
        /// <param name="field"></param>
        /// <param name="schemaXml"></param>
        /// <returns></returns>
        internal static string TokenizeFieldValidationFormula(SPField field, string schemaXml)
        {
            var schemaElement = XElement.Parse(field.SchemaXml);

            var validationNode = schemaElement.Elements("Validation").FirstOrDefault();

            if (validationNode != null)
            {
                var validationNodeValue = validationNode.Value;
                validationNode.Value = validationNodeValue.Replace(field.InternalName, string.Format("[{0}]", field.Title));
            }

            return(schemaElement.ToString());
        }
Пример #14
0
        public bool IsOwnValue(SP.Field field, string valueAsText)
        {
            var fieldChoice = field as SP.FieldChoice;

            if (!fieldChoice.FillInChoice || string.IsNullOrEmpty(valueAsText))
            {
                return(false);
            }
            foreach (string key in fieldChoice.Choices)
            {
                if (key == valueAsText)
                {
                    return(false);
                }
            }
            return(true);
        }
Пример #15
0
        public static TaxonomyFieldValue GetTaxonomyFieldValue(string termName, Microsoft.SharePoint.Client.Field mmField, ClientContext clientContext)
        {
            //Cast field to TaxonomyField to get its TermSetId
            TaxonomyField taxField = clientContext.CastTo <TaxonomyField>(mmField);
            //Get term ID from name and term set ID
            string termId = GetTermIdForTerm(termName, taxField.TermSetId, clientContext);

            if (!string.IsNullOrEmpty(termId))
            {
                //Set TaxonomyFieldValue
                TaxonomyFieldValue termValue = new TaxonomyFieldValue();
                termValue.Label    = termName;
                termValue.TermGuid = termId;
                termValue.WssId    = -1;
                return(termValue);
            }
            return(null);
        }
        public bool IsSelected(SPListItem listItem, SP.Field field, string value)
        {
            if (listItem == null)
            {
                return(false);
            }
            object obj = listItem.Value(field.InternalName);

            if (obj == null)
            {
                return(false);
            }
            SP.FieldLookupValue lookupVal = obj as SP.FieldLookupValue;
            if (lookupVal == null)
            {
                return(false);
            }
            return(lookupVal.LookupId.ToString() == value);
        }
Пример #17
0
        static void Main(string[] args)
        {
            SGMLHelper s = new SGMLHelper();

            s.StoreFolder = "c:\\Foo";

            string action = args[0].ToLower();

            if (action == "file")
            {
                s.ReadSingleFile(args[1]);
            }
            else if (action == "folder")
            {
                s.ReadSingleFolder(args[1]);
            }
            else if (action == "setupsp")
            {
                SharePointHelper             sh   = null;
                System.Net.NetworkCredential cred = null;
                if (args.Length > 2)
                {
                    cred = new System.Net.NetworkCredential(args[2], args[3]);
                    sh   = new SharePointHelper(args[1], cred);
                }
                else
                {
                    sh = new SharePointHelper(args[1]);
                }

                sh.DeleteDocumentLibrary("Reuter");
                List      list  = sh.CreateDocumentLibrary("Reuter", "ReuterFiles");
                TermGroup group = sh.CreateGroup(sh.GetTermStore(), "MachineLearning");
                TermSet   set   = sh.CreateTermSet(group, "MachineLearning");
                sh.DeleteFieldIfExists("Topic");
                Microsoft.SharePoint.Client.Field taxField = sh.CreateTaxonomyField(sh.GetTermStore(), set, "Topic", "Topic", false, false);
                sh.AddTaxFieldToList(list, taxField, true);
            }
            else
            {
                PrintInfo();
            }
        }
 private void GetFilteredValues(List lookupList)
 {
     this.LookupValues.Clear();
     if (!string.IsNullOrEmpty(this.ParentFieldValue.DisplayValue))
     {
         string text = this.ParentFieldValue.DisplayValue;
         text = text.Substring(text.IndexOf('#') + 1, text.Length - text.IndexOf('#') - 1);
         Microsoft.SharePoint.Client.Field byInternalNameOrTitle  = lookupList.Fields.GetByInternalNameOrTitle(this._lookupColumn);
         Microsoft.SharePoint.Client.Field byInternalNameOrTitle2 = lookupList.Fields.GetByInternalNameOrTitle(this._filterColumn);
         this._ClientContext.Load <Microsoft.SharePoint.Client.Field>(byInternalNameOrTitle, new Expression <Func <Microsoft.SharePoint.Client.Field, object> > [0]);
         this._ClientContext.Load <Microsoft.SharePoint.Client.Field>(byInternalNameOrTitle2, new Expression <Func <Microsoft.SharePoint.Client.Field, object> > [0]);
         this._ClientContext.ExecuteQuery();
         ListItemCollection items = lookupList.GetItems(new CamlQuery
         {
             ViewXml = string.Concat(new string[]
             {
                 "<View> <Query> <Where> <Eq> <FieldRef Name='",
                 this._filterColumn,
                 "' /> <Value Type='Text'>",
                 text,
                 "</Value> </Eq> </Where> </Query> </View>"
             })
         });
         this._ClientContext.Load <ListItemCollection>(items, new Expression <Func <ListItemCollection, object> >[]
         {
             (ListItemCollection li) => li.ListItemCollectionPosition,
             (ListItemCollection li) => li.IncludeWithDefaultProperties(new Expression <Func <ListItem, object> >[]
             {
                 (ListItem it) => it.DisplayName,
                 (ListItem it) => it.FieldValuesAsText,
                 (ListItem it) => it[this._lookupColumn],
                 (ListItem it) => it[this._filterColumn],
                 (ListItem it) => (object)it.Id
             })
         });
         this._ClientContext.ExecuteQuery();
         foreach (ListItem current in (IEnumerable <ListItem>)items)
         {
             this.LookupValues.Add(new FilteredLookupItem(current.Id.ToString(), Convert.ToString(current[this._lookupColumn])));
         }
     }
 }
Пример #19
0
        private static void ProcessField(Field field, Guid listGuid, string webId)
        {
            var isDirty = false;

            var existingFieldElement = XElement.Parse(field.SchemaXml);

            isDirty = UpdateFieldAttribute(existingFieldElement, "List", listGuid.ToString(), false);

            isDirty = UpdateFieldAttribute(existingFieldElement, "WebId", webId, isDirty);

            isDirty = UpdateFieldAttribute(existingFieldElement, "SourceID", webId, isDirty);

            if (isDirty)
            {
                field.SchemaXml = existingFieldElement.ToString();

                field.UpdateAndPushChanges(true);
                field.Context.ExecuteQueryRetry();
            }
        }
Пример #20
0
        private static void ProcessField(Field field, Guid listGuid, string webId)
        {
            var isDirty = false;

            var existingFieldElement = XElement.Parse(field.SchemaXml);

            isDirty = UpdateFieldAttribute(existingFieldElement, "List", listGuid.ToString(), false);

            isDirty = UpdateFieldAttribute(existingFieldElement, "WebId", webId, isDirty);

            isDirty = UpdateFieldAttribute(existingFieldElement, "SourceID", webId, isDirty);

            if (isDirty)
            {
                field.SchemaXml = existingFieldElement.ToString();

                field.UpdateAndPushChanges(true);
                field.Context.ExecuteQueryRetry();
            }
        }
Пример #21
0
        private static void CreateFieldRef(ListInfo listInfo, Field field, FieldRef fieldRef)
        {
            XElement element = XElement.Parse(field.SchemaXml);

            element.SetAttributeValue("AllowDeletion", "TRUE");

            field.SchemaXml = element.ToString();

            var createdField = listInfo.SiteList.Fields.Add(field);

            if (!string.IsNullOrEmpty(fieldRef.DisplayName))
            {
                createdField.Title = fieldRef.DisplayName;
            }
            createdField.Hidden   = fieldRef.Hidden;
            createdField.Required = fieldRef.Required;

            createdField.Update();
            createdField.Context.ExecuteQueryRetry();
        }
Пример #22
0
        public Dictionary <string, string> GetChoices(SP.Field field)
        {
            var fieldChoice = field as SP.FieldChoice;
            Dictionary <string, string> result = new Dictionary <string, string>();

            if (!fieldChoice.Required)
            {
                if (fieldChoice.EditFormat == SP.ChoiceFormatType.Dropdown)
                {
                    result.Add(string.Empty, string.Empty);
                }
                else
                {
                    result.Add(string.Empty, "{Not selected}");
                }
            }
            foreach (string item in fieldChoice.Choices)
            {
                result.Add(item, item);
            }
            return(result);
        }
Пример #23
0
 /// <summary>
 /// Returns the REST endpoint for current field.
 /// </summary>
 /// <param name="field"></param>
 /// <example>http://server/site/_api/web/Fields</example>
 /// <example>http://server/site/_api/web/AvailableFields</example>
 /// <example>http://server/site/_api/web/AvailableFields(guid'56747800-d36e-4625-abe3-b1bc74a7d5f8')</example>
 /// <example>http://server/site/_api/web/lists(guid'81c57897-96ad-4b39-94d4-092be56d562d')/fields(guid'1d22ea11-1e32-424e-89ab-9fedbadb6ce1')</example>
 /// <returns></returns>
 public static Uri GetRestUrl(this SPClient.Field field, TreeNode selectedNode)
 {
     if (selectedNode.Parent.Parent.Tag is SPClient.Site)
     {
         SPClient.Site site = selectedNode.Parent.Parent.Tag as SPClient.Site;
         return(new Uri(string.Format("{0}/_api/Web/AvailableFields(guid'{1}')", site.RootWeb.GetUrl(), field.Id)));
     }
     else if (selectedNode.Parent.Parent.Tag is SPClient.Web)
     {
         SPClient.Web web = selectedNode.Parent.Parent.Tag as SPClient.Web;
         return(new Uri(string.Format("{0}/_api/Web/AvailableFields(guid'{1}')", web.GetUrl(), field.Id)));
     }
     else if (selectedNode.Parent.Parent.Tag is SPClient.List)
     {
         SPClient.List list = selectedNode.Parent.Parent.Tag as SPClient.List;
         return(new Uri(string.Format("{0}/_api/Web/Lists(guid'{1}')/Fields(guid'{2}')", list.ParentWeb.GetUrl(), list.Id, field.Id)));
     }
     else
     {
         return(null);
     }
 }
        private void GetLookupValues(List lookupList)
        {
            this.LookupValues.Clear();
            Microsoft.SharePoint.Client.Field byInternalNameOrTitle = lookupList.Fields.GetByInternalNameOrTitle(this._lookupColumn);
            this._ClientContext.Load <Microsoft.SharePoint.Client.Field>(byInternalNameOrTitle, new Expression <Func <Microsoft.SharePoint.Client.Field, object> > [0]);
            this._ClientContext.ExecuteQuery();
            ListItemCollection items = lookupList.GetItems(new CamlQuery
            {
                ViewXml = "<View/>"
            });

            this._ClientContext.Load <ListItemCollection>(items, new Expression <Func <ListItemCollection, object> >[]
            {
                (ListItemCollection li) => li.ListItemCollectionPosition,
                (ListItemCollection li) => li.IncludeWithDefaultProperties(new Expression <Func <ListItem, object> >[]
                {
                    (ListItem it) => it.DisplayName,
                    (ListItem it) => it.FieldValuesAsText,
                    (ListItem it) => it[this._lookupColumn],
                    (ListItem it) => (object)it.Id
                })
            });
            this._ClientContext.ExecuteQuery();
            Dictionary <string, int> dictionary = new Dictionary <string, int>();

            foreach (ListItem current in (IEnumerable <ListItem>)items)
            {
                string text = Convert.ToString(current[this._lookupColumn]);
                if (!dictionary.Keys.Contains(text))
                {
                    dictionary.Add(text, current.Id);
                }
            }
            foreach (string current2 in dictionary.Keys)
            {
                this.LookupValues.Add(new FilteredLookupItem(dictionary[current2].ToString(), current2));
            }
        }
 public string GetOwnValue(SP.Field field, string valueAsText)
 {
     if (string.IsNullOrEmpty(valueAsText))
     {
         return(string.Empty);
     }
     string[] values = GetValues(valueAsText);
     foreach (string value in values)
     {
         bool isOwnValue = true;
         foreach (string choiceValue in GetChoices(field).Values)
         {
             if (choiceValue == value)
             {
                 isOwnValue = false;
             }
         }
         if (isOwnValue)
         {
             return(value);
         }
     }
     return(string.Empty);
 }
Пример #26
0
        public static void addNewRecord(DataRow dr, List targetList, ClientContext ctx)
        {
            //Instantiate dictionary to temporarily store field values
            Dictionary <string, object> itemFieldValues = new Dictionary <string, object>();

            foreach (DataColumn dc in dr.Table.Columns)
            {
                //Get site column that matches the property name
                //ASSUMPTION: Your property names match the internal names of the corresponding site columns
                Microsoft.SharePoint.Client.Field matchingField = targetList.Fields.GetByInternalNameOrTitle(dc.ColumnName);
                ctx.Load(matchingField);
                ctx.ExecuteQuery();

                //Switch on the field type
                switch (matchingField.FieldTypeKind)
                {
                case FieldType.DateTime:
                    try
                    {
                        DateTime date = DateTime.Parse(dr[dc].ToString());
                        itemFieldValues.Add(matchingField.InternalName, date);
                    }
                    catch (Exception ex)
                    {
                    }
                    break;

                case FieldType.User:
                    FieldUserValue userFieldValue = GetUserFieldValue(dr[dc].ToString(), ctx);
                    if (userFieldValue != null)
                    {
                        itemFieldValues.Add(matchingField.InternalName, userFieldValue);
                    }
                    else
                    {
                        throw new Exception("User field value could not be added: " + dr[dc].ToString());
                    }
                    break;

                case FieldType.Lookup:
                    var lookupField = ctx.CastTo <FieldLookup>(matchingField);
                    ctx.Load(lookupField);
                    ctx.ExecuteQuery();
                    FieldLookupValue lookupFieldValue = GetLookupFieldValue(dr[dc].ToString(),
                                                                            lookupField.LookupList, lookupField.LookupField,
                                                                            ctx);
                    if (lookupFieldValue != null)
                    {
                        itemFieldValues.Add(matchingField.InternalName, lookupFieldValue);
                    }
                    else
                    {
                        throw new Exception("Lookup field value could not be added: " + dr[dc].ToString());
                    }
                    break;

                case FieldType.Invalid:
                    switch (matchingField.TypeAsString)
                    {
                    case "TaxonomyFieldType":
                        TaxonomyFieldValue taxFieldValue = GetTaxonomyFieldValue(dr[dc].ToString(), matchingField, ctx);
                        if (taxFieldValue != null)
                        {
                            itemFieldValues.Add(matchingField.InternalName, taxFieldValue);
                        }
                        else
                        {
                            throw new Exception("Taxonomy field value could not be added: " + dr[dc].ToString());
                        }
                        break;

                    default:
                        //Code for publishing site columns not implemented
                        continue;
                    }
                    break;

                default:
                    itemFieldValues.Add(matchingField.InternalName, dr[dc]);
                    break;
                }
            }

            //Add new item to list
            ListItemCreationInformation creationInfo = new ListItemCreationInformation();
            ListItem oListItem = targetList.AddItem(creationInfo);

            foreach (KeyValuePair <string, object> itemFieldValue in itemFieldValues)
            {
                //Set each field value
                oListItem[itemFieldValue.Key] = itemFieldValue.Value;
            }
            //Persist changes
            oListItem.Update();
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine(oListItem["Title"].ToString() + " : Inserted!!");
            ctx.ExecuteQuery();
        }
Пример #27
0
 public ObjectFieldValueChoiceMulti(Field field, Web web)
     : base(field, web)
 {
 }
        private string GetFieldValueAsText(Web web, ListItem listItem, Microsoft.SharePoint.Client.Field field)
        {
            var rawValue = listItem[field.InternalName];

            if (rawValue == null)
            {
                return(null);
            }

            // Since the TaxonomyField is not in the FieldTypeKind enumeration below, a specific check is done here for this type
            if (field is TaxonomyField)
            {
                if (rawValue is TaxonomyFieldValueCollection)
                {
                    List <string> termIds = new List <string>();
                    foreach (var taxonomyValue in (TaxonomyFieldValueCollection)rawValue)
                    {
                        termIds.Add($"{taxonomyValue.TermGuid}");
                    }
                    return(String.Join(";", termIds));
                }
                else if (rawValue is TaxonomyFieldValue)
                {
                    return($"{((TaxonomyFieldValue)rawValue).TermGuid}");
                }
            }

            // Specific operations based on the type of field at hand
            switch (field.FieldTypeKind)
            {
            case FieldType.Geolocation:
                var geoValue = (FieldGeolocationValue)rawValue;
                return($"{geoValue.Altitude},{geoValue.Latitude},{geoValue.Longitude},{geoValue.Measure}");

            case FieldType.URL:
                var urlValue = (FieldUrlValue)rawValue;
                return($"{urlValue.Url},{urlValue.Description}");

            case FieldType.Lookup:
                var strVal = rawValue as string;
                if (strVal != null)
                {
                    return(strVal);
                }
                var singleLookupValue = rawValue as FieldLookupValue;
                if (singleLookupValue != null)
                {
                    return(singleLookupValue.LookupId.ToString());
                }
                var multipleLookupValue = rawValue as FieldLookupValue[];
                if (multipleLookupValue != null)
                {
                    return(string.Join(",", multipleLookupValue.Select(lv => lv.LookupId)));
                }
                throw new Exception("Invalid data in field");

            case FieldType.User:
                var singleUserValue = rawValue as FieldUserValue;
                if (singleUserValue != null)
                {
                    return(GetLoginName(web, singleUserValue.LookupId));
                }
                var multipleUserValue = rawValue as FieldUserValue[];
                if (multipleUserValue != null)
                {
                    return(string.Join(",", multipleUserValue.Select(lv => GetLoginName(web, lv.LookupId))));
                }
                throw new Exception("Invalid data in field");

            case FieldType.MultiChoice:
                var multipleChoiceValue = rawValue as string[];
                if (multipleChoiceValue != null)
                {
                    return(string.Join(";#", multipleChoiceValue));
                }
                return(Convert.ToString(rawValue));

            default:
                return(Convert.ToString(rawValue));
            }
        }
Пример #29
0
        private static Field CreateFieldRef(ListInfo listInfo, Field field, FieldRef fieldRef)
        {
            field.EnsureProperty(f => f.SchemaXmlWithResourceTokens);
            XElement element = XElement.Parse(field.SchemaXmlWithResourceTokens);

            element.SetAttributeValue("AllowDeletion", "TRUE");

            field.SchemaXml = element.ToString();

            var createdField = listInfo.SiteList.Fields.Add(field);

            createdField.Context.Load(createdField, cf => cf.Id, cf => cf.Title, cf => cf.Hidden, cf => cf.Required);
            createdField.Context.ExecuteQueryRetry();

            var isDirty = false;
            if (!string.IsNullOrEmpty(fieldRef.DisplayName) && createdField.Title != fieldRef.DisplayName)
            {
                createdField.Title = fieldRef.DisplayName;
                isDirty = true;
            }
            if (createdField.Hidden != fieldRef.Hidden)
            {
                createdField.Hidden = fieldRef.Hidden;
                isDirty = true;
            }
            if (createdField.Required != fieldRef.Required)
            {
                createdField.Required = fieldRef.Required;
                isDirty = true;
            }
            if (isDirty)
            {
                createdField.Update();
                createdField.Context.ExecuteQueryRetry();
            }

            return createdField;
        }
Пример #30
0
 public ObjectFieldValueUser(Field field, Web web)
     : base(field, web)
 {
 }
Пример #31
0
 public ObjectFieldValueBase(Field field, Web web)
 {
     this.Field = field;
     this.Web = web;
 }
        private void UpdateField(ClientObject web, ListInfo listInfo, Guid fieldId, XElement templateFieldElement, Field existingField, PnPMonitoredScope scope, TokenParser parser)
        {
            web.Context.Load(existingField, f => f.SchemaXml);
            web.Context.ExecuteQueryRetry();

            var existingFieldElement = XElement.Parse(existingField.SchemaXml);

            var equalityComparer = new XNodeEqualityComparer();

            // Is field different in template?
            if (equalityComparer.GetHashCode(existingFieldElement) != equalityComparer.GetHashCode(templateFieldElement))
            {
                // Is existing field of the same type?
                if (existingFieldElement.Attribute("Type").Value == templateFieldElement.Attribute("Type").Value)
                {
                    templateFieldElement = PrepareField(templateFieldElement);

                    foreach (var attribute in templateFieldElement.Attributes())
                    {
                        if (existingFieldElement.Attribute(attribute.Name) != null)
                        {
                            existingFieldElement.Attribute(attribute.Name).Value = attribute.Value;
                        }
                        else
                        {
                            existingFieldElement.Add(attribute);
                        }
                    }
                    foreach (var element in templateFieldElement.Elements())
                    {
                        if (existingFieldElement.Element(element.Name) != null)
                        {
                            existingFieldElement.Element(element.Name).Remove();
                        }
                        existingFieldElement.Add(element);
                    }

                    if (existingFieldElement.Attribute("Version") != null)
                    {
                        existingFieldElement.Attributes("Version").Remove();
                    }
                    existingField.SchemaXml = parser.ParseString(existingFieldElement.ToString(), "~sitecollection", "~site");
                    existingField.UpdateAndPushChanges(true);
                    web.Context.ExecuteQueryRetry();
                }
                else
                {
                    var fieldName = existingFieldElement.Attribute("Name") != null ? existingFieldElement.Attribute("Name").Value : existingFieldElement.Attribute("StaticName").Value;
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id);
                    WriteWarning(string.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id), ProvisioningMessageType.Warning);
                }
            }
        }
Пример #33
0
 public ObjectFieldValueDateTime(Field field, Web web)
     : base(field, web)
 {
 }
Пример #34
0
 public FieldValueProvider(Field field, Web web)
 {
     this.Field = field;
     this.Web = web;
 }
Пример #35
0
 public ObjectFieldValueGeolocation(Field field, Web web)
     : base(field, web)
 {
 }
Пример #36
0
        private static void ProcessField(Field field, List sourceList)
        {
            if (sourceList == null)
                return;

            sourceList.ParentWeb.Context.Load(sourceList.ParentWeb);
            sourceList.ParentWeb.Context.ExecuteQueryRetry();

            ProcessField(field, sourceList.Id, sourceList.ParentWeb.Id.ToString());
        }
Пример #37
0
 private bool CanFieldContentBeIncluded(Field field, bool serialize)
 {
     bool result = false;
     if (field.InternalName.Equals("ID", StringComparison.OrdinalIgnoreCase))
     {
         result = serialize;
     }
     else if (field.InternalName.Equals("ContentTypeId", StringComparison.OrdinalIgnoreCase) && this.List.ContentTypesEnabled)
     {
         result = true;
     }
     else if (field.InternalName.Equals("Attachments", StringComparison.OrdinalIgnoreCase))
     {
         return false;
     }
     else
     {
         if (!field.Hidden && !field.ReadOnlyField && (field.FieldTypeKind != FieldType.Computed))
         {
             //Temporary disabled for custom fields
             if (field.FieldTypeKind != FieldType.Invalid)
             {
                 result = true;
             }
         }
     }
     return result;
 }
Пример #38
0
 public ObjectFieldValueLookup(Field field, Web web)
     : base(field, web)
 {
 }
Пример #39
0
        private FieldValueProvider GetFieldValueProvider(Field field, Web web)
        {
            FieldValueProvider provider = null;

            if (null == m_dictFieldValueProviders)
            {
                m_dictFieldValueProviders = new Dictionary<string, FieldValueProvider>();
            }
            if (!m_dictFieldValueProviders.TryGetValue(field.InternalName, out provider))
            {
                provider = new FieldValueProvider(field, web);
                m_dictFieldValueProviders.Add(field.InternalName, provider);
            }

            return provider;
        }
Пример #40
0
 public ObjectFieldValueBoolean(Field field, Web web)
     : base(field, web)
 {
 }
Пример #41
0
        private static void ProcessField(Field field, Guid listGuid, string webId, string relationshipDeleteBehavior)
        {
            var isDirty = false;

            var existingFieldElement = XElement.Parse(field.SchemaXmlWithResourceTokens);

            isDirty = UpdateFieldAttribute(existingFieldElement, "List", listGuid.ToString(), false);

            isDirty = UpdateFieldAttribute(existingFieldElement, "WebId", webId, isDirty);

            isDirty = UpdateFieldAttribute(existingFieldElement, "SourceID", webId, isDirty);

            if (!string.IsNullOrEmpty(relationshipDeleteBehavior))
                isDirty = UpdateFieldAttribute(existingFieldElement, "RelationshipDeleteBehavior", relationshipDeleteBehavior, isDirty);

            if (isDirty)
            {
                field.SchemaXml = existingFieldElement.ToString();

                field.UpdateAndPushChanges(true);
                field.Context.ExecuteQueryRetry();
            }
        }
        private static Microsoft.SharePoint.Client.ContentType CreateContentType(Web web, ContentType templateContentType, TokenParser parser, FileConnectorBase connector,
                                                                                 List <Microsoft.SharePoint.Client.ContentType> existingCTs = null, List <Microsoft.SharePoint.Client.Field> existingFields = null)
        {
            var name        = parser.ParseString(templateContentType.Name);
            var description = parser.ParseString(templateContentType.Description);
            var id          = parser.ParseString(templateContentType.Id);
            var group       = parser.ParseString(templateContentType.Group);

            var createdCT = web.CreateContentType(name, description, id, group);

            foreach (var fieldRef in templateContentType.FieldRefs)
            {
                var field = web.Fields.GetById(fieldRef.Id);
                web.AddFieldToContentType(createdCT, field, fieldRef.Required, fieldRef.Hidden);
            }

            //Reorder the elements so that the new created Content Type has the same order as defined in the
            //template. The order can be different if the new Content Type inherits from another Content Type.
            //In this case the new Content Type has all field of the original Content Type and missing fields
            //will be added at the end. To fix this issue we ordering the fields once more.
            createdCT.FieldLinks.Reorder(templateContentType.FieldRefs.Select(fld => fld.Name).ToArray());
            createdCT.Update(true);
            web.Context.ExecuteQueryRetry();

            createdCT.ReadOnly = templateContentType.ReadOnly;
            createdCT.Hidden   = templateContentType.Hidden;
            createdCT.Sealed   = templateContentType.Sealed;
            if (!string.IsNullOrEmpty(parser.ParseString(templateContentType.DocumentTemplate)))
            {
                createdCT.DocumentTemplate = parser.ParseString(templateContentType.DocumentTemplate);
            }
            if (!String.IsNullOrEmpty(templateContentType.NewFormUrl))
            {
                createdCT.NewFormUrl = templateContentType.NewFormUrl;
            }
            if (!String.IsNullOrEmpty(templateContentType.EditFormUrl))
            {
                createdCT.EditFormUrl = templateContentType.EditFormUrl;
            }
            if (!String.IsNullOrEmpty(templateContentType.DisplayFormUrl))
            {
                createdCT.DisplayFormUrl = templateContentType.DisplayFormUrl;
            }

            // If the CT is a DocumentSet
            if (templateContentType.DocumentSetTemplate != null)
            {
                // Retrieve a reference to the DocumentSet Content Type
                Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate documentSetTemplate =
                    Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, createdCT);

                if (!String.IsNullOrEmpty(templateContentType.DocumentSetTemplate.WelcomePage))
                {
                    // TODO: Customize the WelcomePage of the DocumentSet
                }

                foreach (String ctId in templateContentType.DocumentSetTemplate.AllowedContentTypes)
                {
                    Microsoft.SharePoint.Client.ContentType ct = existingCTs.FirstOrDefault(c => c.StringId == ctId);
                    if (ct != null)
                    {
                        documentSetTemplate.AllowedContentTypes.Add(ct.Id);
                    }
                }

                foreach (var doc in templateContentType.DocumentSetTemplate.DefaultDocuments)
                {
                    Microsoft.SharePoint.Client.ContentType ct = existingCTs.FirstOrDefault(c => c.StringId == doc.ContentTypeId);
                    if (ct != null)
                    {
                        using (Stream fileStream = connector.GetFileStream(doc.FileSourcePath))
                        {
                            documentSetTemplate.DefaultDocuments.Add(doc.Name, ct.Id, ReadFullStream(fileStream));
                        }
                    }
                }

                foreach (var sharedField in templateContentType.DocumentSetTemplate.SharedFields)
                {
                    Microsoft.SharePoint.Client.Field field = existingFields.FirstOrDefault(f => f.Id == sharedField);
                    if (field != null)
                    {
                        documentSetTemplate.SharedFields.Add(field);
                    }
                }

                foreach (var welcomePageField in templateContentType.DocumentSetTemplate.WelcomePageFields)
                {
                    Microsoft.SharePoint.Client.Field field = existingFields.FirstOrDefault(f => f.Id == welcomePageField);
                    if (field != null)
                    {
                        documentSetTemplate.WelcomePageFields.Add(field);
                    }
                }

                documentSetTemplate.Update(true);
                web.Context.ExecuteQueryRetry();
            }

            web.Context.Load(createdCT);
            web.Context.ExecuteQueryRetry();

            return(createdCT);
        }
Пример #43
0
        private static void CreateFieldRef(ListInfo listInfo, Field field, FieldRef fieldRef)
        {
            XElement element = XElement.Parse(field.SchemaXml);

            element.SetAttributeValue("AllowDeletion", "TRUE");

            field.SchemaXml = element.ToString();

            var createdField = listInfo.SiteList.Fields.Add(field);
            if (!string.IsNullOrEmpty(fieldRef.DisplayName))
            {
                createdField.Title = fieldRef.DisplayName;
            }
            createdField.Hidden = fieldRef.Hidden;
            createdField.Required = fieldRef.Required;

            createdField.Update();
            createdField.Context.ExecuteQueryRetry();
        }
Пример #44
0
        public override TokenParser ProvisionObjects(Web web, ProvisioningTemplate template, TokenParser parser, ProvisioningTemplateApplyingInformation applyingInformation)
        {
            using (var scope = new PnPMonitoredScope(this.Name))
            {
                if (template.Lists.Any())
                {
                    var rootWeb = (web.Context as ClientContext).Site.RootWeb;

                    web.EnsureProperties(w => w.ServerRelativeUrl);

                    web.Context.Load(web.Lists, lc => lc.IncludeWithDefaultProperties(l => l.RootFolder.ServerRelativeUrl));
                    web.Context.ExecuteQueryRetry();
                    var existingLists     = web.Lists.AsEnumerable <List>().Select(existingList => existingList.RootFolder.ServerRelativeUrl).ToList();
                    var serverRelativeUrl = web.ServerRelativeUrl;

                    #region DataRows

                    foreach (var listInstance in template.Lists)
                    {
                        if (listInstance.DataRows != null && listInstance.DataRows.Any())
                        {
                            scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Processing_data_rows_for__0_, listInstance.Title);
                            // Retrieve the target list
                            var list = web.Lists.GetByTitle(parser.ParseString(listInstance.Title));
                            web.Context.Load(list);

                            // Retrieve the fields' types from the list
                            Microsoft.SharePoint.Client.FieldCollection fields = list.Fields;
                            web.Context.Load(fields, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.TypeAsString));
                            web.Context.ExecuteQueryRetry();

                            var keyColumnType   = "Text";
                            var parsedKeyColumn = parser.ParseString(listInstance.DataRows.KeyColumn);
                            if (!string.IsNullOrEmpty(parsedKeyColumn))
                            {
                                var keyColumn = fields.FirstOrDefault(f => f.InternalName.Equals(parsedKeyColumn, StringComparison.InvariantCultureIgnoreCase));
                                if (keyColumn != null)
                                {
                                    switch (keyColumn.FieldTypeKind)
                                    {
                                    case FieldType.User:
                                    case FieldType.Lookup:
                                        keyColumnType = "Lookup";
                                        break;

                                    case FieldType.URL:
                                        keyColumnType = "Url";
                                        break;

                                    case FieldType.DateTime:
                                        keyColumnType = "DateTime";
                                        break;

                                    case FieldType.Number:
                                    case FieldType.Counter:
                                        keyColumnType = "Number";
                                        break;
                                    }
                                }
                            }

                            foreach (var dataRow in listInstance.DataRows)
                            {
                                try
                                {
                                    scope.LogDebug(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_list_item__0_, listInstance.DataRows.IndexOf(dataRow) + 1);


                                    bool     create   = true;
                                    ListItem listitem = null;
                                    if (!string.IsNullOrEmpty(listInstance.DataRows.KeyColumn))
                                    {
                                        // Get value from key column
                                        var dataRowValues = dataRow.Values.Where(v => v.Key == listInstance.DataRows.KeyColumn);

                                        // if it is empty, skip the check
                                        if (dataRowValues.Any())
                                        {
                                            var query     = $@"<View><Query><Where><Eq><FieldRef Name=""{parsedKeyColumn}""/><Value Type=""{keyColumnType}"">{dataRowValues.FirstOrDefault().Value}</Value></Eq></Where></Query><RowLimit>1</RowLimit></View>";
                                            var camlQuery = new CamlQuery()
                                            {
                                                ViewXml = query
                                            };
                                            var existingItems = list.GetItems(camlQuery);
                                            list.Context.Load(existingItems);
                                            list.Context.ExecuteQueryRetry();
                                            if (existingItems.Count > 0)
                                            {
                                                if (listInstance.DataRows.UpdateBehavior == UpdateBehavior.Skip)
                                                {
                                                    create = false;
                                                }
                                                else
                                                {
                                                    listitem = existingItems[0];
                                                    create   = true;
                                                }
                                            }
                                        }
                                    }

                                    if (create)
                                    {
                                        if (listitem == null)
                                        {
                                            var listitemCI = new ListItemCreationInformation();
                                            listitem = list.AddItem(listitemCI);
                                        }

                                        foreach (var dataValue in dataRow.Values)
                                        {
                                            Field dataField = fields.FirstOrDefault(
                                                f => f.InternalName == parser.ParseString(dataValue.Key));

                                            if (dataField != null)
                                            {
                                                String fieldValue = parser.ParseString(dataValue.Value);

                                                switch (dataField.FieldTypeKind)
                                                {
                                                case FieldType.Geolocation:
                                                    // FieldGeolocationValue - Expected format: Altitude,Latitude,Longitude,Measure
                                                    var geolocationArray = fieldValue.Split(',');
                                                    if (geolocationArray.Length == 4)
                                                    {
                                                        var geolocationValue = new FieldGeolocationValue
                                                        {
                                                            Altitude  = Double.Parse(geolocationArray[0]),
                                                            Latitude  = Double.Parse(geolocationArray[1]),
                                                            Longitude = Double.Parse(geolocationArray[2]),
                                                            Measure   = Double.Parse(geolocationArray[3]),
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = geolocationValue;
                                                    }
                                                    else
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    }
                                                    break;

                                                case FieldType.Lookup:
                                                    // FieldLookupValue - Expected format: LookupID or LookupID,LookupID,LookupID...
                                                    if (fieldValue.Contains(","))
                                                    {
                                                        var lookupValues = new List <FieldLookupValue>();
                                                        fieldValue.Split(',').All(value =>
                                                        {
                                                            lookupValues.Add(new FieldLookupValue
                                                            {
                                                                LookupId = int.Parse(value),
                                                            });
                                                            return(true);
                                                        });
                                                        listitem[parser.ParseString(dataValue.Key)] = lookupValues.ToArray();
                                                    }
                                                    else
                                                    {
                                                        var lookupValue = new FieldLookupValue
                                                        {
                                                            LookupId = int.Parse(fieldValue),
                                                        };
                                                        listitem[parser.ParseString(dataValue.Key)] = lookupValue;
                                                    }
                                                    break;

                                                case FieldType.URL:
                                                    // FieldUrlValue - Expected format: URL,Description
                                                    var urlArray  = fieldValue.Split(',');
                                                    var linkValue = new FieldUrlValue();
                                                    if (urlArray.Length == 2)
                                                    {
                                                        linkValue.Url         = urlArray[0];
                                                        linkValue.Description = urlArray[1];
                                                    }
                                                    else
                                                    {
                                                        linkValue.Url         = urlArray[0];
                                                        linkValue.Description = urlArray[0];
                                                    }
                                                    listitem[parser.ParseString(dataValue.Key)] = linkValue;
                                                    break;

                                                case FieldType.User:
                                                    // FieldUserValue - Expected format: loginName or loginName,loginName,loginName...
                                                    if (fieldValue.Contains(","))
                                                    {
                                                        var userValues = new List <FieldUserValue>();
                                                        fieldValue.Split(',').All(value =>
                                                        {
                                                            var user = web.EnsureUser(value);
                                                            web.Context.Load(user);
                                                            web.Context.ExecuteQueryRetry();
                                                            if (user != null)
                                                            {
                                                                userValues.Add(new FieldUserValue
                                                                {
                                                                    LookupId = user.Id,
                                                                });;
                                                            }
                                                            return(true);
                                                        });
                                                        listitem[parser.ParseString(dataValue.Key)] = userValues.ToArray();
                                                    }
                                                    else
                                                    {
                                                        var user = web.EnsureUser(fieldValue);
                                                        web.Context.Load(user);
                                                        web.Context.ExecuteQueryRetry();
                                                        if (user != null)
                                                        {
                                                            var userValue = new FieldUserValue
                                                            {
                                                                LookupId = user.Id,
                                                            };
                                                            listitem[parser.ParseString(dataValue.Key)] = userValue;
                                                        }
                                                        else
                                                        {
                                                            listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                        }
                                                    }
                                                    break;

                                                case FieldType.DateTime:
                                                    var dateTime = DateTime.MinValue;
                                                    if (DateTime.TryParse(fieldValue, out dateTime))
                                                    {
                                                        listitem[parser.ParseString(dataValue.Key)] = dateTime;
                                                    }
                                                    break;

                                                default:
                                                    listitem[parser.ParseString(dataValue.Key)] = fieldValue;
                                                    break;
                                                }
                                                listitem.Update();
                                            }
                                        }
                                        web.Context.ExecuteQueryRetry(); // TODO: Run in batches?

                                        if (dataRow.Security != null && (dataRow.Security.ClearSubscopes == true || dataRow.Security.CopyRoleAssignments == true || dataRow.Security.RoleAssignments.Count > 0))
                                        {
                                            listitem.SetSecurity(parser, dataRow.Security);
                                        }
                                    }
                                }
                                catch (Exception ex)
                                {
                                    if (ex.GetType().Equals(typeof(ServerException)) &&
                                        (ex as ServerException).ServerErrorTypeName.Equals("Microsoft.SharePoint.SPDuplicateValuesFoundException", StringComparison.InvariantCultureIgnoreCase) &&
                                        applyingInformation.IgnoreDuplicateDataRowErrors)
                                    {
                                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_duplicate);
                                        continue;
                                    }
                                    else
                                    {
                                        scope.LogError(CoreResources.Provisioning_ObjectHandlers_ListInstancesDataRows_Creating_listitem_failed___0_____1_, ex.Message, ex.StackTrace);
                                        throw;
                                    }
                                }
                            }
                        }
                    }

                    #endregion
                }
            }

            return(parser);
        }
Пример #45
0
        private static Microsoft.SharePoint.Client.ContentType CreateContentType(Web web, ContentType templateContentType, TokenParser parser, FileConnectorBase connector, PnPMonitoredScope scope,
                                                                                 List <Microsoft.SharePoint.Client.ContentType> existingCTs = null, List <Microsoft.SharePoint.Client.Field> existingFields = null, bool isNoScriptSite = false)
        {
            var name        = parser.ParseString(templateContentType.Name);
            var description = parser.ParseString(templateContentType.Description);
            var id          = parser.ParseString(templateContentType.Id);
            var group       = parser.ParseString(templateContentType.Group);

            var createdCT = web.CreateContentType(name, description, id, group);

            foreach (var fieldRef in templateContentType.FieldRefs)
            {
                Microsoft.SharePoint.Client.Field field = null;
                try
                {
                    field = web.AvailableFields.GetById(fieldRef.Id);
                }
                catch (ArgumentException)
                {
                    if (!string.IsNullOrEmpty(fieldRef.Name))
                    {
                        field = web.AvailableFields.GetByInternalNameOrTitle(fieldRef.Name);
                    }
                }
                // Add it to the target content type
                // Notice that this code will fail if the field does not exist
                web.AddFieldToContentType(createdCT, field, fieldRef.Required, fieldRef.Hidden);
            }

            // Add new CTs
            parser.AddToken(new ContentTypeIdToken(web, name, id));

#if !ONPREMISES
            // Set resources
            if (templateContentType.Name.ContainsResourceToken())
            {
                createdCT.NameResource.SetUserResourceValue(templateContentType.Name, parser);
            }
            if (templateContentType.Description.ContainsResourceToken())
            {
                createdCT.DescriptionResource.SetUserResourceValue(templateContentType.Description, parser);
            }
#endif
            //Reorder the elements so that the new created Content Type has the same order as defined in the
            //template. The order can be different if the new Content Type inherits from another Content Type.
            //In this case the new Content Type has all field of the original Content Type and missing fields
            //will be added at the end. To fix this issue we ordering the fields once more.

            createdCT.FieldLinks.Reorder(templateContentType.FieldRefs.Select(fld => parser.ParseString(fld.Name)).ToArray());

            createdCT.ReadOnly = templateContentType.ReadOnly;
            createdCT.Hidden   = templateContentType.Hidden;
            createdCT.Sealed   = templateContentType.Sealed;

            if (templateContentType.DocumentSetTemplate == null)
            {
                // Only apply a document template when the contenttype is not a document set
                if (!string.IsNullOrEmpty(parser.ParseString(templateContentType.DocumentTemplate)))
                {
                    createdCT.DocumentTemplate = parser.ParseString(templateContentType.DocumentTemplate);
                }
            }

            // Skipping updates of forms as we can't upload forms to noscript sites
            if (!isNoScriptSite)
            {
                if (!string.IsNullOrEmpty(parser.ParseString(templateContentType.NewFormUrl)))
                {
                    createdCT.NewFormUrl = parser.ParseString(templateContentType.NewFormUrl);
                }
                if (!string.IsNullOrEmpty(parser.ParseString(templateContentType.EditFormUrl)))
                {
                    createdCT.EditFormUrl = parser.ParseString(templateContentType.EditFormUrl);
                }
                if (!string.IsNullOrEmpty(parser.ParseString(templateContentType.DisplayFormUrl)))
                {
                    createdCT.DisplayFormUrl = parser.ParseString(templateContentType.DisplayFormUrl);
                }
            }
            else
            {
                if (!string.IsNullOrEmpty(parser.ParseString(templateContentType.DisplayFormUrl)) ||
                    !string.IsNullOrEmpty(parser.ParseString(templateContentType.EditFormUrl)) ||
                    !string.IsNullOrEmpty(parser.ParseString(templateContentType.NewFormUrl)))
                {
                    // log message
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ContentTypes_SkipCustomFormUrls, name);
                }
            }

            createdCT.Update(true);
            web.Context.ExecuteQueryRetry();

            // If the CT is a DocumentSet
            if (templateContentType.DocumentSetTemplate != null)
            {
                // Retrieve a reference to the DocumentSet Content Type
                Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate documentSetTemplate =
                    Microsoft.SharePoint.Client.DocumentSet.DocumentSetTemplate.GetDocumentSetTemplate(web.Context, createdCT);

                // Load the collections to allow for deletion scenarions
                web.Context.Load(documentSetTemplate, d => d.AllowedContentTypes, d => d.DefaultDocuments, d => d.SharedFields, d => d.WelcomePageFields);
                web.Context.ExecuteQueryRetry();

                if (!String.IsNullOrEmpty(templateContentType.DocumentSetTemplate.WelcomePage))
                {
                    // TODO: Customize the WelcomePage of the DocumentSet
                }

                // Add additional content types to the set of allowed content types
                bool hasDefaultDocumentContentTypeInTemplate = false;
                foreach (String ctId in templateContentType.DocumentSetTemplate.AllowedContentTypes)
                {
                    Microsoft.SharePoint.Client.ContentType ct = existingCTs.FirstOrDefault(c => c.StringId == ctId);
                    if (ct != null)
                    {
                        if (ct.Id.StringValue.Equals("0x0101", StringComparison.InvariantCultureIgnoreCase))
                        {
                            hasDefaultDocumentContentTypeInTemplate = true;
                        }

                        documentSetTemplate.AllowedContentTypes.Add(ct.Id);
                    }
                }
                // If the default document content type (0x0101) is not in our definition then remove it
                if (!hasDefaultDocumentContentTypeInTemplate)
                {
                    Microsoft.SharePoint.Client.ContentType ct = existingCTs.FirstOrDefault(c => c.StringId == "0x0101");
                    if (ct != null)
                    {
                        documentSetTemplate.AllowedContentTypes.Remove(ct.Id);
                    }
                }

                if (!isNoScriptSite)
                {
                    foreach (var doc in templateContentType.DocumentSetTemplate.DefaultDocuments)
                    {
                        Microsoft.SharePoint.Client.ContentType ct = existingCTs.FirstOrDefault(c => c.StringId == doc.ContentTypeId);
                        if (ct != null)
                        {
                            using (Stream fileStream = connector.GetFileStream(doc.FileSourcePath))
                            {
                                documentSetTemplate.DefaultDocuments.Add(doc.Name, ct.Id, ReadFullStream(fileStream));
                            }
                        }
                    }
                }
                else
                {
                    if (templateContentType.DocumentSetTemplate.DefaultDocuments.Any())
                    {
                        scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ContentTypes_SkipDocumentSetDefaultDocuments, name);
                    }
                }

                foreach (var sharedField in templateContentType.DocumentSetTemplate.SharedFields)
                {
                    Microsoft.SharePoint.Client.Field field = existingFields.FirstOrDefault(f => f.Id == sharedField);
                    if (field != null)
                    {
                        documentSetTemplate.SharedFields.Add(field);
                    }
                }

                foreach (var welcomePageField in templateContentType.DocumentSetTemplate.WelcomePageFields)
                {
                    Microsoft.SharePoint.Client.Field field = existingFields.FirstOrDefault(f => f.Id == welcomePageField);
                    if (field != null)
                    {
                        documentSetTemplate.WelcomePageFields.Add(field);
                    }
                }

                documentSetTemplate.Update(true);
                web.Context.ExecuteQueryRetry();
            }

            web.Context.Load(createdCT);
            web.Context.ExecuteQueryRetry();

            return(createdCT);
        }
Пример #46
0
        private Field UpdateField(ClientObject web, ListInfo listInfo, Guid fieldId, XElement templateFieldElement, Field existingField, PnPMonitoredScope scope, TokenParser parser, string originalFieldXml)
        {
            Field field = null;
            web.Context.Load(existingField, f => f.SchemaXmlWithResourceTokens);
            web.Context.ExecuteQueryRetry();

            var existingFieldElement = XElement.Parse(existingField.SchemaXmlWithResourceTokens);

            var equalityComparer = new XNodeEqualityComparer();

            // Is field different in template?
            if (equalityComparer.GetHashCode(existingFieldElement) != equalityComparer.GetHashCode(templateFieldElement))
            {
                // Is existing field of the same type?
                if (existingFieldElement.Attribute("Type").Value == templateFieldElement.Attribute("Type").Value)
                {
                    templateFieldElement = PrepareField(templateFieldElement);
                    if (IsFieldXmlValid(parser.ParseString(templateFieldElement.ToString()), parser, web.Context))
                    {
                        foreach (var attribute in templateFieldElement.Attributes())
                        {
                            if (existingFieldElement.Attribute(attribute.Name) != null)
                            {
                                existingFieldElement.Attribute(attribute.Name).Value = attribute.Value;
                            }
                            else
                            {
                                existingFieldElement.Add(attribute);
                            }
                        }
                        foreach (var element in templateFieldElement.Elements())
                        {
                            if (existingFieldElement.Element(element.Name) != null)
                            {
                                existingFieldElement.Element(element.Name).Remove();
                            }
                            existingFieldElement.Add(element);
                        }

                        if (existingFieldElement.Attribute("Version") != null)
                        {
                            existingFieldElement.Attributes("Version").Remove();
                        }
                        existingField.SchemaXml = parser.ParseString(existingFieldElement.ToString(), "~sitecollection", "~site");
                        existingField.UpdateAndPushChanges(true);
                        web.Context.ExecuteQueryRetry();
                        bool isDirty = false;
            #if !SP2013
                        if (originalFieldXml.ContainsResourceToken())
                        {
                            var originalFieldElement = XElement.Parse(originalFieldXml);
                            var nameAttributeValue = originalFieldElement.Attribute("DisplayName") != null ? originalFieldElement.Attribute("DisplayName").Value : "";
                            if (nameAttributeValue.ContainsResourceToken())
                            {
                                if (existingField.TitleResource.SetUserResourceValue(nameAttributeValue, parser))
                                {
                                    isDirty = true;
                                }
                            }
                            var descriptionAttributeValue = originalFieldElement.Attribute("Description") != null ? originalFieldElement.Attribute("Description").Value : "";
                            if (descriptionAttributeValue.ContainsResourceToken())
                            {
                                if (existingField.DescriptionResource.SetUserResourceValue(descriptionAttributeValue, parser))
                                {
                                    isDirty = true;
                                }
                            }
                        }
            #endif
                        if (isDirty)
                        {
                            existingField.Update();
                            web.Context.ExecuteQueryRetry();
                            field = existingField;
                        }
                    }
                    else
                    {
                        // The field Xml was found invalid
                        var tokenString = parser.GetLeftOverTokens(originalFieldXml).Aggregate(String.Empty, (acc, i) => acc + " " + i);
                        scope.LogError("The field was found invalid: {0}", tokenString);
                        throw new Exception(string.Format("The field was found invalid: {0}", tokenString));
                    }
                }
                else
                {
                    var fieldName = existingFieldElement.Attribute("Name") != null ? existingFieldElement.Attribute("Name").Value : existingFieldElement.Attribute("StaticName").Value;
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id);
                    WriteWarning(string.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id), ProvisioningMessageType.Warning);
                }
            }
            return field;
        }
Пример #47
0
 public ObjectFieldValueContentTypeId(Field field, Web web)
     : base(field, web)
 {
 }
Пример #48
0
        protected override void ExecuteCmdlet()
        {
            if (!System.IO.Path.IsPathRooted(Path))
            {
                Path = System.IO.Path.Combine(SessionState.Path.CurrentFileSystemLocation.Path, Path);
            }

            var template = ReadSiteTemplate
                           .LoadSiteTemplateFromFile(Path,
                                                     TemplateProviderExtensions, (e) =>
            {
                WriteError(new ErrorRecord(e, "TEMPLATENOTVALID", ErrorCategory.SyntaxError, null));
            });

            if (template == null)
            {
                throw new ApplicationException("Invalid template file!");
            }
            //We will remove a list if it's found so we can get the list

            ListInstance listInstance = template.Lists.Find(l => l.Title == List.Title);

            if (listInstance == null)
            {
                throw new ApplicationException("List does not exist in the template file!");
            }

            List spList = List.GetList(SelectedWeb);

            ClientContext.Load(spList, l => l.RootFolder, l => l.HasUniqueRoleAssignments);
            ClientContext.ExecuteQueryRetry();

            if (TokenizeUrls.IsPresent)
            {
                ClientContext.Load(ClientContext.Web, w => w.Url, w => w.ServerRelativeUrl, w => w.Id);
                ClientContext.Load(ClientContext.Site, s => s.Url, s => s.ServerRelativeUrl, s => s.Id);
                ClientContext.Load(ClientContext.Web.Lists, lists => lists.Include(l => l.Title, l => l.RootFolder.ServerRelativeUrl));
            }

            CamlQuery query = new CamlQuery();

            var viewFieldsStringBuilder = new StringBuilder();

            if (Fields != null)
            {
                viewFieldsStringBuilder.Append("<ViewFields>");
                foreach (var field in Fields)
                {
                    viewFieldsStringBuilder.AppendFormat("<FieldRef Name='{0}'/>", field);
                }
                viewFieldsStringBuilder.Append("</ViewFields>");
            }

            query.ViewXml = string.Format("<View>{0}{1}</View>", Query, viewFieldsStringBuilder);
            var listItems = spList.GetItems(query);

            ClientContext.Load(listItems, lI => lI.Include(l => l.HasUniqueRoleAssignments, l => l.ContentType.StringId));
            ClientContext.ExecuteQueryRetry();

            Microsoft.SharePoint.Client.FieldCollection fieldCollection = spList.Fields;
            ClientContext.Load(fieldCollection, fs => fs.Include(f => f.InternalName, f => f.FieldTypeKind, f => f.ReadOnlyField));
            ClientContext.ExecuteQueryRetry();

            var rows = new DataRowCollection(template);

            foreach (var listItem in listItems)
            {
                //Make sure we don't pull Folders.. Of course this won't work
                if (listItem.ServerObjectIsNull == false)
                {
                    ClientContext.Load(listItem);
                    ClientContext.ExecuteQueryRetry();
                    if (!(listItem.FileSystemObjectType == FileSystemObjectType.Folder))
                    {
                        DataRow row = new DataRow();
                        if (IncludeSecurity && listItem.HasUniqueRoleAssignments)
                        {
                            row.Security.ClearSubscopes      = true;
                            row.Security.CopyRoleAssignments = false;

                            var roleAssignments = listItem.RoleAssignments;
                            ClientContext.Load(roleAssignments);
                            ClientContext.ExecuteQueryRetry();

                            ClientContext.Load(roleAssignments, r => r.Include(a => a.Member.LoginName, a => a.Member, a => a.RoleDefinitionBindings));
                            ClientContext.ExecuteQueryRetry();

                            foreach (var roleAssignment in roleAssignments)
                            {
                                var principalName = roleAssignment.Member.LoginName;
                                var roleBindings  = roleAssignment.RoleDefinitionBindings;
                                foreach (var roleBinding in roleBindings)
                                {
                                    row.Security.RoleAssignments.Add(new PnP.Framework.Provisioning.Model.RoleAssignment()
                                    {
                                        Principal = principalName, RoleDefinition = roleBinding.Name
                                    });
                                }
                            }
                        }
                        if (Fields != null)
                        {
                            foreach (var fieldName in Fields)
                            {
                                Microsoft.SharePoint.Client.Field dataField = fieldCollection.FirstOrDefault(f => f.InternalName == fieldName);

                                if (dataField != null)
                                {
                                    var defaultFieldValue = GetFieldValueAsText(ClientContext.Web, listItem, dataField);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        defaultFieldValue = Tokenize(defaultFieldValue, ClientContext.Web, ClientContext.Site);
                                    }

                                    row.Values.Add(fieldName, defaultFieldValue);
                                }
                            }
                        }
                        else
                        {
                            //All fields are added except readonly fields and unsupported field type
                            var fieldsToExport = fieldCollection.AsEnumerable()
                                                 .Where(f => !f.ReadOnlyField && !_unsupportedFieldTypes.Contains(f.FieldTypeKind));
                            foreach (var field in fieldsToExport)
                            {
                                var fldKey = (from f in listItem.FieldValues.Keys where f == field.InternalName select f).FirstOrDefault();
                                if (!string.IsNullOrEmpty(fldKey))
                                {
                                    var fieldValue = GetFieldValueAsText(ClientContext.Web, listItem, field);
                                    if (TokenizeUrls.IsPresent)
                                    {
                                        fieldValue = Tokenize(fieldValue, ClientContext.Web, ClientContext.Site);
                                    }
                                    row.Values.Add(field.InternalName, fieldValue);
                                }
                            }
                        }

                        rows.Add(row);
                    }
                }
            }
            template.Lists.Remove(listInstance);
            listInstance.DataRows.AddRange(rows);
            template.Lists.Add(listInstance);

            var outFileName = System.IO.Path.GetFileName(Path);
            var outPath     = new FileInfo(Path).DirectoryName;

            var fileSystemConnector = new FileSystemConnector(outPath, "");
            var formatter           = XMLPnPSchemaFormatter.LatestFormatter;
            var extension           = new FileInfo(Path).Extension.ToLowerInvariant();

            if (extension == ".pnp")
            {
                XMLTemplateProvider provider = new XMLOpenXMLTemplateProvider(new OpenXMLConnector(Path, fileSystemConnector));
                var templateFileName         = outFileName.Substring(0, outFileName.LastIndexOf(".", StringComparison.Ordinal)) + ".xml";

                provider.SaveAs(template, templateFileName, formatter, TemplateProviderExtensions);
            }
            else
            {
                XMLTemplateProvider provider = new XMLFileSystemTemplateProvider(Path, "");
                provider.SaveAs(template, Path, formatter, TemplateProviderExtensions);
            }
        }
Пример #49
0
        private void UpdateField(ClientObject web, ListInfo listInfo, Guid fieldId, XElement templateFieldElement, Field existingField)
        {
            web.Context.Load(existingField, f => f.SchemaXml);
            web.Context.ExecuteQueryRetry();

            var existingFieldElement = XElement.Parse(existingField.SchemaXml);

            var equalityComparer = new XNodeEqualityComparer();

            // Is field different in template?
            if (equalityComparer.GetHashCode(existingFieldElement) != equalityComparer.GetHashCode(templateFieldElement))
            {
                // Is existing field of the same type?
                if (existingFieldElement.Attribute("Type").Value == templateFieldElement.Attribute("Type").Value)
                {
                    var listIdentifier = templateFieldElement.Attribute("List") != null
                        ? templateFieldElement.Attribute("List").Value
                        : null;

                    if (listIdentifier != null)
                    {
                        // Temporary remove list attribute from list
                        templateFieldElement.Attribute("List").Remove();
                    }

                    foreach (var attribute in templateFieldElement.Attributes())
                    {
                        if (existingFieldElement.Attribute(attribute.Name) != null)
                        {
                            existingFieldElement.Attribute(attribute.Name).Value = attribute.Value;
                        }
                        else
                        {
                            existingFieldElement.Add(attribute);
                        }
                    }
                    foreach (var element in templateFieldElement.Elements())
                    {
                        if (existingFieldElement.HasAttributes && existingFieldElement.Attribute(element.Name) != null)
                        {
                            existingFieldElement.Attribute(element.Name).Remove();
                        }
                        existingFieldElement.Add(element);
                    }

                    if (existingFieldElement.Attribute("Version") != null)
                    {
                        existingFieldElement.Attributes("Version").Remove();
                    }
                    existingField.SchemaXml = existingFieldElement.ToString();
                    existingField.UpdateAndPushChanges(true);
                    web.Context.ExecuteQueryRetry();
                }
                else
                {
                    var fieldName = existingFieldElement.Attribute("Name") != null ? existingFieldElement.Attribute("Name").Value : existingFieldElement.Attribute("StaticName").Value;
                    WriteWarning(string.Format("Field {0} ({1}) exists in list {2} ({3}) but is of different type. Skipping field.", fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id), ProvisioningMessageType.Warning);
                }
            }
        }
        private Model.Field CreateField(Field listField)
        {
            Model.Field field;

            switch (listField.FieldTypeKind)
            {
                case FieldType.Choice:
                    field = new Model.FieldChoice
                    {
                        Choices = ((Client.FieldChoice)listField).Choices
                    };
                    break;
                case FieldType.MultiChoice:
                    field = new Model.FieldChoice
                    {
                        Choices = ((Client.FieldMultiChoice)listField).Choices
                    };
                    break;

                case FieldType.DateTime:
                    field = new Model.FieldDateTime { DateOnly = ((Client.FieldDateTime)listField).DisplayFormat == DateTimeFieldFormatType.DateOnly };
                    break;

                case FieldType.Lookup:
                    field = new Model.FieldLookup { AllowMultivalue = ((Client.FieldLookup)listField).AllowMultipleValues };
                    break;

                case FieldType.User:
                    field = new Model.FieldLookup { AllowMultivalue = ((Client.FieldUser)listField).AllowMultipleValues };
                    break;

                case FieldType.Invalid:
                    switch (listField.TypeAsString)
                    {
                        case "TaxonomyFieldType":
                            field = new Model.FieldTaxonomy {AllowMultivalue = false, Type = Model.FieldType.Taxonomy, IsReadonly = true};
                            break;
                        case "TaxonomyFieldTypeMulti":
                            field = new Model.FieldTaxonomy { AllowMultivalue = true, Type = Model.FieldType.Taxonomy, IsReadonly = true};
                            break;
                        default:
                            field = new Model.Field();
                            break;
                    }
                    break;

                default:
                    field = new Model.Field();
                    break;
            }

            field.Id = listField.Id;
            field.IsHidden = listField.Hidden;
            field.IsReadonly |= listField.ReadOnlyField;
            field.Title = listField.Title;
            field.InternalName = listField.InternalName;
            field.Group = listField.Group;
            if( field.Type == 0 ) field.Type = (Model.FieldType)listField.FieldTypeKind;

            return field;
        }
Пример #51
0
        private void UpdateField(ClientObject web, ListInfo listInfo, Guid fieldId, XElement templateFieldElement, Field existingField, PnPMonitoredScope scope, TokenParser parser, string originalFieldXml)
        {
            web.Context.Load(existingField, f => f.SchemaXmlWithResourceTokens);
            web.Context.ExecuteQueryRetry();

            var existingFieldElement = XElement.Parse(existingField.SchemaXmlWithResourceTokens);

            var equalityComparer = new XNodeEqualityComparer();

            // Is field different in template?
            if (equalityComparer.GetHashCode(existingFieldElement) != equalityComparer.GetHashCode(templateFieldElement))
            {
                // Is existing field of the same type?
                if (existingFieldElement.Attribute("Type").Value == templateFieldElement.Attribute("Type").Value)
                {
                    templateFieldElement = PrepareField(templateFieldElement);

                    foreach (var attribute in templateFieldElement.Attributes())
                    {
                        if (existingFieldElement.Attribute(attribute.Name) != null)
                        {
                            existingFieldElement.Attribute(attribute.Name).Value = attribute.Value;
                        }
                        else
                        {
                            existingFieldElement.Add(attribute);
                        }
                    }
                    foreach (var element in templateFieldElement.Elements())
                    {
                        if (existingFieldElement.Element(element.Name) != null)
                        {
                            existingFieldElement.Element(element.Name).Remove();
                        }
                        existingFieldElement.Add(element);
                    }

                    if (existingFieldElement.Attribute("Version") != null)
                    {
                        existingFieldElement.Attributes("Version").Remove();
                    }
                    existingField.SchemaXml = parser.ParseString(existingFieldElement.ToString(), TokenParser.SPSiteTokenKeys);
                    existingField.UpdateAndPushChanges(true);
                    web.Context.ExecuteQueryRetry();
                    bool isDirty = false;
            #if !CLIENTSDKV15
                    if (originalFieldXml.ContainsResourceToken())
                    {
                        var originalFieldElement = XElement.Parse(originalFieldXml);
                        var nameAttributeValue = originalFieldElement.Attribute("Name") != null ? originalFieldElement.Attribute("Name").Value : "";
                        if (nameAttributeValue.ContainsResourceToken())
                        {
                            if (existingField.TitleResource.SetUserResourceValue(nameAttributeValue, parser))
                            {
                                isDirty = true;
                            }
                        }
                        var descriptionAttributeValue = originalFieldElement.Attribute("Description") != null ? originalFieldElement.Attribute("Description").Value : "";
                        if (descriptionAttributeValue.ContainsResourceToken())
                        {
                            if (existingField.DescriptionResource.SetUserResourceValue(descriptionAttributeValue, parser))
                            {
                                isDirty = true;
                            }
                        }
                    }
            #endif
                    if (isDirty)
                    {
                        existingField.Update();
                        web.Context.ExecuteQuery();
                    }

                }
                else
                {
                    var fieldName = existingFieldElement.Attribute("Name") != null ? existingFieldElement.Attribute("Name").Value : existingFieldElement.Attribute("StaticName").Value;
                    scope.LogWarning(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id);
                    WriteWarning(string.Format(CoreResources.Provisioning_ObjectHandlers_ListInstances_Field__0____1___exists_in_list__2____3___but_is_of_different_type__Skipping_field_, fieldName, fieldId, listInfo.TemplateList.Title, listInfo.SiteList.Id), ProvisioningMessageType.Warning);
                }
            }
        }