Thursday, May 23, 2013

Calculating Size of Site Collection, Sub Sites in Programming

Simple console application program to calculating Size of Site Collection, Sub Sites in SharePoint




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

namespace CalculatingSPSitesSize
{
    class Program
    {
        static void Main(string[] args)
        {
            long siteCollectionSize = 0; 
            string baseUrl = "http://Portal";       
           
            Console.WriteLine("Base Url: " + baseUrl + " (Change baseUrl to list sites starting with)"); 
            using (SPSite mainSite = new SPSite(baseUrl))
            { 
                foreach (SPWeb web in mainSite.AllWebs)
                { 
                    long webSize = GetSPFolderSize(web.RootFolder) + web.RecycleBin.Cast<SPRecycleBinItem>().Sum(r => r.Size);
                    if (web.Url.StartsWith(baseUrl))
                    {
                        Console.WriteLine(string.Format("({0} {1}", web.Url, FormatSize(webSize)));
                        siteCollectionSize += webSize;
                    }
                }
            } 
            Console.WriteLine("Total Size: " + FormatSize(siteCollectionSize));
            Console.ReadKey(false);
        }


        public static long GetSPFolderSize(SPFolder folder)
        {
            long folderSize = 0;
            foreach (SPFile file in folder.Files)
                folderSize += file.TotalLength
                    + file.Versions.Cast<SPFileVersion>().Sum(f => f.Size);
            folderSize += folder.SubFolders.Cast<SPFolder>().Sum(sf => GetSPFolderSize(sf));
            return folderSize;
        }
       
        public static string FormatSize(long size)
        {
            if (size > Math.Pow(1024, 3))
                return (size / Math.Pow(1024, 3)).ToString("#,#.##") + " GB";
            else if (size > Math.Pow(1024, 2))
                return (size / Math.Pow(1024, 2)).ToString("#,#.##") + " MB";
            else if (size > 1024)
                return (size / 1024).ToString("#,#.##") + " KB";
            else
                return size.ToString("#,#.##") + " Bytes";
        }
    }
}





Reference
http://www.c-sharpcorner.com/UploadFile/40e97e/calculating-size-of-site-collection-sub-sites-in-multiple-w/

Upgrade Site Collection from MOSS 2007 to SharePoint 2010


In order to understand and make the upgrading process smooth, please refer to this SharePoint Server 2010 link, especially the checklist at the bottom of the page. In addition to this information I’d like to describe the problems that I encountered during this process.

The upgrade process recommended by Microsoft, is by attaching the content database to the existing web application; in my case, my content db had more than one site collection and I needed to upgrade only one. I had to move this site collection to a separate content database.

The mergecontentdbs of stsadm commands deals with this process as follows:

§  Store the site collection list into xml file
stsadm -o enumsites -url http://[server_name] -databasename [contentdb_name] > splitSites.xml
§  Open the splitSites.xml file for editing
§  On the root element “Sites” set the “Count” value to 1
§  Remove all “Site” elements except one that associates with the site collection for upgrade, and save the file
§  If the destination database is not present, it must be created via the Central Admin site
§  On the Central Administration site, browse to Application Management and click Content databases link under SharePoint Web Application Management section. On this screen, click on “Add a content database” link to create a new content database. (Leave the settings at their default)
§  Merge the databases
stsadm -o mergecontentdbs -url http://[server_name] -sourcedatabasename [sourcedb_name] - destinationdatabasename [destinationdb_name] -operation 3 -filename splitSites.xml
§  Perform an IISRESET once the operation completes successfully

Now, we can start with the upgrading, by attaching the content database to the existing web application. There are a couple of facts I have to point out:
§  On the SharePoint 2010 side you have to be a Farm Administrator to perform the action
§  If you add a content db through stsadm command, always open the command prompt as administrator (“Run as administrator”)
In SQL server make sure that you are a db_owner on both: the new content database and configuration data base. Otherwise, you will get an “Access Denied” message when executing the stsadm commands


