private static void AddWebParts(SPFeatureReceiverProperties properties, string url, System.Web.UI.WebControls.WebParts.WebPart[] webPart, string[] zones)
        {
            SPWeb  web  = (SPWeb)properties.Feature.Parent;
            SPFile file = web.GetFile(url);
            SPLimitedWebPartManager manager = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
            int index = 2;

            while (manager.WebParts.Count > 0)
            {
                manager.DeleteWebPart(manager.WebParts[0]);
            }

            for (int i = 0; i < webPart.Length; i++)
            {
                manager.AddWebPart(webPart[i], zones[i], index);
                index += 2;
            }

            file.Update();

            if (manager.Web != null)
            {
                manager.Web.Dispose();
            }

            manager.Dispose();
        }
Exemplo n.º 2
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;
                        }
                    }
                }
        }
        private static void ConnectWebParts(SPFeatureReceiverProperties properties, string url, System.Web.UI.WebControls.WebParts.WebPart provider,
                                            System.Web.UI.WebControls.WebParts.WebPart[] consumer)
        {
            SPWeb  web  = (SPWeb)properties.Feature.Parent;
            SPFile file = web.GetFile(url);
            SPLimitedWebPartManager manager       = file.GetLimitedWebPartManager(PersonalizationScope.Shared);
            ProviderConnectionPoint providerPoint = null;
            ConsumerConnectionPoint consumerPoint = null;
            int index = 6;

            while (manager.WebParts.Count > 0)
            {
                manager.DeleteWebPart(manager.WebParts[0]);
            }

            manager.AddWebPart(consumer[0], "MiddleColumn", 2);
            manager.AddWebPart(provider, "MiddleColumn", 4);

            for (int i = 1; i < consumer.Length; i++)
            {
                System.Web.UI.WebControls.WebParts.WebPart webpart = consumer[i];

                manager.AddWebPart(webpart, "MiddleColumn", index);
                index += 2;
            }

            providerPoint = manager.GetProviderConnectionPoints(provider)[0];
            consumerPoint = manager.GetConsumerConnectionPoints(consumer[0])[0];
            manager.SPConnectWebParts(provider, providerPoint, consumer[0], consumerPoint);
            file.Update();

            if (manager.Web != null)
            {
                manager.Web.Dispose();
            }

            manager.Dispose();
        }
        /// <summary>
        /// Replaces the content of a <see cref="CmsDataFormWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>
        /// The modified web part.  This returned web part is what must be used when saving any changes.
        /// </returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           CmsDataFormWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.HeaderXslLink) && string.IsNullOrEmpty(wp.ItemXslLink) && string.IsNullOrEmpty(wp.MainXslLink))
                return wp;

            bool isHeaderXslLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.HeaderXslLink))
                isHeaderXslLinkMatch = regex.IsMatch(wp.HeaderXslLink);

            bool isItemXslLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ParameterBindings))
                isItemXslLinkMatch = regex.IsMatch(wp.ItemXslLink);

            bool isMainXslLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ListName))
                isMainXslLinkMatch = regex.IsMatch(wp.MainXslLink);

            if (!isHeaderXslLinkMatch && !isItemXslLinkMatch && !isMainXslLinkMatch)
                return wp;

            string headerXslLinkContent = wp.HeaderXslLink;
            string itemXslLinkContent = wp.ItemXslLink;
            string mainXslLinkContent = wp.MainXslLink;

            string headerXslLinkResult = headerXslLinkContent;
            string itemXslLinkResult = itemXslLinkContent;
            string mainXslLinkResult = mainXslLinkContent;

            if (!string.IsNullOrEmpty(headerXslLinkContent))
                headerXslLinkResult = regex.Replace(headerXslLinkContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(itemXslLinkContent))
                itemXslLinkResult = regex.Replace(itemXslLinkContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(mainXslLinkContent))
                mainXslLinkResult = regex.Replace(mainXslLinkContent, settings.ReplaceString);

            if (isHeaderXslLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, headerXslLinkContent, headerXslLinkResult);
            if (isItemXslLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, itemXslLinkContent, itemXslLinkResult);
            if (isMainXslLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, mainXslLinkContent, mainXslLinkResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (CmsDataFormWebPart)manager.WebParts[wp.ID];

                if (isHeaderXslLinkMatch)
                    wp.HeaderXslLink = headerXslLinkResult;
                if (isItemXslLinkMatch)
                    wp.ItemXslLink = itemXslLinkResult;
                if (isMainXslLinkMatch)
                    wp.MainXslLink = mainXslLinkResult;

                modified = true;
            }
            return wp;
        }
        /// <summary>
        /// Replaces the content of a <see cref="ContentByQueryWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           ContentByQueryWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.ListGuid) && string.IsNullOrEmpty(wp.WebUrl) && string.IsNullOrEmpty(wp.GroupBy))
                return wp;

            bool isListGuidMatch = false;
            if (!string.IsNullOrEmpty(wp.ListGuid))
                isListGuidMatch = regex.IsMatch(wp.ListGuid);

            bool isWebUrlMatch = false;
            if (!string.IsNullOrEmpty(wp.WebUrl))
                isWebUrlMatch = regex.IsMatch(wp.WebUrl);

            bool isGroupByMatch = false;
            if (!string.IsNullOrEmpty(wp.GroupBy))
                isGroupByMatch = regex.IsMatch(wp.GroupBy);

            if (!isListGuidMatch && !isWebUrlMatch && !isGroupByMatch)
                return wp;

            string listGuidContent = wp.ListGuid;
            string webUrlContent = wp.WebUrl;
            string groupByContent = wp.GroupBy;

            string listGuidResult = listGuidContent;
            string webUrlResult = webUrlContent;
            string groupByResult = groupByContent;

            if (!string.IsNullOrEmpty(listGuidContent))
                listGuidResult = regex.Replace(listGuidContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(webUrlContent))
                webUrlResult = regex.Replace(webUrlContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(groupByContent))
                groupByResult = regex.Replace(groupByContent, settings.ReplaceString);

            if (isListGuidMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, listGuidContent, listGuidResult);
            if (isWebUrlMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, webUrlContent, webUrlResult);

            if (isGroupByMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, groupByContent, groupByResult);

            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (ContentByQueryWebPart)manager.WebParts[wp.ID];

                if (isListGuidMatch)
                    wp.ListGuid = listGuidResult;
                if (isWebUrlMatch)
                    wp.WebUrl = webUrlResult;
                if (isGroupByMatch)
                    wp.GroupBy = groupByResult;

                modified = true;
            }
            return wp;
        }
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           PeopleCoreResultsWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.FixedQuery) && string.IsNullOrEmpty(wp.Xsl))
                return wp;

            bool isFixedQueryMatch = false;
            if (!string.IsNullOrEmpty(wp.FixedQuery))
                isFixedQueryMatch = regex.IsMatch(wp.FixedQuery);

            bool isXslMatch = false;
            if (!string.IsNullOrEmpty(wp.Xsl))
                isXslMatch = regex.IsMatch(wp.Xsl);

            if (!isFixedQueryMatch && !isXslMatch)
                return wp;

            string fixedQueryContent = wp.FixedQuery;
            string xslContent = wp.Xsl;

            string fixedQueryResult = fixedQueryContent;
            string xslResult = xslContent;

            if (!string.IsNullOrEmpty(fixedQueryContent))
                fixedQueryResult = regex.Replace(fixedQueryContent, settings.ReplaceString);
            try
            {
                if (!string.IsNullOrEmpty(xslContent))
                {
                    if (!settings.UnsafeXml)
                        xslResult = ReplaceXmlValues(regex, settings.ReplaceString, xslContent);
                    else
                        xslResult = regex.Replace(xslContent, settings.ReplaceString);
                }
            }
            catch (XmlException ex)
            {
                isXslMatch = false;
                string msg = string.Format(
                    "WARNING: An error occured replacing data in a PeopleCoreResultsWebPart: File={0}, WebPart={1}\r\n{2}",
                    file.ServerRelativeUrl, wp.Title, Utilities.FormatException(ex));
                Logger.WriteWarning(msg);
            }
            if (isFixedQueryMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, fixedQueryContent, fixedQueryResult);
            if (isXslMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, xslContent, xslResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (PeopleCoreResultsWebPart)manager.WebParts[wp.ID];

                if (isFixedQueryMatch)
                    wp.FixedQuery = fixedQueryResult;
                if (isXslMatch)
                    wp.Xsl = xslResult;

                modified = true;
            }
            return wp;
        }
        /// <summary>
        /// Replaces the content of a <see cref="ImageWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           ImageWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.ImageLink) && string.IsNullOrEmpty(wp.AlternativeText))
                return wp;

            bool isAltTextMatch = false;
            if (!string.IsNullOrEmpty(wp.AlternativeText))
                isAltTextMatch = regex.IsMatch(wp.AlternativeText);

            bool isLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ImageLink))
                isLinkMatch = regex.IsMatch(wp.ImageLink);

            if (!isAltTextMatch && !isLinkMatch)
                return wp;

            string altTextContent = wp.AlternativeText;
            string linkContent = wp.ImageLink;

            string altTextResult = altTextContent;
            string linkResult = linkContent;

            if (!string.IsNullOrEmpty(altTextContent))
                altTextResult = regex.Replace(altTextContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(linkContent))
                linkResult = regex.Replace(linkContent, settings.ReplaceString);

            if (isAltTextMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, altTextContent, altTextResult);
            if (isLinkMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, linkContent, linkResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (ImageWebPart)manager.WebParts[wp.ID];

                if (isAltTextMatch)
                    wp.AlternativeText = altTextResult;
                if (isLinkMatch)
                    wp.ImageLink = linkResult;

                modified = true;
            }
            return wp;
        }
        /// <summary>
        /// Replaces the content of a <see cref="ContentEditorWebPart"/>.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
            SPFile file,
            Settings settings,
            ContentEditorWebPart wp,
            Regex regex,
            ref SPLimitedWebPartManager manager,
            ref bool wasCheckedOut,
            ref bool modified)
        {
            if (wp.Content.FirstChild == null && string.IsNullOrEmpty(wp.ContentLink))
                return wp;

            // The first child of a the content XmlElement for a ContentEditorWebPart is a CDATA section
            // so we want to work with that to make sure we don't accidentally replace the CDATA text itself.
            bool isContentMatch = false;
            if (wp.Content.FirstChild != null)
                isContentMatch = regex.IsMatch(wp.Content.FirstChild.InnerText);
            bool isLinkMatch = false;
            if (!string.IsNullOrEmpty(wp.ContentLink))
                isLinkMatch = regex.IsMatch(wp.ContentLink);

            if (!isContentMatch && !isLinkMatch)
                return wp;

            string content;
            if (isContentMatch)
                content = wp.Content.FirstChild.InnerText;
            else
                content = wp.ContentLink;

            string result = content;
            if (!string.IsNullOrEmpty(content))
                result = regex.Replace(content, settings.ReplaceString);

            Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                              file.ServerRelativeUrl, wp.Title, content, result);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (ContentEditorWebPart)manager.WebParts[wp.ID];

                if (isContentMatch)
                    wp.Content = GetDataAsXmlElement("Content", "http://schemas.microsoft.com/WebPart/v2/ContentEditor", result);
                else
                    wp.ContentLink = result;

                modified = true;
            }
            return wp;
        }
