Программное резервное копирование контента
Дата последнего изменения: 4 ноября 2010 г.
Применимо к: SharePoint Foundation 2010
В этом разделе описывается процесс создания программы для резервного копирования компонента контента SharePoint Foundation. Информация данного раздела предполагает, что пользователь ознакомился с разделами Обзор резервного копирования и восстановления данных в SharePoint Foundation и Программирование с использованием объектной модели резервного копирования и восстановления SharePoint Foundation.
Резервное копирование компонента контента
В проект Visual Studio добавьте ссылку на Microsoft.SharePoint, а в файл кода добавьте операторы using для пространств имен Microsoft.SharePoint.Administration и Microsoft.SharePoint.Administration.Backup.
Внутри метода Main вставьте запрос пользователю для указания места хранения резервной копии.
Console.Write("Enter full UNC path to the directory where the backup will be stored:"); String backupLocation = Console.ReadLine();
Console.Write("Enter full UNC path to the directory where the backup will be stored:") Dim backupLocation As String = Console.ReadLine()
Внутри метода Main создайте объект SPBackupSettings с помощью статического метода GetBackupSettings. В качестве первого параметра передайте адрес, по которому будет храниться резервная копия, а в качестве второго — строковую версию одного из значений SPBackupMethodType.
SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");
Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")
Выведите пользователю запрос на указание копируемого компонента контента и присвойте его имя свойству IndividualItem. Чтобы получить подробную информацию об именах компонентов фермы, которые могут участвовать в резервном копировании, выполните команду stsadm -o backup -showtree в командной строке сервера или обратитесь к разделу Операции > Выполнить резервное копирование в приложении центра администрирования. Чтобы указать всю ферму, используйте "Farm" в качестве имени. (Установка свойства в значение null также выбирает всю ферму для резервного копирования, если далее в коде для идентификации копируемого компонента используется IndividualItem (что рекомендуется). Пример приведен при демонстрации метода FindItems() на этапе 8.)
Console.Write("Enter name of component to backup (default is whole farm):"); settings.IndividualItem = Console.ReadLine();
Console.Write("Enter name of component to backup (default is whole farm):") settings.IndividualItem = Console.ReadLine()
Дополнительно можно настроить одно или несколько свойств IsVerbose, UpdateProgress и BackupTheads() (дополнительные сведения об этих свойствах см. в соответствующих разделах справки).
settings.IsVerbose = true; settings.UpdateProgress = 10; settings.BackupThreads = 2;
settings.IsVerbose = True settings.UpdateProgress = 10 settings.BackupThreads = 2
Создайте операцию резервного копирования с помощью метода CreateBackupRestore(). (Для операции также создается объект истории. Дополнительные сведения см. в описании SPBackupRestoreHistoryObject и SPBackupRestoreHistoryList.)
Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);
Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
Если пользовательский интерфейс предполагает ручной ввод имени компонента, а не его выбор из списка, необходимо убедиться в том, что введенное имя относится только к одному компоненту. К методу Main необходимо добавить следующую строку.
SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);
Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
Добавьте следующую реализацию метода EnsureUniqueValidComponentName. Используйте метод FindItems() для получения коллекции объектов контента, имена которых совпадают с именем, введенным пользователем. Если совпадений нет, выведите пользователю запрос на повторный ввод. Если совпадений несколько, выведите запрос на уточнение выбора. Если введенное пользователем имя компонента действительно и однозначно, получите ссылку на объект SPBackupRestoreObject, представляющий компонент, который восстанавливается пользователем.
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
В методе Main создайте флаг Boolean, который будет сигнализировать о наличии достаточного дискового пространства для резервной копии, а также условную структуру, которая будет запущена только в том случае, если метод EnsureUniqueValidComponentName возвратил действительный узел.
Boolean targetHasEnoughSpace = false; if (node != null) { targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node); }
Dim targetHasEnoughSpace As Boolean = False If node IsNot Nothing Then targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node) End If
Добавьте следующую реализацию метода EnsureEnoughDiskSpace. Используйте метод DiskSizeRequired() для получения сведений о требуемом объеме пространства, а метод DiskSize() — для определения доступного пространства на диске назначения.
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; }
Private Shared Function EnsureEnoughDiskSpace(ByVal location As String, ByVal backup As Guid, ByVal node As SPBackupRestoreObject) As Boolean Dim backupSize As UInt64 = SPBackupRestoreConsole.DiskSizeRequired(backup, node) Dim diskFreeSize As UInt64 = 0 Dim diskSize As UInt64 = 0 Dim hasEnoughSpace As Boolean = True Try SPBackupRestoreConsole.DiskSize(location, diskFreeSize, diskSize) Catch diskSize = UInt64.MaxValue diskFreeSize = diskSize End Try If backupSize > diskFreeSize Then ' 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 ElseIf backupSize = UInt64.MaxValue OrElse diskFreeSize = 0 Then ' 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 End If Return hasEnoughSpace End Function
В методе Main создайте условную структуру, которая будет запускаться только в том случае, если метод EnsureEnoughDiskSpace вернет значение true.
if (targetHasEnoughSpace) { // TODO: Set the backup operation as the active operation // and run it. }
If targetHasEnoughSpace Then ' TODO: Set the backup operation as the active operation ' and run it. End If
Замените строку "TODO" в предыдущем шаге следующим кодом. Этот код делает операцию активной в методе SetActive() и выполняет проверку ее успешного выполнения. Если возникла ошибка (что может произойти, если уже выполняется другая операция резервного копирования или восстановления), то следует вывести ошибку в интерфейс приложения.
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."); }
If SPBackupRestoreConsole.SetActive(backup) = 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
В той ветви кода, которая выполняется при успешном выполнении вызова SetActive(), выполните операцию с помощью метода Run(). Проверьте успешность выполнения операции. Если возникла ошибка, выведите ошибку операции в пользовательский интерфейс. Следующий код заменяет строку "TODO" в предыдущем шаге.
if (SPBackupRestoreConsole.Run(backup, node) == false) { // Report "error" through your UI. String error = SPBackupRestoreConsole.Get(backup).FailureMessage; Console.WriteLine(error); }
If SPBackupRestoreConsole.Run(backup, node) = False Then ' Report "error" through your UI. Dim [error] As String = SPBackupRestoreConsole.Get(backup).FailureMessage Console.WriteLine([error]) End If
Выполните очистку операции восстановления с помощью метода Remove(). Добавьте следующий код перед закрывающей скобкой, вставленной на шаге 11.
// Clean up the operation. SPBackupRestoreConsole.Remove(backup); Console.WriteLine("Backup attempt complete. Press Enter to continue."); Console.ReadLine();
' Clean up the operation. SPBackupRestoreConsole.Remove(backup) Console.WriteLine("Backup attempt complete. Press Enter to continue.") Console.ReadLine()
Пример
Код ниже иллюстрирует способ программного резервного копирования компонента контента.
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
Imports System
Imports Microsoft.SharePoint.Administration
Imports Microsoft.SharePoint.Administration.Backup
Namespace MyCompany.SharePoint.Administration.Backup
Module Backup
Sub Main(ByVal args() As String)
' Identify the location for the backup storage.
Console.Write("Enter full UNC path to the directory where the backup will be stored:")
Dim backupLocation As String = Console.ReadLine()
' Create the backup settings.
Dim settings As SPBackupSettings = 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.
Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
' Ensure that user has identified a valid and unique component.
Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
' Ensure that there is enough space.
Dim targetHasEnoughSpace As Boolean = False
If node IsNot Nothing Then
targetHasEnoughSpace = EnsureEnoughDiskSpace(backupLocation, backup, node)
End If
' If there is enough space, attempt to run the backup.
If targetHasEnoughSpace Then
' Set the backup as the active job and run it.
If SPBackupRestoreConsole.SetActive(backup) = True Then
If SPBackupRestoreConsole.Run(backup, node) = False Then
' Report "error" through your UI.
Dim [error] As String = SPBackupRestoreConsole.Get(backup).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(backup)
Console.WriteLine("Backup attempt complete. Press Enter to continue.")
Console.ReadLine()
End If
End Sub ' end Main
Private 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
Private Function EnsureEnoughDiskSpace(ByVal location As String, ByVal backup As Guid, ByVal node As SPBackupRestoreObject) As Boolean
Dim backupSize As UInt64 = SPBackupRestoreConsole.DiskSizeRequired(backup, node)
Dim diskFreeSize As UInt64 = 0
Dim diskSize As UInt64 = 0
Dim hasEnoughSpace As Boolean = True
Try
SPBackupRestoreConsole.DiskSize(location, diskFreeSize, diskSize)
Catch
diskSize = UInt64.MaxValue
diskFreeSize = diskSize
End Try
If backupSize > diskFreeSize Then
' 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
ElseIf backupSize = UInt64.MaxValue OrElse diskFreeSize = 0 Then
' 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
End If
Return hasEnoughSpace
End Function ' end EnsureEnoughDiskSpace
End Module ' end Backup class
End Namespace ' end namespace
См. также
Задачи
Программное резервное копирование и восстановление одного семейства сайтов
Программное восстановление контента
Создание класса контента, который можно заархивировать и восстановить
Ссылка
Microsoft.SharePoint.Administration.Backup