Friday, June 28, 2013

How to bypass Edit Properties Page or Skip EditForm.aspx Page while uploading documents in a document library

How to bypass Edit Properties Page while uploading documents in a document library(or)
Skip EditForm.aspx while uploading documents to document library in SharePoint 2010.

1.       Append this to the end of the URL for .aspx URL:   &ToolPaneView=2   and press Enter 

YourSiteName – Name of your Site DNS Name or Server Name
YourListName – Name of list or document library Name
YourFormName – Name of the form (page) name

2.  Click Add a Web Part and add a Content Editor Web Part

3.  Move the Content Editor Web Part below the list web part
Edit the web part and click the Source Editor button

Add the following...

<script type="text/javascript">
function GetQueryStringArgs()
{
    //fetch querystring and remove first ?
    var qs=(location.search.length>0?location.search.substring(1):"");
    //create an object for saving data
    var args={};
    var items=qs.split("&");
    var item=null,
        name=null,
        value=null;
    //add to args object one by one
    for(var i=0;i<items.length;i++)
   {
        item=items[i].split("=");
        name=decodeURIComponent(item [0]);
        value=decodeURIComponent(item[1]);
        args[name]=value ;
     }
        return args ;
    }
var args=GetQueryStringArgs();
var urlReferrer=document.referrer.toString ();
if(urlReferrer.indexOf("Upload")!=-1)
{
    window.frameElement.commitPopup();
}
</script>

Reference:

Monday, June 24, 2013

Programmatically delete all sub sites in a site collection(Sharepoint)


I have found one of the very useful code below to delete all sub sites in a site collection.


using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Text;  
using Microsoft.SharePoint;  
using Microsoft.SharePoint.Security;  
 
 
namespace SiteDeletion  
{  
    class Program  
    {  
        static void Main(string[] args)  
        {  
            Console.WriteLine("Executing program");  
 
            //Target site to delete sub sites from  
            string siteURL = "http://YourSiteURL/";  
 
            SPSecurity.RunWithElevatedPrivileges(delegate()  
            {  
                Console.WriteLine("Opening site");  
                using (SPSite oSite = new SPSite(siteURL))  
                {  
                    Console.WriteLine("Opening web");  
                    using (SPWeb osubWeb = oSite.OpenWeb())  
                    {  
                        Console.WriteLine("Getting sub sites");  
                        SPWebCollection subSites = osubWeb.GetSubwebsForCurrentUser();  
                        Console.WriteLine("looping");  
                        foreach (SPWeb subWeb in subSites)  
                        {  
                            //If you need to keep sites of a particular name  
                            if (subWeb.Title.Contains("Template"))  
                            {  
                                Console.WriteLine("NOT deleteing site: " + subWeb.Title);  
                            }  
                            else 
                            {  
                                Console.WriteLine("DELETING: " + subWeb.Title);  
                                DeleteWeb(subWeb);  
                            }  
                        }  
                    }  
 
 
 
                }  
            });  
 
            //Console.ReadLine();  
        }  
 
        public static void DeleteWeb(SPWeb web)  
        {  
            SPWebCollection subwebSites = web.GetSubwebsForCurrentUser();  
 
            if (subwebSites.Count > 0)  
            {  
                foreach (SPWeb w in subwebSites)  
                {  
                    DeleteWeb(w);  
                }  
            }  
 
            web.Delete();  
            return;  
        }  
 
    }  
}

Reference

http://simplisticsharepoint.blogspot.sg/2013/03/programmatically-delete-all-sites-in.html 

Programmatically changing the logo to Sharepoint all sites and subsites

I have found one of the very useful code below to change logo to Sharepoint all sites and subsites
using Console application. Happy coding. Cheers.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
namespace UpdateLogo
{
    class Program
    {
        static void Main(string[] args)
        {
            string site;
            string siteLogo;
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                    Console.WriteLine("Enter the Site Logo URL:");
                    siteLogo = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                    siteLogo = args[1];
                }
                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;
                //Enumerate through each site
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    //Enumerate through each web for the site
                    foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                    {
                        //Update the logo for the current Web
                        tmpWeb.AllowUnsafeUpdates = true;
                        tmpWeb.SiteLogoUrl = siteLogo;
                        tmpWeb.Update();                                         
                        tmpWeb.AllowUnsafeUpdates = false;
                        //Log to a file, where the logo is applied!
                        StreamWriter SW;
                        SW = File.AppendText("C:\\LogoLog.txt");
                        SW.WriteLine(tmpWeb.Url);
                        SW.Close();
                        //Dispose of the Web Object
                        tmpWeb.Dispose();
                    }
                    //Dispose of the Site Object
                    tmpSite.Dispose();
                }
                //Dispose of the Root Site Object
                tmpRoot.Dispose();
                //Confirmation Message
                Console.WriteLine("The operation completed successfully");
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Logo Updater", ex.Message);
                //Failure Message
                Console.WriteLine("The operation failed");
            }
        }
    }
}

Programmatically applying themes to Sharepoint all sites and subsites


I have found one of the very useful code below to apply themes to Sharepoint all sites and subsites
using Console application. Enjoy coding. Cheers.


using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;
using System.IO;
namespace Theme_Update
{
    class Theme_Update
    {
        static void Main(string[] args)
        {
            string site;
            string siteTheme;
            try
            {
                if (args.Length == 0)
                {
                    Console.WriteLine("Enter the Web Application URL:");
                    site = Console.ReadLine();
                    Console.WriteLine("Enter the Site Theme:");
                    siteTheme = Console.ReadLine();
                }
                else
                {
                    site = args[0];
                    siteTheme = args[1];
                }
                SPSite tmpRoot = new SPSite(site);
                SPSiteCollection tmpRootColl = tmpRoot.WebApplication.Sites;
                //Enumerate through each site
                foreach (SPSite tmpSite in tmpRootColl)
                {
                    //Enumerate through each web for the site
                    foreach (SPWeb tmpWeb in tmpSite.AllWebs)
                    {
                            //Apply the default theme for the current Web
                            tmpWeb.AllowUnsafeUpdates = true;
                            tmpWeb.ApplyTheme("none");
                            tmpWeb.Update();
                            tmpWeb.ApplyTheme(siteTheme);
                            tmpWeb.Update();
                            tmpWeb.AllowUnsafeUpdates = false;

                        //Log to a file, where the theme is applied!
                            StreamWriter SW;
                            SW = File.AppendText("C:\\ThemeLog.txt");
                            SW.WriteLine(tmpWeb.Url);
                            SW.Close();

                            //Dispose of the Web Object
                            tmpWeb.Dispose();
                        }
                    //Dispose of the Site Object
                    tmpSite.Dispose();
                }
                //Dispose of the Root Site Object
                tmpRoot.Dispose();
                //Confirmation Message
                Console.WriteLine("The operation completed successfully");
            }
            catch (Exception ex)
            {
                System.Diagnostics.EventLog.WriteEntry("Theme Updater", ex.Message);
                //Failure Message
                Console.WriteLine("The operation failed");
            }
        }
    }
}

 

Create a Setup Project with desktop shortcut in a Visual studio 2008/2010/2012


 
Add a Setup Project to your Solution
·  1. Right click on your Solution and add a new project
·  2. Select Other Project Types >> Setup and Deployment >> Visual studio installer.
·  3. Add a name and Location to the project.
·  4. Click OK

Add item to Application Folder.
·  1. Right click on Application Folder>>ADD>>Project Output
·  2. Select the appropriate project
·  3. Select Primary Output on the selection area.
·  4. Click OK

Add item to User’s desktop Program Menu.
·  1. In the left pane of the Setup/File System window click on Application Folder.
·  2. Right click on the primary output/(active).
·  3. Select short cut to Primary output.
·  4. Drag the shortcut item to User’s desktop.
·  5. Repeat steps 1 to 3
·  6. Drag the shortcut item to User’s Program Menu.

Change the Desktop icon
·  1. Right click on the root folder (File system on Target machine).
        A drop down menu will popup.
·  2. Select custom folder on the bottom of the menu. and name as Icon.
·  3. Select an icon and copy that into the custom folder.
·  4. Open User's desk top folder under root and select the shortcut.
        Right click on the shortcut and go to properties window.
·  5. Go to properties Icon and select the icon on 'Icon' folder.
·  6. Select User's programme menu and repeat steps 4 and 5.

Build the Application and Install on a machine.

Reference

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