Reference




Moving Content Database from SP 2007 to SP 2010


After installing and configuring your new SharePoint 2010,

Moving Content Database from SP 2007 to SP 2010

1) Find the content Database; These are listed under Central Admin->Application Management->Site Collection List

2) Backup the content database, You could alternatively detach it, and copy it. Just doing a backup in SQL Server Management studio is easier.

3) Restore content database to new server, Copy the BAK file to new server. Create an empty DB in Management Studio, restore from backup, you may need to change an option in the "options" tab of the restore dialog to get it to work. (Overwrite db).

4) Create Web App on SharePoint 2010

5) Remove Content Database from the new web app.

6) Add Content Database which you have restored it (step 3)

 Use STSADM to add restored DB to this web app

c:\program files\common files\microsoft shared\web server extentions\14\bin on new server is where you can find the STSADM.

run this command from there. Which will upgrade the content db to 2010?

stsadm -o addcontentdb -url http://yourwebapp -databasename yourcontentdb -databaseserver yoursqlserver

7) Run IISRESET from command prompt


Reference


How to move the mysites from http://portal/personal to a new web application at http://mysite ?


Mysite web application was created either when creating the new SSP as the new mysite host or manually using My Site Host template, in which case you need to add an wildcard inclusion to /personal manged path

Backup and Restore

enumerate all the mysites that were already created (output it to a file for easier work):

stsadm –o enumsites –url http://portal/personal/ > c:\mysites.txt

ex: stsadm –o enumsites –url  http://YourMysite/personal/ > C:\mysites.txt


Edit the txt file and create 3 batch files of it:

One for backing up the mysites, one for creating the destination mysites, one for restoring from backup at the destination: for instance, the following line from the initial file resulted (mysites.txt)

<Site Url=http://portal/personal/username Owner="Domain\username" SecondaryOwner="Domain\administrator" ContentDatabase="ContentDBName" StorageUsedMB="0.4" StorageWarningMB="80" StorageMaxMB="100" />

Ex:  <Site Url="https://YourMysite/personal/YourUserName" Owner=" Your DomainName\YourPrimaryUserName " SecondaryOwner=" YourDomainName\YourSecondaryUserName " ContentDatabase="Your MySite Content DB Name" StorageUsedMB="Your Mysite Data Size" StorageWarningMB="0" StorageMaxMB="0" />

It will become (in 3 bat files):

Backup

stsadm -o backup -url http://portal/personal/username -filename c:\backup\username.dat

Ex: stsadm -o backup -url https://YourMysite/personal/YourUserName  -filename c:\backup\username.dat

Create MySite

stsadm -o createsite -url http://mysite/personal/username -sitetemplate SPSPERS -owneremail username@domain.com -ownerlogin "Domain\username"

Ex: stsadm -o createsite -url https://YourMysite/personal/YourUserName -sitetemplate SPSPERS -owneremail  YourEmailAddress@DomainName.com  -ownerlogin "Your DomainName\YourUserName"

Restore

stsadm -o restore -url http://mysite/personal/username -filename c:\backup\username.dat –overwrite

Ex: stsadm -o restore -url https://YourMysite/personal/YourUserName -filename “c:\backup\username.dat” -overwrite

That’s it. Do it same for the rest of my sites

Wednesday, May 22, 2013

Attaching a Content DB to a Web Application in SharePoint 2007




For each Web Application you create in SharePoint, by default, there is a single Content DB that is assigned to it. Typically, the steps for creating a web application are as follows:
  1. Launch your Central Administration web site.
  2. On the Quick Launch bar to the left of the page, click on Application Management.
  3. Under the SharePoint Web Application Management heading, click on Create or extend Web application.
  4. Click on Create a new Web Application.
  5. The Create New Web Application page requires some information before creating your new web application. I won’t go through all of this in detail, but let’s pay particular attention to the Database Name and Authentication section. I have attempted in the past to alter the database name to match the already existing content db i would like this web application to use. This is not recommended nor does it work consistently. What you’ll want to do is accept all defaults for the database name and proceed with creating your web application. In the next steps we’ll outline how you swap this content db out for the one your already existing content db.
