コード例 #1
0
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        internal static string GetWebPartDetailsMinimal(WebPart wp, SPLimitedWebPartManager manager)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement wpXml = xmlDoc.CreateElement("WebPart");

            xmlDoc.AppendChild(wpXml);

            wpXml.SetAttribute("id", wp.ID);

            XmlElement prop = xmlDoc.CreateElement("Title");

            prop.InnerText = wp.Title;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("Description");
            prop.InnerText = wp.Description;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("DisplayTitle");
            prop.InnerText = wp.DisplayTitle;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("Hidden");
            prop.InnerText = wp.Hidden.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsClosed");
            prop.InnerText = wp.IsClosed.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsShared");
            prop.InnerText = wp.IsShared.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsStandalone");
            prop.InnerText = wp.IsStandalone.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsStatic");
            prop.InnerText = wp.IsStatic.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Zone");
            if (wp.Zone != null)
            {
                prop.InnerText = wp.Zone.ToString();
            }
            else
            {
                prop.InnerText = manager.GetZoneID(wp);
            }
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("ZoneIndex");
            prop.InnerText = wp.ZoneIndex.ToString();
            wpXml.AppendChild(prop);

            return(Utilities.GetFormattedXml(xmlDoc));
        }
コード例 #2
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.
        }
コード例 #3
0
        public string GetZoneId(SPWebPartInstance webPart)
        {
            if (webPart == null)
            {
                throw new JavaScriptException(this.Engine, "Error", "A web part must be supplied as the first argument.");
            }

            return(m_limitedWebPartManager.GetZoneID(webPart.WebPart));
        }
コード例 #4
0
        internal static WebPart GetSourceWebPart(string url, string webPartTitle, string webPartId, out string zone)
        {
            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);
                        }
                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            WebPart webPart = null;
                            if (!string.IsNullOrEmpty(webPartTitle))
                            {
                                webPart = Utilities.GetWebPartByTitle(web, url, webPartTitle, out manager);
                            }
                            else if (!string.IsNullOrEmpty(webPartId))
                            {
                                webPart = Utilities.GetWebPartById(web, url, webPartId, out manager);
                            }

                            if (manager != null)
                            {
                                zone = manager.GetZoneID(webPart);
                            }
                            else
                            {
                                zone = null;
                            }
                            return(webPart);
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
コード例 #5
0
        private string ClearWebParts(SPLimitedWebPartManager webPartManager)
        {
            string zoneId      = "Bottom";
            var    webPartList = new List <System.Web.UI.WebControls.WebParts.WebPart>();

            foreach (System.Web.UI.WebControls.WebParts.WebPart webpart in webPartManager.WebParts)
            {
                webPartList.Add(webpart);
            }

            if (webPartList.Any())
            {
                // take any of the webpart zones Id
                zoneId = webPartManager.GetZoneID(webPartList[0]);

                foreach (var webpart in webPartList)
                {
                    webPartManager.DeleteWebPart(webpart);
                }
            }
            return(zoneId);
        }
コード例 #6
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.
        }
