Wednesday, May 30, 2012

how to migrate data of sharepoint 2007 site to sharepoint 2010 site through database attach deattach approach (Part1).


                      SharePoint 2007 Migration to SharePoint 2010
Requirements and prerequisites:
·          Destination Server: SharePoint 2010 database server must be 64-bit version and SQL Server 2008 SP1 with cumulative update 2.
·          Source Server: SharePoint 2007 must have SP2 and latest CU (Verify Oct 2009 MOSS/WSS SharePoint CU Installed in SharePoint Server 2007)
Please refer below link for above prerequisite upgrades
Pre-upgrade check
·          The stsadm.exe command PreUpgradeCheck can be used to analyze the existing SP2007 site collections, looking for situations that could cause grief during an upgrade, such as customized (unghosted) artifacts, changes in database schemas, missing features and other potential issues and relevant information like Alternate Access Mappings(AAM) url’s, site definitions used and large lists. Please refer following link
Attached WSS Database to SharePoint database using SQL server 2008
Step1: selected existing wss3.0 content database, as shown in below screen

 









Step2: once selected database and click backup option, as shown in below screen




 









Step3: click ok button. This backup file saved in particular folder, as shown in below screens
 


 






Restoring a copy of your SharePoint 2007 content database into SharePoint Foundation 2010
Step4: Right click on Databases and select Restore Database.
Select your source and destination as follows;

Click on Options and ensure you have selected Overwrite the existing database.

Click OK.
We should receive the following confirmation message once the database has been successfully restored.

 






Verifying the Content Database using Power shell Cmdlet:
Step5: The next tool that we will be using is the Test-SPContentDatabase Windows PowerShell cmdlet.  This cmdlet will test and verify that any custom components that are required for this content database has been installed and configured in the SharePoint 2010 environment.
Test-SPContentDatabase –Name <database name> -WebApplication <URL>

Launch the SharePoint 2010 Management Shell and type the above command, ensuring you have entered your Database Name and URL.
Test-SPContentDatabase –Name WSS_Content_4670 -WebApplication http://hiredc987:1200/default.aspx

The Test-SPContentDatabase is a great reporting tool that will list any missing setup files, web parts and provide you with information on how to remedy any errors.  It will also specify whether these missing features will block the upgrade from succeeding.











Removing Existing Content database using central admin web application
Step6: you can remove the existing attached database by clicking on the actual database name and then clicking on the “Remove content database” check box.

You will receive the above warning which is safe to ignore.  In this instance we are not deleting the actual database but disassociating it from the selected Web Application.


 Further steps, I will post in NEXT BLOG...(Part II)





Monday, May 28, 2012

Ways of adding a Custom or OOB Webparts to a Sharepoint Site programmatically.

Through onet.xml if you have a customized SharePoint Site Definition :

 In the <Module></Module>  (which is within <Modules></Modules> node)  node of onet.xml file, we have another child node <File></File>. After identifying this node we need to get our file through its Url property and after that need to put our web part code in in xslt format. Code will be as below:

 <File Url="Home.aspx"  NavBarHome="True" Type="Ghostable">

          <AllUsersWebPart WebPartZoneID="Left" WebPartOrder="1">
              <![CDATA[         
          <WebPart xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/WebPart/v2">
          <Assembly>MyProject1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=116306ce04211e35</Assembly>
          <TypeName>MyProject1.WebPart1</TypeName>
          <FrameType>None</FrameType>
          <Title>My Custom Web Part</Title>         
          <PartStorage xmlns="http://schemas.microsoft.com/WebPart/v2/Xml" />
          </WebPart>
         ]]>

          </AllUsersWebPart>
          

