Beispiel #1
0
        //public virtual void ExportWebPart(WebPart webPart, XmlWriter writer)
        //{
        //    if (webPart == null)
        //    {
        //        throw new ArgumentNullException("webPart");
        //    }
        //    if (!this.Controls.Contains(webPart))
        //    {
        //        throw new ArgumentException(SR.GetString("UnknownWebPart"), "webPart");
        //    }
        //    if (writer == null)
        //    {
        //        throw new ArgumentNullException("writer");
        //    }
        //    if (webPart.ExportMode == WebPartExportMode.None)
        //    {
        //        throw new ArgumentException(SR.GetString("WebPartManager_PartNotExportable"), "webPart");
        //    }
        //    bool arg_79_0 = (webPart.ExportMode != WebPartExportMode.NonSensitiveData) ? false : (this.Personalization.Scope != PersonalizationScope.Shared);
        //    bool flag = arg_79_0;
        //    writer.WriteStartElement("webParts");
        //    writer.WriteStartElement("webPart");
        //    writer.WriteAttributeString("xmlns", "http://schemas.microsoft.com/WebPart/v3");
        //    writer.WriteStartElement("metaData");
        //    writer.WriteStartElement("type");
        //    Control control = webPart.ToControl();
        //    UserControl userControl = control as UserControl;
        //    if (userControl == null)
        //    {
        //        writer.WriteAttributeString("name", WebPartUtil.SerializeType(control.GetType()));
        //    }
        //    else
        //    {
        //        writer.WriteAttributeString("src", userControl.AppRelativeVirtualPath);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteElementString("importErrorMessage", webPart.ImportErrorMessage);
        //    writer.WriteEndElement();
        //    writer.WriteStartElement("data");
        //    IDictionary personalizablePropertyValues = PersonalizableAttribute.GetPersonalizablePropertyValues(webPart, PersonalizationScope.Shared, flag);
        //    writer.WriteStartElement("properties");
        //    if (!(webPart is GenericWebPart))
        //    {
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    else
        //    {
        //        this.ExportIPersonalizable(writer, control, flag);
        //        IDictionary personalizablePropertyValues2 = PersonalizableAttribute.GetPersonalizablePropertyValues(control, PersonalizationScope.Shared, flag);
        //        this.ExportToWriter(personalizablePropertyValues2, writer);
        //        writer.WriteEndElement();
        //        writer.WriteStartElement("genericWebPartProperties");
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //}

        private static void CreateDefaultWebPart(SPWeb web, SPLimitedWebPartManager webPartManager, WebpartDefinition wp, System.Web.UI.WebControls.WebParts.WebPart concerateWP)
        {
            //TODO : find a solution to create default webpart late
            return;

            if (wp is XSLTListViewWP)
            {
                XSLTListViewWP xstlWP = wp as XSLTListViewWP;
                if (xstlWP.CreateDefaultWP)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);
                        concerateWP.ExportMode = System.Web.UI.WebControls.WebParts.WebPartExportMode.All;

                        webPartManager.ExportWebPart(concerateWP, writer);


                        var webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);

                        //var fileStream
                        SPFile spfile = webPartGallery.RootFolder.Files.Add(wp.Title + ".webpart", ms.GetBuffer(), true);

                        // Commit
                        webPartGallery.RootFolder.Update();
                        webPartGallery.Update();
                    }
                }
            }
        }
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        /// <returns></returns>
        internal static string GetWebPartDetails(WebPart wp, SPLimitedWebPartManager manager)
        {
            if (wp.ExportMode == WebPartExportMode.None)
            {
                Logger.WriteWarning("Unable to export {0}", wp.Title);
                return "";
            }
            StringBuilder sb = new StringBuilder();

            XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
            xmlWriter.Formatting = Formatting.Indented;
            manager.ExportWebPart(wp, xmlWriter);
            xmlWriter.Flush();

            XmlDocument xmlDoc = new XmlDocument();
            xmlDoc.LoadXml(sb.ToString());

            XmlElement elem = xmlDoc.DocumentElement;
            if (xmlDoc.DocumentElement.Name == "webParts")
            {
                elem = (XmlElement)xmlDoc.DocumentElement.ChildNodes[0];

                // We've found a v3 web part but the export method does not export what the zone ID is so we
                // have to manually add that in.  Unfortunately the Zone property is always null because we are
                // using a SPLimitedWebPartManager so we have to use the helper method GetZoneID to set the zone ID.
                XmlElement property = xmlDoc.CreateElement("property");
                property.SetAttribute("name", "ZoneID");
                property.SetAttribute("type", "string");
                property.InnerText = manager.GetZoneID(wp);
                elem.ChildNodes[1].ChildNodes[0].AppendChild(property);
            }

            return elem.OuterXml.Replace(" xmlns=\"\"", ""); // Just some minor cleanup to deal with erroneous namespace tags added due to the zoneID being added manually.
        }
