protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var definition = webPartModel.WithAssertAndCast<PageViewerWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(BuiltInWebPartTemplates.PageViewerWebPart);

            if (!string.IsNullOrEmpty(definition.ContentLink))
            {
                var contentLinkValue = definition.ContentLink ?? string.Empty;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Original contentLinkValue: [{0}]", contentLinkValue);

                contentLinkValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                {
                    Value = contentLinkValue,
                    Context = listItemModelHost
                }).Value;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Token replaced contentLinkValue: [{0}]", contentLinkValue);

                wpXml.SetOrUpdatePageViewerWebPartProperty("ContentLink", contentLinkValue);
            }

            if (!string.IsNullOrEmpty(definition.SourceType))
            {
                wpXml.SetOrUpdatePageViewerWebPartProperty("SourceType", definition.SourceType);
            }

            return wpXml.ToString();
        }
        protected override string GetWebpartXmlDefinition(
            ListItemModelHost listItemModelHost,
            WebPartDefinitionBase webPartModel)
        {
            var typedDefinition = webPartModel.WithAssertAndCast<SilverlightWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions.LoadWebpartXmlDocument(this.ProcessCommonWebpartProperties(BuiltInWebPartTemplates.SilverlightWebPart, webPartModel));

            if (!string.IsNullOrEmpty(typedDefinition.Url))
            {
                var linkValue = typedDefinition.Url;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Original Url: [{0}]", linkValue);

                linkValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                {
                    Value = linkValue,
                    Context = listItemModelHost.HostClientContext
                }).Value;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Token replaced Url: [{0}]", linkValue);

                wpXml.SetOrUpdateProperty("Url", linkValue);
            }

            if (!string.IsNullOrEmpty(typedDefinition.CustomInitParameters))
            {
                wpXml.SetOrUpdateProperty("CustomInitParameters", typedDefinition.CustomInitParameters);
            }

            return wpXml.ToString();
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            if (!listItemModelHost.HostWeb.IsObjectPropertyInstantiated("Id"))
            {
                var webContext = listItemModelHost.HostWeb.Context;
                webContext.Load(listItemModelHost.HostWeb, w => w.Id);
                webContext.ExecuteQueryWithTrace();
            }

            var webId = listItemModelHost.HostWeb.Id.ToString();
            var wpModel = webPartModel.WithAssertAndCast<ClientWebPartDefinition>("model", value => value.RequireNotNull());

            // Enhance 'ClientWebPart' provision - ProductWebId should be current web by default #623
            // https://github.com/SubPointSolutions/spmeta2/issues/623
            var productId = wpModel.ProductId;

            if (!productId.HasGuidValue())
                productId = listItemModelHost.HostWeb.Id;

            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(BuiltInWebPartTemplates.ClientWebPart)
                .SetOrUpdateProperty("FeatureId", wpModel.FeatureId.ToString())
                .SetOrUpdateProperty("ProductId", productId.ToString())
                .SetOrUpdateProperty("WebPartName", wpModel.WebPartName)
                .SetOrUpdateProperty("ProductWebId", webId)
                .ToString();

            return wpXml;
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var typedModel = webPartModel.WithAssertAndCast<ContentEditorWebPartDefinition>("model", value => value.RequireNotNull());

            var wpXml = WebpartXmlExtensions.LoadWebpartXmlDocument(BuiltInWebPartTemplates.ContentEditorWebPart);

            if (!string.IsNullOrEmpty(typedModel.Content))
                wpXml.SetOrUpdateContentEditorWebPartProperty("Content", typedModel.Content, true);

            if (!string.IsNullOrEmpty(typedModel.ContentLink))
            {
                var urlValue = typedModel.ContentLink ?? string.Empty;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Original value: [{0}]", urlValue);

                urlValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                {
                    Value = urlValue,
                    Context = listItemModelHost.HostClientContext
                }).Value;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Token replaced value: [{0}]", urlValue);

                wpXml.SetOrUpdateContentEditorWebPartProperty("ContentLink", urlValue);
            }

            return wpXml.ToString();
        }
        protected override void OnBeforeDeploy(ListItemModelHost host, WebPartDefinitionBase webpart)
        {
            base.OnBeforeDeploy(host, webpart);

            // pre-load web id
            if (!host.HostWeb.IsPropertyAvailable("Id"))
            {
                host.HostWeb.Context.Load(host.HostWeb, w => w.Id);
                host.HostWeb.Context.ExecuteQueryWithTrace();
            }

            var context = host.HostClientContext;
            var wpModel = webpart.WithAssertAndCast<ListViewWebPartDefinition>("model", value => value.RequireNotNull());

            // save the old default view ID, then restore in OnAfterDeploy
            _currentListBindContext = XsltListViewWebPartModelHandler.LookupBindContext(host,
                                    wpModel.WebUrl, wpModel.WebId,
                                    wpModel.ListUrl, wpModel.ListTitle, wpModel.ListId,
                                    wpModel.ViewName, wpModel.ViewId,
                                    wpModel.TitleUrl);

            if (_currentListBindContext.TargetView != null)
            {
                _currentListBindContext.TargetView.DefaultView = true;
                _currentListBindContext.TargetView.Update();

                context.ExecuteQueryWithTrace();
            }
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var wpModel = webPartModel.WithAssertAndCast<SiteFeedWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(BuiltInWebPartTemplates.SiteFeedWebPart)
                .ToString();

            return wpXml;
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var typedModel = webPartModel.WithAssertAndCast<PictureLibrarySlideshowWebPartDefinition>("model", value => value.RequireNotNull());

            var wpXml = WebpartXmlExtensions.LoadWebpartXmlDocument(BuiltInWebPartTemplates.PictureLibrarySlideshowWebPart);

            // TODO, specific XML processing

            return wpXml.ToString();
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var wpModel = webPartModel.WithAssertAndCast<MyMembershipWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(BuiltInWebPartTemplates.MyMembershipWebPart);
                
            // TODO, process XML

            return wpXml.ToString();
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var wpModel = webPartModel.WithAssertAndCast<ScriptEditorWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(BuiltInWebPartTemplates.ScriptEditorWebPart)
                //.SetOrUpdateProperty("Content", HttpUtility.HtmlEncode(wpModel.Content))
                .SetOrUpdateProperty("Content", wpModel.Content, true)
                .ToString();

            return wpXml;
        }
        protected override string ProcessCommonWebpartProperties(string webPartXml, WebPartDefinitionBase definition)
        {
            var result = base.ProcessCommonWebpartProperties(webPartXml, definition);

            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(result)
                // Error while putting ClientWebPart to a WikiPage #575
                .RemoveProperty("Id")
                .ToString();

            return wpXml;
        }