<AllUsersWebPart WebPartZoneID="Left" WebPartOrder="5">
              <![CDATA[
         <WebPart xmlns="http://schemas.microsoft.com/WebPart/v2"
         xmlns:cewp="http://schemas.microsoft.com/WebPart/v2/ContentEditor">
         <Assembly>Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c</Assembly>
         <TypeName>Microsoft.SharePoint.WebPartPages.ContentEditorWebPart</TypeName>
         <Title>Content Editor Webpart Demo</Title>
         <FrameType>None</FrameType>
        <cewp:Content>
         &lt;link href=&quot;/_layouts/Styles/GlobalStyles.css&quot; rel=&quot;Stylesheet&quot; type=&quot;text/css&quot; /&gt;<br />
         &lt;table cellSpacing=&quot;0&quot; class=&quot;tbl-Webpart&quot;&gt;<br />
          &lt;tr class=&quot;tr-WebpartHeading&quot;&gt;<br />
            &lt;td  colspan=&quot;3&quot; class=&quot;tc-WebpartHeading&quot;&gt; <br />
              My Learning<br />
              &lt;tr class=&quot;tr-WebpartSubHeading&quot;&gt;<br />
            &lt;td  colspan=&quot;3&quot; class=&quot;tc-WebpartSubHeading&quot;&gt; <br />
              Use the resource below to start to develop or enhance those skills<br />
           &lt;/td&gt;<br />
        &lt;/tr&gt;<br />
        &lt;tr&gt;<br />
          &lt;td &gt;<br />
          &lt;img  src=&quot;/_layouts/Images/MyLearningLogo.jpg&quot; /&gt;<br />
        
         &lt;td &gt;<br />
            &lt;a href=&quot;./Pages/Page1.aspx&quot;&gt; &lt;img src=&quot;/_layouts/Images/StartNow.jpg&quot; /&gt;&lt;/a&gt;<br />
            Sample text&lt;b&gt; integrated&lt;/br&gt;  Sample text &lt;/b&gt; &lt;/br&gt;  Sample text,&lt;/br&gt; region and group<br />
         &lt;/td&gt;<br />
        &lt;td &gt;<br />
        &lt;img src=&quot;/_layouts/Images/Calender.jpg&quot; &gt;<br />
          &lt;a href =&quot;./Pages/page2.aspx&quot; &gt;Sample Text &lt;/a&gt;<br />
        &lt;/td&gt;<br />
      &lt;/tr&gt;<br />
    &lt;/table&gt;
       
       
     </cewp:Content>
     </WebPart>]]>
</AllUsersWebPart>
</File>

The content highlighted with light blue colour shows the way of adding an custom Webpart My Custom Web Part including Assembly and Class Name which contains it. However content with another background  adding an OOB webpart here it is  Content Editor Webpart Content Editor Webpart Demo within cewp tags. You can any other webpart in place of these. 

Through avtivation of a feature in a existing SharePoint Site :


We just need to call these two methods to on feature activation to add a webpart programmatically:

First Call this method to check that webpart exists in current page or not ?

 private static bool CheckWebPartExist(SPWeb site, string PageUrl, string title)
        {
            bool CheckWebPartExist = false;
            SPWebPartCollection webparts = site.GetWebPartCollection(PageUrl, Storage.Shared);
            foreach (ContentEditorWebPart contentEditorWP in webparts)
            {
                if (contentEditorWP.Title == title)
                {
                    CheckWebPartExist = true;
                    break;
                }
            }
            return CheckWebPartExist;
        }

For adding a Content editor webpart :