Beispiel #3
0
 private void btn_Export_Click(object sender, EventArgs e)
 {
     using (SPSite site = new SPSite(siteUrl))
     {
         using (SPWeb web = site.OpenWeb(webUrl))
         {
             SPFile thePage = web.GetFile(pageUrl);
             SPLimitedWebPartManager    theWebPartManager = thePage.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
             SPLimitedWebPartCollection webParts          = theWebPartManager.WebParts;
             XmlWriter writer = null;
             for (int i = 0; i < webParts.Count; i++)
             {
                 try
                 {
                     writer = new XmlTextWriter(tb_ExportPath.Text + webParts[i].Title + ".xml", Encoding.UTF8);
                     theWebPartManager.ExportWebPart(webParts[i], writer);
                     writer.Flush();
                     writer.Close();
                     tb_Message.Text += webParts[i].Title + "Export Success...";
                 }
                 catch
                 {
                     tb_Message.Text += webParts[i].Title + "Export Failed...";
                 }
             }
         }
     }
 }
Beispiel #4
0
        public override TabPage[] GetTabPages()
        {
            ArrayList alPages = new ArrayList();

            alPages.AddRange(base.GetTabPages());


            if (this.Parent.Tag != null)
            {
                string xml = string.Empty;

                SPLimitedWebPartManager manager = (SPLimitedWebPartManager)this.Parent.Tag;
                using (StringWriter writer = new StringWriter())
                {
                    XmlTextWriter xtw = new XmlTextWriter(writer);
                    //this.ASPWebPart.ExportMode == WebPartExportMode.All;
                    manager.ExportWebPart(this.ASPWebPart, xtw);
                    xml = writer.ToString();
                }
                TabXmlPage xmlPage = TabPages.GetXmlPage("Xml", xml);
                alPages.Add(xmlPage);
            }

            return((TabPage[])alPages.ToArray(typeof(TabPage)));
        }
        private static string ExportToXml(System.Web.UI.WebControls.WebParts.WebPart webPart, SPLimitedWebPartManager wpMgr)
        {
            StringBuilder builder  = new StringBuilder();
            UTF8Encoding  encoding = new UTF8Encoding(true);
            MemoryStream  stream   = new MemoryStream();
            StreamWriter  w        = new StreamWriter(stream);
            XmlTextWriter writer   = new XmlTextWriter(w);

            wpMgr.ExportWebPart(webPart, writer);
            writer.Flush();
            return(new string(encoding.GetChars((w.BaseStream as MemoryStream).ToArray())));
        }
        public Base64EncodedByteArrayInstance ExportWebPart(SPWebPartInstance webPart)
        {
            if (webPart == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "A web part must be supplied as the first argument.");
            }

            using (var ms = new MemoryStream())
            {
                var writer = XmlWriter.Create(ms);
                m_limitedWebPartManager.ExportWebPart(webPart.WebPart, writer);
                writer.Flush();
                return(new Base64EncodedByteArrayInstance(this.Engine.Object.InstancePrototype, ms.ToArray()));
            }
        }
