Пример #1
0
        public void AddWikiOrPublishingPageWebParts(ClientContext ctx, Web web, string contentFieldName)
        {
            var rootWeb = ctx.Site.RootWeb;

            rootWeb.EnsureProperties(w => w.Url, w => w.ServerRelativeUrl);

            if (WebParts == null || WebParts.Count == 0)
            {
                var pageContent = ListItemFieldValues.Find(p => p.FieldName == contentFieldName)?.Value ?? String.Empty;

                if (web.ServerRelativeUrl != "/")
                {
                    File.ListItemAllFields[contentFieldName] = pageContent.Replace("{@WebUrl}", web.Url).Replace("{@WebServerRelativeUrl}", web.ServerRelativeUrl).Replace("{@SiteUrl}", rootWeb.Url).Replace("{@SiteServerRelativeUrl}", rootWeb.ServerRelativeUrl);
                }
                else
                {
                    //In this case the web is the root web
                    File.ListItemAllFields[contentFieldName] = pageContent.Replace("{@WebUrl}", web.Url).Replace("{@WebServerRelativeUrl}", "").Replace("{@SiteUrl}", web.Url).Replace("{@SiteServerRelativeUrl}", "");
                }
                File.ListItemAllFields.Update();

                return;
            }

            var newIdMappings = new Dictionary <string, string>();

            var limitedWebPartManager = File.GetLimitedWebPartManager(PersonalizationScope.Shared);

            AddWikiOrPublishingContentPageWebParts(ctx, web, rootWeb, newIdMappings, limitedWebPartManager);
            UpdateWikiOrPublishingContentWithStorageKeys(newIdMappings, web, rootWeb, contentFieldName);
            LoadWebPartManagerFromSharePoint(ctx, limitedWebPartManager);
            MoveWebPartsToWikiOrPublishingContentEditorWebPartZone(ctx, newIdMappings, limitedWebPartManager);
            SetPageListViews(ctx, web, newIdMappings);
        }
Пример #2
0
        private void UpdateWikiOrPublishingContentWithStorageKeys(Dictionary <string, string> newIdMappings, Web web, string contentFieldName)
        {
            var pageContent = ListItemFieldValues.Find(p => p.FieldName == contentFieldName)?.Value ?? String.Empty;

            File.ListItemAllFields[contentFieldName] =
                WikiPageUtility.GetUpdatedWikiContentText(pageContent, WikiPageWebPartStorageKeyMappings,
                                                          newIdMappings)
                .Replace("{@WebServerRelativeUrl}", web.ServerRelativeUrl != "/" ? web.ServerRelativeUrl : "");
            File.ListItemAllFields.Update();
            File.Context.ExecuteQuery();
        }