Esempio n. 11
0
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            throw new SPMeta2NotSupportedException("UserCode web part provision is not supported by CSOM (SP API limitations) - https://officespdev.uservoice.com/forums/224641-general/suggestions/7300326-add-support-for-spusercodewebpart-import-via-limit");

            var wpModel = webPartModel.WithAssertAndCast<UserCodeWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(BuiltInWebPartTemplates.UserCodeWebPart)
                .SetOrUpdateMetadataPropertyAttribute("type", "name", wpModel.AssemblyFullName)
                .SetOrUpdateMetadataPropertyAttribute("Solution", "SolutionId", wpModel.SolutionId.ToString("D"))
                //.SetOrUpdateMetadataPropertyAttribute("Solution", "xmlns", "http://schemas.microsoft.com/sharepoint/")
                .ToString();

            return wpXml;
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var definition = webPartModel.WithAssertAndCast<RefinementScriptWebPartDefinition>("model", value => value.RequireNotNull());
            var xml = WebpartXmlExtensions.LoadWebpartXmlDocument(ProcessCommonWebpartProperties(BuiltInWebPartTemplates.RefinementScriptWebPart, webPartModel));

            if (!string.IsNullOrEmpty(definition.SelectedRefinementControlsJson))
                xml.SetOrUpdateProperty("SelectedRefinementControlsJson", definition.SelectedRefinementControlsJson);

            if (!string.IsNullOrEmpty(definition.EmptyMessage))
                xml.SetOrUpdateProperty("EmptyMessage", definition.EmptyMessage);


            return xml.ToString();
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var wpModel = webPartModel.WithAssertAndCast<ListViewWebPartDefinition>("model", value => value.RequireNotNull());

            var bindContext = LookupBindContext(listItemModelHost, wpModel);

            var wpXml = WebpartXmlExtensions.LoadWebpartXmlDocument(BuiltInWebPartTemplates.ListViewWebPart)
                                         .SetOrUpdateListVieweWebPartProperty("ListName", bindContext.ListId.ToString("B"))
                                         .SetOrUpdateListVieweWebPartProperty("ListId", bindContext.ListId.ToString("D").ToLower())
                                         //.SetOrUpdateListVieweWebPartProperty("ViewGuid", bindContext.ViewId.ToString("D").ToLower())
                                         .SetTitleUrl(bindContext.TitleUrl)
                                         .ToString();

            return wpXml;
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var definition = webPartModel.WithAssertAndCast<ContentBySearchWebPartDefinition>("model", value => value.RequireNotNull());
            var xml = WebpartXmlExtensions.LoadWebpartXmlDocument(BuiltInWebPartTemplates.ContentBySearchWebPart);

            // JSON
            if (!string.IsNullOrEmpty(definition.DataProviderJSON))
                xml.SetDataProviderJSON(definition.DataProviderJSON);

            // templates
            if (!string.IsNullOrEmpty(definition.GroupTemplateId))
                xml.SetGroupTemplateId(definition.GroupTemplateId);

            if (!string.IsNullOrEmpty(definition.ItemTemplateId))
                xml.SetItemTemplateId(definition.ItemTemplateId);

            if (!string.IsNullOrEmpty(definition.RenderTemplateId))
                xml.SetRenderTemplateId(definition.RenderTemplateId);

            // item counts
            if (definition.NumberOfItems.HasValue)
                xml.SetNumberOfItems(definition.NumberOfItems.Value);

            if (definition.ResultsPerPage.HasValue)
                xml.SetResultsPerPage(definition.ResultsPerPage.Value);

            // misc
            if (!string.IsNullOrEmpty(definition.PropertyMappings))
                xml.SetPropertyMappings(definition.PropertyMappings);

            if (definition.OverwriteResultPath.HasValue)
                xml.SetOverwriteResultPath(definition.OverwriteResultPath.Value);

            if (definition.ShouldHideControlWhenEmpty.HasValue)
                xml.SetShouldHideControlWhenEmpty(definition.ShouldHideControlWhenEmpty.Value);

            if (definition.LogAnalyticsViewEvent.HasValue)
                xml.SetLogAnalyticsViewEvent(definition.LogAnalyticsViewEvent.Value);

            if (definition.AddSEOPropertiesFromSearch.HasValue)
                xml.SetAddSEOPropertiesFromSearch(definition.AddSEOPropertiesFromSearch.Value);

            if (definition.StartingItemIndex.HasValue)
                xml.SetStartingItemIndex(definition.StartingItemIndex.Value);

            return xml.ToString();
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var wpModel = webPartModel.WithAssertAndCast<XsltListViewWebPartDefinition>("model", value => value.RequireNotNull());
            var bindContext = LookupBindContext(listItemModelHost, wpModel);

            var wpXml = WebpartXmlExtensions.LoadWebpartXmlDocument(BuiltInWebPartTemplates.XsltListViewWebPart)
                                .SetListName(bindContext.ListId.ToString())
                                .SetListId(bindContext.ListId.ToString())
                                .SetTitleUrl(bindContext.TitleUrl)
                                .SetJSLink(wpModel.JSLink);

            if (wpModel.CacheXslStorage.HasValue)
                wpXml.SetOrUpdateProperty("CacheXslStorage", wpModel.CacheXslStorage.Value.ToString());

            if (wpModel.CacheXslTimeOut.HasValue)
                wpXml.SetOrUpdateProperty("CacheXslTimeOut", wpModel.CacheXslTimeOut.Value.ToString());

            if (!string.IsNullOrEmpty(wpModel.BaseXsltHashKey))
                wpXml.SetOrUpdateProperty("BaseXsltHashKey", wpModel.BaseXsltHashKey);

            // xsl
            if (!string.IsNullOrEmpty(wpModel.Xsl))
                wpXml.SetOrUpdateCDataProperty("Xsl", wpModel.Xsl);

            if (!string.IsNullOrEmpty(wpModel.XslLink))
                wpXml.SetOrUpdateProperty("XslLink", wpModel.XslLink);

            if (!string.IsNullOrEmpty(wpModel.GhostedXslLink))
                wpXml.SetOrUpdateProperty("GhostedXslLink", wpModel.GhostedXslLink);

            // xml
            if (!string.IsNullOrEmpty(wpModel.XmlDefinition))
                wpXml.SetOrUpdateCDataProperty("XmlDefinition", wpModel.Xsl);

            if (!string.IsNullOrEmpty(wpModel.XmlDefinitionLink))
                wpXml.SetOrUpdateProperty("XmlDefinitionLink", wpModel.XmlDefinitionLink);

