Freigeben über


How to: Programmatically Back Up Content

Introduction

This post explains how to program a backup of a content component, including custom components, in a Windows SharePoint Services 3.0 farm. The post assumes that you are familiar with my previous posts Overview of Backing Up and Restoring Data in Windows SharePoint Services and Programming with the Windows SharePoint Services Backup/Restore Object Model.

Note: Unless specified otherwise, all classes referred to in this post are in the Microsoft.SharePoint.Administration.Backup namespace. Classes that you create are in bold pink.

Procedures

 

To Back Up a Content Component

1. Add a reference to Windows SharePoint Services 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, prompt the user to specify where the backup should be stored.

[C#]

Console.Write("Enter full UNC path to the directory where the backup will be stored:");

String backupLocation = Console.ReadLine();

3. Inside the Main method, create a SPBackupSettings object by using the static SPBackupRestoreSettings.GetBackupSettings method. For the first parameter pass the path where the backup should be stored. For the second parameter pass a string version of one of the values of SPBackupMethodType.

[C#]

SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");

4. Prompt the user to specify the content component to back up and assign its name to the SPBackupRestoreSettings.IndividualItem property. To see an itemization of the names of the components on your farm that can be the objects of backup operations, you can either run the command stsadm -o backup -showtree at the server command line or visit Operations > Perform a Backup 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 SPBackupRestoreSettings.IndividualItem in all subsequent code to identify by name the component to be backed up, as you should. For an example, see the use of the SPBackupRestoreConsole.FindItems method in step 8.)

[C#]

Console.Write("Enter name of component to backup (default is whole farm):");

settings.IndividualItem = Console.ReadLine();

5. Optionally, set one or more of the SPBackupRestoreSettings.IsVerbose, SPBackupRestoreSettings.UpdateProgress, and SPBackupSettings.BackupTheads properties. (For details about these properties, see the reference topics for them.)

[C#]

settings.IsVerbose = true;

settings.UpdateProgress = 10;

settings.BackupThreads = 2;

6. Create the backup operation with the SPBackupRestoreConsole.CreateBackupRestore method. (A history object for the operation is also created. For more information, see SPBackupRestoreHistoryObject and SPBackupRestoreHistoryList.)

[C#]

Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);

7. 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.

[C#]

SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);

8. Add the following declaration and implementation of your EnsureUniqueValidComponentName method. Use the SPBackupRestoreConsole.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.

[C#]

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;

 

}

9. In the Main method, create a Boolean flag that will signal whether there is sufficient space for the backup, and a conditional structure that will run only if your EnsureUniqueValidComponentName method has returned a valid node.

[C#]

Boolean targetHasEnoughSpace = false;

if (node != null)

{

    targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node);

}

10. Add the following declaration and implementation of your EnsureEnoughDiskSpace method. Use the SPBackupRestoreConsole.DiskSizeRequired method to obtain the amount of space that is needed, and the SPBackupRestoreConsole.DiskSize method to determine how much free space is available on the destination disk.

[C#]

private static Boolean EnsureEnoughDiskSpace(String location, Guid backup, SPBackupRestoreObject node)

{

    UInt64 backupSize = SPBackupRestoreConsole.DiskSizeRequired(backup, node);

    UInt64 diskFreeSize = 0;

    UInt64 diskSize = 0;

    Boolean hasEnoughSpace = true;

 

    try

    {

        SPBackupRestoreConsole.DiskSize(location, out diskFreeSize, out diskSize);

    }

    catch

    {

        diskFreeSize = diskSize = UInt64.MaxValue;

    }

 

    if (backupSize > diskFreeSize)

    {

        // Report through your UI that there is not enough disk space.

        Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, location, diskFreeSize);

        Console.WriteLine("Please try again with a different backup location or a smaller component.");

        hasEnoughSpace = false;

    }

    else if (backupSize == UInt64.MaxValue || diskFreeSize == 0)

  {

        // Report through your UI that it cannot be determined whether there is enough disk space.

        Console.WriteLine("Cannot determine if that location has enough disk space.");

        Console.WriteLine("Please try again with a different backup location or a smaller component.");

        hasEnoughSpace = false;

    }

    return hasEnoughSpace;

 

}

11. In the Main method, create a conditional structure that will run only if your EnsureEnoughDiskSpace returns true.

[C#]

if (targetHasEnoughSpace)

{

    // TODO: Set the backup operation as the active operation

    // and run it.

}

12. Replace the "TODO" line in the previous step with the following code. This sets the operation to be the active operation with the SPBackupRestoreConsole.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.

[C#]

if (SPBackupRestoreConsole.SetActive(backup) == 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.");

}

13. In the code branch that runs if the SPBackupRestoreConsole.SetActive call succeeds, run the operation with the SPBackupRestoreConsole.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.

[C#]

if (SPBackupRestoreConsole.Run(backup, node) == false)

{

    // Report "error" through your UI.

    String error = SPBackupRestoreConsole.Get(backup).FailureMessage;

    Console.WriteLine(error);

}

14. Clean up the restore with the SPBackupRestoreConsole.Remove method. Add the following code just before the closing brace you inserted in step 11.

[C#]

// Clean up the operation.

SPBackupRestoreConsole.Remove(backup);

 

Console.WriteLine("Backup attempt complete. Press Enter to continue.");

Console.ReadLine();

 

 

 

Example

The following code shows how to program a backup of a content component.

 

using System;

using Microsoft.SharePoint.Administration;

using Microsoft.SharePoint.Administration.Backup;

 

namespace MyCompany.SharePoint.Administration.Backup

{

    class Backup

    {

        static void Main(string[] args)

        {

            // Identify the location for the backup storage.

            Console.Write("Enter full UNC path to the directory where the backup will be stored:");

            String backupLocation = Console.ReadLine();

           

            // Create the backup settings.

            SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");

 

            // Identify the content component to backup.

            Console.Write("Enter name of component to backup (default is whole farm):");

            settings.IndividualItem = Console.ReadLine();

           

            // Set optional operation parameters.

           settings.IsVerbose = true;

            settings.UpdateProgress = 10;

            settings.BackupThreads = 10;

 

            // Create the backup operation and return its ID.

            Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);

 

            // Ensure that user has identified a valid and unique component.

            SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);

 

            // Ensure that there is enough space.

            Boolean targetHasEnoughSpace = false;

            if (node != null)

            {

                targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node);

            }

 

            // If there is enough space, attempt to run the backup.

            if (targetHasEnoughSpace)

            {

                // Set the backup as the active job and run it.

                if (SPBackupRestoreConsole.SetActive(backup) == true)

                {

                    if (SPBackupRestoreConsole.Run(backup, node) == false)

                    {

                        // Report "error" through your UI.

                        String error = SPBackupRestoreConsole.Get(backup).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(backup);

 

               Console.WriteLine("Backup 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

 

     private static Boolean EnsureEnoughDiskSpace(String location, Guid backup, SPBackupRestoreObject node)

        {

            UInt64 backupSize = SPBackupRestoreConsole.DiskSizeRequired(backup, node);

            UInt64 diskFreeSize = 0;

            UInt64 diskSize = 0;

            Boolean hasEnoughSpace = true;

 

            try

            {

                SPBackupRestoreConsole.DiskSize(location, out diskFreeSize, out diskSize);

            }

            catch

            {

                diskFreeSize = diskSize = UInt64.MaxValue;

            }

 

            if (backupSize > diskFreeSize)

            {

                // Report through your UI that there is not enough disk space.

                Console.WriteLine("{0} bytes of space is needed but the disk hosting {1} has only {2}.", backupSize, location, diskFreeSize);

                Console.WriteLine("Please try again with a different backup location or a smaller component.");

                hasEnoughSpace = false;

        }

            else if (backupSize == UInt64.MaxValue || diskFreeSize == 0)

            {

                // Report through your UI that it cannot be determined whether there is enough disk space.

                Console.WriteLine("Cannot determine if that location has enough disk space.");

                Console.WriteLine("Please try again with a different backup location or a smaller component.");

                hasEnoughSpace = false;

            }

            return hasEnoughSpace;

 

        }// end EnsureEnoughDiskSpace

 

    }// end Backup class

}// end namespace

See Also

Programming with the Windows SharePoint Services Backup/Restore Object Model

How to: Programmatically Restore Content

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

Comments

  • Anonymous
    February 07, 2008
    The comment has been removed
  • Anonymous
    February 07, 2008
    The comment has been removed