Пример #3
0
        private void UpdateListItem(ClientContext ctx, Web web)
        {
            if (ListItemFieldValues == null || ListItemFieldValues.Count == 0)
            {
                return;
            }

            var rootWeb = ctx.Site.RootWeb;

            rootWeb.EnsureProperties(w => w.Url, w => w.ServerRelativeUrl);

            var specialTypes = new List <string>()
            {
                "Lookup",
                "DateTime",
                "User",
                "TaxonomyFieldType",
                "TaxonomyFieldTypeMulti"
            };

            var specialNames = new List <string>()
            {
                "ContentTypeId",
                "ContentType",
                WikiPageContentFieldName,      //Should ignore, set elsewhere
                PublishingPageContentFieldName //Should ignore, set elsewhere
            };

            var             item            = File.ListItemAllFields;
            TaxonomySession taxonomySession = null;
            TermStore       termStore       = null;
            ClientContext   tempCtx         = ctx.Clone(web.Url);
            var             library         = tempCtx.Web.Lists.GetByTitle(List);

            tempCtx.Load(library, l => l.ContentTypes, l => l.Fields);
            tempCtx.ExecuteQueryRetry();

            if (ListItemFieldValues.FirstOrDefault(fv => fv.FieldType != null && fv.FieldType.StartsWith("TaxonomyField")) != null)
            {
                taxonomySession = TaxonomySession.GetTaxonomySession(tempCtx);
                termStore       = TermStoreUtility.GetTermStore(tempCtx, taxonomySession);
            }

            var lookupFields  = library.Fields.Where(f => f.FieldTypeKind == FieldType.Lookup && ListItemFieldValues.FirstOrDefault(fv => fv.FieldName == f.InternalName) != null);
            var lookupQueries = new Dictionary <string, string[]>();

            foreach (var field in lookupFields)
            {
                var lookupField = tempCtx.CastTo <FieldLookup>(field);
                lookupField.EnsureProperties(lf => lf.LookupList, lf => lf.LookupField);
                var lookupListId = lookupField.LookupList;
                var lookupList   = tempCtx.Web.Lists.GetById(Guid.Parse(lookupListId));
                tempCtx.Load(lookupList, l => l.Title);
                try
                {
                    tempCtx.ExecuteQueryRetry();
                }
                catch
                {
                    //Ignore
                }

                lookupQueries[field.InternalName] = new string[]
                {
                    lookupList.Title,
                    $"<View><ViewFields><FieldRef Name='{lookupField.LookupField}'/></ViewFields><Query><Where><Contains><FieldRef Name='{lookupField.LookupField}' /><Value Type='Text'>#VALUE#</Value></Contains></Where></Query><RowLimit>1</RowLimit></View>"
                };
            }

            foreach (var fieldInfo in ListItemFieldValues)
            {
                if (!specialNames.Contains(fieldInfo.FieldName) &&
                    !specialTypes.Contains(fieldInfo.FieldType))
                {
                    item[fieldInfo.FieldName] =
                        fieldInfo.Value.Replace("{@WebUrl}", web.Url)
                        .Replace("{@WebServerRelativeUrl}", web.ServerRelativeUrl)
                        .Replace("{@SiteUrl}", rootWeb.Url)
                        .Replace("{@SiteServerRelativeUrl}", rootWeb.ServerRelativeUrl);
                }
                else if (fieldInfo.FieldType == "DateTime")
                {
                    item[fieldInfo.FieldName] = DateTime.ParseExact(fieldInfo.Value, "yyyy-MM-ddTHH:mm:ss.fffZ",
                                                                    CultureInfo.InvariantCulture);
                }
                else if (fieldInfo.FieldType == "User")
                {
                    try
                    {
                        var user = tempCtx.Web.EnsureUser(fieldInfo.Value);
                        tempCtx.Load(user);
                        tempCtx.ExecuteQueryRetry();
                        item[fieldInfo.FieldName] = user.Id;
                    }
                    catch
                    {
                        //ignore
                        //TODO: Notification event
                    }
                }
                else if (fieldInfo.FieldType == "Lookup")
                {
                    if (lookupQueries.ContainsKey(fieldInfo.FieldName))
                    {
                        var lookupListTitle = lookupQueries[fieldInfo.FieldName][0];
                        var viewXml         = lookupQueries[fieldInfo.FieldName][1].Replace(
                            "#VALUE#", fieldInfo.Value);

                        var lookupList = tempCtx.Web.Lists.GetByTitle(lookupListTitle);
                        var query      = new CamlQuery();
                        query.ViewXml = viewXml;
                        var listItems = lookupList.GetItems(query);
                        tempCtx.Load(listItems);
                        try
                        {
                            tempCtx.ExecuteQueryRetry();
                            if (listItems.Count == 0)
                            {
                                //TODO: Notify
                            }
                            else
                            {
                                item[fieldInfo.FieldName] = listItems[0].Id;
                            }
                        }
                        catch (Exception ex)
                        {
                            //TODO: Notify
                            //OnNotify(ProvisioningNotificationLevels.Verbose, $"Unable to find {fieldInfo.Value} in {lookupListTitle}. An exception occurred: {ex.Message}. Skipping attempt to set list item value.");
                        }
                    }
                }
                else if (fieldInfo.FieldType != null && fieldInfo.FieldType.StartsWith("TaxonomyField"))
                {
                    tempCtx.Web.EnsureProperty(w => w.Language);
                    var termSetName = fieldInfo.Value.GetInnerText("{@TermSet:", "}");
                    var termNames   = fieldInfo.Value.GetInnerText("{@Terms:", "}").Split(';');
                    var termSets    = termStore.GetTermSetsByName(termSetName, (int)tempCtx.Web.Language);
                    tempCtx.Load(termSets, ts => ts.Include(t => t.Id));
                    tempCtx.ExecuteQueryRetry();

                    if (termSets.Count == 0)
                    {
                        //OnNotify(ProvisioningNotificationLevels.Verbose,
                        //    $"Unable to find term set {termSetName}. Skipping list item field!");
                    }
                    else if (termNames.Length == 0)
                    {
                        //OnNotify(ProvisioningNotificationLevels.Verbose,
                        //    $"Bad field value token {fieldInfo.Value}. Skipping list item field!");
                    }
                    else
                    {
                        var termSet = GetCorrectTermSet(ctx, termNames[0], termSets);
                        var terms   = termSet.GetAllTerms();
                        tempCtx.Load(terms);
                        tempCtx.ExecuteQueryRetry();

                        var fieldValue = string.Empty;
                        for (var c = 0; c < termNames.Length; c++)
                        {
                            var termName = termNames[c];

                            var foundTerm = terms.FirstOrDefault(t => t.Name == termName);

                            if (foundTerm == null)
                            {
                                //OnNotify(ProvisioningNotificationLevels.Verbose, $"Unable to find term {termName}. Skipping list item field!");
                                break;
                            }

                            if (fieldValue != String.Empty)
                            {
                                fieldValue = fieldValue + ";";
                            }

                            if (termNames.Length == 1)
                            {
                                fieldValue = $"-1;#{termName}|{foundTerm.Id}";
                            }
                            else
                            {
                                fieldValue = fieldValue + $"{termName}|{foundTerm.Id}";
                            }
                        }
                        if (fieldValue != String.Empty)
                        {
                            item[fieldInfo.FieldName] = fieldValue;
                        }
                    }
                }
                else if (fieldInfo.FieldName == "ContentType")
                {
                    var itemCType =
                        library.ContentTypes.FirstOrDefault(ctype => ctype.Name == fieldInfo.Value);
                    if (itemCType == null)
                    {
                        throw new InvalidOperationException(
                                  $"Content type {fieldInfo.Value} not found in list. Unable to add item.");
                    }
                    else
                    {
                        item["ContentTypeId"] = itemCType.Id;
                    }
                }
            }
            item.Update();
        }