private static void AddContentEditorWebPartToPage(SPWeb site, string PageUrl, string ZoneID, string title, string InnerText, bool CheckWebPartExist)
        {
            if (!CheckWebPartExist)
            {
                using (SPLimitedWebPartManager webpartsOnTheJob = site.GetLimitedWebPartManager(PageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
                {
                    //SPLimitedWebPartManager webpartsOnTheJob = site.GetLimitedWebPartManager(PageUrl, System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared);
                    ContentEditorWebPart contentEditorWP = new ContentEditorWebPart();

                    //set properties of new webpart object    
                    contentEditorWP.ZoneID = ZoneID;
                    contentEditorWP.Title = title;
                    contentEditorWP.ChromeState = System.Web.UI.WebControls.WebParts.PartChromeState.Normal;
                    contentEditorWP.ChromeType = System.Web.UI.WebControls.WebParts.PartChromeType.None;
                    //Add content to CEWP
                    XmlDocument xmlDoc = new XmlDocument();
                    XmlElement xmlElement = xmlDoc.CreateElement("Root");
                    xmlElement.InnerText = InnerText;
                    contentEditorWP.Content = xmlElement;
                    contentEditorWP.Content.InnerText = xmlElement.InnerText;
                    //Adding Web part to page.
                    webpartsOnTheJob.AddWebPart(contentEditorWP, contentEditorWP.ZoneID, 0);

                }

            }
        }

Now for adding a custom webpart :

 private void AddCustomWebpartsToPage(SPWeb objSPWeb, string strPageUrl, string strWebpartName, string zoneID, int zoneIndex, bool CheckWebPartExist)
        {
                if (!CheckWebPartExist)
                {
                    using (SPLimitedWebPartManager webPartManager = objSPWeb.GetLimitedWebPartManager(
                            strPageUrl, PersonalizationScope.Shared))
                    {
                        SPListItemCollection webParts;
                        bool isExists = CheckIfWebPartExistsInGallery(objSPWeb, strWebpartName, webPartManager, out webParts);
                        if (isExists)
                        {
                            using (System.Web.UI.WebControls.WebParts.WebPart webPart = CreateWebPart(objSPWeb, strWebpartName, webPartManager, webParts))
                            {
                                webPart.ChromeType = PartChromeType.None;
                                webPartManager.AddWebPart(webPart, zoneID, zoneIndex);
                            }
                        }
                    }
                }
            }



Check for Custom Webpart Exists in Page or not :

private bool CheckWebPartExist(SPWeb site, string PageUrl, string title)
{
bool CheckWebPartExist = false;
SPWebPartCollection webparts = site.GetWebPartCollection(PageUrl, Storage.Shared);
foreach (System.Web.UI.WebControls.WebParts.WebPart contentEditorWP in webparts)
{
if (contentEditorWP.Title == title)
{
CheckWebPartExist = true;
break;
}
}
return CheckWebPartExist;
}
Chaeck for custom webpart exists in WebPart Gallery or not :

private static bool CheckIfWebPartExistsInGallery(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager, out SPListItemCollection webParts)
{
bool isExists = false;
SPQuery qry = new SPQuery();
qry.Query = String.Format(CultureInfo.CurrentCulture,
"<Where><Eq><FieldRef Name='FileLeafRef'/><Value Type='File'>{0}</Value></Eq></Where>",
webPartName);
SPList webPartGallery = null;
if (null == web.ParentWeb)
{
webPartGallery = web.GetCatalog(SPListTemplateType.WebPartCatalog);
}
else
{
webPartGallery = web.Site.RootWeb.GetCatalog(SPListTemplateType.WebPartCatalog);
}
webParts = webPartGallery.GetItems(qry);
if (webParts.Count > 0)
{
isExists = true;
}
else
{
isExists = false;
}
return isExists;
}

Create WebPart Custom Webpart instance through code
public static System.Web.UI.WebControls.WebParts.WebPart CreateWebPart(SPWeb web, string webPartName, SPLimitedWebPartManager webPartManager, SPListItemCollection webParts)
{
XmlReader xmlReader = new XmlTextReader(webParts[0].File.OpenBinaryStream());
string errorMsg;
System.Web.UI.WebControls.WebParts.WebPart webPart = webPartManager.ImportWebPart(xmlReader, out errorMsg);
return webPart;
}  All you need to provide is thses parameters correctly.

How to get cascaded List Boxes using SharePoint lists as data source..

List boxes have been usually used for selecting multiple values e.g. "Countries".  Now you need to populate another list box containing "Landmarks" of that all selected countries. In this case we need  two cascaded list boxes, on the selection of list box "Countries" items can trigger to population of another list box "Landmarks" and also depopulate the  list box "Landmarks" on the deselection of list box "Countries" items. In this kind of cases we need cascaded list boxes. Here are the steps to do it using SharePoint list as a data source.

1.) At first we need to put four list boxes in our .aspx page as pairs of selected and available and also four  buttons in pairs of two to add and remove functionality. I have also put it in Update Panel so that whole page should not be post back on buttons click. Code is as follows:

                <asp:UpdatePanel runat="server" ID="updatePanelCountries" UpdateMode="Conditional">
                    <contenttemplate>
                        <table width="50%">
                            <tr>
                                <td>
                                    <asp:ListBox ID="lstCountryAvailable" runat="server"
                                        SelectionMode="Multiple" BackColor="#f2f2f7" >
                                    </asp:ListBox>
                                </td>
                                <td>
                                    <asp:ImageButton runat="server" ID="btnCountryAdd" ImageUrl="/_layouts/Images/AddSelect.jpg" OnClick="btnCountryAdd_Click" /><br />
                                    <asp:ImageButton runat="server" ID="btnCountryRemove" ImageUrl="/_layouts/Images/RemoveSelect.jpg" OnClick="btnCountryRemove_Click" /><br />
                               <td rowspan="4" class="tdListBox_Skills">
                            <asp:ListBox ID="llstCountrySelected" runat="server"
                                SelectionMode="Multiple" BackColor="#f2f2f7">
                            </asp:ListBox>
                        </td>
                    </tr>
                </table>
                 </contenttemplate>
                    <triggers>
                    <asp:AsyncPostBackTrigger ControlID="btnLandmarksSelected" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="BtnLandmarksRemove" EventName="Click" />
                </triggers>
                </asp:UpdatePanel>
            </td>
        </tr>
        <tr>
            <td >
             <asp:UpdatePanel runat="server" ID="updatePanelLandmarks" UpdateMode="Conditional">
                    <contenttemplate>
                <table>
                    <tr>
                        <td>
                            <asp:ListBox ID="lstLandmarksAvailable" runat="server" SelectionMode="Multiple"
                                Rows="12" BackColor="#f2f2f7" ></asp:ListBox>
                        </td>
                        <td class="tdAddRemoveButton">
                            <asp:ImageButton ID="btnLandmarksAdd" runat="server" ImageUrl="/_layouts/Images/AddSelect.jpg" OnClick="btnLandmarksAdd_Click" /><br />
                            <asp:ImageButton runat="server" ID="btnLandmarksRemove" ImageUrl="/_layouts/Images/RemoveSelect.jpg" OnClick="btnLandmarksRemove_Click" /><br />
                        </td>
                        <td>
                            <asp:ListBox ID="lstLandmarksSelected" runat="server"
                                SelectionMode="Multiple" Rows="12">
                            </asp:ListBox>
                        </td>
                    </tr>
                </table>
                 </contenttemplate>
                    <triggers>
                    <asp:AsyncPostBackTrigger ControlID="btnCountryAdd" EventName="Click" />
                    <asp:AsyncPostBackTrigger ControlID="btnCountryRemove" EventName="Click" />
                </triggers>
                </asp:UpdatePanel>

2.) After putting all these code in your .aspx page you need to write .cs file for handling all button clicks. So we need to add following code.