#if !NET35
            if (wpModel.ShowTimelineIfAvailable.HasValue)
                wpXml.SetOrUpdateProperty("ShowTimelineIfAvailable", wpModel.ShowTimelineIfAvailable.Value.ToString());
#endif

            return wpXml.ToString();
        }
Esempio n. 16
0
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            if (!listItemModelHost.HostWeb.IsObjectPropertyInstantiated("Id"))
            {
                var webContext = listItemModelHost.HostWeb.Context;
                webContext.Load(listItemModelHost.HostWeb, w => w.Id);
                webContext.ExecuteQueryWithTrace();
            }

            var webId = listItemModelHost.HostWeb.Id.ToString();

            var wpModel = webPartModel.WithAssertAndCast<ClientWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions
                .LoadWebpartXmlDocument(BuiltInWebPartTemplates.ClientWebPart)
                .SetOrUpdateProperty("FeatureId", wpModel.FeatureId.ToString())
                .SetOrUpdateProperty("ProductId", wpModel.ProductId.ToString())
                .SetOrUpdateProperty("WebPartName", wpModel.WebPartName)
                .SetOrUpdateProperty("ProductWebId", webId)
                .ToString();

            return wpXml;
        }
        protected override void OnBeforeDeploy(ListItemModelHost host, WebPartDefinitionBase webpart)
        {
            base.OnBeforeDeploy(host, webpart);

            var context = host.HostClientContext;
            var wpModel = webpart.WithAssertAndCast<XsltListViewWebPartDefinition>("model", value => value.RequireNotNull());

            // save the old default view ID, then restore in OnAfterDeploy
            _currentListBindContext = LookupBindContext(host, wpModel);

            if (_currentListBindContext.TargetView != null)
            {
                _currentListBindContext.TargetView.DefaultView = true;
                _currentListBindContext.TargetView.Update();

                context.ExecuteQueryWithTrace();
            }
        }
        protected override string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var typedDefinition = webPartModel.WithAssertAndCast<ContentByQueryWebPartDefinition>("model", value => value.RequireNotNull());
            var wpXml = WebpartXmlExtensions.LoadWebpartXmlDocument(this.ProcessCommonWebpartProperties(BuiltInWebPartTemplates.ContentByQueryWebPart, webPartModel));

            // xslt links
            if (!string.IsNullOrEmpty(typedDefinition.MainXslLink))
            {
                var linkValue = typedDefinition.MainXslLink;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Original MainXslLink: [{0}]", linkValue);

                linkValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                {
                    Value = linkValue,
                    Context = listItemModelHost.HostClientContext
                }).Value;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Token replaced MainXslLink: [{0}]", linkValue);

                wpXml.SetOrUpdateProperty("MainXslLink", linkValue);
            }

            if (!string.IsNullOrEmpty(typedDefinition.ItemXslLink))
            {
                var linkValue = typedDefinition.ItemXslLink;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Original ItemXslLink: [{0}]", linkValue);

                linkValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                {
                    Value = linkValue,
                    Context = listItemModelHost.HostClientContext
                }).Value;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Token replaced ItemXslLink: [{0}]", linkValue);

                wpXml.SetOrUpdateProperty("ItemXslLink", linkValue);
            }

            if (!string.IsNullOrEmpty(typedDefinition.HeaderXslLink))
            {
                var linkValue = typedDefinition.HeaderXslLink;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Original HeaderXslLink: [{0}]", linkValue);

                linkValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                {
                    Value = linkValue,
                    Context = listItemModelHost.HostClientContext
                }).Value;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Token replaced HeaderXslLink: [{0}]", linkValue);

                wpXml.SetOrUpdateProperty("HeaderXslLink", linkValue);
            }

            // styles
            if (!string.IsNullOrEmpty(typedDefinition.ItemStyle))
                wpXml.SetItemStyle(typedDefinition.ItemStyle);

            if (!string.IsNullOrEmpty(typedDefinition.GroupStyle))
                wpXml.SetGroupStyle(typedDefinition.GroupStyle);


            // cache settings
            if (typedDefinition.UseCache.HasValue)
                wpXml.SetUseCache(typedDefinition.UseCache.ToString());

            if (typedDefinition.CacheXslStorage.HasValue)
                wpXml.SetOrUpdateProperty("CacheXslStorage", typedDefinition.CacheXslStorage.ToString());

            if (typedDefinition.CacheXslTimeOut.HasValue)
                wpXml.SetOrUpdateProperty("CacheXslTimeOut", typedDefinition.CacheXslTimeOut.ToString());

            // item limit
            if (typedDefinition.ItemLimit.HasValue)
                wpXml.SetOrUpdateProperty("ItemLimit", typedDefinition.ItemLimit.ToString());

            // mappings
            if (!string.IsNullOrEmpty(typedDefinition.DataMappings))
                wpXml.SetOrUpdateProperty("DataMappings", typedDefinition.DataMappings);

            if (!string.IsNullOrEmpty(typedDefinition.DataMappingViewFields))
                wpXml.SetOrUpdateProperty("DataMappingViewFields", typedDefinition.DataMappingViewFields);

            // misc
            if (typedDefinition.ShowUntargetedItems.HasValue)
                wpXml.SetOrUpdateProperty("ShowUntargetedItems", typedDefinition.ShowUntargetedItems.ToString());

            if (typedDefinition.PlayMediaInBrowser.HasValue)
                wpXml.SetOrUpdateProperty("PlayMediaInBrowser", typedDefinition.PlayMediaInBrowser.ToString());

            // FilterTypeXXX
            if (!string.IsNullOrEmpty(typedDefinition.FilterType1))
                wpXml.SetOrUpdateProperty("FilterType1", typedDefinition.FilterType1);

            if (!string.IsNullOrEmpty(typedDefinition.FilterType2))
                wpXml.SetOrUpdateProperty("FilterType2", typedDefinition.FilterType2);

            if (!string.IsNullOrEmpty(typedDefinition.FilterType3))
                wpXml.SetOrUpdateProperty("FilterType3", typedDefinition.FilterType3);

            // FilterFieldXXX
            if (!string.IsNullOrEmpty(typedDefinition.FilterField1))
                wpXml.SetOrUpdateProperty("FilterField1", typedDefinition.FilterField1);

            if (!string.IsNullOrEmpty(typedDefinition.FilterField2))
                wpXml.SetOrUpdateProperty("FilterField2", typedDefinition.FilterField2);

            if (!string.IsNullOrEmpty(typedDefinition.FilterField3))
                wpXml.SetOrUpdateProperty("FilterField3", typedDefinition.FilterField3);

            // FilterXXXIsCustomValue
            if (typedDefinition.Filter1IsCustomValue.HasValue)
                wpXml.SetOrUpdateProperty("Filter1IsCustomValue", typedDefinition.Filter1IsCustomValue.ToString());

            if (typedDefinition.Filter2IsCustomValue.HasValue)
                wpXml.SetOrUpdateProperty("Filter2IsCustomValue", typedDefinition.Filter2IsCustomValue.ToString());

            if (typedDefinition.Filter3IsCustomValue.HasValue)
                wpXml.SetOrUpdateProperty("Filter3IsCustomValue", typedDefinition.Filter3IsCustomValue.ToString());

            // FilterValueXXX
            if (!string.IsNullOrEmpty(typedDefinition.FilterValue1))
                wpXml.SetOrUpdateProperty("FilterValue1", typedDefinition.FilterValue1);

            if (!string.IsNullOrEmpty(typedDefinition.FilterValue2))
                wpXml.SetOrUpdateProperty("FilterValue2", typedDefinition.FilterValue2);

            if (!string.IsNullOrEmpty(typedDefinition.FilterValue3))
                wpXml.SetOrUpdateProperty("FilterValue3", typedDefinition.FilterValue3);

            var filterChainingOperatorType = "Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterChainingOperator, Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c";

            if (!string.IsNullOrEmpty(typedDefinition.Filter1ChainingOperator))
                wpXml.SetTypedProperty("Filter1ChainingOperator", typedDefinition.Filter1ChainingOperator, filterChainingOperatorType);

            if (!string.IsNullOrEmpty(typedDefinition.Filter2ChainingOperator))
                wpXml.SetTypedProperty("Filter2ChainingOperator", typedDefinition.Filter2ChainingOperator, filterChainingOperatorType);


            // sorting
            if (!string.IsNullOrEmpty(typedDefinition.SortBy))
                wpXml.SetOrUpdateProperty("SortBy", typedDefinition.SortBy);

            if (!string.IsNullOrEmpty(typedDefinition.SortByDirection))
                wpXml.SetTypedProperty("SortByDirection", typedDefinition.SortByDirection, "Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+SortDirection, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");

            if (!string.IsNullOrEmpty(typedDefinition.SortByFieldType))
                wpXml.SetOrUpdateProperty("SortByFieldType", typedDefinition.SortByFieldType);

            if (!string.IsNullOrEmpty(typedDefinition.GroupByDirection))
                wpXml.SetTypedProperty("GroupByDirection", typedDefinition.GroupByDirection, "Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+SortDirection, Microsoft.SharePoint.Publishing, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");

            var filterOperatorType = "Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterFieldQueryOperator, Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c";


            // FilterOperatorXXX
            if (!string.IsNullOrEmpty(typedDefinition.FilterOperator1))
                wpXml.SetTypedProperty("FilterOperator1", typedDefinition.FilterOperator1, filterOperatorType);

            if (!string.IsNullOrEmpty(typedDefinition.FilterOperator2))
                wpXml.SetTypedProperty("FilterOperator2", typedDefinition.FilterOperator2, filterOperatorType);

            if (!string.IsNullOrEmpty(typedDefinition.FilterOperator3))
                wpXml.SetTypedProperty("FilterOperator3", typedDefinition.FilterOperator3, filterOperatorType);

            // FilterDisplayValueXXX

            if (!string.IsNullOrEmpty(typedDefinition.FilterDisplayValue1))
                wpXml.SetOrUpdateProperty("FilterDisplayValue1", typedDefinition.FilterDisplayValue1);

            if (!string.IsNullOrEmpty(typedDefinition.FilterDisplayValue2))
                wpXml.SetOrUpdateProperty("FilterDisplayValue2", typedDefinition.FilterDisplayValue2);

            if (!string.IsNullOrEmpty(typedDefinition.FilterDisplayValue3))
                wpXml.SetOrUpdateProperty("FilterDisplayValue3", typedDefinition.FilterDisplayValue3);


            // bindings
            if (typedDefinition.ServerTemplate.HasValue)
                wpXml.SetOrUpdateProperty("ServerTemplate", typedDefinition.ServerTemplate.ToString());

            if (!string.IsNullOrEmpty(typedDefinition.ContentTypeName))
                wpXml.SetOrUpdateProperty("ContentTypeName", typedDefinition.ContentTypeName);

            if (!string.IsNullOrEmpty(typedDefinition.ContentTypeBeginsWithId))
                wpXml.SetOrUpdateProperty("ContentTypeBeginsWithId", typedDefinition.ContentTypeBeginsWithId);

            if (typedDefinition.ListId.HasGuidValue())
                wpXml.SetTypedProperty("ListId", typedDefinition.ListId.Value.ToString("D"), "Microsoft.SharePoint.Publishing.WebControls.ContentByQueryWebPart+FilterChainingOperator, Microsoft.SharePoint.Publishing, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c");

            if (typedDefinition.ListGuid.HasGuidValue())
                wpXml.SetOrUpdateProperty("ListGuid", typedDefinition.ListGuid.Value.ToString("D"));

            if (!string.IsNullOrEmpty(typedDefinition.ListName))
                wpXml.SetOrUpdateProperty("ListName", typedDefinition.ListName);

            if (!string.IsNullOrEmpty(typedDefinition.WebUrl))
                wpXml.SetOrUpdateProperty("WebUrl", typedDefinition.WebUrl);

            // overrides
            if (!string.IsNullOrEmpty(typedDefinition.ListsOverride))
                wpXml.SetOrUpdateProperty("ListsOverride", typedDefinition.ListsOverride);

            if (!string.IsNullOrEmpty(typedDefinition.ViewFieldsOverride))
                wpXml.SetOrUpdateProperty("ViewFieldsOverride", typedDefinition.ViewFieldsOverride);

            if (!string.IsNullOrEmpty(typedDefinition.QueryOverride))
                wpXml.SetOrUpdateProperty("QueryOverride", typedDefinition.QueryOverride);

            if (!string.IsNullOrEmpty(typedDefinition.CommonViewFields))
                wpXml.SetOrUpdateProperty("CommonViewFields", typedDefinition.CommonViewFields);

            if (typedDefinition.FilterByAudience.HasValue)
                wpXml.SetOrUpdateProperty("FilterByAudience", typedDefinition.FilterByAudience.ToString());


            return wpXml.ToString();
        }
