Wednesday, August 10, 2011

Find out which site template has been used to create a SharePoint site

  1. First option is, this is my recommended choice and very easy too. By using SharePoint Manager tool [available for both 2010 and 2007.] Download it for free from Codeplex and install it. Now, open the SharePoint Manager and connect to the SharePoint site collection. When you click on a specific SharePoint site, on the right side it will show you all the properties available in the SP object model for that site. In it find for TemplateID and check the value showing there. That's it. What is TemplateID and how to know template name from it? Navigate to end of this post for TemplateID to Name mapping.
  2. Second option is, if there is no way to install SharePoint manager or if any other problems, then save the current site as site template[.STP extension]. Now, save it to disk somewhere. Now, navigate to that location and rename the file to .CAB extension. Extract the CAB file and find the manifest.xml file. Now, in the file check for the TemplateID string and get the value. Navigate to end of this post for the TemplateID to Name mapping.
  3. From the SP Object Model: Through managed code we can identify this very easily with below code.
    1. using (SPWeb web = site.OpenWeb("/"))   
    2. {      
    3.    string templateID = web.WebTemplateId.ToString();   
    4. }   
  4. Using STSADM.EXE: It needs high level permissions. Means the user should be an administrator on the server. Below is the command we need to use for knowing the site template.
    stsadm.exe -o enumallwebs -database [content database name]
  5. From Sql Server: Sql server has all the information about SharePoint. So, if you have access to database then login to the sql server management studio and execute below query on the content database of the application.
    SELECT Title, WebTemplate FROM dbo.Webs WHERE Title='Test Publishing Site'

Wednesday, July 27, 2011

Removing Orphan sites from SharePoint 2007

I am sure you have seen enough blog posts on this and so I thought will add one more to the ever growing list!!
So for last few days I have been working with one my my colleagues to install and Configure Enterprise Portal (AX 2009) with SharePoint 2007 Farm (1 WFE + 1 App Server connecting to SQL) – it’s a different war altogether but let me tell you how we landed up with multiple orphan site collections. EP was failing to install every time (and we did this at least 10 times) since it could not create the site collation with the Custom Site Definition. we finally got around it, but in the process EP installer was invoking a web service to create the namespace every time >> http://%3csharepointsitednsname%3e/sites/DynamicsAX .
Finally when the EP installation completed successfully we could not browse the EP Role Center Site. after few hours of banging our head we finally went in SQL (ContentDB >> Site table) and saw a bunch of entries which shouldn’t be there >> Touching SQL Content Db in SharePoint is not supported – so don’t do it, I will tell you how to find orphan sites without touching SQL.
when you run stsadm –o databaserepair command – it shows the orphan items in a content DB .. however, our showed 0, reason being, there wasn’t anything in the content DB per say. so what to do??
Make sure you have SP2 for MOSS first.
There are primarily two ways to find this out.
  1. preupgradecheck – it not for upgrade only. it checks your MOSS health and lets you know what you should be doing. ideally you should run this on a scheduled manner to ensure MOSS is healthy. We ran stsadm –o preupgrade and it did tell us the bunch of orphan site collections

    image

    Below this it also notifies to run databaserepair and or detach / attach content DB – we did this but it didn’t resolve the issue and preupgradecheck continued to report the orphaned site collections
  2. enumallwebs – this was the savior !! this command runs against content DB and not on a URL context. We ran it and it displayed some 8 sites where the InSiteMap property was False. this denotes that the Site Collections are orphaned. See below:

    image

    The command is stsadm –o enumallwebs –databasename YourSQLName –databaseserver YourSQLServerName
    http://technet.microsoft.com/en-us/library/dd789634(office.12).aspx 
ok so we found the orphan addresses, now clean up time. Since attach / detach and databaserepair with deletecorruption switch didn’t help us, we decided to manually delete the Sites with SiteID. if you note above, EnumAllWebs shows the GUID of the Sites that we will use to delete them and clean up the WebApp

The command to run here is : (copy site ID from above output for all of them where InSiteMap=False) - http://technet.microsoft.com/en-us/library/cc288016(office.12).aspx 
stsadm -o deletesite -force -siteid 40ca628e-8d7c-461b-9340-c5bb518cf399
-databasename wss_content_ep -databaseserver sql08W2008X64

image
That did it!! to Verify, we ran preupgradecheck again and it didn’t report any Orphan Site Collections.
Hope this helps.



Another Way:

Delete orphaned sites or items in sharepoint 2007.

To delete orphaned sites or item from a sharepoint site, we have 2 options.