Now once your content db has been created, you’ll need to go back to the Application Management screen. From there, try the following:
  1. Click on Content databases.
  2. On the right of the toolbar, look for the Web Application drop down. Make sure you change this to match the web app you’re trying to replace the content db for. I find that sometimes this is defaulted to the Central Admin web application which is not what we want.
  3. Click on the database name link, this should bring up the Manage Content Database Settings page. Change your Database status to Offline and check Remove content database. Click OK. This content db shouldn’t contain anything since we just created this web application.
  4. We should now be redirected back to the Manage Content Databases page. Click on Add a content database.
  5. The only thing you need to change on this page is the Database Name field. Set this to the name of the content db you want to add. Set the search server and click OK.
Now typically this is a smooth operation, however, if you encounter the error below:
" Attaching this database requires an upgrade, which could time out the browser session. You must use the STSADM command ‘addcontentdb’ to attach this database."
Open up a command prompt window, and type the following stsadm command in:

stsadm -o addcontentdb -url http://server01/ -databasename WSS_Content
There are other arguments you can use for this command, to see a list of those, type:

stsadm -o addcontentdb
Once the command has completed successfully, try loading your site. If you have any issues at all with this, drop me a line.

Reference
http://blog.qumsieh.ca/2009/02/13/attatching-a-content-db-to-a-web-application/

SharePoint Site Template Codes


SharePoint Site Template Codes