Esempio n. 19
0
 protected virtual void OnBeforeDeploy(ListItemModelHost host, WebPartDefinitionBase webpart)
 {
 }
        protected override void OnAfterDeploy(ListItemModelHost host, WebPartDefinitionBase webpart)
        {
            if (_currentListBindContext != null)
            {
                var context = host.HostClientContext;
                var wpModel = webpart.WithAssertAndCast<ListViewWebPartDefinition>("model", value => value.RequireNotNull());

                var bindingContext = XsltListViewWebPartModelHandler.LookupBindContext(host,
                                    wpModel.WebUrl, wpModel.WebId,
                                    wpModel.ListUrl, wpModel.ListTitle, wpModel.ListId,
                                    wpModel.ViewName, wpModel.ViewId,
                                    wpModel.TitleUrl);

                // reverting back the dafult view
                var view = bindingContext.List.GetView(_currentListBindContext.DefaultViewId);
                view.DefaultView = true;
                view.Update();

                context.ExecuteQueryWithTrace();
            }
        }
Esempio n. 21
0
        protected virtual string ProcessCommonWebpartProperties(string webPartXml, WebPartDefinitionBase definition)
        {
            var xml = WebpartXmlExtensions.LoadWebpartXmlDocument(webPartXml)
                                            .SetTitle(definition.Title)
                                            .SetID(definition.Id);

            if (definition.Width.HasValue)
                xml.SetWidth(definition.Width.Value);

            if (definition.Height.HasValue)
                xml.SetHeight(definition.Height.Value);

            if (!string.IsNullOrEmpty(definition.Description))
                xml.SetDescription(definition.Description);

            if (!string.IsNullOrEmpty(definition.ImportErrorMessage))
                xml.SetImportErrorMessage(definition.ImportErrorMessage);

            if (!string.IsNullOrEmpty(definition.TitleUrl))
            {
                var urlValue = definition.TitleUrl ?? string.Empty;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Original value: [{0}]", urlValue);

                urlValue = TokenReplacementService.ReplaceTokens(new TokenReplacementContext
                {
                    Value = urlValue,
                    Context = CurrentClientContext
                }).Value;

                TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Token replaced value: [{0}]", urlValue);

                xml.SetTitleUrl(urlValue);
            }

            if (!string.IsNullOrEmpty(definition.TitleIconImageUrl))
                xml.SetTitleIconImageUrl(definition.TitleIconImageUrl);

            if (!string.IsNullOrEmpty(definition.ChromeState))
                xml.SetChromeState(definition.ChromeState);

            if (!string.IsNullOrEmpty(definition.ChromeType))
            {
                var chromeType = string.Empty;

                if (xml.IsV3version())
                    chromeType = WebPartChromeTypesConvertService.NormilizeValueToPartChromeTypes(definition.ChromeType);
                else if (xml.IsV2version())
                    chromeType = WebPartChromeTypesConvertService.NormilizeValueToFrameTypes(definition.ChromeType);

                // SetChromeType() sets correct XML props depending on V2/V3 web part XML
                xml.SetChromeType(chromeType);
            }

            if (!string.IsNullOrEmpty(definition.ExportMode))
                xml.SetExportMode(definition.ExportMode);

            // bindings
            ProcessParameterBindings(definition, xml);

            // properties
            ProcessWebpartProperties(definition, xml);

            return xml.ToString();
        }
Esempio n. 22
0
 protected virtual void ProcessWebpartProperties(WebPartDefinitionBase definition, XDocument xml)
 {
     if (definition.Properties != null && definition.Properties.Count > 0)
     {
         foreach (var prop in definition.Properties)
         {
             var isCdata = prop.IsCData.HasValue && prop.IsCData.Value;
             xml.SetOrUpdateProperty(prop.Name, prop.Value, prop.Type, isCdata);
         }
     }
 }
Esempio n. 23
0
        protected virtual void ProcessParameterBindings(WebPartDefinitionBase definition, XDocument xml)
        {
            if (definition.ParameterBindings != null && definition.ParameterBindings.Count > 0)
            {
                var parameterBinder = new WebPartParameterBindingsOptions();

                foreach (var binding in definition.ParameterBindings)
                    parameterBinder.AddParameterBinding(binding.Name, binding.Location);

                var parameterBindingValue = SecurityElement.Escape(parameterBinder.ParameterBinding);
                xml.SetOrUpdateProperty("ParameterBindings", parameterBindingValue);
            }
        }
Esempio n. 24
0
        protected WebPart FindExistingWebPart(IEnumerable<Microsoft.SharePoint.Client.WebParts.WebPartDefinition> webPartDefenitions,
                                              WebPartDefinitionBase webPartModel,
                                              out Microsoft.SharePoint.Client.WebParts.WebPartDefinition wpDefinition)
        {
            TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Resolving web part by Title: [{0}]", webPartModel.Title);

            wpDefinition = null;

            // gosh, you got to be kidding
            // internally, SharePoint returns StorageKey as ID. hence.. no ability to trace unique web part on the page
            // the only thing is comparing Titles an utilize them as a primary key

            foreach (var webPartDefinition in webPartDefenitions)
            {
                if (String.Compare(webPartDefinition.WebPart.Title, webPartModel.Title, System.StringComparison.OrdinalIgnoreCase) == 0)
                {
                    wpDefinition = webPartDefinition;

                    return webPartDefinition.WebPart;
                }
            }

            return null;
        }
Esempio n. 25
0
        private void HandleWikiPageProvision(ListItem listItem,
            WebPartDefinitionBase webpartModel, Guid? currentWebPartStoreKey, Guid? oldWebParStoreKey)
        {
            if (!webpartModel.AddToPageContent)
                return;

            TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "AddToPageContent = true. Handling wiki/publishig page provision case.");

            var context = listItem.Context;

            var targetFieldName = string.Empty;

            if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.WikiField))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "WikiField field is detected. Switching to wiki page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.WikiField;
            }
            else if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.PublishingPageLayout))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "PublishingPageLayout field is detected. Switching to publishin page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.PublishingPageContent;
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Not PublishingPageLayout field, nor WikiField is detected. Skipping.");
                return;
            }

            // any on the page?
            var existingWebPartId = string.Empty;

            // current from the new provision
            var upcomingWebPartId = string.Empty;

            // weird, by some web part ignor ID from the XML
            // so webpartStoreKey from the previous CSOM adding web part to the page must be used

            // M2 covers that fact with the regression testing, so we know what are they
            // and we have NOD idea why it happens
            if (ShouldUseWebPartStoreKeyForWikiPage)
            {
                upcomingWebPartId = currentWebPartStoreKey.ToString()
                                      .Replace("g_", string.Empty)
                                      .Replace("_", "-"); ;
            }
            else
            {
                // get from the model
                upcomingWebPartId = webpartModel.Id.ToString()
                                       .Replace("g_", string.Empty)
                                       .Replace("_", "-"); ;
            }

            if (!oldWebParStoreKey.HasGuidValue())
            {
                // first provision
                existingWebPartId = currentWebPartStoreKey.ToString()
                                      .Replace("g_", string.Empty)
                                      .Replace("_", "-");
            }
            else
            {
                // second provision,
                // we had web part on the page and can reuse that ID to relink on wiki content
                existingWebPartId = oldWebParStoreKey.ToString()
                                      .Replace("g_", string.Empty)
                                      .Replace("_", "-");
            }

            var content = listItem[targetFieldName] == null
                ? string.Empty
                : listItem[targetFieldName].ToString();

            var wikiTemplate = new StringBuilder();

            // actual ID will be replaced later
            wikiTemplate.AppendFormat("​​​​​​​​​​​​​​​​​​​​​​<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'>");
            wikiTemplate.Append("     <div class='ms-rtestate-read {0}' id='div_{0}'>");
            wikiTemplate.AppendFormat("     </div>");
            wikiTemplate.AppendFormat("</div>");

            var wikiTemplateOutput = wikiTemplate.ToString();

            if (string.IsNullOrEmpty(content))
            {
                // page is empty, pre-generating HTML
                // pushing web part as the current WebPart Key
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall,
                    "Page content is empty Generating new one.");

                content = string.Format(wikiTemplateOutput, upcomingWebPartId);

                listItem[targetFieldName] = content;
                listItem.Update();

                context.ExecuteQueryWithTrace();
            }
            else
            {
                // there is a content on the page
                // there might be some web parts too
                if (oldWebParStoreKey.HasGuidValue())
                {
                    // there was an old web part on the page
                    // checking if markup has the ID

                    if (content.ToUpper().IndexOf(existingWebPartId.ToUpper()) != -1)
                    {
                        // was old web part on the page?
                        // yes, replacing ID
                        TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                            string.Format("Replacing web part with ID: [{0}] to [{1}] on the page content.",
                                existingWebPartId, upcomingWebPartId),
                            null);

                        content = content.Replace(existingWebPartId, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                    // original from the definigion?
                    else if (content.ToUpper().IndexOf(upcomingWebPartId.ToUpper()) != -1)
                    {
                        // yes, replacing ID
                        TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                            string.Format("Replacing web part with ID: [{0}] to [{1}] on the page content.",
                                existingWebPartId, upcomingWebPartId),
                            null);

                        // do nothing

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                    else
                    {
                        // adding new, from scratch
                        TraceService.WarningFormat((int)LogEventId.ModelProvisionCoreCall,
                            "Cannot find web part ID: [{0}] the page content. Adding a new one.",
                            new object[]
                            {
                                existingWebPartId
                            });

                        content = content + string.Format(wikiTemplateOutput, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                }
                else
                {
                    // first provision of the web part on the page
                    if (content.ToUpper().IndexOf(upcomingWebPartId.ToUpper()) != -1)
                    {
                        // do nothing

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                    else
                    {
                        // adding new, from scratch
                        TraceService.WarningFormat((int)LogEventId.ModelProvisionCoreCall,
                            "Cannot find web part ID: [{0}] the page content. Adding a new one.",
                            new object[]
                            {
                                existingWebPartId
                            });

                        content = content + string.Format(wikiTemplateOutput, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                }
            }
        }
Esempio n. 26
0
        protected WebPart FindExistingWebPart(
            IEnumerable<Microsoft.SharePoint.Client.WebParts.WebPartDefinition> webPartDefenitions,
            WebPartDefinitionBase webPartModel)
        {
            Microsoft.SharePoint.Client.WebParts.WebPartDefinition wpDefinition = null;

            return FindExistingWebPart(webPartDefenitions, webPartModel, out wpDefinition);
        }
Esempio n. 27
0
        private void HandleWikiPageProvision(ListItem listItem, WebPartDefinitionBase webpartModel)
        {
            if (!webpartModel.AddToPageContent)
                return;

            TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "AddToPageContent = true. Handling wiki/publishig page provision case.");

            var context = listItem.Context;

            var targetFieldName = string.Empty;

            if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.WikiField))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "WikiField field is detected. Switching to wiki page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.WikiField;
            }
            else if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.PublishingPageLayout))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "PublishingPageLayout field is detected. Switching to publishin page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.PublishingPageContent;
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Not PublishingPageLayout field, nor WikiField is detected. Skipping.");
                return;
            }

            var wikiTemplate = new StringBuilder();

            var wpId = webpartModel.Id
                .Replace("g_", string.Empty)
                .Replace("_", "-");

            var content = listItem[targetFieldName] == null
                ? string.Empty
                : listItem[targetFieldName].ToString();

            wikiTemplate.AppendFormat(
                "​​​​​​​​​​​​​​​​​​​​​​<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'>");
            wikiTemplate.AppendFormat("     <div class='ms-rtestate-read {0}' id='div_{0}'>", wpId);
            wikiTemplate.AppendFormat("     </div>");
            wikiTemplate.AppendFormat("</div>");

            var wikiResult = wikiTemplate.ToString();

            if (string.IsNullOrEmpty(content))
            {
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall, "Page content is empty Generating new one.");

                content = wikiResult;

                listItem[targetFieldName] = content;
                listItem.Update();

                context.ExecuteQueryWithTrace();
            }
            else
            {
                if (content.ToUpper().IndexOf(wpId.ToUpper()) == -1)
                {
                    TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall, "Replacing web part with ID: [{0}] on the page content.", wpId);

                    content += wikiResult;

                    listItem[targetFieldName] = content;
                    listItem.Update();

                    context.ExecuteQueryWithTrace();
                }
                else
                {
                    TraceService.WarningFormat((int)LogEventId.ModelProvisionCoreCall,
                        "Cannot find web part ID: [{0}] the page content. Provision won't add web part on the page content.",
                        new object[]
                        {
                           wpId
                        });
                }
            }
        }
