Redirection using Content Editor WebPart programmatically in migration

November 1st, 2011 | Categories: SharePoint 2010, Solutions, WSS 3.0 | Tags: , ,

SharePoint migration, the area where several challenges occur and all we need to do is to mitigate all the risk factors and provide a secured migration strategy.

 

In this blog, I’m going ahead to elaborate a very common approach which is applicable for most of our migration plan. After the migration is done, in most cases customer requires the OLD SharePoint site should be live in read-only state for some times and the site user’s must able to view the information like ‘ This site has been migrated to……’.

 

In many cases, we have seen there are couple of thousand users exist for one site collection and it is not feasible to notified all site users about the migration date and plan. In other words their browser link for the old SharePoint link is not going to change and providing this kind of information they can update the new link.

 

The objective is to display some kind of information about the recent migration to end user and allowed them to redirect to new site after pausing let’s say 10 sec.

 

We have a choice utilize out of the box Content Editor webpart for taking care this approach. Question is what will happens when we found there are many sub sites (don’t be surprised to see a site collection contains more than 500 sub sites).

 

For the similar scenario, we can use one simple console application which will dynamically put one content editor webpart from root level site collection home page to all its sub site home pages. Obviously you can implement this methodology as a kind of feature, if you want. I prefer the tool/console level approach because this is just need to run once and no need to deactivate or activate latter one, ultimately down the line the old site will be deleted.

 

Let’s start and see how to build up and run this application. As I said, this would be a console application so first thing is to create a console application project named it ‘RedirectToSharePoint2010’ using Visual Studio.NET.

 

Next steps is to add the common SharePoint assembly i.e. Microsoft.SharePoint.dll which you can found at ISAPI folder under 14 hive structure.

Now, first add your app.config file here. This is a configuration file where you will place your old version of SharePoint url, new version of SharePoint url, and the action. The action item would be either ‘Add’ or ‘Remove’. This has been introduced as a back of strategy. For example, after running this application when all the subsites has the new redirection content editor webpart, if you want to remove all the newly added content editor webparts from the sub sites for any reasons, then this back of strategy will help you.

 

So, let’s say your existing/old SharePoint site url is  http://wss3.sharepoint. com/sites/MyOwnTest and your new site url is http://wss3.sharepoint. com/teams/SP2010Test.

 

So whatever sub-webs under sites/MyOwnTest will now mapped under teams/SP2010Test. In other words, the sub-web at http://wss3.sharepoint.com/sites/MyOwnTest/foo will now points to http://wss3.sharepoint.com/teams/SP2010Test/foo.

 

The above configuration is being implemented using the App.config file here.

<?xml version=”1.0″ encoding=”utf-8″ ?>

<configuration>

<appSettings>

<add key=”RootSiteURL” value=” http://wss3.sharepoint. com/sites/MyOwnTest”/>

<add key=”NewURL” value=” http://wss3.sharepoint. com/teams/SP2010Test”/>

<add key=”action” value=”add”/> <!– Value should be either Add or Remove–>

<add key=”WebPartTitle” value=”Redirect to SharePoint 2010″/>

</appSettings>

</configuration>

 

Let’s start with console application. Simple console application which when run, will read the app.config file, open the old SharePoint environment and site collection/subsite and place a content editor in each of the sub-webs which will redirect visitors after a few seconds to its newly SharePoint spce.

The above code is self explanorty and if you have any question, please feel free to let me know.

 

Program.cs

using System.Web.Util;

using System.Web.UI.WebControls.WebParts;

using System.Configuration;

using Microsoft.SharePoint;

using Microsoft.SharePoint.WebPartPages;

using Microsoft.SharePoint.WebControls;

 

 

namespace RedirectToSharePoint2010

{

    class Program

    {

        string ActionAdd        = “add”;

        string ActionRemove     = “remove”;

       

static void Main(string[] args)

        {

 

            string RootSiteUrl          = string.Empty;

            string ActionElement        = string.Empty;

 

            Program obj = new Program();

 

            //Get old SharePoint url(RootSiteURL) and action from application configuration

            RootSiteUrl = ConfigurationManager.AppSettings["RootSiteURL"].ToString();

            ActionElement = ConfigurationManager.AppSettings["action"].ToString();

 

            Console.WriteLine(ActionElement + ” has been started. Please wait untill complete…”);

          

            if (ActionElement.ToLower() == obj.ActionAdd)

            {

                obj.AddWebPart(RootSiteUrl);

            }

 

            if (ActionElement.ToLower() == obj.ActionRemove)

            {

                obj.RemoveWebPart(RootSiteUrl);

            }

           

 

            Console.WriteLine(“Operation completed. Press any key to exit.”);

            Console.Read();

 

        }

 

        ///<summary>

        /// Function GetWebPartContent() determines the new migratd url and build the redirection JavaScript

        ///</summary>

        ///<param name=”SiteUrl”>SharePoint site URL which is being migrated</param>

        ///<returns>newly migrated SharePoint url where the redirection will reach out</returns>

        public static string GetWebPartContent(string SiteUrl)

        {

            string OldUrl       = string.Empty;

            string RedirectUrl  = string.Empty;

 

            OldUrl      = ConfigurationManager.AppSettings["RootSiteURL"].ToString();

            RedirectUrl = ConfigurationManager.AppSettings["NewURL"].ToString();

            RedirectUrl = SiteUrl.Replace(OldUrl, RedirectUrl);

           

            //Javascript code for redirection

            RedirectUrl = “<script> var t=setTimeout(‘redirectToSp2010()’,10000); function redirectToSp2010() { window.location.href=’” + RedirectUrl.ToString().Replace(“‘”, “\\’”) + “‘; }</script> This site will be redirected to SharePoint2010 url in 10 secs”;

 

            return RedirectUrl;

        }

 

 

        ///<summary>

        /// Function AddWebPart() added the CotentEditor webpart to root web as well as all its sub sites

        ///</summary>

        ///<param name=”RootSiteUrl”>SharePoint root site URL which is being migrated</param>

        public void AddWebPart(string RootSiteUrl)

        {

            using (SPSite site = new SPSite(RootSiteUrl))

            {

                using (SPWeb rootWeb = site.OpenWeb())

                {

                    try

                    {

                        Console.WriteLine(“Adding webpart to the web: “ + rootWeb.Url);

                        //Adding the webpart in root web

                        CreateWebPart(rootWeb);

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine(“Error occurred in web: “ + rootWeb.Url + ” and the error is: “ + ex.Message.ToString());

                    }

                    //If root website has child sub-webs, it will go through all sub-webs and add web part on each child sub webs

                    if (rootWeb.Webs.Count > 0) RunForChildSites(rootWeb, ActionAdd);

                }

            }

        }

 

 

        public static void CreateWebPart(SPWeb spWeb)

        {

            try

            {

                string SharePointHomePage = “default.aspx”;

                string NewWebPartTitle = ConfigurationManager.AppSettings["WebPartTitle"].ToString();

 

                string WebPartContent = GetWebPartContent(spWeb.Url.ToString());

 

                //Get the shared Web Part manager on the Default.aspx page.

                using (SPLimitedWebPartManager webPartManager = spWeb.GetLimitedWebPartManager(SharePointHomePage, PersonalizationScope.Shared))

                {

                    using (ContentEditorWebPart contentEditorWebPart = new ContentEditorWebPart())

                    {

                        contentEditorWebPart.Title = NewWebPartTitle;

                        contentEditorWebPart.AllowClose = true;

                        contentEditorWebPart.AllowEdit = true;

                        contentEditorWebPart.AllowMinimize = true;

                        contentEditorWebPart.Visible = true;

 

 

                        //Create an XmlElement to hold the value of the Content property.

                        XmlDocument xmlDoc = new XmlDocument();

                        XmlElement xmlElement = xmlDoc.CreateElement(“script”);

                        xmlElement.InnerText = WebPartContent;

                        contentEditorWebPart.Content = xmlElement;

 

 

                        contentEditorWebPart.ChromeState = PartChromeState.Normal;

                        contentEditorWebPart.ChromeType = PartChromeType.Default;

 

                        webPartManager.AddWebPart(contentEditorWebPart, “Left”, 0);

                        spWeb.Update();

                        Console.WriteLine(“Webpart added successfully”);

                    }

                }

            }

            catch (Exception ex)

            {

                Console.WriteLine(“Error occurred while adding webpart to the web: “ + spWeb.Url + ” and the error is: “ + ex.Message);

            }

        }

 

 