Each Site Template that is installed on SharePoint 2007 has a unique name and number to allow for referencing when coding applications or using STSADM for site deployment (when using the -sitetemplate parameter, e.g. -site template STS#0 would apply a team site template) 

WSS Templates 

Team Site: STS#0 

Blank Site: STS#1 

Document Workspace: STS#2 

Wiki Site: WIKI#0 

Blog Site: BLOG#0 

Basic Meeting Workspace: MPS#0 

Blank Meeting Workspace: MPS#1 

Decision Meeting Workspace: MPS#2 

Social Meeting Workspace: MPS#3 

Multiple Meeting Workspace: MPS#4 

MOSS Templates 

Document Center: BDR#0 

Site Directory: SPSSITE#0 

Report Center: SPSREPORTCENTER#0 

Search Center with Tabs: SRCHCEN#0 

My Site Host: SPSMSITEHOST#0 

Search Center: SRCHCENTERLITE#0 

Personalisation Site: SPSMSITE#0 

Collaboration Portal: SPSPORTAL#0 

Publishing Portal: BLANKINTERNETCONTAINER#0 

Publishing Site: CMSPUBLISHING#0 

Publishing Site with Workflow: BLANKINTERNET#2 

News Site: SPSNHOME#0


Reference

How to find the template name of SharePoint site?

General Questions:

I have SharePoint site which is fully customized I would like to know the template name of site, because the SharePoint is created by some body else I don't know which template the guy had selected (like team site, blank site, publishing, collaboration site etc. while creating the site.

Answer

  • Code Snippet
    <%@ Assembly Name="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c"%>
    <%@ Page Language="C#" MasterPageFile="~/_layouts/application.master" Inherits="Microsoft.SharePoint.WebControls.LayoutsPageBase" %>
    <%@ Import Namespace="Microsoft.SharePoint" %>

    <script runat="server">
    protected override void OnLoad(EventArgs e){
    SPSecurity.RunWithElevatedPrivileges(delegate()
    {
    using (SPWeb thisWeb = this.Web)
    {
    lblWebTempalte.Text = thisWeb.WebTemplate;
    lblWebTemplateID.Text = thisWeb.WebTemplateId.ToString();
    }
    });
    }
    </script>
    <asp:Content ID="Main" runat="server" contentplaceholderid="PlaceHolderMain" >
    <p>
    Web Template: <asp:Label ID="lblWebTempalte" runat="server" />
    </p>
    Web Template ID: <asp:Label ID="lblWebTemplateID" runat="server" />
    </asp:Content>

    <asp:Content ID="PageTitle" runat="server" contentplaceholderid="PlaceHolderPageTitle" >
    Site Template Information
    </asp:Content>

    <asp:Content ID="PageTitleInTitleArea" runat="server" contentplaceholderid="PlaceHolderPageTitleInTitleArea" >
    Site Template Information
    </asp:Content>

    Please follow the steps to know the template name of sharepoint site:
    • Save the code snippet code as .aspx page ( eg:webtemplate.aspx) to your layouts folder (usually C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS)
    • Once the page is saved you can access it from any of your sharepoint sites via http://servername/_layouts/webtemplate.aspx
    • Compare the web template ID with the below List of MOSS 2007 Template ID Information

    List of MOSS 2007 Template ID Information
    0 - GLOBAL (SetupPath=global) - "Global template"
    1 - STS - "windows SharePoint Services Site", "Team Site", "Blank Site", "Document Workspace"
    2 - MPS - "Basic Meeting Workspace", "Blank Meeting Workspace", "Decision Meeting Workspace", "Social Meeting Workspace", "Multipage Meeting Workspace"
    3 - CENTRALADMIN - "Central Admin Site"
    4 - WIKI - "Wiki Site"
    7 - BDR - "Document Center"
    9 - BLOG - "Blog"
    20 - SPS (OBSOLETE) - "SharePoint Portal Server Site"
    21 - SPSPERS - "SharePoint Portal Server Personal Space"
    22 - SPSMSITE - "Personalization Site"
    30 - SPSTOC (OBSOLETE) - "Contents area Template"
    31 - SPSTOPIC (OBSOLETE) - "Topic area template"
    32 - SPSNEWS (OBSOLETE) - "News area template"
    33 - SPSNHOME (SubWebOnly) - "News Home template"
    34 - SPSSITES - "Site Directory area template"
    36 - SPSCOMMU (OBSOLETE) - "Community area template"
    38 - SPSREPORTCENTER - "Report Center Site"
    39 - CMSPUBLISHING (SetupPath=SiteTemplates\PUBLISHING) - "Publishing and Team Collaboration Site"
    40 - OSRV (SetupPath=SiteTemplates\OSRV) - "Shared Services Administration Site"
    47 - SPSPORTAL - "Corporate Intranet Site"
    50 - SRCHCEN - "Search Center"
    51 - PROFILES - "Profiles"
    52 - BLANKINTERNETCONTAINER - "Internet Presence Web Site"
    53 - BLANKINTERNET - "Publishing Site", "Press Releases Site", "Publishing Site"
    54 - SPSMSITEHOST - "My Site Host"
    90 - SRCHCENTERLITE (SetupPath=SiteTemplates\SRCHCENTERLITE) - "Search Center Lite"
    6221 - PWA (SetupPath=SiteTemplates\PWA) - "Project Web Access Site"
    6215 - PWS (SetupPath=SiteTemplates\PWS) - "Project Workspace"
    14483 - OFFILE - "Records Repository", "Records Repository"

    For more information please visit
    http://blog.rafelo.com/2008/05/determining-site-template-used-on.html
    http://www.frontpages-web-hosting.net/forums/microsoft-office-sharepoint-server-2007-moss-2007-development-topics/486-moss-2007-template-id-information.html

Reference
http://social.technet.microsoft.com/Forums/en-US/sharepointgeneral/thread/721bec39-2d32-4bbc-9094-a021a0d06dcb


Determining size of SharePoint sites / site collections



General Question

How to get the size (in bytes) of each site collection in SharePoint?

Answers

stsadm -o enumsites -url http://url

Example

<Sites Count="1">
  <Site
    Url="http://url"
    Owner="DomainName\user"
    SecondaryOwner="DomainName\user2" 
    ContentDatabase="WSS_Content_DB"
    StorageUsedMB="13756"
    StorageWarningMB="0"
    StorageMaxMB="0" />
</Sites>


Save to Notepad (.txt) file

stsadm -o enumsites -url "http://url"  > c:\sites.txt



Monday, May 20, 2013

DisableLoopbackCheck registry key


Issues: 1
I was working on a server and we were trying to access the local SharePoint site http://127.0.0.1 or http://NameofLocalServer/pages/default.aspx and I was constantly prompted for the username and password. In SharePoint 2007/2010, it can really annoy you by not accepting your username password credentials in the popup window.
Issues: 2
You receive error 401.1 when browsing a local IIS with Windows Authentication
This usually happens when you try browsing your ADFS from within the same machine where ADFS is running. This is not related to ADFS, but it's an issue with Windows Integrated Authentication in IIS in general.
To fix this you have to set a registry key on the ADFS machine.
To set the DisableLoopbackCheck registry key yourself, follow these steps:
1.      Click Start, click Run, type regedit, and then click OK.
2.      In Registry Editor, locate and then click the following registry key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
3.      Right-click Lsa, point to New, and then click DWORD Value.
4.      Type DisableLoopbackCheck, and then press ENTER.
5.      Right-click DisableLoopbackCheck, and then click Modify.
6.      In the Value data box, type 1, and then click OK.
7.      Quit Registry Editor, and then restart your computer.


Here is a PowerShell one-liner to change that key:

Set-ItemProperty -path "HKLM:\SYSTEM\CurrentControlSet\Control\Lsa" -name "DisableLoopbackCheck" -value 1 -Type DWORD

Reference


Friday, May 17, 2013

List All SharePoint 2010 PowerShell Commands


Use this PowerShell command to output a list of all cmdlets that are found within the SharePoint 2010 namespace:


PS C:\> Get-Command -PSSnapin "Microsoft.SharePoint.PowerShell" | select name, definition | format-list > C:\SP2010_PowerShell_Commands.txt

Get-Command –PSSnapin “Microsoft.SharePoint.PowerShell” | select name, definition | format-list > C:\SP2010_PowerShell_Commands.txt

How to get a list of all Managed service accounts on a SharePoint 2010


We can use the below Powershell cmd to get the all Managed service accounts on a SharePoint 2010

PS C:\> Get-SPManagedAccount





But we have some issues like above and PowerShell truncates table by default.
Here are the results of that command, showing a table with column names that span multiple lines and rows with data that is not useful:

If you try to solve this problem by looking at the help for Format-Table, you may come across the AutoSize parameter.  The AutoSize parameter allows you to tell PowerShell that you want the formatter to automatically size the table columns, showing as much data as possible.  Here is what happens if you add the AutoSize parameter to the same command you just ran:

PS C:\> Get-SPManagedAccount | Format-Table -Property * -AutoSize





This is on the right track for what you are after, but notice the warning text that is output at the top of the resulting table.  It indicates that 10 columns do not fit into the display and were removed.  If you pipe the results of this command to Out-File, PowerShell will simply pass what you see on the screen to the file you are writing to, which is not sufficient for your needs.


Solution: 

Using Parameters for Format-Table like below

PS C:\> Get-SPManagedAccount | Format-Table -Property UserName
,PasswordExpiration, AutomaticChange –AutoSize

Using Out-String and width if you have many parameters to pass

PS C:\Users\sg-tst-spsql> Get-SPManagedAccount | Format-Table -Property *
 -AutoSize | Out-String -Width 4096




The above command that might not look very useful either, but look what happens when you take this one step further and pass the results to Out-File.  Here is the command to do this:
3. Using Out File

Get-SPManagedAccount 
| Format-Table -Property * -AutoSize | Out-String -Width 4096 
| Out-File C:\ServiceAccount.txt





Opening the resulting ServiceAccount.txt file shows the following contents:


Note: In your notepad, Go to Format and Uncheck the Word Wrap if its checked to get the above result.

Reference: