Saturday, October 27, 2012

Programmatically how to create backup and restore a sitecolletion in SharePoint 2010

In previous post, have seen how to take backup and restore a site collection using power shell commands.

Here will take back up and restore a site collection using SharePoint API.

There are two methods to create back up and restore a site collection.

1. Backup and
2. Restore.

Here i want to maintain one log file for tracing backup and restore creation details, so for that created the following method.

here we need to create two folder in D drive for saving backup file and log file.
D:\SiteBackupLog and D:\SiteBackUp


        public static void siteBackupLog(string message)
        {
            string PathName = "D:\\SiteBackupLog\\";
     PathName = PathName + "Backuplog-" + DateTime.Now.ToString("dd-MM-yyyy") + ".log";
            StreamWriter sw = new StreamWriter(PathName, true);
            sw.WriteLine(message + " - " + DateTime.Now);
            sw.Flush();
            sw.Close();
        }

Now , for taking backup of a site collection , used the following method.

        private void btnBackup_Click(object sender, EventArgs e)
        {
            string sourceSiteCollURL = "http://ukreddy:6969";
            string time = DateTime.Now.ToString("dd-MM-yyyy");
            string backupfilename = "D:\\SiteBackup\\SharePointSiteBackup_" + time + ".bak";
            siteBackup(sourceSiteCollURL, backupfilename);
        }
        public static void siteBackup(string siteURL, string fileName)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWebApplication webApplication = null;
                    webApplication = SPWebApplication.Lookup(new Uri(siteURL));
                    SPSiteCollection sitecols = webApplication.Sites;
                    string backupName = fileName;
                    sitecols.Backup(siteURL, backupName, true);//true is used for if already bak file created with the same name , it will overwrite
                });
                siteBackupLog("Site Collection backup created succuessfully");
            }
            catch (Exception ex)
            {
                siteBackupLog(ex.Message);
            }
        }  

in the above code we are try to create backup file and saving it in the specified location and also writing log also.

And the following code is used to restore site collection in new web application i.e http://ukreddy:2727 and restore it as root site collection.


        private void btnRestore_Click(object sender, EventArgs e)
        {
            string sitecollectionURL = "http://ukreddy:2727";
            string backupfilename = "D:\\SiteBackup\\SharePointSiteBackup_27-10-2012.bak";
            SiteRestore(sitecollectionURL, backupfilename);
        }

        private void SiteRestore(string siteURL, string fileName)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    SPWebApplication webApplication = null;
                    webApplication = SPWebApplication.Lookup(new Uri(siteURL));
                    SPSiteCollection sitecols = webApplication.Sites;
                sitecols.Restore("/", fileName, true);// overwrite sitecollection if already exists
                });
                siteBackupLog("Site collection restored successfully");
            }
            catch (Exception ex)
            {
               siteBackupLog(ex.Message);
            }
        }

here the screen shot of actual site collection i.e http://ukreddy:6969 and restored site collection i.e http://ukreddy:2727 respectively.






Thats it...


pls let me know if u have questions/suggestions.




Friday, October 19, 2012

How to move site collection from one web application to another web application using powershell


There are some situations where you want to move your site collection from one web application to another web application or where you want to change site collection port number or site collection path.

1. Take a backup of site collection from old webapplication
2. Restore backup in new web application.
3. Remove site collection from old web application
4. Delete backup file.

Here is my requirement, i have two web applications

1. http://ukreddy:2727 in this i have one root site collection
2. http://ukreddy:3636 This is my new web application 

now i want to move site collection from http://ukreddy:2727 web application to http://ukreddy:3636 web application or i want to change site collection port number.

In my site collection i have added some documents to document library, added events to calendar and add tasks to task list for testing.





1. Take backup of site collection 

Take backup of site from old web application(i.e http://ukreddy:2727).

Backup-SPSite -Identity http://ukreddy:2727 -Path "C:\\MoveSiteCollection.bak" 

or

Backup-SPSite -Identity http://ukreddy:2727 -Path "C:\\MoveSiteCollection.bak" -force

Note: -force is swicht parameter and it is used to create/overwrite if .bak file already exist.

This cmdlet will create .bak file in  "C:\\" path with the given name in cmdlet.



2. Restore backup file to new web application(i.e http://ukreddy:3636):

Here assuming that http://ukreddy:3636 web application created and root site collection not yet created.

Restore-SPSite -Identity http://ukreddy:3636 -Path "C:\\MoveSiteCollection.bak" 




or 

Restore-SPSite -Identity http://ukreddy:3636 -Path "C:\\MoveSiteCollection.bak"  -Confirm:$false



if you use -Confirm:$false parameter then it wont ask your confirmation for restore of site collection. Simply restore site collection.

This cmdlet will create root site collection in http://ukreddy:3636 as is it which in http://ukreddy:2727





3. Remove site collection 

Remove site collection from old web application.

Remove-SPSite -Identity http://ukreddy:2727 -Confirm:$false




4. Remove backup file

Remove the backup file from the path where we given path for backup.

Remove-Item "C:\\MoveSiteCollection.bak"




Here the code snippet copy the snippet and save it as .ps1 and run the .ps1 file in powershell....

###############################################################################

#Get the from Site Collection URL
$fromURL = "http://ukreddy:2727"
#Get the to Site Collection URL 
$toURL = "http://ukreddy:3636"

#Location to the backup file directory to store Site Collection backup files
$backupPath = "C:\\test.bak"

#Backing up Site Collection prior to moving
Write-Host "Backing Up Site Collection…."
Backup-SPSite $fromURL -Path C:\test.bak -force

#Removing Site Collection from old web application path
Write-Host "Removing Site Collection from old managed path location…"
Remove-SPSite -Identity $fromURL -Confirm:$false

#Restoring Site Collection to new Managed Path
Write-Host "Restoring Site Collection to new managed path location…"
Restore-SPSite -Identity $toURL -Path c:\test.bak -Confirm:$false

#Remove backup files from the backup dirctory
Remove-Item c:\test.bak

###############################################################################


Wednesday, October 17, 2012

How to create,get and delete managed path in SharePoint 2010 using PowerShell

In this article we will see 

1. How to get all managed paths 
2. How to create managed path
3. How to delete defined managed path

1.Get all managed paths in a web application:

a. Click On the Start menu, click All Programs.
b. Click Microsoft SharePoint 2010 Products.
c. Click SharePoint 2010 Management Shell.
Type the following command.

Get-SPManagedPath -WebApplication http://ukreddy:8998



and press enter.




2. Create managed path in a web application :

Now type the following command.

New-SPManagedPath "/newmanagedpath" -WebApplication http://ukreddy:8998



and press enter.



Now we can use get all managedpaths command to see all existing managed paths in a web application.

3. Delete managed path in a web application:

we can also delete managed path in a web application using the following command,

Remove-SPManagedPath -Identity "/newmanagedpath" -WebApplication http://ukreddy:8998



The above command will promt a message, asking end user confirmation to delete managed path.


if u dont want to prompt confirmation message use the following command.


Remove-SPManagedPath -Identity "/newmanagedpath" -WebApplication http://ukreddy:8998 -Confirm:$false




Monday, October 15, 2012

Programmatically How to create,get and delete managed path in SharePoint 2010


Introduction:

Managed Paths - We can specify which paths in the URL namespace of a Web application are used for site collections. We can also specify that one or more site collections exists at a specified path.

Types of Managed Paths:

Explicit inclusion.
Wildcard inclusion.

Explicit inclusion:

An explicitly named path is used for a single site collection.

Example: http://server/sites/team.

Wildcard inclusion:

A wildcard path of "sites" indicates that child URLs of the path are site collections. An wildcard named path is used for a multiple site collections.

Example: http://server/sites/

In this article we will be seeing the following

Programmatically create managed paths for a web application,
Programmatically get all the managed paths for a web application, and
Programmatically delete a managed path from a web application.

1. Creating a managed path:

string path = "NewManagedPath";
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://ukreddy:6969/"));
SPPrefixCollection prefixColl = webApp.Prefixes;
if (prefixColl.Contains(path) == false)
   {
      SPPrefix newPrefix = webApp.Prefixes.Add(path, SPPrefixType.ExplicitInclusion);
      MessageBox.Show(path + " is successfully added to the web application");
   }
else
  {
       MessageBox.Show(path + " already existe in the web application");
  }


the above code is used to create managed path in http://ukreddy:6969 web application.

the following screen shot show managed paths before executing the above code.
to get the list of managed path we use the step 2 code.



Once the above code is executed, it will create managed path in the web application.

the following screen show shows the message after successfuly creation of managed path.

Once the path is created once again retrieving list of managed path in the web application.


2. Get all managed paths:

SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://ukreddy:6969/"));
SPPrefixCollection prefixColl = webApp.Prefixes;
string str = "";
foreach (SPPrefix prefix in prefixColl)
  {
      str += "Managed Path :" + prefix.Name + ", Prefix Type :" + prefix.PrefixType + "\n";
  }
MessageBox.Show(str);

the following screen show showing list of managed path in the web application i.e http://ukreddy:6969.



3. Delete a managed path:

string path = "NewManagedPath";
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://ukreddy:6969/"));
SPPrefixCollection prefixColl = webApp.Prefixes;
if (prefixColl.Contains(path) == true)
  {
      webApp.Prefixes.Delete(path);
      MessageBox.Show(path + " is successfully deleted from the web application");
  }
else
  {
      MessageBox.Show(path + " managed path not exist in the web application");
  }

The above code is used to delete a managed path from the web application.

Once we sucessfully execute the above code it will display message,




after deletion of managed path , the following screen shows list of managed paths.



here the complete source code...

Reference to this link.

Error Type: This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products.

When i was creating SharePoint 2010 windows application on windows server 2008 R2 i got the following error ...

"This operation can be performed only on a computer that is joined to a server farm by users who have permissions in SQL Server to read from the configuration database. To connect this server to the server farm, use the SharePoint Products Configuration Wizard, located on the Start menu in Microsoft SharePoint 2010 Products."



The reason for the error is my windows application's platform target is (by default) set to "x86" in application properties window.


but SharePoint applications runs on x64. so , i changed platform target to x64 or u can set to any cpu.

Then my application runs without any error.


Wednesday, October 10, 2012

How to remove web application using PowerShell 2010


Method 1:

Remove-SPWebApplication -Identity http://ukreddy:6789

This cmdlet will ask for user's confirmation.


Remove-SPWebApplication -Identity http://ukreddy:6789 -Confirm:$false

This cmdlet won't ask for user's confirmation.



This cmdlet permanently removes the Web application at http://ukreddy:6789. This command does not remove the content databases or the IIS Web site.

Method 2:


Remove-SPWebApplication -Identity http://ukreddy:6789 -DeleteIISSite -RemoveContentDatabase


This cmdlet will ask for user's confirmation.


Remove-SPWebApplication -Identity http://ukreddy:6789  -Confirm:$false -DeleteIISSite -RemoveContentDatabase

This cmdlet won't ask for user's confirmation.




This cmdlet permanently removes the Web application at http://ukreddy:6789. This command also remove the content databases or the IIS Web site.


Tuesday, October 9, 2012

How to create page layout with code behind file in visual studio for SharePoint


In my previous post , have shown how to create page layout content type.

Now once again showing how to creating page layout and after creating pagelayout , adding  textbox,buttons and label to pagelayout and also add click events to the buttons, when the user clicks the button a messages will be display in labels.


1. Open Visual Studio 2010 -> Create new Project.

2. Select 'Content Type' Template and specify Project name, Click on 'OK'.

3. Then Specify URL for debugging and select 'Deploy as farm solution' then Click on 'Next'.

4. Select Parent Content Type for the custom page layout i.e 'Page' then Click on Finish.

5. It will automatically Open Elements.xml of Content Type, Change Name of content type if need and add FieldRef with the name of PublishingPageContent'.

6. Here will add New Module to the project.
right click on project--> add new item --> select Module template and give a name.



7.By default module template contain simple.txt file, you can rename simple.txt to pagename.aspx or delete simple.txt and right click on module--> add new item --> select Text file Template and name it as 'Pagename.aspx'.



8. Now open Elements.xml file which is in Module folder,
do the following changes.

a. Add URL to Module tag as Url='_catalogs/masterpage'. This is for deploy the page layout in _catalogs/masterpage path.

b. In File tag's Url attribute should contain .aspx only and add Type attribute as Type="GhostableInLibrary".

c. Now add 3 Property tag under File Tag, Named as ContentType,Title, and PublishingAssociatedCOntentType
<Property Name="ContentType" 
Value="$Resources:cmscore,contenttype_pagelayout_name;"/>
(Here No need to change this tag, simple copy and paste.)
<Property Name="Title" Value="Page Layout Title"/> here change value attribute value.
<Property Name="PublishingAssociatedContentType" Value=";#<Name of the ContentType which is in Elements.xml which is in ContentType folder>;#<ID of ContentType which is in Elememnts.xml of Content Type folder> "/>



9. A really cool capability of page layouts is that you can code them just like any ASP.NET page, including server-side code.  In the same folder as your .ASPX (in the Module folder), add a new class.

Right Click on PageLayout Module folder --> add --> Class.

10. Give proper class name and click on 'OK'.

11. Now add two references to the project
a. System.Web
b. Microsoft.SharePoint.Publishing

12. Add 'Using System.web.UI.WebControls;' namespace.

13. Inherit 'Microsoft.SharePoint.Publishing.PublishingLayoutPage'.

14. and Add public keyword before Class keyword.

15. In this example , am adding one Text box, two buttons and two labels.In first button click event will display current date and time in one label in second button click will display message "hello," along with textbox value in label two.

finally pagename.aspx.cs file will looks like this

16. Now open <pagename>.aspx page which is in module folder and add the following code.

Note: Textbox,button and label variable's name in .cs file and Textbox, button and label tag's ids should be same and OnClick Events containsFunction Names these functions are available in aspx.cs file.

$SharePoint.Project.AssemblyFullName$ that is used, The compiler will automatically replace this with the 4-part name of our assembly.
(The complete code for this solution is attached to the post.)

17. Now here going to add safe control.

Click on PageLayout Module and press F4 and Click on Safe Controls Collection, That will bring up a new window that makes it easy to define a new safecontrol entry.


18. Now Click on 'Add' and 'OK' buttons. No need to change any value.

19. The content type will be deployed to the site collection, while the page layout is deployed to the master page gallery in a single web.  Therefore, we need two separate features scoped differently.

Now right click on Features Folder, by default we have one feature,delete default feature and add new feature.

20. Rename newly add feature to 'Site' and Change Title,Description and set Scope to 'Site' and add ContentType to 'Items in the feature'. look at the screen shot.

21. Now add another feature and rename it 'web' and change Title, Description and set Scope to 'Web' and add Page layout module to 'Items in the feature'.



22. Right click on Package and select 'View Designer' then u can see two features which are avail in the package.



23. Now deploy the project.

24. After successfully deployment of the project, you can see the newly added page layout in "_Catalogs/master" path.

go to site --> Site Actions --> Site Setting--> Master pages and page layouts which is under Galleries.

Now u can see newly added pagelayout in list of page layouts.

25. Now we will try to create new page with newly added content type.

Go to create new page(i.e publishing page) specify page name, description and select newly add pagelayout then click on 'Create'.

26. Finaly the page looks like this.

27. Click on 'Get Time' Button it will display current date and time in label.

28. Now enter some text in text box and click on 'Click Me' button, it will display message as "Hello, <textbox text> !!!" in the second label.


Let me know if u have any queries or suggestions. catch me here
Here the complete source code...
Reference: MSDN Blog