Beispiel #7
0
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        /// <returns></returns>
        internal static string GetWebPartDetails(WebPart wp, SPLimitedWebPartManager manager)
        {
            if (wp.ExportMode == WebPartExportMode.None)
            {
                Logger.WriteWarning("Unable to export {0}", wp.Title);
                return("");
            }
            StringBuilder sb = new StringBuilder();

            XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));

            xmlWriter.Formatting = Formatting.Indented;
            manager.ExportWebPart(wp, xmlWriter);
            xmlWriter.Flush();

            XmlDocument xmlDoc = new XmlDocument();

            xmlDoc.LoadXml(sb.ToString());

            XmlElement elem = xmlDoc.DocumentElement;

            if (xmlDoc.DocumentElement.Name == "webParts")
            {
                elem = (XmlElement)xmlDoc.DocumentElement.ChildNodes[0];

                // We've found a v3 web part but the export method does not export what the zone ID is so we
                // have to manually add that in.  Unfortunately the Zone property is always null because we are
                // using a SPLimitedWebPartManager so we have to use the helper method GetZoneID to set the zone ID.
                XmlElement property = xmlDoc.CreateElement("property");
                property.SetAttribute("name", "ZoneID");
                property.SetAttribute("type", "string");
                property.InnerText = manager.GetZoneID(wp);
                elem.ChildNodes[1].ChildNodes[0].AppendChild(property);
            }

            return(elem.OuterXml.Replace(" xmlns=\"\"", "")); // Just some minor cleanup to deal with erroneous namespace tags added due to the zoneID being added manually.
        }
        /// <summary>
        /// Adds the web part.
        /// </summary>
        /// <param name="file">The page.</param>
        /// <param name="webPartXml">The web part XML file.</param>
        /// <param name="webPartTitle">The web part title.</param>
        /// <param name="zone">The zone.</param>
        /// <param name="zoneId">The zone id.</param>
        /// <param name="deleteWebPart">if set to <c>true</c> [delete web part].</param>
        /// <param name="customReplaceText">The custom replace text.</param>
        /// <param name="chromeType">Type of the chrome.</param>
        /// <param name="publish">if set to <c>true</c> [publish].</param>
        /// <returns></returns>
        public WebPart AddWebPart(SPFile file, string webPartXml, string assembly, string typeName, string webPartTitle, string zone, int zoneId, bool deleteWebPart, Hashtable customReplaceText, PartChromeType chromeType, bool publish)
        {
            bool cleanupContext = false;
            bool checkBackIn    = false;

            if (file.InDocumentLibrary)
            {
                if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                {
                    checkBackIn = true;
                    file.CheckOut();
                }
                // If it's checked out by another user then this will throw an informative exception so let it do so.
            }

            if (HttpContext.Current == null)
            {
                cleanupContext = true;
                HttpRequest httpRequest = new HttpRequest("", file.Item.ParentList.ParentWeb.Url, "");
                HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                SPControl.SetContextWeb(HttpContext.Current, file.Item.ParentList.ParentWeb);
            }

            string url = file.Item.ParentList.ParentWeb.Site.MakeFullUrl(file.ServerRelativeUrl);

            using (SPLimitedWebPartManager manager = file.Item.ParentList.ParentWeb.GetLimitedWebPartManager(url, PersonalizationScope.Shared))
            {
                try
                {
                    WebPart wp;
                    if (!string.IsNullOrEmpty(webPartXml))
                    {
                        wp = AddWebPart(manager, file, webPartXml, customReplaceText);
                    }
                    else
                    {
                        wp = AddWebPart(assembly, typeName);
                    }

                    if (!string.IsNullOrEmpty(webPartTitle))
                    {
                        wp.Title = webPartTitle;
                    }
                    webPartTitle  = wp.Title;
                    wp.ChromeType = chromeType;

                    // Delete existing web part with same title so that we only have the latest version on the page
                    foreach (WebPart wpTemp in manager.WebParts)
                    {
                        try
                        {
                            if (wpTemp.Title == wp.Title)
                            {
                                if (deleteWebPart)
                                {
                                    manager.DeleteWebPart(wpTemp);
                                    break;
                                }
                                else
                                {
                                    continue;
                                }
                            }
                        }
                        finally
                        {
                            wpTemp.Dispose();
                        }
                    }

                    try
                    {
                        manager.AddWebPart(wp, zone, zoneId);
                    }
                    catch (Exception)
                    {
                        System.Net.ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };

                        // We've not already added the web part so use the web service to do this.
                        using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                        {
                            // We failed adding via the OM so try the web service as a fall back.
                            svc.Url         = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                            svc.Credentials = System.Net.CredentialCache.DefaultCredentials;

                            try
                            {
                                // Add the web part to the web service.  We use a web service because many
                                // web parts require the SPContext.Current variables to be set which are
                                // not set when run from a command line.
                                StringBuilder sb        = new StringBuilder();
                                XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                xmlWriter.Formatting = Formatting.Indented;
                                manager.ExportWebPart(wp, xmlWriter);
                                xmlWriter.Flush();

                                svc.AddWebPartToZone(url, sb.ToString(), WebPartPagesWebService.Storage.Shared, zone, zoneId);
                            }
                            catch (System.Web.Services.Protocols.SoapException ex)
                            {
                                throw new Exception(ex.Detail.OuterXml);
                            }
                        }
                    }
                    return(wp);
                }
                finally
                {
                    if (cleanupContext)
                    {
                        HttpContext.Current = null;
                    }
                    if (manager != null)
                    {
                        manager.Web.Dispose();
                        manager.Dispose();
                    }

                    if (file.InDocumentLibrary && Utilities.IsCheckedOut(file.Item) && (checkBackIn || publish))
                    {
                        file.CheckIn("Checking in changes to page due to new web part being added: " + webPartTitle);
                    }

                    if (publish && file.InDocumentLibrary && file.Item.ParentList.EnableMinorVersions)
                    {
                        try
                        {
                            file.Publish("Publishing changes to page due to new web part being added: " + webPartTitle);
                            if (file.Item.ModerationInformation != null)
                            {
                                file.Approve("Approving changes to page due to new web part being added: " + webPartTitle);
                            }
                        }
                        catch (Exception ex)
                        {
                            WriteWarning("Unable to publish or approve file: " + ex.Message);
                        }
                    }
                }
            }
        }