コード例 #7
0
        public static int GetLatestWebPartIndex(SPWeb web, string pageUrl, string zoneId)
        {
            int idx = 0;

            try
            {
                string fullPageUrl = string.Format("{0}/{1}", web.Url.TrimEnd('/'), pageUrl.TrimStart('/'));

                SPLimitedWebPartManager mgr = web.GetLimitedWebPartManager(
                    fullPageUrl,
                    System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

                foreach (System.Web.UI.WebControls.WebParts.WebPart wp in mgr.WebParts)
                {
                    if (string.IsNullOrEmpty(zoneId) || (!string.IsNullOrEmpty(zoneId) && mgr.GetZoneID(wp) == zoneId))
                    {
                        if (idx < wp.ZoneIndex)
                        {
                            idx = wp.ZoneIndex;
                        }
                    }
                }
            }
            catch (Exception) { }

            return(idx);
        }
コード例 #8
0
        internal static void SetWebPart(string url, SetWebPartStateAction action, string webPartId, string webPartTitle, string webPartZone, string webPartZoneIndex, Hashtable props, bool publish)
        {
            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)
                        {
                            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.
                            }
                        }

                        string  displayTitle            = string.Empty;
                        WebPart wp                      = null;
                        SPLimitedWebPartManager manager = null;
                        try
                        {
                            if (!string.IsNullOrEmpty(webPartId))
                            {
                                wp = Utilities.GetWebPartById(web, url, webPartId, out manager);
                            }
                            else
                            {
                                wp = Utilities.GetWebPartByTitle(web, url, webPartTitle, out manager);
                                if (wp == null)
                                {
                                    throw new SPException(
                                              "Unable to find specified web part using title \"" + webPartTitle + "\". Try specifying the -id parameter instead (use Get-SPWebPartList to get the ID)");
                                }
                            }

                            if (wp == null)
                            {
                                throw new SPException("Unable to find specified web part.");
                            }

                            // Set this so that we can add it to the check-in comment.
                            displayTitle = wp.DisplayTitle;

                            if (action == SetWebPartStateAction.Delete)
                            {
                                manager.DeleteWebPart(wp);
                            }
                            else if (action == SetWebPartStateAction.Close)
                            {
                                manager.CloseWebPart(wp);
                            }
                            else if (action == SetWebPartStateAction.Open)
                            {
                                manager.OpenWebPart(wp);
                            }


                            if (action != SetWebPartStateAction.Delete)
                            {
                                string zoneID    = manager.GetZoneID(wp);
                                int    zoneIndex = wp.ZoneIndex;

                                if (!string.IsNullOrEmpty(webPartZone))
                                {
                                    zoneID = webPartZone;
                                }
                                if (!string.IsNullOrEmpty(webPartZoneIndex))
                                {
                                    zoneIndex = int.Parse(webPartZoneIndex);
                                }

                                manager.MoveWebPart(wp, zoneID, zoneIndex);

                                if (props != null && props.Count > 0)
                                {
                                    SetWebPartProperties(wp, props);
                                }
                                manager.SaveChanges(wp);
                            }
                        }
                        finally
                        {
                            if (manager != null)
                            {
                                manager.Web.Dispose();
                                manager.Dispose();
                            }
                            if (wp != null)
                            {
                                wp.Dispose();
                            }

                            if (checkIn)
                            {
                                file.CheckIn("Checking in changes to page due to state change of web part " + displayTitle);
                            }
                            if (publish && file.InDocumentLibrary)
                            {
                                PublishItems pi = new PublishItems();
                                pi.PublishListItem(file.Item, file.Item.ParentList, false, "Set-SPWebPart", "Checking in changes to page due to state change of web part " + displayTitle, null);
                            }
                        }
                    }
                    finally
                    {
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }
        private static void CopyAllWebParts(string destinationPageUrlServerRelative, SPWeb destinationPageWeb, string sourcePageUrlServerRelative, SPWeb sourcePageWeb, bool shouldOverwriteDestinationWebParts)
        {
            SPWeb web  = null;
            SPWeb web2 = null;

            try
            {
                SPLimitedWebPartManager limitedWebPartManager = destinationPageWeb.GetLimitedWebPartManager(destinationPageUrlServerRelative, PersonalizationScope.Shared);
                SPLimitedWebPartManager manager2 = sourcePageWeb.GetLimitedWebPartManager(sourcePageUrlServerRelative, PersonalizationScope.Shared);
                web2 = limitedWebPartManager.Web;
                web  = manager2.Web;
                SPLimitedWebPartCollection webParts = manager2.WebParts;
                SPLimitedWebPartCollection parts2   = limitedWebPartManager.WebParts;

                if (webParts.Count > 0)
                {
                    foreach (System.Web.UI.WebControls.WebParts.WebPart part in webParts)
                    {
                        if (!part.IsClosed)
                        {
                            System.Web.UI.WebControls.WebParts.WebPart webPart = parts2[part.ID];
                            if (webPart == null)
                            {
                                try
                                {
                                    string zoneID = manager2.GetZoneID(part);
                                    limitedWebPartManager.AddWebPart(part, zoneID, part.ZoneIndex);
                                }
                                catch (ArgumentException e)
                                {
                                }
                            }
                            else
                            {
                                if (webPart.IsClosed)
                                {
                                    limitedWebPartManager.OpenWebPart(webPart);
                                }
                            }
                        }
                    }
                }
            }
            catch (Exception e)
            {
                if (HttpContext.Current != null)
                {
                    throw;
                }
            }
            finally
            {
                if ((web != sourcePageWeb) && (web != null))
                {
                    web.Close();
                }
                if ((web2 != destinationPageWeb) && (web2 != null))
                {
                    web2.Close();
                }
            }
        }
        private static XElement ExportPublishingPage(PublishingPage page, SPWeb web, ISharePointCommandContext context)
        {
            string siteCollectionUrl = web.Site.Url;

            XElement xModule = new XElement("Module",
                                            new XAttribute("Name", web.Title),
                                            new XAttribute("Url", "$Resources:osrvcore,List_Pages_UrlName;"),
                                            new XAttribute("Path", ""));

            XElement xFile = new XElement("File",
                                          new XAttribute("Url", page.Name),
                                          new XAttribute("Type", "GhostableInLibrary"));

            // export content
            SPListItem listItem = page.ListItem;

            foreach (SPField f in listItem.Fields)
            {
                string value = listItem[f.Id] as string;
                if (value != null)
                {
                    xFile.Add(new XElement("Property",
                                           new XAttribute("Name", f.InternalName),
                                           new XAttribute("Value", value.Replace(siteCollectionUrl, "~SiteCollection"))));
                }
            }

            // export web parts
            if (HttpContext.Current == null)
            {
                HttpRequest request = new HttpRequest("", web.Url, "");
                HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
                HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
            }

            using (SPLimitedWebPartManager wpMgr = web.GetLimitedWebPartManager(page.Uri.ToString(), PersonalizationScope.Shared))
            {
                foreach (System.Web.UI.WebControls.WebParts.WebPart wp in wpMgr.WebParts)
                {
                    if (wp.ExportMode != WebPartExportMode.None)
                    {
                        try
                        {
                            string webPartXml = ExportToXml(wp, wpMgr);
                            xFile.Add(new XElement("AllUsersWebPart",
                                                   new XAttribute("WebPartZoneID", wpMgr.GetZoneID(wp)),
                                                   new XAttribute("WebPartOrder", wp.ZoneIndex),
                                                   new XCData(webPartXml)));
                        }
                        catch (Exception ex)
                        {
                            context.Logger.WriteLine(String.Format("The following error has occured while exporting Web Part '{0}': {1}",
                                                                   wp.Title,
                                                                   ex.Message), LogCategory.Error);
                        }
                    }
                }
            }

            xModule.Add(xFile);

            return(xModule);
        }