Exemplo n.º 9
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);
        }
Exemplo n.º 10
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;
                        }
                    }
                }
        }
Exemplo n.º 11
0
        public static WebPart AddWebPartToWikiPage(SPListItem item, string webPartXml, string title, int row, int col, bool addSpace, Hashtable customReplaceText, PartChromeType chromeType, bool publish)
        {
            string      wikiField = (string)item["WikiField"];
            XmlDocument xd        = new XmlDocument();

            xd.PreserveWhitespace = true;
            xd.LoadXml(wikiField);

            // Sometimes the wikifield content seems to be surrounded by an additional div?
            XmlElement layoutsTable = xd.SelectSingleNode("div/div/table") as XmlElement;

            if (layoutsTable == null)
            {
                layoutsTable = xd.SelectSingleNode("div/table") as XmlElement;
            }

            XmlElement layoutsZoneInner = layoutsTable.SelectSingleNode(string.Format("tbody/tr[{0}]/td[{1}]/div/div", row, col)) as XmlElement;

            if (layoutsZoneInner == null)
            {
                throw new ArgumentException("Unable to locate row and/or column to insert HTML into.");
            }

            bool checkBackIn = false;

            if (item.File.InDocumentLibrary)
            {
                bool ignoreCheckOut = item.File.CheckOutType == SPFile.SPCheckOutType.None && !item.ParentList.ForceCheckout;
                if (!ignoreCheckOut)
                {
                    if (!Utilities.IsCheckedOut(item) || !Utilities.IsCheckedOutByCurrentUser(item))
                    {
                        checkBackIn = true;
                        item.File.CheckOut();
                    }
                }
                // If it's checked out by another user then this will throw an informative exception so let it do so.
            }

            SPLimitedWebPartManager limitedWebPartManager = null;
            WebPart wpdNew = null;

            try
            {
                limitedWebPartManager = item.File.GetLimitedWebPartManager(System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                wpdNew            = SPCmdletImportWebPart.AddWebPart(limitedWebPartManager, item.File, webPartXml, customReplaceText);
                wpdNew.ChromeType = chromeType;
                limitedWebPartManager.AddWebPart(wpdNew, "wpz", 0);
                Guid storageKey = limitedWebPartManager.GetStorageKey(wpdNew);


                // - space element
                XmlElement space = xd.CreateElement("p");
                XmlText    text  = xd.CreateTextNode(" ");
                space.AppendChild(text);

                // - wpBoxDiv
                XmlElement wpBoxDiv = xd.CreateElement("div");
                layoutsZoneInner.AppendChild(wpBoxDiv);

                if (addSpace)
                {
                    layoutsZoneInner.AppendChild(space);
                }

                XmlAttribute attribute = xd.CreateAttribute("class");
                wpBoxDiv.Attributes.Append(attribute);
                attribute.Value = "ms-rtestate-read ms-rte-wpbox";
                attribute       = xd.CreateAttribute("contentEditable");
                wpBoxDiv.Attributes.Append(attribute);
                attribute.Value = "false";
                // - div1
                XmlElement div1 = xd.CreateElement("div");
                wpBoxDiv.AppendChild(div1);
                div1.IsEmpty = false;
                attribute    = xd.CreateAttribute("class");
                div1.Attributes.Append(attribute);
                attribute.Value = "ms-rtestate-read " + storageKey.ToString("D");
                attribute       = xd.CreateAttribute("id");
                div1.Attributes.Append(attribute);
                attribute.Value = "div_" + storageKey.ToString("D");
                // - div2
                XmlElement div2 = xd.CreateElement("div");
                wpBoxDiv.AppendChild(div2);
                div2.IsEmpty = false;
                attribute    = xd.CreateAttribute("style");
                div2.Attributes.Append(attribute);
                attribute.Value = "display:none";
                attribute       = xd.CreateAttribute("id");
                div2.Attributes.Append(attribute);
                attribute.Value = "vid_" + storageKey.ToString("D");

                item["WikiField"] = xd.OuterXml;
                item.Update();

                if (wpdNew.Title != title)
                {
                    wpdNew.Title = title;
                    limitedWebPartManager.SaveChanges(wpdNew);
                }
            }
            finally
            {
                if (limitedWebPartManager != null)
                {
                    limitedWebPartManager.Dispose();
                }

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

                if (publish && file.InDocumentLibrary)
                {
                    file.Publish("Publishing changes to page due to new web part being added: " + title);
                    if (file.Item.ModerationInformation != null)
                    {
                        file.Approve("Approving changes to page due to new web part being added: " + title);
                    }
                }
            }
            return(wpdNew);
        }
Exemplo n.º 12
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;
                        }
                    }
                }
        }
Exemplo n.º 13
0
        public void InitializeWebpartProperties(SPWeb web)
        {
            string wnWpConfig = string.Empty;

            try
            {
                wnWpConfig = web.AllProperties["WhatsNewLists"].ToString();
            }
            catch (NullReferenceException x)
            {
                wnWpConfig = string.Empty;
            }

            if (string.IsNullOrEmpty(wnWpConfig))
            {
                return;
            }

            string processedWNWpConfig = string.Empty;

            processedWNWpConfig = wnWpConfig;

            Dictionary <string, string> listAndGuids = new Dictionary <string, string>();
            SPList listHolder = null;

            if (!string.IsNullOrEmpty(processedWNWpConfig))
            {
                string[] listConfigs = processedWNWpConfig.Split('|');

                foreach (string listConfig in listConfigs)
                {
                    if (!string.IsNullOrEmpty(listConfig))
                    {
                        string tempLstName = listConfig.Replace("\'", "");
                        string listName    = tempLstName.Split(',')[0];
                        listHolder = web.Lists.TryGetList(listName);
                        if (listHolder != null && !listAndGuids.ContainsKey(listName))
                        {
                            listAndGuids.Add(listName, listHolder.ID.ToString("D"));
                        }
                    }
                }
            }

            foreach (KeyValuePair <string, string> lstAndGuid in listAndGuids)
            {
                if (processedWNWpConfig.Contains(lstAndGuid.Key))
                {
                    processedWNWpConfig = processedWNWpConfig.Replace(lstAndGuid.Key, lstAndGuid.Value);
                }
            }

            processedWNWpConfig = processedWNWpConfig.Replace("|", "\n");
            processedWNWpConfig = System.Text.RegularExpressions.Regex.Replace(processedWNWpConfig, "\n$", "");

            SPLimitedWebPartManager myMgr = web.GetLimitedWebPartManager("default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);

            if (myMgr != null)
            {
                foreach (System.Web.UI.WebControls.WebParts.WebPart myPart in myMgr.WebParts)
                {
                    if (myPart.GetType().Equals(typeof(Microsoft.SharePoint.Applications.GroupBoard.WebPartPages.WhatsNewWebPart)))
                    {
                        Microsoft.SharePoint.Applications.GroupBoard.WebPartPages.WhatsNewWebPart myWNPart = (Microsoft.SharePoint.Applications.GroupBoard.WebPartPages.WhatsNewWebPart)myPart;

                        myWNPart.NumItemsPerson = 10;
                        myWNPart.NumItemsShared = 10;
                        myWNPart.ShowDetails    = true;
                        myWNPart.TargetConfig   = processedWNWpConfig;
                        myMgr.SaveChanges(myWNPart);
                    }
                }
                myMgr.Dispose();
            }
        }
Exemplo n.º 14
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;
                        }
                    }
                }
        }
        /// <summary>
        /// Replaces the content of a <see cref="MediaWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
           SPFile file,
           Settings settings,
           MediaWebPart wp,
           Regex regex,
           ref SPLimitedWebPartManager manager,
           ref bool wasCheckedOut,
           ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.MediaSource) && string.IsNullOrEmpty(wp.TemplateSource) && string.IsNullOrEmpty(wp.PreviewImageSource))
                return wp;

            bool isMediaSourceMatch = false;
            if (!string.IsNullOrEmpty(wp.MediaSource))
                isMediaSourceMatch = regex.IsMatch(wp.MediaSource);

            bool isTemplateSourceMatch = false;
            if (!string.IsNullOrEmpty(wp.TemplateSource))
                isTemplateSourceMatch = regex.IsMatch(wp.TemplateSource);

            bool isPreviewImageSourceMatch = false;
            if (!string.IsNullOrEmpty(wp.PreviewImageSource))
                isPreviewImageSourceMatch = regex.IsMatch(wp.PreviewImageSource);

            if (!isMediaSourceMatch && !isTemplateSourceMatch && !isPreviewImageSourceMatch)
                return wp;

            string mediaSourceContent = wp.MediaSource;
            string templateSourceContent = wp.TemplateSource;
            string previewImageSourceContent = wp.PreviewImageSource;

            string mediaSourceResult = mediaSourceContent;
            string templateSourceResult = templateSourceContent;
            string previewImageSourceResult = previewImageSourceContent;

            if (!string.IsNullOrEmpty(mediaSourceContent))
                mediaSourceResult = regex.Replace(mediaSourceContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(templateSourceContent))
                templateSourceResult = regex.Replace(templateSourceContent, settings.ReplaceString);
            if (!string.IsNullOrEmpty(previewImageSourceContent))
                previewImageSourceResult = regex.Replace(previewImageSourceContent, settings.ReplaceString);

            if (isMediaSourceMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, mediaSourceContent, mediaSourceResult);
            if (isTemplateSourceMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, templateSourceContent, templateSourceResult);
            if (isPreviewImageSourceMatch)
                Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                                  file.ServerRelativeUrl, wp.Title, previewImageSourceContent, previewImageSourceResult);
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (MediaWebPart)manager.WebParts[wp.ID];

                if (isMediaSourceMatch)
                    wp.MediaSource = mediaSourceResult;
                if (isTemplateSourceMatch)
                    wp.TemplateSource = templateSourceResult;
                if (isPreviewImageSourceMatch)
                    wp.PreviewImageSource = previewImageSourceResult;

                modified = true;
            }
            return wp;
        }
        public static void Retarget(string url, bool allMatching, string webPartId, string webPartTitle, string listUrl, string listType, string siteUrl, 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
                {
                    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 wasCheckedOut = true;
                    if (file.CheckOutStatus == SPFile.SPCheckOutStatus.None)
                    {
                        file.CheckOut();
                        wasCheckedOut = false;
                    }
                    else if (!Utilities.IsCheckedOutByCurrentUser(file.Item))
                    {
                        // We don't want to mess with files that are checked out to other users so exit out.
                        throw new SPException("The file is currently checked out by another user.");
                    }

                    string displayTitle             = string.Empty;
                    bool   modified                 = false;
                    SPLimitedWebPartManager manager = null;
                    try
                    {
                        if (!allMatching)
                        {
                            bool cleanupContext = false;
                            if (HttpContext.Current == null)
                            {
                                HttpRequest request = new HttpRequest("", web.Url, "");
                                HttpContext.Current = new HttpContext(request, new HttpResponse(new StringWriter()));
                                SPControl.SetContextWeb(HttpContext.Current, web);
                                cleanupContext = true;
                            }

                            WebPart wp = 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. Try specifying the -ID parameter instead (use enumpagewebparts to get the ID) or use -AllMatching to adjust all web parts that match the specified title.");
                                    }
                                }
                                if (wp == null)
                                {
                                    throw new SPException("Unable to find specified web part.");
                                }

                                AdjustWebPart(web, wp, manager, listUrl, listType, siteUrl);
                                modified = true;

                                // Set this so that we can add it to the check-in comment.
                                displayTitle = wp.DisplayTitle;
                            }
                            finally
                            {
                                if (cleanupContext)
                                {
                                    HttpContext.Current = null;
                                }

                                if (wp != null)
                                {
                                    wp.Dispose();
                                }
                            }
                        }
                        else
                        {
                            manager = web.GetLimitedWebPartManager(url, PersonalizationScope.Shared);
                            foreach (WebPart tempWP in manager.WebParts)
                            {
                                try
                                {
                                    if (!(tempWP is ContentByQueryWebPart))
                                    {
                                        continue;
                                    }

                                    if (tempWP.DisplayTitle.ToLowerInvariant() == webPartTitle.ToLowerInvariant())
                                    {
                                        AdjustWebPart(web, tempWP, manager, listUrl, listType, siteUrl);
                                        displayTitle = tempWP.DisplayTitle;
                                        modified     = true;
                                    }
                                }
                                finally
                                {
                                    tempWP.Dispose();
                                }
                            }
                        }
                    }
                    finally
                    {
                        if (manager != null)
                        {
                            manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                            manager.Dispose();
                        }

                        if (modified)
                        {
                            file.CheckIn("Checking in changes to page layout due to retargeting of content query web part " + displayTitle);
                        }
                        else if (!wasCheckedOut)
                        {
                            file.UndoCheckOut();
                        }

                        if (modified && publish)
                        {
                            file.Publish("Publishing changes to page layout due to retargeting of content query web part " + displayTitle);
                            if (file.Item.ModerationInformation != null)
                            {
                                file.Approve("Approving changes to page layout due to retargeting of content query web part " + displayTitle);
                            }
                        }
                    }
                }
        }
Exemplo n.º 17
0
        /// <summary>
        /// Adds a List View Web Part to the specified page.
        /// </summary>
        /// <param name="pageUrl">The page URL.</param>
        /// <param name="listUrl">The list URL.</param>
        /// <param name="title">The title.</param>
        /// <param name="viewTitle">Title of the view.</param>
        /// <param name="zoneId">The zone ID.</param>
        /// <param name="zoneIndex">Index within the zone.</param>
        /// <param name="linkTitle">if set to <c>true</c> [link title].</param>
        /// <param name="chromeType">Type of the chrome.</param>
        /// <param name="publish">if set to <c>true</c> [publish].</param>
        /// <returns></returns>
        public static Microsoft.SharePoint.WebPartPages.WebPart Add(string pageUrl, string listUrl, string title, string viewTitle, string zoneId, int zoneIndex, bool linkTitle, string jsLink, PartChromeType chromeType, bool publish)
        {
            using (SPSite site = new SPSite(pageUrl))
                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
                {
                    SPFile file = web.GetFile(pageUrl);

                    // 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.

                    SPList list = Utilities.GetListFromViewUrl(listUrl);
                    if (list == null)
                    {
                        throw new ArgumentException("List not found.");
                    }

                    SPView view = null;
                    if (!string.IsNullOrEmpty(viewTitle))
                    {
                        view = list.Views.Cast <SPView>().FirstOrDefault(v => v.Title == viewTitle);
                        if (view == null)
                        {
                            throw new ArgumentException("The specified view was not found.");
                        }
                    }

                    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.
                    }
                    string displayTitle = string.Empty;
                    Microsoft.SharePoint.WebPartPages.WebPart lvw = null;

                    SPLimitedWebPartManager manager = null;
                    try
                    {
                        manager = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared);
                        lvw     = new XsltListViewWebPart();
                        if (list.BaseTemplate == SPListTemplateType.Events)
                        {
                            lvw = new ListViewWebPart();
                        }

                        if (lvw is ListViewWebPart)
                        {
                            ((ListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant();
                            ((ListViewWebPart)lvw).WebId    = list.ParentWeb.ID;
                            if (view != null)
                            {
                                ((ListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant();
                            }
                        }
                        else
                        {
                            ((XsltListViewWebPart)lvw).ListName = list.ID.ToString("B").ToUpperInvariant();
#if !SP2010
                            if (!string.IsNullOrEmpty(jsLink))
                            {
                                ((XsltListViewWebPart)lvw).JSLink = jsLink;
                            }
#endif
                            ((XsltListViewWebPart)lvw).WebId = list.ParentWeb.ID;
                            if (view != null)
                            {
                                ((XsltListViewWebPart)lvw).ViewGuid = view.ID.ToString("B").ToUpperInvariant();
                            }
                        }

                        if (linkTitle)
                        {
                            if (view != null)
                            {
                                lvw.TitleUrl = view.Url;
                            }
                            else
                            {
                                lvw.TitleUrl = list.DefaultViewUrl;
                            }
                        }

                        if (!string.IsNullOrEmpty(title))
                        {
                            lvw.Title = title;
                        }

                        lvw.ChromeType = chromeType;

                        displayTitle = lvw.DisplayTitle;

                        manager.AddWebPart(lvw, zoneId, zoneIndex);
                    }
                    finally
                    {
                        if (manager != null)
                        {
                            manager.Web.Dispose();
                            manager.Dispose();
                        }
                        if (lvw != null)
                        {
                            lvw.Dispose();
                        }

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

                        if (publish && file.InDocumentLibrary)
                        {
                            file.Publish("Publishing changes to page due to new web part being added: " + displayTitle);
                            if (file.Item.ModerationInformation != null)
                            {
                                file.Approve("Approving changes to page due to new web part being added: " + displayTitle);
                            }
                        }
                    }
                    return(lvw);
                }
        }
        /// <summary>
        /// Replaces the content of a <see cref="SummaryLinkWebPart"/> web part.
        /// </summary>
        /// <param name="web">The web that the file belongs to.</param>
        /// <param name="file">The file that the web part is associated with.</param>
        /// <param name="settings">The settings object containing user provided parameters.</param>
        /// <param name="wp">The web part whose content will be replaced.</param>
        /// <param name="regex">The regular expression object which contains the search pattern.</param>
        /// <param name="manager">The web part manager.  This value may get updated during this method call.</param>
        /// <param name="wasCheckedOut">if set to <c>true</c> then the was checked out prior to this method being called.</param>
        /// <param name="modified">if set to <c>true</c> then the web part was modified as a result of this method being called.</param>
        /// <returns>The modified web part.  This returned web part is what must be used when saving any changes.</returns>
        internal static WebPart ReplaceValues(SPWeb web,
            SPFile file,
            Settings settings,
            SummaryLinkWebPart wp,
            Regex regex,
            ref SPLimitedWebPartManager manager,
            ref bool wasCheckedOut,
            ref bool modified)
        {
            if (string.IsNullOrEmpty(wp.SummaryLinkStore))
                return wp;

            bool isLinkMatch = false;
            string originalContent = wp.SummaryLinkStore;

            SummaryLinkFieldValue links = wp.SummaryLinkValue;

            // Make all appropriate changes here and then reset the value below.
            // We don't want to manipulate the store itself because we risk messing up the XML.
            foreach (SummaryLink link in links.SummaryLinks)
            {
                if (!string.IsNullOrEmpty(link.Description) && regex.IsMatch(link.Description))
                {
                    link.Description = regex.Replace(link.Description, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.ImageUrl) && regex.IsMatch(link.ImageUrl))
                {
                    link.ImageUrl = regex.Replace(link.ImageUrl, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.ImageUrlAltText) && regex.IsMatch(link.ImageUrlAltText))
                {
                    link.ImageUrlAltText = regex.Replace(link.ImageUrlAltText, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.LinkUrl) && regex.IsMatch(link.LinkUrl))
                {
                    link.LinkUrl = regex.Replace(link.LinkUrl, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.Title) && regex.IsMatch(link.Title))
                {
                    link.Title = regex.Replace(link.Title, settings.ReplaceString);
                    isLinkMatch = true;
                }
                if (!string.IsNullOrEmpty(link.LinkToolTip) && regex.IsMatch(link.LinkToolTip))
                {
                    link.LinkToolTip = regex.Replace(link.LinkToolTip, settings.ReplaceString);
                    isLinkMatch = true;
                }
            }
            if (!isLinkMatch)
                return wp;

            Logger.Write("Match found: File={0}, WebPart={1}, Replacement={2} => {3}",
                              file.ServerRelativeUrl, wp.Title, originalContent, links.ToString());
            if (!settings.Test)
            {
                if (file.CheckOutType == SPFile.SPCheckOutType.None)
                {
                    file.CheckOut();
                    wasCheckedOut = false;
                }
                // We need to reset the manager and the web part because a checkout (now or from an earlier call)
                // could mess things up so safest to just reset every time.
                manager.Web.Dispose(); // manager.Dispose() does not dispose of the SPWeb object and results in a memory leak.
                manager.Dispose();
                manager = web.GetLimitedWebPartManager(file.Url, PersonalizationScope.Shared);

                wp.Dispose();
                wp = (SummaryLinkWebPart)manager.WebParts[wp.ID];

                wp.SummaryLinkValue = links;

                modified = true;
            }
            return wp;
        }
        /// <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);
                        }
                    }
                }
            }
        }
Exemplo n.º 20
0
        internal static string GetWebPartXml(string pageUrl, bool simple)
        {
            using (SPSite site = new SPSite(pageUrl))
                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
                {
                    SPLimitedWebPartManager webPartMngr = null;
                    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);
                        }

                        webPartMngr = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.Shared);

                        XmlDocument xmlDoc = new XmlDocument();
                        xmlDoc.AppendChild(xmlDoc.CreateElement("WebParts"));
                        xmlDoc.DocumentElement.SetAttribute("page", web.Site.MakeFullUrl(webPartMngr.ServerRelativeUrl));

                        XmlElement shared = xmlDoc.CreateElement("Shared");
                        xmlDoc.DocumentElement.AppendChild(shared);


                        string tempXml = string.Empty;
                        foreach (WebPart wp in webPartMngr.WebParts)
                        {
                            if (!simple)
                            {
                                tempXml += GetWebPartDetails(wp, webPartMngr);
                            }
                            else
                            {
                                tempXml += GetWebPartDetailsSimple(wp, webPartMngr);
                            }
                        }
                        shared.InnerXml = tempXml;

                        XmlElement user = xmlDoc.CreateElement("User");
                        xmlDoc.DocumentElement.AppendChild(user);

                        webPartMngr.Web.Dispose();
                        webPartMngr.Dispose();

                        webPartMngr = web.GetLimitedWebPartManager(pageUrl, PersonalizationScope.User);
                        tempXml     = string.Empty;
                        foreach (WebPart wp in webPartMngr.WebParts)
                        {
                            if (!simple)
                            {
                                tempXml += GetWebPartDetails(wp, webPartMngr);
                            }
                            else
                            {
                                tempXml += GetWebPartDetailsSimple(wp, webPartMngr);
                            }
                        }
                        user.InnerXml = tempXml;
                        return(Utilities.GetFormattedXml(xmlDoc));
                    }
                    finally
                    {
                        if (webPartMngr != null)
                        {
                            webPartMngr.Web.Dispose();
                            webPartMngr.Dispose();
                        }
                        if (HttpContext.Current != null && cleanupContext)
                        {
                            HttpContext.Current = null;
                        }
                    }
                }
        }