Esempio n. 28
0
        protected virtual string ProcessCommonWebpartProperties(string webPartXml, WebPartDefinitionBase definition)
        {
            var xml = WebpartXmlExtensions.LoadWebpartXmlDocument(webPartXml)
                                            .SetTitle(definition.Title)
                                            .SetID(definition.Id);

            if (definition.Width.HasValue)
                xml.SetWidth(definition.Width.Value);

            if (definition.Height.HasValue)
                xml.SetHeight(definition.Height.Value);

            if (!string.IsNullOrEmpty(definition.Description))
                xml.SetDescription(definition.Description);

            if (!string.IsNullOrEmpty(definition.ImportErrorMessage))
                xml.SetImportErrorMessage(definition.ImportErrorMessage);

            if (!string.IsNullOrEmpty(definition.TitleUrl))
                xml.SetTitleUrl(definition.TitleUrl);

            if (!string.IsNullOrEmpty(definition.TitleIconImageUrl))
                xml.SetTitleIconImageUrl(definition.TitleIconImageUrl);

            if (!string.IsNullOrEmpty(definition.ChromeState))
                xml.SetChromeState(definition.ChromeState);

            if (!string.IsNullOrEmpty(definition.ChromeType))
            {
                var chromeType = string.Empty;

                if (xml.IsV3version())
                    chromeType = WebPartChromeTypesConvertService.NormilizeValueToPartChromeTypes(definition.ChromeType);
                else if (xml.IsV2version())
                    chromeType = WebPartChromeTypesConvertService.NormilizeValueToFrameTypes(definition.ChromeType);

                // SetChromeType() sets correct XML props depending on V2/V3 web part XML
                xml.SetChromeType(chromeType);
            }

            if (!string.IsNullOrEmpty(definition.ExportMode))
                xml.SetExportMode(definition.ExportMode);

            if (definition.ParameterBindings != null && definition.ParameterBindings.Count > 0)
            {
                var parameterBinder = new WebPartParameterBindingsOptions();

                foreach (var binding in definition.ParameterBindings)
                    parameterBinder.AddParameterBinding(binding.Name, binding.Location);

                var parameterBindingValue = SecurityElement.Escape(parameterBinder.ParameterBinding);
                xml.SetOrUpdateProperty("ParameterBindings", parameterBindingValue);
            }

            return xml.ToString();
        }
Esempio n. 29
0
        protected virtual string GetWebpartXmlDefinition(ListItemModelHost listItemModelHost, WebPartDefinitionBase webPartModel)
        {
            var result = string.Empty;
            var context = listItemModelHost.HostListItem.Context;

            if (!string.IsNullOrEmpty(webPartModel.WebpartFileName))
            {
                lock (_wpCacheLock)
                {
                    var wpKey = webPartModel.WebpartFileName.ToLower();

                    if (_wpCache.ContainsKey(wpKey))
                        result = _wpCache[wpKey];
                    else
                    {

                        var rootWeb = listItemModelHost.HostSite.RootWeb;
                        var rootWebContext = rootWeb.Context;

                        var webPartCatalog =
                            rootWeb.QueryAndGetListByUrl(BuiltInListDefinitions.Calalogs.Wp.GetListUrl());
                        //var webParts = webPartCatalog.GetItems(CamlQuery.CreateAllItemsQuery());

                        //rootWebContext.Load(webParts);
                        //rootWebcontext.ExecuteQueryWithTrace();

                        ListItem targetWebPart = SearchItemByName(webPartCatalog, webPartCatalog.RootFolder,
                            webPartModel.WebpartFileName);

                        //foreach (var webPart in webParts)
                        //    if (webPart["FileLeafRef"].ToString().ToUpper() == webPartModel.WebpartFileName.ToUpper())
                        //        targetWebPart = webPart;

                        if (targetWebPart == null)
                            throw new SPMeta2Exception(string.Format("Cannot find web part file by name:[{0}]",
                                webPartModel.WebpartFileName));

                        var webPartFile = targetWebPart.File;

                        rootWebContext.Load(webPartFile);
                        rootWebContext.ExecuteQueryWithTrace();


                        // does not work for apps - https://github.com/SubPointSolutions/spmeta2/issues/174
                        //var fileInfo = Microsoft.SharePoint.Client.File.OpenBinaryDirect(listItemModelHost.HostclientContext, webPartFile.ServerRelativeUrl);

                        //using (var reader = new StreamReader(fileInfo.Stream))
                        //{
                        //    webPartXML = reader.ReadToEnd();
                        //}

                        var data = webPartFile.OpenBinaryStream();

                        context.Load(webPartFile);
                        context.ExecuteQueryWithTrace();

                        using (var reader = new StreamReader(data.Value))
                        {
                            result = reader.ReadToEnd();
                        }

                        if (!_wpCache.ContainsKey(wpKey))
                            _wpCache.Add(wpKey, result);
                        else
                            _wpCache[wpKey] = result;
                    }
                }
            }

            if (!string.IsNullOrEmpty(webPartModel.WebpartType))
                throw new Exception("WebpartType is not supported yet.");

            if (!string.IsNullOrEmpty(webPartModel.WebpartXmlTemplate))
                result = webPartModel.WebpartXmlTemplate;

            return result;
        }