Option 1.

  • Opened a command Prompt and went to this directory: C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\BIN
  • Type following command to list the orphaned sites: stsadm -o databaserepair -url http://URLofWindowsSharePointServicesSite -databasename DatabaseName
  • To delete orphaned site :stsadm -o databaserepair -url http://URLofWindowsSharePointServicesSite -databasename DatabaseName -deletecorruptionThe above command might delete orphaned sites and items.
If above steps doesn't resolve orphan issue then apply below mentioned Option 2
Option 2
  • Go to command prompt as given in Option 1. Run command stsadm -o deletecontentdb -url http://URLofWindowsSharePointServicesSite -databasename "databasename" (remember database name)
  • Now run command stsadm -o addcontentdb -url http://URLofWindowsSharePointServicesSite -databasename "databasename"
I hope option 2 might resolve orphan issue.

Thursday, June 2, 2011

Visual Web Parts: Tree View



<%@ Assembly Name="$SharePoint.Project.AssemblyFullName$" %>
<%@ Assembly Name="Microsoft.Web.CommandUI, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %> 
<%@ Register Tagprefix="Utilities" Namespace="Microsoft.SharePoint.Utilities" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Register Tagprefix="asp" Namespace="System.Web.UI" Assembly="System.Web.Extensions, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" %>
<%@ Import Namespace="Microsoft.SharePoint" %> 
<%@ Register Tagprefix="WebPartPages" Namespace="Microsoft.SharePoint.WebPartPages" Assembly="Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" %>
<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="SasiTreeViewUserControl.ascx.cs" Inherits="May9thVisualWebParts.SasiTreeView.SasiTreeViewUserControl" %>
<asp:TreeView ID="siteStructure" runat="server">
</asp:TreeView>






using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;


namespace May9thVisualWebParts.SasiTreeView
{
    public partial class SasiTreeViewUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SPWeb thisWeb = SPContext.Current.Web;
            TreeNode node = new TreeNode(thisWeb.Title, null, null, thisWeb.Url, "_self");
            siteStructure.Nodes.Add(node);


            TreeNode ParentNode = node;


            foreach (SPList list in thisWeb.Lists)
            {
                if (!list.Hidden)
                {
                    node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
                    ParentNode.ChildNodes.Add(node);
                }
            }




            foreach (SPWeb childWeb in thisWeb.Webs)
            {
                AddWebs(childWeb, ParentNode);
                childWeb.Dispose();
            }


            siteStructure.CollapseAll();
        }


        void AddWebs(SPWeb web, TreeNode ParentNode)
        {
            TreeNode node = new TreeNode(web.Title, null, null, web.Url, "_self");
            ParentNode.ChildNodes.Add(node);
            ParentNode = node;
            foreach (SPList list in web.Lists)
            {
                node = new TreeNode(list.Title, null, null, list.DefaultViewUrl, "_self");
                ParentNode.ChildNodes.Add(node);


            }
            foreach (SPWeb childWeb in web.Webs)
            {
                AddWebs(childWeb, ParentNode);
                childWeb.Dispose();
            }
        }
    }
}


-----


using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlClient;
using System.Data;



namespace May9thVisualWebParts.DeepakGV
{
    public partial class DeepakGVUserControl : UserControl
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection("Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=WSS_Content_9997;Data Source=BALDH01-NB\\SQL2008");
            DataSet ds = new DataSet();
            SqlDataAdapter da = new SqlDataAdapter("Select top 10 * from alllists", con);
            da.Fill(ds, "allLists");
            GridView1.DataSource = ds.Tables[0].DefaultView;
            GridView1.DataBind();




        }
    }
}

Friday, May 20, 2011

SharePoint Visual How tos List

WSS 3.0 Visual How tos
http://msdn.microsoft.com/en-us/library/bb931737(v=office.12).aspx


SharePoint 2007 Visual How tos
http://msdn.microsoft.com/en-us/library/bb726436(v=office.12).aspx

SharePoint 2010 Visual How tos
http://msdn.microsoft.com/en-us/library/gg252010.aspx

Wednesday, May 18, 2011

SharePoint 2010 Feature Creation - Element.xml


Important files that we need to have an Idea:

http://msdn.microsoft.com/en-us/library/ms460194.aspx   CustomAction Element
http://msdn.microsoft.com/en-us/library/bb802730.aspx   Default Custom Action Locations and IDs
http://msdn.microsoft.com/en-us/library/ee537543.aspx CommandUIDefinition: Default Server Ribbon Customization Locations
http://msdn.microsoft.com/en-us/library/ms465980.aspx Custom Action Definition Schema
http://msdn.microsoft.com/en-us/library/ff458373.aspx Command UI Definition // Button, Tab, checkBox code ...