protected void btnCountryAdd_Click(object sender, EventArgs e)
        {
            try
            {
                MoveCascadedListBoxItems(lstCountryAvailable, llstCountrySelected, lstLandmarksAvailable, lstLandmarksSelected, true, "ADD");
                SortListBox(lstSkillCategorySelected);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
        }


public static void MoveCascadedListBoxItems(ListBox lstBoxAvailable, ListBox lstBoxSelected, ListBox lstSkill, ListBox lstSkillSelected, bool Cascade, string action)
        {
            if ((lstBoxAvailable != null) && (lstBoxSelected != null))
            {
                for (int i = lstBoxAvailable.Items.Count - 1; i >= 0; i--)
                {
                    if (lstBoxAvailable.Items[i].Selected)
                    {
                        lstBoxSelected.Items.Add(new ListItem
                        {
                            Text = lstBoxAvailable.Items[i].Text,
                            Value = lstBoxAvailable.Items[i].Value
                        });
                        if (action == "REMOVE")
                        {
                            DataTable dt = GetSPDataTable("Skills", string.Empty);
                            string[] newVal = lstBoxAvailable.Items[i].Text.Split('_');
                            DataRow[] dr = dt.Select("Skill_x0020_Category='" + newVal[1] + "'");
                            if (dr.Length > 0)
                            {
                                for (int j = 0; j < dr.Length; j++)
                                {
                                    if (lstSkill.Items.Count > 0)
                                    {
                                        ListItem item = lstSkill.Items.FindByText(dr[j]["Prefixvalue"].ToString() + "_" + dr[j]["Title"].ToString());
                                        lstSkill.Items.Remove(item);
                                    }
                                    if (lstSkillSelected.Items.Count > 0)
                                    {
                                        ListItem item = lstSkillSelected.Items.FindByText(dr[j]["Prefixvalue"].ToString() + "_" + dr[j]["Title"].ToString());
                                        lstSkillSelected.Items.Remove(item);
                                    }
                                }
                            }
                        }
                        else if (action == "REMOVESkill")
                        {
                            DataTable dt = GetSPDataTable("Skills", string.Empty);
                            DataRow[] dr = dt.Select("Skill_x0020_Category='" + lstBoxAvailable.Items[i].Value + "'");
                            if (dr.Length > 0)
                            {
                                for (int j = 0; j < dr.Length; j++)
                                {
                                    if (lstSkill.Items.Count > 0)
                                    {
                                        ListItem item = lstSkill.Items.FindByValue(dr[j]["Title"].ToString());
                                        lstSkill.Items.Remove(item);
                                    }
                                    if (lstSkillSelected.Items.Count > 0)
                                    {
                                        ListItem item = lstSkillSelected.Items.FindByValue(dr[j]["Title"].ToString());
                                        lstSkillSelected.Items.Remove(item);
                                    }
                                }
                            }
                        }
                        lstBoxAvailable.Items.Remove(lstBoxAvailable.Items[i]);
                    }
                }
            }
            if (Cascade && action == "ADD")
            {
                BindChildListBox(lstBoxSelected, lstSkill, lstSkillSelected);
            }
        }

public static void BindChildListBox(ListBox lstSkillcategorySelected, ListBox lstSkill, ListBox lstSkillSelected)
        {
            List<string> selectedValueList = new List<string>();
            foreach (ListItem item in lstSkillcategorySelected.Items)
            {
                selectedValueList.Add(item.Value);
            }
            string query = PrepareQuery(selectedValueList);
            DataTable colItems = GetChildSPDataTable("Skills", query);
            if (!String.IsNullOrEmpty(query))
            {
                if (null != colItems && colItems.Rows.Count > 0)
                {
                    foreach (DataRow item in colItems.Rows)
                    {
                        if (lstSkill.Items.FindByText((item["Prefixvalue"] + "_" + item[Constants.TITLE].ToString().Trim())) == null && lstSkillSelected.Items.FindByText((item["Prefixvalue"] + "_" + item[Constants.TITLE].ToString().Trim())) == null)
                        {
                            lstSkill.Items.Add(new ListItem((item["Prefixvalue"] + "_" + item[Constants.TITLE].ToString().Trim()), item[Constants.ID].ToString().Trim()));
                        }
                    }
                }
            }
        }

 protected void btnCountryRemove_Click(object sender, EventArgs e)
        {
            try
            {
                MoveCascadedListBoxItems(lstLandmarksSelected, lstLandmarksAvailable, lstCountryAvailable, llstCountrySelected, true, "REMOVE");
                SortListBox(lstSkillCategory);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
        }

protected void SortListBox(ListBox lstBox)
        {
            List<ListItem> t = new List<ListItem>();
            Comparison<ListItem> compare = new Comparison<ListItem>(CompareListItems);
            foreach (ListItem lbItem in lstBox.Items)
                t.Add(lbItem);

            t.Sort(compare);
            lstBox.Items.Clear();
            lstBox.Items.AddRange(t.ToArray());
        }

int CompareListItems(ListItem li1, ListItem li2)
        {
            return String.Compare(li1.Text, li2.Text);
        }

 protected void btnLandmarksAdd_Click(object sender, EventArgs e)
        {
            try
            {
                MoveCascadedListBoxItems(lstLandmarksAvailable, lstLandmarksSelected, lstLandmarksAvailable, lstLandmarksSelected, false, "ADD");
                SortListBox(lstLandmarksSelected);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
        }

 protected void btnLandmarksRemove_Click(object sender, EventArgs e)
        {
            try
            {
                MoveCascadedListBoxItems(lstLandmarksSelected, lstLandmarksAvailable, lstLandmarksAvailable, lstLandmarksSelected, false, "REMOVESkill");
                SortListBox(lstLandmarksAvailable);
            }
            catch (Exception ex)
            {
                Logger.Write(ex);
            }
        }
*prefixValue is a string value that I put to combine two different Texts in List Box. Please ignore it.

** I have used Constants.TITLE for column name to query or bind.

*** PrepareQuery is a method which is used to generate CAML query at run time. I have posted it in another blog and you can navigate to it.