Esempio n. 30
0
        private void HandleWikiPageProvision(ListItem listItem,
            WebPartDefinitionBase webpartModel, Guid? webPartStoreKey, Guid? oldWebParKey)
        {
            if (!webpartModel.AddToPageContent)
                return;

            TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "AddToPageContent = true. Handling wiki/publishig page provision case.");

            var context = listItem.Context;

            var targetFieldName = string.Empty;

            if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.WikiField))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "WikiField field is detected. Switching to wiki page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.WikiField;
            }
            else if (listItem.FieldValues.ContainsKey(BuiltInInternalFieldNames.PublishingPageLayout))
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "PublishingPageLayout field is detected. Switching to publishin page web part provision.");

                targetFieldName = BuiltInInternalFieldNames.PublishingPageContent;
            }
            else
            {
                TraceService.Information((int)LogEventId.ModelProvisionCoreCall, "Not PublishingPageLayout field, nor WikiField is detected. Skipping.");
                return;
            }

            var wikiTemplate = new StringBuilder();

            var existingWebPartId = string.Empty;

            var definitionWebPartId = webpartModel.Id.ToString()
                                      .Replace("g_", string.Empty)
                                      .Replace("_", "-"); ;

            var upcomingWebPartId = definitionWebPartId;

            // aa....
            // extremely unfortunate
            if (webpartModel is XsltListViewWebPartDefinition)
            {
                upcomingWebPartId = webPartStoreKey.ToString()
                                      .Replace("g_", string.Empty)
                                      .Replace("_", "-"); ;
            }

            if (!oldWebParKey.HasGuidValue())
            {
                // first provision
                existingWebPartId = webPartStoreKey.ToString()
                                      .Replace("g_", string.Empty)
                                      .Replace("_", "-");
            }
            else
            {
                // second, so that we had web part and use that ID
                existingWebPartId = oldWebParKey.ToString()
                                      .Replace("g_", string.Empty)
                                      .Replace("_", "-");
            }

            var content = listItem[targetFieldName] == null
                ? string.Empty
                : listItem[targetFieldName].ToString();

            // actual ID will be replaced later
            wikiTemplate.AppendFormat("​​​​​​​​​​​​​​​​​​​​​​<div class='ms-rtestate-read ms-rte-wpbox' contentEditable='false'>");
            wikiTemplate.Append("     <div class='ms-rtestate-read {0}' id='div_{0}'>");
            wikiTemplate.AppendFormat("     </div>");
            wikiTemplate.AppendFormat("</div>");

            var wikiTemplateOutput = wikiTemplate.ToString();

            if (string.IsNullOrEmpty(content))
            {
                // page is empty, pre-generating HTML
                // pushing web part as the current WebPart Key
                TraceService.Verbose((int)LogEventId.ModelProvisionCoreCall,
                    "Page content is empty Generating new one.");

                content = string.Format(wikiTemplateOutput, upcomingWebPartId);

                listItem[targetFieldName] = content;
                listItem.Update();

                context.ExecuteQueryWithTrace();
            }
            else
            {
                // we had web part on the page
                // so we need to change the ID
                if (oldWebParKey.HasGuidValue())
                {
                    // was old on the page?
                    if (content.ToUpper().IndexOf(existingWebPartId.ToUpper()) != -1)
                    {
                        // yes, replacing ID
                        TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                            string.Format("Replacing web part with ID: [{0}] to [{1}] on the page content.",
                                existingWebPartId, upcomingWebPartId),
                            null);

                        content = content.Replace(existingWebPartId, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                    // original from the definigion?
                    else if (content.ToUpper().IndexOf(definitionWebPartId.ToUpper()) != -1)
                    {
                        // yes, replacing ID
                        TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                            string.Format("Replacing web part with ID: [{0}] to [{1}] on the page content.",
                                existingWebPartId, upcomingWebPartId),
                            null);

                        content = content.Replace(definitionWebPartId, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                    else
                    {
                        // adding new, from scratch
                        TraceService.WarningFormat((int)LogEventId.ModelProvisionCoreCall,
                            "Cannot find web part ID: [{0}] the page content. Adding a new one.",
                            new object[]
                            {
                                existingWebPartId
                            });

                        content = string.Format(wikiTemplateOutput, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                }
                else
                {
                    // first provision, no web parts on the wiki page

                    // there should be a definition based web part id in the template
                    // updatting to a upcoming ID
                    if (content.ToUpper().IndexOf(definitionWebPartId.ToUpper()) != -1)
                    {
                        // yes, replacing ID
                        TraceService.VerboseFormat((int)LogEventId.ModelProvisionCoreCall,
                            string.Format("Replacing web part with ID: [{0}] to [{1}] on the page content.",
                                definitionWebPartId, upcomingWebPartId),
                            null);

                        content = content.Replace(definitionWebPartId, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                    else
                    {
                        // adding new, from scratch
                        TraceService.WarningFormat((int)LogEventId.ModelProvisionCoreCall,
                            "Cannot find web part ID: [{0}] the page content. Adding a new one.",
                            new object[]
                            {
                                existingWebPartId
                            });

                        content = string.Format(wikiTemplateOutput, upcomingWebPartId);

                        listItem[targetFieldName] = content;
                        listItem.Update();

                        context.ExecuteQueryWithTrace();
                    }
                }
            }
        }