Share via


How to: Programmatically Restore Content

Applies to: SharePoint Foundation 2010

This topic explains how to create an application that restores a SharePoint Foundation content component from a backup. The topic assumes that you are familiar with Overview of Backing Up and Restoring Data in SharePoint Foundation and Programming with the SharePoint Foundation Backup/Restore Object Model.

To Restore a Content Component

  1. Add a reference to Microsoft.SharePoint to your Visual Studio project and add using statements for the Microsoft.SharePoint.Administration and Microsoft.SharePoint.Administration.Backup namespaces to you code file.

  2. Inside the Main method, create a SPRestoreSettings object by using the static GetRestoreSettings method. For the first parameter pass the path where the backup is stored. For the second parameter pass a string version of one of the values of SPRestoreMethodType.

    SPRestoreSettings settings = SPBackupRestoreSettings.GetRestoreSettings((@"\\Server\WSSBackups", "Overwrite");
    
    Dim settings As SPRestoreSettings = SPBackupRestoreSettings.GetRestoreSettings(("\\Server\WSSBackups", "Overwrite")
    
  3. Prompt the user to specify the content component that is to be restored and assign its name to the IndividualItem property. To see an itemization of the names of the components on your farm that were included in the last full backup and that can be the objects of restore operations, you can either run the command stsadm -o restore -showtree at the server command line. To specify a different full backup package, use the -backupid parameter. Alternatively, you can visit Operations > Perform a Restore in the Central Administration application. To specify the whole farm, use "Farm" as the name. (Setting the property to null also selects the whole farm for backup assuming that you use IndividualItem in all subsequent code to identify by name the component to be restored, as you should. For an example, see the use of the FindItems() method in step 9.)

    Console.Write("Enter name of component to restore (default is whole farm):");
    settings.IndividualItem = Console.ReadLine();
    
    Console.Write("Enter name of component to restore (default is whole farm):")
    settings.IndividualItem = Console.ReadLine()
    
  4. If you want to restore from a backup other than the most recent, identify the backup package by assigning its GUID to the BackupId property. A record of each backup operation for a particular backup location is stored in spbrtoc.xml in the root of the location. Each backup and restore operation is represented in the file by an <SPHistoryObject> element. If the operation is a backup, the <IsBackup> child of the <SPHistoryObject> element is "True". The <SPId> element of the <SPHistoryObject> element contains the GUID of the backup.

    Note

    To programmatically obtain the list of all backup and restore operations, use the GetHistory() method. This method returns an SPBackupRestoreHistoryList object that contains SPBackupRestoreHistoryObject objects. Each of the latter represents an operation and holds its GUID in the SelfId property.

    settings.BackupId = new Guid("GUID");
    
    settings.BackupId = New Guid("GUID")
    
  5. Optionally, set one or both of the IsVerbose and UpdateProgress properties. (For details about these properties, see the reference topics for them.)

    settings.IsVerbose = true;
    settings.UpdateProgress = 10;
    
    settings.IsVerbose = True
    settings.UpdateProgress = 10
    
  6. If necessary, set the FarmAdminLoginName and FarmAdminLoginPassword() properties.

    settings.FarmAdminLoginName = "Bob";
    settings.FarmAdminPassword = "7*j2U";
    
    settings.FarmAdminLoginName = "Bob"
    settings.FarmAdminPassword = "7*j2U"
    
  7. Create the restore operation with the CreateBackupRestore() method. (A history object for the operation is also created.)

    Guid restore = SPBackupRestoreConsole.CreateBackupRestore(settings);
    
    Dim restore As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
    
  8. If your UI has users type a component name instead of pick one from a list, you must make sure that the name entered matches exactly one component. Add the following line to your Main method.

    SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref restore);
    
    Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, restore)
    
  9. Add the following implementation of your EnsureUniqueValidComponentName method. Use the FindItems() method to retrieve a collection of content objects whose names match the user-entered name. If there is no match, prompt the user to try again. If there is more than one, prompt the user to be more specific. If the component name that the user entered is valid and not ambiguous, get a reference to the SPBackupRestoreObject object that represents the component that the user wants to restore.

    private static SPBackupRestoreObject EnsureUniqueValidComponentName(SPBackupRestoreSettings settings, ref Guid operationGUID)
    {
        SPBackupRestoreObjectCollection list = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem);
        SPBackupRestoreObject component = null;
    
        if (list.Count <= 0)
        {
            Console.WriteLine("There is no component with that name. Run again with a new name.");
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
        else if (list.Count > 1)  // The component name specified is ambiguous. Prompt user to be more specific.
        {
            Console.WriteLine("More than one component matches the name you entered.");
            Console.WriteLine("Run again with one of the following:");
            for (int i = 0; i < list.Count; i++)
            {
                Console.WriteLine("\t{0}", list[i].ToString());
            }
            Console.WriteLine("Press Enter to continue.");
            Console.ReadLine();
        }
        else
        {
            component = list[0];
        }
    
        return component;
    
    }
    
    Private Shared Function EnsureUniqueValidComponentName(ByVal settings As SPBackupRestoreSettings, ByRef operationGUID As Guid) As SPBackupRestoreObject
        Dim list As SPBackupRestoreObjectCollection = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem)
        Dim component As SPBackupRestoreObject = Nothing
    
        If list.Count <= 0 Then
            Console.WriteLine("There is no component with that name. Run again with a new name.")
            Console.WriteLine("Press Enter to continue.")
            Console.ReadLine()
        ElseIf list.Count > 1 Then ' The component name specified is ambiguous. Prompt user to be more specific.
            Console.WriteLine("More than one component matches the name you entered.")
            Console.WriteLine("Run again with one of the following:")
            For i As Integer = 0 To list.Count - 1
                Console.WriteLine(vbTab & "{0}", list(i).ToString())
            Next i
            Console.WriteLine("Press Enter to continue.")
            Console.ReadLine()
        Else
            component = list(0)
        End If
    
        Return component
    
    End Function
    
  10. In the Main method, create a conditional structure that will run only if your EnsureUniqueValidComponentName method has returned a valid node.

    if (node != null)
    {
        // TODO: Set the restore operation as the active operation
        // and run it.
    }
    
    If node IsNot Nothing Then
        ' TODO: Set the restore operation as the active operation
        ' and run it.
    End If
    
  11. Replace the "TODO" line in the previous step with the following code. This sets the operation to be the active operation with the SetActive() method and tests to verify that it succeeded. If it fails, which it will if another backup or restore operation is already underway, report an error to the UI of your application.

    if (SPBackupRestoreConsole.SetActive(restore) == true)
    {
        // TODO: Run the operation. See next step.
    }
    else
    {
        // Report through your UI that another backup
        // or restore operation is underway. 
        Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.");
    }
    
    If SPBackupRestoreConsole.SetActive(restore) = True Then
        ' TODO: Run the operation. See next step.
    Else
        ' Report through your UI that another backup
        ' or restore operation is underway. 
        Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.")
    End If
    
  12. In the code branch that runs if the SetActive() call succeeds, run the operation with the Run() method. Test that the operation succeeds. If it fails, report the operation's failure message to your UI. The following code replaces the "TODO" line in the previous step.

    if (SPBackupRestoreConsole.Run(restore, node) == false)
    {
        // Report "error" through your UI.
        String error = SPBackupRestoreConsole.Get(restore).FailureMessage;
        Console.WriteLine(error);
    }
    
    If SPBackupRestoreConsole.Run(restore, node) = False Then
        ' Report "error" through your UI.
        Dim [error] As String = SPBackupRestoreConsole.Get(restore).FailureMessage
        Console.WriteLine([error])
    End If
    
  13. Clean up the restore with the Remove() method. Add the following code just before the closing brace you inserted in step 10.

    // Clean up the operation.
    SPBackupRestoreConsole.Remove(restore);
    
    Console.WriteLine("Restore attempt complete. Press Enter to continue.");
    Console.ReadLine();
    
    ' Clean up the operation.
    SPBackupRestoreConsole.Remove(restore)
    
    Console.WriteLine("Restore attempt complete. Press Enter to continue.")
    Console.ReadLine()
    

Example

The following code shows how to program a restoration of a content component. Replace the placeholder \\Server\WSSBackups with the path of your backup location. The runtime will automatically find the most recent backup at that location.

using System;
using Microsoft.SharePoint.Administration;
using Microsoft.SharePoint.Administration.Backup;

namespace MyCompany.SharePoint.Administration.Backup
{
    class Restore
    {
        static void Main(string[] args)
        {
            // Create the restore settings.
            SPRestoreSettings settings = SPBackupRestoreSettings.GetRestoreSettings(@"\\Server\WSSBackups", "Overwrite");

            // Identify the content component to restore.
            Console.Write("Enter name of component to restore (default is whole farm):");
            settings.IndividualItem = Console.ReadLine();
            
            // Set optional operation parameters.
            settings.IsVerbose = true;
            settings.UpdateProgress = 10;
            
            // Create the restore operation and return its ID.
            Guid restore = SPBackupRestoreConsole.CreateBackupRestore(settings);

            SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref restore);

            if (node != null)
            {
                // Set the restore as the active job and run it.
                if (SPBackupRestoreConsole.SetActive(restore) == true)
                {
                    if (SPBackupRestoreConsole.Run(restore, node) == false)
                    {
                        // Report "error" through your UI.
                        String error = SPBackupRestoreConsole.Get(restore).FailureMessage;
                        Console.WriteLine(error);
                    }
                }
                else
                {
                    // Report through your UI that another backup
                    // or restore operation is underway. 
                    Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.");
                }

                // Clean up the operation.
                SPBackupRestoreConsole.Remove(restore);

                Console.WriteLine("Restore attempt complete. Press Enter to continue.");
                Console.ReadLine();
            }
        }// end Main

        private static SPBackupRestoreObject EnsureUniqueValidComponentName(SPBackupRestoreSettings settings, ref Guid operationGUID)
        {
            SPBackupRestoreObjectCollection list = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem);
            SPBackupRestoreObject component = null;

            if (list.Count <= 0)
            {
                Console.WriteLine("There is no component with that name. Run again with a new name.");
                Console.WriteLine("Press Enter to continue.");
                Console.ReadLine();
            }
            else if (list.Count > 1)  // The component name specified is ambiguous. Prompt user to be more specific.
            {
                Console.WriteLine("More than one component matches the name you entered.");
                Console.WriteLine("Run again with one of the following:");
                for (int i = 0; i < list.Count; i++)
                {
                    Console.WriteLine("\t{0}", list[i].ToString());
                }
                Console.WriteLine("Press Enter to continue.");
                Console.ReadLine();
            }
            else
            {
                component = list[0];
            }

            return component;

        }// end EnsureUniqueValidComponentName

    }// end Restore class
}// end namespace
Imports System
Imports Microsoft.SharePoint.Administration
Imports Microsoft.SharePoint.Administration.Backup

Namespace MyCompany.SharePoint.Administration.Backup
    Friend Class Restore
        Shared Sub Main(ByVal args() As String)
            ' Create the restore settings.
            Dim settings As SPRestoreSettings = SPBackupRestoreSettings.GetRestoreSettings("\\Server\WSSBackups", "Overwrite")

            ' Identify the content component to restore.
            Console.Write("Enter name of component to restore (default is whole farm):")
            settings.IndividualItem = Console.ReadLine()

            ' Set optional operation parameters.
            settings.IsVerbose = True
            settings.UpdateProgress = 10

            ' Create the restore operation and return its ID.
            Dim restore As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)

            Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, restore)

            If node IsNot Nothing Then
                ' Set the restore as the active job and run it.
                If SPBackupRestoreConsole.SetActive(restore) = True Then
                    If SPBackupRestoreConsole.Run(restore, node) = False Then
                        ' Report "error" through your UI.
                        Dim [error] As String = SPBackupRestoreConsole.Get(restore).FailureMessage
                        Console.WriteLine([error])
                    End If
                Else
                    ' Report through your UI that another backup
                    ' or restore operation is underway. 
                    Console.WriteLine("Another backup or restore operation is already underway. Try again when it ends.")
                End If

                ' Clean up the operation.
                SPBackupRestoreConsole.Remove(restore)

                Console.WriteLine("Restore attempt complete. Press Enter to continue.")
                Console.ReadLine()
            End If
        End Sub ' end Main

        Private Shared Function EnsureUniqueValidComponentName(ByVal settings As SPBackupRestoreSettings, ByRef operationGUID As Guid) As SPBackupRestoreObject
            Dim list As SPBackupRestoreObjectCollection = SPBackupRestoreConsole.FindItems(operationGUID, settings.IndividualItem)
            Dim component As SPBackupRestoreObject = Nothing

            If list.Count <= 0 Then
                Console.WriteLine("There is no component with that name. Run again with a new name.")
                Console.WriteLine("Press Enter to continue.")
                Console.ReadLine()
            ElseIf list.Count > 1 Then ' The component name specified is ambiguous. Prompt user to be more specific.
                Console.WriteLine("More than one component matches the name you entered.")
                Console.WriteLine("Run again with one of the following:")
                For i As Integer = 0 To list.Count - 1
                    Console.WriteLine(vbTab & "{0}", list(i).ToString())
                Next i
                Console.WriteLine("Press Enter to continue.")
                Console.ReadLine()
            Else
                component = list(0)
            End If

            Return component

        End Function ' end EnsureUniqueValidComponentName

    End Class ' end Restore class
End Namespace ' end namespace

See Also

Tasks

How to: Programmatically Back Up Content

How to: Programmatically Back Up and Restore a Single Site Collection

How to: Create a Content Class That Can Be Backed Up and Restored

How to: Extend the STSADM Utility

Reference

Microsoft.SharePoint.Administration.Backup

Backup

Restore

Concepts

Programming with the SharePoint Foundation Backup/Restore Object Model

Other Resources

Stsadm.exe command-line tool