Beispiel #9
0
        //public virtual void ExportWebPart(WebPart webPart, XmlWriter writer)
        //{
        //    if (webPart == null)
        //    {
        //        throw new ArgumentNullException("webPart");
        //    }
        //    if (!this.Controls.Contains(webPart))
        //    {
        //        throw new ArgumentException(SR.GetString("UnknownWebPart"), "webPart");
        //    }
        //    if (writer == null)
        //    {
        //        throw new ArgumentNullException("writer");
        //    }
        //    if (webPart.ExportMode == WebPartExportMode.None)
        //    {
        //        throw new ArgumentException(SR.GetString("WebPartManager_PartNotExportable"), "webPart");
        //    }
        //    bool arg_79_0 = (webPart.ExportMode != WebPartExportMode.NonSensitiveData) ? false : (this.Personalization.Scope != PersonalizationScope.Shared);
        //    bool flag = arg_79_0;
        //    writer.WriteStartElement("webParts");
        //    writer.WriteStartElement("webPart");
        //    writer.WriteAttributeString("xmlns", "http://schemas.microsoft.com/WebPart/v3");
        //    writer.WriteStartElement("metaData");
        //    writer.WriteStartElement("type");
        //    Control control = webPart.ToControl();
        //    UserControl userControl = control as UserControl;
        //    if (userControl == null)
        //    {
        //        writer.WriteAttributeString("name", WebPartUtil.SerializeType(control.GetType()));
        //    }
        //    else
        //    {
        //        writer.WriteAttributeString("src", userControl.AppRelativeVirtualPath);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteElementString("importErrorMessage", webPart.ImportErrorMessage);
        //    writer.WriteEndElement();
        //    writer.WriteStartElement("data");
        //    IDictionary personalizablePropertyValues = PersonalizableAttribute.GetPersonalizablePropertyValues(webPart, PersonalizationScope.Shared, flag);
        //    writer.WriteStartElement("properties");
        //    if (!(webPart is GenericWebPart))
        //    {
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    else
        //    {
        //        this.ExportIPersonalizable(writer, control, flag);
        //        IDictionary personalizablePropertyValues2 = PersonalizableAttribute.GetPersonalizablePropertyValues(control, PersonalizationScope.Shared, flag);
        //        this.ExportToWriter(personalizablePropertyValues2, writer);
        //        writer.WriteEndElement();
        //        writer.WriteStartElement("genericWebPartProperties");
        //        this.ExportIPersonalizable(writer, webPart, flag);
        //        this.ExportToWriter(personalizablePropertyValues, writer);
        //    }
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //    writer.WriteEndElement();
        //}
        private static void CreateDefaultWebPart(SPWeb web, SPLimitedWebPartManager webPartManager, WebpartDefinition wp, System.Web.UI.WebControls.WebParts.WebPart concerateWP)
        {
            //TODO : find a solution to create default webpart late
            return;
            if (wp is XSLTListViewWP)
            {
                XSLTListViewWP xstlWP = wp as XSLTListViewWP;
                if (xstlWP.CreateDefaultWP)
                {
                    using (MemoryStream ms = new MemoryStream())
                    {

                        XmlWriter writer = new XmlTextWriter(ms, Encoding.UTF8);
                        concerateWP.ExportMode = System.Web.UI.WebControls.WebParts.WebPartExportMode.All;

                        webPartManager.ExportWebPart(concerateWP, writer);

                        var webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);

                        //var fileStream
                        SPFile spfile = webPartGallery.RootFolder.Files.Add(wp.Title + ".webpart", ms.GetBuffer(), true);

                        // Commit
                        webPartGallery.RootFolder.Update();
                        webPartGallery.Update();

                    }

                }
            }
        }