<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <CustomAction
    Id="NewUIRibbonControl"
    RegistrationType="List"
    RegistrationId="101"
    Location="CommandUI.Ribbon">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
           Location="Ribbon.Documents.New.Controls._children">
          <Button
             Id="NewUIRibbonControl.ShowHelp"
             Alt="Help"
             Sequence="1981"
             Command="ShowHelp"
             Image32by32="/_layouts/images/helpicon.gif"
             LabelText="Help"
             TemplateAlias="o1"/>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
         Command="ShowHelp"
         CommandAction="javascript:window.open('http://msdn.microsoft.com/en-us/library/ee539395%28office.14%29.aspx');" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>

<CustomAction Id="Ribbon.Library.Actions.ReplacementButton"
    Location="CommandUI.Ribbon"
    RegistrationId="101"
    RegistrationType="List"
    Title="Replace a Ribbon Button">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Library.Actions.ConnectToClient">
          <Button Id="Ribbon.Library.Actions.ConnectToClient.ReplacementButton"
            Command="ReplacementButtonCommand"
            Image16by16="/_layouts/images/actionseditpage16.gif"
            Image32by32="/_layouts/images/actionssettings.gif"
            LabelText="Replaced Button"
            TemplateAlias="o2" />
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="ReplacementButtonCommand"
          CommandAction="javascript:alert('This button has been replaced.');" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>


 <CustomAction
   Id="MyCustomRibbonTab"
   Location="CommandUI.Ribbon.ListView"
   RegistrationId="101"
   RegistrationType="List">
    <CommandUIExtension>
      <CommandUIDefinitions>
        <CommandUIDefinition
          Location="Ribbon.Tabs._children">
          <Tab
            Id="Ribbon.CustomTabExample"
            Title="My Custom Tab"
            Description="This holds my custom commands!"
            Sequence="501">
            <Scaling
              Id="Ribbon.CustomTabExample.Scaling">
              <MaxSize
                Id="Ribbon.CustomTabExample.MaxSize"
                GroupId="Ribbon.CustomTabExample.CustomGroupExample"
                Size="OneLargeTwoMedium"/>
              <Scale
                Id="Ribbon.CustomTabExample.Scaling.CustomTabScaling"
                GroupId="Ribbon.CustomTabExample.CustomGroupExample"
                Size="OneLargeTwoMedium" />
            </Scaling>
            <Groups Id="Ribbon.CustomTabExample.Groups">
              <Group
                Id="Ribbon.CustomTabExample.CustomGroupExample"
                Description="This is a custom group!"
                Title="Custom Group"
                Sequence="52"
                Template="Ribbon.Templates.CustomTemplateExample">
                <Controls Id="Ribbon.CustomTabExample.CustomGroupExample.Controls">
                  <Button
                    Id="Ribbon.CustomTabExample.CustomGroupExample.HelloWorld"
                    Command="CustomTabExample.HelloWorldCommand"
                    Sequence="15"
                    Description="Says hello to the World!"
                    LabelText="Hello, World!"
                    TemplateAlias="cust1"/>
                  <Button
                    Id="Ribbon.CustomTabExample.CustomGroupExample.GoodbyeWorld"
                    Command="CustomTabExample.GoodbyeWorldCommand"
                    Sequence="17"
                    Description="Says good-bye to the World!"
                    LabelText="Good-bye, World!"
                    TemplateAlias="cust2"/>
                  <Button
                    Id="Ribbon.CustomTabExample.CustomGroupExample.LoveWorld"
                    Command="CustomTabExample.LoveWorldCommand"
                    Sequence="19"
                    Description="Says I love the World!"
                    LabelText="I love you, World!"
                    TemplateAlias="cust3"/>
                </Controls>
              </Group>
            </Groups>
          </Tab>
        </CommandUIDefinition>
        <CommandUIDefinition Location="Ribbon.Templates._children">
          <GroupTemplate Id="Ribbon.Templates.CustomTemplateExample">
            <Layout
              Title="OneLargeTwoMedium"
              LayoutTitle="OneLargeTwoMedium">
              <Section Alignment="Top" Type="OneRow">
                <Row>
                  <ControlRef DisplayMode="Large" TemplateAlias="cust1" />
                </Row>
              </Section>
              <Section Alignment="Top" Type="TwoRow">
                <Row>
                  <ControlRef DisplayMode="Medium" TemplateAlias="cust2" />
                </Row>
                <Row>
                  <ControlRef DisplayMode="Medium" TemplateAlias="cust3" />
                </Row>
              </Section>
            </Layout>
          </GroupTemplate>
        </CommandUIDefinition>
      </CommandUIDefinitions>
      <CommandUIHandlers>
        <CommandUIHandler
          Command="CustomTabExample.HelloWorldCommand"
          CommandAction="javascript:alert('Hello, world!');" />
        <CommandUIHandler
          Command="CustomTabExample.GoodbyeWorldCommand"
          CommandAction="javascript:alert('Good-bye, world!');" />
        <CommandUIHandler
          Command="CustomTabExample.LoveWorldCommand"
          CommandAction="javascript:alert('I love you, world!');" />
      </CommandUIHandlers>
    </CommandUIExtension>
  </CustomAction>