コード例 #11
0
        private static void RestoreDataViewOutZone(SPWeb web, string filePath)
        {
            if (!File.Exists(filePath) || web == null)
            {
                return;
            }

            XmlDocument doc = new XmlDocument();

            try
            {
                doc.Load(filePath);
            }
            catch (XmlException)
            {
                return;
            }

            XmlNodeList xFixupFiles = doc.DocumentElement.SelectNodes("FixupFiles/FixupFile[@DataViewOutZone=\"TRUE\"]");

            foreach (XmlNode xFixupFile in xFixupFiles)
            {
                XmlAttribute xRelativePath = xFixupFile.Attributes["RelativePath"];
                if (xRelativePath == null)
                {
                    continue;
                }
                string relativePath = xRelativePath.Value;

                SPFile file = web.GetFile(relativePath);
                if (file == null)
                {
                    continue;
                }

                string fileName = file.Name;

                string content = String.Empty;
                using (StreamReader reader = new StreamReader(file.OpenBinaryStream()))
                {
                    content = reader.ReadToEnd();
                    content = SubstituteGuid(web, filePath, content);
                }

                UTF8Encoding encoder        = new UTF8Encoding();
                byte[]       contentAsBytes = encoder.GetBytes(content);

                // store to temporary file
                SPFile temp = web.Files.Add("temp.aspx", contentAsBytes);

                SPLimitedWebPartManager    sourceManager  = file.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                SPLimitedWebPartCollection sourceWebParts = sourceManager.WebParts;

                SPLimitedWebPartManager targetManager = temp.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                foreach (System.Web.UI.WebControls.WebParts.WebPart webPart in sourceWebParts)
                {
                    string zoneId = sourceManager.GetZoneID(webPart);
                    targetManager.AddWebPart(webPart, zoneId, webPart.ZoneIndex);
                }

                foreach (SPWebPartConnection connection in sourceManager.SPWebPartConnections)
                {
                    targetManager.SPConnectWebParts(connection.Provider, connection.ProviderConnectionPoint, connection.Consumer, connection.ConsumerConnectionPoint, connection.Transformer);
                }

                file.Delete();

                temp.CopyTo(fileName);
                temp.Delete();

                web.Update();
            }
        }