        private void RunForChildSites(SPWeb web, string operation)

        {

            foreach (SPWeb childSite in web.Webs)

            {

                try

                {

                    if (operation.ToLower().Equals(ActionAdd, StringComparison.InvariantCultureIgnoreCase))

                    {

                        Console.WriteLine(“Adding webpart to the web: “ + childSite.Url);

                        CreateWebPart(childSite);

                    }

                    else if (operation.ToLower().Equals(ActionRemove, StringComparison.InvariantCultureIgnoreCase))

                    {

                        Console.WriteLine(“Removing webpart from the web: “ + childSite.Url);

                        DeleteWebPart(childSite);

                    }

                }

                catch (Exception ex)

                {

                    Console.WriteLine(“Error occurred in web: “ + childSite.Url + ” and the error is: “ + ex.Message);

                }

                if (childSite.Webs.Count > 0) RunForChildSites(childSite, operation);

            }

        }

 

 

        public void RemoveWebPart(string RootSiteUrl)

        {

            using (SPSite site = new SPSite(RootSiteUrl))

            {

                using (SPWeb rootWeb = site.OpenWeb())

                {

                    try

                    {

                        Console.WriteLine(“Removing webpart from the web: “ + rootWeb.Url);

                        //Deleting from parent web

                        DeleteWebPart(rootWeb);

                    }

                    catch (Exception ex)

                    {

                        Console.WriteLine(“Error occurred in web: “ + rootWeb.Url + ” and the error is: “ + ex.Message.ToString());

                    }

                    if (rootWeb.Webs.Count > 0) RunForChildSites(rootWeb, ActionRemove);

                }

            }

        }

 

 

       

 

        public static void DeleteWebPart(SPWeb spWeb)

        {

            try

            {

                string SharePointHomePage = “default.aspx”;

                string WebPartTitle = ConfigurationManager.AppSettings["WebPartTitle"].ToString();

               

                //Get the shared Web Part manager on the Default.aspx page.

                using (SPLimitedWebPartManager webPartManager = spWeb.GetLimitedWebPartManager(SharePointHomePage, PersonalizationScope.Shared))

                {

                    //foreach (Microsoft.SharePoint.WebPartPages.WebPart webPart in webPartManager.WebParts)

                    for (int iCounter = webPartManager.WebParts.Count – 1; iCounter >= 0; iCounter–)

                    {

                        Microsoft.SharePoint.WebPartPages.WebPart webPart = (Microsoft.SharePoint.WebPartPages.WebPart)webPartManager.WebParts[iCounter];

                        if (webPart.Title.Contains(WebPartTitle))

                        {

                            try

                            {

                                webPartManager.DeleteWebPart(webPart);

                                spWeb.Update();

                                Console.WriteLine(“Webpart removed successfully”);

                            }

                            catch (Exception ex)

                            {

                                Console.WriteLine(“Error occurred while deleting the webpart from the web: “ + spWeb.Url + ” and the error is: “ + ex.Message);

                            }                           

                        }

 

                    }

                }               

            }

            catch (Exception ex)

            {

                Console.WriteLine(“Error occurred while removing webpart from the web: “ + spWeb.Url + ” and the error is: “ + ex.Message);

            }

        }

 

 

    }

}

However, we can extend this code a little further by implementing the same logic for document libraries/list in each sub-web as well. This will allow site user/visitor to redirect to newly SharePoint environment document library/list.

 

Hopefully the above program will help you in redirection strategy after the migration.

No comments yet.
You must be logged in to post a comment.