</Elements>

Tuesday, May 17, 2011

How to add a user to a SharePoint Group & Feature Stapling

How to create a feature with feature stapplingin SharePoint?

1) Open a new sharepoint visual studio 2010 project

2) Make your feature as normal

3) Find the site definition id you want to staple your feature to

C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\1033\XML\webtemp*.xml
4) Create a new module, call it "Stapling" or something

5) Insert this into the module file, replacing the site definition template name and feature guid:

<?xml version="1.0" encoding="utf-8"?>
<Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  <FeatureSiteTemplateAssociation Id="FEATUREGUID" TemplateName="YOURSITETEMPLATE#0" />
</Elements>
6) A new feature should have been created for "Stapling", but if it has not, create it and the Stapling module to it

7) Set the deployment scope to "Farm"

8) You should have 2 features in your project now

9) Package and deploy


--

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Microsoft.SharePoint;

namespace AddUsers
{
class AddUserClass
{
static void Main(string[] args)
{

SPSite siteCollection = new SPSite(“Site URL”);
SPWeb site = siteCollection.OpenWeb();

SPGroup AddUserGroup = site.Groups["Group Name"];
AddUserGroup.AddUser(“domain/alias”, “email address”, “Name”, “Description”);

OR

SPRoleAssignment MyRoleAssign = new SPRoleAssignment(“domain/alias”, “email address”, “Name”, “Description”);

SPRoleDefinition MyRoleDef = newSubWeb.RoleDefinitions["Contribute"];
MyRoleAssign.RoleDefinitionBindings.Add(MyRoleDef);
site.RoleAssignments.Add(MyRoleAssign);

site.Dispose();
siteCollection.Dispose();
}
}
}

Monday, May 9, 2011

Moving Content Database from One Site to Other Site / One Env to Other Environment


In our source server, let us do the following steps: 


1. In the Command Prompt, let us change to the directory where the STSADM command-line tool is located. By default, it is on C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN. 


2. The next step is to prepare our content database before moving it by setting up the profile and membership synchronization service. It prevents the synchronization service from failing and losing related settings. To do this, let us type the following command, and then press Enter: 


STSADM –o preparetomove –contentdb <content database name>

stsadm -o preparetomove -ContentDB Usildb218-qa:WSS_Content_sales_Prod


3. Now, let us detach our content database by executing the command below. We have to take note, however, that removing the content database simply removes the association of the database with our SharePoint Web application and does not exactly delete the database. 


STSADM -o deletecontentdb –url <URL name> -databasename <database name> -databaseserver <database server name> 


stsadm -o deletecontentdb -url "https://kmqa.ca.com/sales" -databasename WSS_Content_sales_Prod -databaseserver usildb218-qa


4. Let us open our Microsoft SQL Server 2008 Management Studio, and detach the content database. Finally, we will copy the corresponding .mdf and .ldf files to our destination server. 


In our destination server, let us do the following steps: 


NOTE: It is assumed that you have created a corresponding Web site in you destination server and deleted its content database – like what we have did in steps 2 and 3. With this, we are now ready to restore/move the content database of our source server to the destination server. Thanks Amlan for the comment. 


5. Let us open our Microsoft SQL Server 2008 Management Studio, and attach the content database that we transferred in the previous step. 


6. In the Command Prompt, let us change to the directory where the STSADM command-line tool is located. By default, it is on C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\12\BIN. 


7. Now, to add the content database to our destination server, let us type the following command, and then press Enter: 


STSADM –o addcontentdb –url <URL name> -databasename <database name> -databaseserver <database server name> 






stsadm -o addcontentdb -url "http://kmdev.ca.com/sales" -databasename "WSS_Content_sales_Prod" -databaseserver "usildb218-qa"


8. And finally let us start a full crawl. We must be aware, moreover, that a full crawl will occur the first time even if the next crawling scheduled is set to incremental mode in the content database we have restored.