コード例 #12
0
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        internal static string GetWebPartDetailsMinimal(WebPart wp, SPLimitedWebPartManager manager)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement wpXml = xmlDoc.CreateElement("WebPart");
            xmlDoc.AppendChild(wpXml);

            wpXml.SetAttribute("id", wp.ID);

            XmlElement prop = xmlDoc.CreateElement("Title");
            prop.InnerText = wp.Title;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Description");
            prop.InnerText = wp.Description;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("DisplayTitle");
            prop.InnerText = wp.DisplayTitle;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Hidden");
            prop.InnerText = wp.Hidden.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsClosed");
            prop.InnerText = wp.IsClosed.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsShared");
            prop.InnerText = wp.IsShared.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStandalone");
            prop.InnerText = wp.IsStandalone.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStatic");
            prop.InnerText = wp.IsStatic.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Zone");
            if (wp.Zone != null)
                prop.InnerText = wp.Zone.ToString();
            else
                prop.InnerText = manager.GetZoneID(wp);
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ZoneIndex");
            prop.InnerText = wp.ZoneIndex.ToString();
            wpXml.AppendChild(prop);

            return Utilities.GetFormattedXml(xmlDoc);
        }
コード例 #13
0
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        internal static string GetWebPartDetailsSimple(WebPart wp, SPLimitedWebPartManager manager)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement wpXml = xmlDoc.CreateElement("WebPart");
            xmlDoc.AppendChild(wpXml);

            wpXml.SetAttribute("id", wp.ID);

            XmlElement prop = xmlDoc.CreateElement("Title");
            prop.InnerText = wp.Title;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowClose");
            prop.InnerText = wp.AllowClose.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowConnect");
            prop.InnerText = wp.AllowConnect.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowEdit");
            prop.InnerText = wp.AllowEdit.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowHide");
            prop.InnerText = wp.AllowHide.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("TitleUrl");
            prop.InnerText = wp.TitleUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowMinimize");
            prop.InnerText = wp.AllowMinimize.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("AllowZoneChange");
            prop.InnerText = wp.AllowZoneChange.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("CatalogIconImageUrl");
            prop.InnerText = wp.CatalogIconImageUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ChromeState");
            prop.InnerText = wp.ChromeState.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ChromeType");
            prop.InnerText = wp.ChromeType.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Description");
            prop.InnerText = wp.Description;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("DisplayTitle");
            prop.InnerText = wp.DisplayTitle;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("HasSharedData");
            prop.InnerText = wp.HasSharedData.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("HasUserData");
            prop.InnerText = wp.HasUserData.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Hidden");
            prop.InnerText = wp.Hidden.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsClosed");
            prop.InnerText = wp.IsClosed.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsShared");
            prop.InnerText = wp.IsShared.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStandalone");
            prop.InnerText = wp.IsStandalone.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("IsStatic");
            prop.InnerText = wp.IsStatic.ToString();
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Subtitle");
            prop.InnerText = wp.Subtitle;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("TitleUrl");
            prop.InnerText = wp.TitleUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("TitleIconImageUrl");
            prop.InnerText = wp.TitleIconImageUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Zone");
            if (wp.Zone != null)
                prop.InnerText = wp.Zone.ToString();
            else
                prop.InnerText = manager.GetZoneID(wp);
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("ZoneIndex");
            prop.InnerText = wp.ZoneIndex.ToString();
            wpXml.AppendChild(prop);

            return Utilities.GetFormattedXml(xmlDoc);
        }
コード例 #14
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;
                        }
                    }
                }
        }
コード例 #15
0
        public List <WebPartToDisplay> GetAllWebPartsOnPage(SPWeb web, string pageUrl, bool includeSharePointWebParts, bool includeCustomWebParts)
        {
            if (web == null)
            {
                return(new List <WebPartToDisplay>());
            }
            if (string.IsNullOrEmpty(pageUrl))
            {
                return(new List <WebPartToDisplay>());
            }

            bool isContextNull = false;

            if (HttpContext.Current == null)
            {
                isContextNull = true;
                HttpRequest request = new HttpRequest(string.Empty, web.Url, string.Empty);
                HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
                HttpContext.Current.Items["HttpHandlerSPWeb"] = web;
            }

            List <WebPartToDisplay> allWebParts = new List <WebPartToDisplay>();

            using (SPLimitedWebPartManager webpartManager = web.GetFile(pageUrl).GetLimitedWebPartManager(PersonalizationScope.Shared))
            {
                foreach (object webpartObject in webpartManager.WebParts)
                {
                    try
                    {
                        WebPartToDisplay webpartToDisplay = new WebPartToDisplay();
                        if (webpartObject is Microsoft.SharePoint.WebPartPages.WebPart)
                        {
                            // This is a SharePoint web part
                            Microsoft.SharePoint.WebPartPages.WebPart sharepointWebPart = webpartObject as Microsoft.SharePoint.WebPartPages.WebPart;
                            webpartToDisplay.Title       = sharepointWebPart.Title;
                            webpartToDisplay.Description = sharepointWebPart.Description;
                            webpartToDisplay.Type        = sharepointWebPart.GetType().ToString();
                            webpartToDisplay.Zone        = sharepointWebPart.ZoneID;
                            webpartToDisplay.PageUrl     = web.Url + "/" + pageUrl;
                            webpartToDisplay.Visible     = sharepointWebPart.Visible;
                            webpartToDisplay.Category    = GetWebPartCategory(webpartToDisplay.Type);
                        }
                        else if (webpartObject is System.Web.UI.WebControls.WebParts.WebPart)
                        {
                            // This is a ASP.NET web part
                            System.Web.UI.WebControls.WebParts.WebPart aspnetWebPart = webpartObject as System.Web.UI.WebControls.WebParts.WebPart;
                            webpartToDisplay.Title       = aspnetWebPart.Title;
                            webpartToDisplay.Description = aspnetWebPart.Description;
                            webpartToDisplay.Type        = aspnetWebPart.GetType().ToString();
                            webpartToDisplay.Zone        = webpartManager.GetZoneID(aspnetWebPart);
                            webpartToDisplay.PageUrl     = web.Url + "/" + pageUrl;
                            webpartToDisplay.Visible     = aspnetWebPart.Visible;
                            webpartToDisplay.Category    = GetWebPartCategory(webpartToDisplay.Type);
                        }

                        if (webpartToDisplay.Category == WebPartCategory.SharePoint && !includeSharePointWebParts)
                        {
                            continue;
                        }
                        if (webpartToDisplay.Category == WebPartCategory.Custom && !includeCustomWebParts)
                        {
                            continue;
                        }

                        allWebParts.Add(webpartToDisplay);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                    finally
                    {
                        if (isContextNull)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
                webpartManager.Dispose();
            }

            if (isContextNull)
            {
                HttpContext.Current = null;
            }

            return(allWebParts);
        }
コード例 #16
0
        /// <summary>
        /// Gets the web part details.
        /// </summary>
        /// <param name="wp">The web part.</param>
        /// <param name="manager">The web part manager.</param>
        internal static string GetWebPartDetailsSimple(WebPart wp, SPLimitedWebPartManager manager)
        {
            XmlDocument xmlDoc = new XmlDocument();

            XmlElement wpXml = xmlDoc.CreateElement("WebPart");

            xmlDoc.AppendChild(wpXml);

            wpXml.SetAttribute("id", wp.ID);

            XmlElement prop = xmlDoc.CreateElement("Title");

            prop.InnerText = wp.Title;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("AllowClose");
            prop.InnerText = wp.AllowClose.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("AllowConnect");
            prop.InnerText = wp.AllowConnect.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("AllowEdit");
            prop.InnerText = wp.AllowEdit.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("AllowHide");
            prop.InnerText = wp.AllowHide.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("TitleUrl");
            prop.InnerText = wp.TitleUrl;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("AllowMinimize");
            prop.InnerText = wp.AllowMinimize.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("AllowZoneChange");
            prop.InnerText = wp.AllowZoneChange.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("CatalogIconImageUrl");
            prop.InnerText = wp.CatalogIconImageUrl;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("ChromeState");
            prop.InnerText = wp.ChromeState.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("ChromeType");
            prop.InnerText = wp.ChromeType.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("Description");
            prop.InnerText = wp.Description;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("DisplayTitle");
            prop.InnerText = wp.DisplayTitle;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("HasSharedData");
            prop.InnerText = wp.HasSharedData.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("HasUserData");
            prop.InnerText = wp.HasUserData.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("Hidden");
            prop.InnerText = wp.Hidden.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsClosed");
            prop.InnerText = wp.IsClosed.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsShared");
            prop.InnerText = wp.IsShared.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsStandalone");
            prop.InnerText = wp.IsStandalone.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("IsStatic");
            prop.InnerText = wp.IsStatic.ToString();
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("Subtitle");
            prop.InnerText = wp.Subtitle;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("TitleUrl");
            prop.InnerText = wp.TitleUrl;
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("TitleIconImageUrl");
            prop.InnerText = wp.TitleIconImageUrl;
            wpXml.AppendChild(prop);

            prop = xmlDoc.CreateElement("Zone");
            if (wp.Zone != null)
            {
                prop.InnerText = wp.Zone.ToString();
            }
            else
            {
                prop.InnerText = manager.GetZoneID(wp);
            }
            wpXml.AppendChild(prop);

            prop           = xmlDoc.CreateElement("ZoneIndex");
            prop.InnerText = wp.ZoneIndex.ToString();
            wpXml.AppendChild(prop);

            return(Utilities.GetFormattedXml(xmlDoc));
        }