Beispiel #10
0
        internal static void SetWebPart(string url, Type oldType, Type newType, string title, Hashtable properties, bool publish, bool test)
        {
            using (SPSite site = new SPSite(url))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }


                        SPFile file = web.GetFile(url);

                        // file.Item will throw "The object specified does not belong to a list." if the url passed
                        // does not correspond to a file in a list.

                        bool checkIn = false;
                        if (file.InDocumentLibrary && !test)
                        {
                            if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                            {
                                file.CheckOut();
                                checkIn = true;
                                // If it's checked out by another user then this will throw an informative exception so let it do so.
                            }
                        }

                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            List <WebPart> webParts = Utilities.GetWebPartsByType(web, url, oldType, out manager);
                            foreach (var oldWebPart in webParts)
                            {
                                if (oldWebPart.IsClosed)
                                {
                                    continue;
                                }

                                string wpTitle = oldWebPart.Title;
                                if (string.IsNullOrEmpty(wpTitle))
                                {
                                    wpTitle = oldWebPart.DisplayTitle;
                                }

                                if (!string.IsNullOrEmpty(title) &&
                                    (oldWebPart.DisplayTitle.ToLowerInvariant() != title.ToLowerInvariant() &&
                                     oldWebPart.Title.ToLowerInvariant() != title.ToLowerInvariant()))
                                {
                                    continue;
                                }
                                Logger.Write("Replacing web part \"{0}\"...", wpTitle);
                                string  zone       = manager.GetZoneID(oldWebPart);
                                WebPart newWebPart = (WebPart)Activator.CreateInstance(newType);
                                if (SetProperties(oldWebPart, newWebPart, properties))
                                {
                                    Logger.WriteWarning("An error was encountered setting web part properties so try one more time in case the error is the result of a sequencing issue.");
                                    if (SetProperties(oldWebPart, newWebPart, properties))
                                    {
                                        Logger.WriteWarning("Unable to set all properties for web part.");
                                    }
                                }
                                if (!test)
                                {
                                    manager.DeleteWebPart(oldWebPart);
                                }

                                try
                                {
                                    if (!test)
                                    {
                                        manager.AddWebPart(newWebPart, zone, oldWebPart.ZoneIndex);
                                    }
                                }
                                catch (Exception)
                                {
                                    ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };

                                    // We've not already added the web part so use the web service to do this.
                                    using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                                    {
                                        // We failed adding via the OM so try the web service as a fall back.
                                        svc.Url         = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                                        svc.Credentials = CredentialCache.DefaultCredentials;

                                        try
                                        {
                                            // Add the web part to the web service.  We use a web service because many
                                            // web parts require the SPContext.Current variables to be set which are
                                            // not set when run from a command line.
                                            StringBuilder sb        = new StringBuilder();
                                            XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                            xmlWriter.Formatting = Formatting.Indented;
                                            manager.ExportWebPart(newWebPart, xmlWriter);
                                            xmlWriter.Flush();

                                            svc.AddWebPartToZone(url, sb.ToString(), Storage.Shared, zone, oldWebPart.ZoneIndex);
                                        }
                                        catch (SoapException ex)
                                        {
                                            throw new Exception(ex.Detail.OuterXml);
                                        }
                                    }
                                }
                                finally
                                {
                                    oldWebPart.Dispose();
                                    newWebPart.Dispose();
                                }
                                if (zone == "wpz" && file.InDocumentLibrary)
                                {
                                    foreach (SPField field in file.Item.Fields)
                                    {
                                        if (!field.ReadOnlyField && field is SPFieldMultiLineText && ((SPFieldMultiLineText)field).WikiLinking && file.Item[field.Id] != null)
                                        {
                                            string content = file.Item[field.Id].ToString();
                                            if (content.Contains(oldWebPart.ID.Replace("_", "-").Substring(2)))
                                            {
                                                Logger.Write("Replacing web part identifier in text field \"{0}\"...", field.InternalName);
                                                if (!test)
                                                {
                                                    file.Item[field.Id] = content.Replace(oldWebPart.ID.Replace("_", "-").Substring(2), newWebPart.ID.Replace("_", "-").Substring(2));
                                                    file.Item.SystemUpdate();
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }

                            if (!test)
                            {
                                if (checkIn)
                                {
                                    file.CheckIn("Checking in changes to page due to web part being replaced with a different type.");
                                }
                                if (publish && file.InDocumentLibrary)
                                {
                                    PublishItems pi = new PublishItems();
                                    pi.PublishListItem(file.Item, file.Item.ParentList, false, "Replace-SPWebPartType", "Checking in changes to page due to web part being replaced with a different type.", null);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
        protected void TabContainerRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            // Panel is the place holder to show web parts in a tab.
            Panel panel = (Panel)e.Item.FindControl("TabContainer");

            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                if (panel != null)
                {
                    using (SPLimitedWebPartManager wpManager = SPContext.Current.File.GetLimitedWebPartManager(PersonalizationScope.Shared))
                    {
                        try
                        {
                            // Elevated previleges required for EXPORT and IMPORT. Else Users with normal read access will get errors.
                            SPSecurity.RunWithElevatedPrivileges(delegate()
                            {
                                // Retrieve the web part titles in the ConfigureTabs XML string for this tab.
                                var webPartTitles = from t in xDocument.Descendants("webPart")
                                                    where (string)t.Parent.Attribute("name") == (string)e.Item.DataItem
                                                    select(string) t.Attribute("title");

                                foreach (string wpTitle in webPartTitles)
                                {
                                    foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in wpManager.WebParts)
                                    {
                                        // Find the matched closed web part in WebParts collection
                                        if (webPart.Title == wpTitle && webPart.IsClosed == true)
                                        {
                                            string errorMessage;
                                            MemoryStream stream  = new MemoryStream();
                                            XmlTextWriter writer = new XmlTextWriter(stream, System.Text.Encoding.UTF8);

                                            // Export the closed webpart to a memory stream.
                                            wpManager.ExportWebPart(webPart, writer);

                                            writer.Flush();
                                            stream.Position = 0;

                                            XmlTextReader reader = new XmlTextReader(stream);

                                            // Import the exported webpart.
                                            System.Web.UI.WebControls.WebParts.WebPart newWebPart = wpManager.ImportWebPart(reader, out errorMessage);

                                            reader.Close();
                                            writer.Close();

                                            // Show the imported webpart.
                                            panel.Controls.Add(newWebPart);
                                            break;
                                        }
                                    }
                                }
                            });
                        }
                        catch (Exception ex)
                        {
                            // For debugging use only.
                            Label label = new Label();
                            label.Text = "Please check your XML configuration for error. " + Environment.NewLine + ex.Message;
                            panel.Controls.Add(label);
                        }
                    }
                }
            }
        }
Beispiel #12
0
        internal static void SetWebPart(WebPart sourceWebPart, string targetUrl, string zone, int?zoneIndex, bool publish, bool test)
        {
            if (sourceWebPart.IsClosed)
            {
                sourceWebPart.Dispose();
                throw new Exception("The source web part is closed and cannot be copied.");
            }

            int zoneIndex1 = sourceWebPart.ZoneIndex;

            if (zoneIndex.HasValue)
            {
                zoneIndex1 = zoneIndex.Value;
            }
            Guid   storageKey = Guid.NewGuid();
            string id         = StorageKeyToID(storageKey);

            using (SPSite site = new SPSite(targetUrl))
                using (SPWeb web = site.OpenWeb()) // The url contains a filename so AllWebs[] will not work unless we want to try and parse which we don't
                {
                    bool cleanupContext = false;
                    try
                    {
                        if (HttpContext.Current == null)
                        {
                            cleanupContext = true;
                            HttpRequest httpRequest = new HttpRequest("", web.Url, "");
                            HttpContext.Current = new HttpContext(httpRequest, new HttpResponse(new StringWriter()));
                            SPControl.SetContextWeb(HttpContext.Current, web);
                        }


                        SPFile file = web.GetFile(targetUrl);

                        // file.Item will throw "The object specified does not belong to a list." if the url passed
                        // does not correspond to a file in a list.

                        bool checkIn = false;
                        if (file.InDocumentLibrary && !test)
                        {
                            if (!Utilities.IsCheckedOut(file.Item) || !Utilities.IsCheckedOutByCurrentUser(file.Item))
                            {
                                file.CheckOut();
                                checkIn = true;
                                // If it's checked out by another user then this will throw an informative exception so let it do so.
                            }
                        }

                        SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
                        try
                        {
                            string wpTitle = sourceWebPart.Title;
                            if (string.IsNullOrEmpty(wpTitle))
                            {
                                wpTitle = sourceWebPart.DisplayTitle;
                            }

                            Logger.Write("Copying web part \"{0}\"...", wpTitle);
                            WebPart newWebPart = (WebPart)Activator.CreateInstance(sourceWebPart.GetType());
                            if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                            {
                                Logger.WriteWarning("An error was encountered setting web part properties so try one more time in case the error is the result of a sequencing issue.");
                                if (SPCmdletReplaceWebPartType.SetProperties(sourceWebPart, newWebPart, null))
                                {
                                    Logger.WriteWarning("Unable to set all properties for web part.");
                                }
                            }

                            try
                            {
                                if (!test)
                                {
                                    newWebPart.ID = id;

                                    manager.AddWebPart(newWebPart, zone, zoneIndex1);
                                }
                            }
                            catch (Exception)
                            {
                                ServicePointManager.ServerCertificateValidationCallback += delegate { return(true); };

                                // We've not already added the web part so use the web service to do this.
                                using (WebPartPagesWebService.WebPartPagesWebService svc = new WebPartPagesWebService.WebPartPagesWebService())
                                {
                                    // We failed adding via the OM so try the web service as a fall back.
                                    svc.Url         = manager.Web.Url + "/_vti_bin/WebPartPages.asmx";
                                    svc.Credentials = CredentialCache.DefaultCredentials;

                                    try
                                    {
                                        // Add the web part to the web service.  We use a web service because many
                                        // web parts require the SPContext.Current variables to be set which are
                                        // not set when run from a command line.
                                        StringBuilder sb        = new StringBuilder();
                                        XmlTextWriter xmlWriter = new XmlTextWriter(new StringWriter(sb));
                                        xmlWriter.Formatting = Formatting.Indented;
                                        manager.ExportWebPart(newWebPart, xmlWriter);
                                        xmlWriter.Flush();

                                        svc.AddWebPartToZone(targetUrl, sb.ToString(), Storage.Shared, zone, zoneIndex1);
                                    }
                                    catch (SoapException ex)
                                    {
                                        throw new Exception(ex.Detail.OuterXml);
                                    }
                                }
                            }
                            finally
                            {
                                sourceWebPart.Dispose();
                                newWebPart.Dispose();
                            }
                            if (zone == "wpz" && file.InDocumentLibrary)
                            {
                                foreach (SPField field in file.Item.Fields)
                                {
                                    if (!field.ReadOnlyField && field is SPFieldMultiLineText && ((SPFieldMultiLineText)field).WikiLinking)
                                    {
                                        string content = null;
                                        if (file.Item[field.Id] != null)
                                        {
                                            content = file.Item[field.Id].ToString();
                                        }

                                        string div = string.Format(CultureInfo.InvariantCulture, "<div class=\"ms-rtestate-read ms-rte-wpbox\" contentEditable=\"false\"><div class=\"ms-rtestate-read {0}\" id=\"div_{0}\"></div><div style='display:none' id=\"vid_{0}\"/></div>", new object[] { storageKey.ToString("D") });
                                        content += div;
                                        Logger.Write("Adding web part to text field \"{0}\"...", field.InternalName);
                                        if (!test)
                                        {
                                            file.Item[field.Id] = content;
                                            file.Item.SystemUpdate();
                                        }
                                    }
                                }
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }

                            if (!test)
                            {
                                if (checkIn)
                                {
                                    file.CheckIn("Checking in changes to page due to web part being replaced with a different type.");
                                }
                                if (publish && file.InDocumentLibrary)
                                {
                                    PublishItems pi = new PublishItems();
                                    pi.PublishListItem(file.Item, file.Item.ParentList, false, "Copy-SPWebPart", "Checking in changes to page due to web part being copied from another page.", null);
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }