Gewusst wie: Programmgesteuertes Sichern von Inhalten

Letzte Änderung: Donnerstag, 4. November 2010

Gilt für: SharePoint Foundation 2010

In diesem Thema wird erklärt, wie Sie eine Sicherung einer SharePoint Foundation-Inhaltskomponente programmieren. Dabei wird davon ausgegangen, dass Sie mit den Themen Übersicht über das Sichern und Wiederherstellen von Daten in SharePoint Foundation und Programmieren mit dem Sicherungs-/Wiederherstellungsobjektmodell von SharePoint Foundation vertraut sind.

So sichern Sie eine Inhaltskomponente

  1. Fügen Sie Ihrem Visual Studio-Projekt einen Verweis auf Microsoft.SharePoint hinzu, und fügen Sie Ihrer Codedatei using-Anweisungen für den Microsoft.SharePoint.Administration- und den Microsoft.SharePoint.Administration.Backup-Namespace hinzu.

  2. Legen Sie innerhalb der Main-Methode fest, dass der Benutzer zur Angabe des Speicherorts für die Sicherung aufgefordert wird.

    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()
    
  3. Erstellen Sie innerhalb der Main-Methode ein SPBackupSettings-Objekt, indem Sie die statische GetBackupSettings-Methode verwenden. Übergeben Sie für den ersten Parameter den Pfad, unter dem die Sicherung gespeichert werden soll. Übergeben Sie für den zweiten Parameter eine Zeichenfolgenversion einer der Werte von SPBackupMethodType.

    SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");
    
    Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")
    
  4. Fordern Sie den Benutzer auf, die zu sichernde Inhaltskomponente anzugeben, und weisen Sie deren Namen der IndividualItem-Eigenschaft zu. Zum Anzeigen einer Einzelauflistung der Namen der Komponenten in der Farm, die Objekte von Sicherungsvorgängen sein können, können Sie entweder in der Befehlszeile des Servers den Befehl stsadm -o backup -showtree ausführen oder zu Vorgänge > Sicherung ausführen in der Zentraladministration gehen. Wenn Sie die gesamte Farm angeben möchten, verwenden Sie "Farm" als Namen. (Wenn Sie die Eigenschaft auf null festlegen, wird ebenfalls die gesamte Farm für die Sicherung ausgewählt, dann müssen Sie aber im gesamten nachfolgenden Code IndividualItem zur namentlichen Angabe der zu sichernden Komponente verwenden. Ein Beispiel finden Sie unter der Beschreibung der Verwendung der FindItems()-Methode in Schritt 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()
    
  5. Legen Sie optional eine oder mehrere der folgenden Eigenschaften fest: IsVerbose, UpdateProgress und BackupTheads(). (Einzelheiten zu diesen Eigenschaften finden Sie in den einschlägigen Referenzthemen.)

    settings.IsVerbose = true;
    settings.UpdateProgress = 10;
    settings.BackupThreads = 2;
    
    settings.IsVerbose = True
    settings.UpdateProgress = 10
    settings.BackupThreads = 2
    
  6. Erstellen Sie den Sicherungsvorgang mit der CreateBackupRestore()-Methode. (Ein Verlaufsobjekt für den Vorgang wird ebenfalls erstellt. Weitere Informationen dazu finden Sie unter SPBackupRestoreHistoryObject und SPBackupRestoreHistoryList.)

    Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);
    
    Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
    
  7. Wenn die Benutzer auf der Benutzeroberfläche einen Komponentennamen eingeben müssen, anstatt ihn aus einer Liste auszuwählen, müssen Sie sicherstellen, dass der eingegebene Name exakt mit einer Komponente übereinstimmt. Fügen Sie der Main-Methode die folgende Zeile hinzu.

    SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);
    
    Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
    
  8. Fügen Sie die folgende Implementierung der EnsureUniqueValidComponentName-Methode hinzu. Rufen Sie mithilfe der FindItems()-Methode eine Auflistung von Inhaltsobjekten ab, deren Namen dem vom Benutzer eingegebenen Namen entsprechen können. Wird kein übereinstimmender Name gefunden, fordern Sie den Benutzer auf, den Namen erneut einzugeben. Werden mehrere Übereinstimmungen gefunden, fordern Sie den Benutzer auf, den Namen genauer anzugeben. Ist der vom Benutzer eingegebene Komponentenname gültig und eindeutig, rufen Sie einen Verweis auf das SPBackupRestoreObject-Objekt ab, das die Komponente darstellt, die der Benutzer wiederherstellen möchte.

    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
    
  9. Erstellen Sie in der Main-Methode ein Boolean-Flag, das meldet, ob ausreichend Speicherplatz für die Sicherung vorhanden ist, sowie eine bedingte Struktur, die nur ausgeführt wird, wenn die EnsureUniqueValidComponentName-Methode einen gültigen Knoten zurückgegeben hat.

    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
    
  10. Fügen Sie die folgende Implementierung der EnsureEnoughDiskSpace-Methode hinzu. Rufen Sie mithilfe der DiskSizeRequired()-Methode den benötigten Speicherplatz ab, und ermitteln Sie anhand der DiskSize()-Methode, wie viel freier Speicherplatz auf dem Zieldatenträger verfügbar ist.

    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
    
  11. Erstellen Sie in der Main-Methode eine bedingte Struktur, die nur ausgeführt wird, wenn die EnsureEnoughDiskSpace-Methode true zurückgibt.

    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
    
  12. Ersetzen Sie die "TODO"-Zeile im vorherigen Schritt durch den folgenden Code. Dadurch wird der Vorgang mit der SetActive()-Methode als aktiver Vorgang festgelegt und überprüft, ob er erfolgreich ausgeführt wurde. Tritt ein Fehler auf, was der Fall sein wird, wenn bereits ein anderer Sicherungs- oder Wiederherstellungsvorgang ausgeführt wird, legen Sie fest, dass der Fehler entsprechend auf der Benutzeroberfläche der Anwendung gemeldet wird.

    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
    
  13. Führen Sie in dem Codezweig, der bei erfolgreicher Ausführung des SetActive()-Aufrufs ausgeführt wird, den Vorgang mit der Run()-Methode aus. Testen Sie, ob der Vorgang erfolgreich ausgeführt wird. Falls ein Fehler auftritt, legen Sie fest, dass der Fehler entsprechend auf der Benutzeroberfläche gemeldet wird. Der folgende Code ersetzt die "TODO"-Zeile im vorherigen Schritt.

    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
    
  14. Bereinigen Sie die Wiederherstellung mithilfe der Remove()-Methode. Fügen Sie den folgenden Code direkt vor der schließenden Klammer ein, die Sie in Schritt 11 eingefügt haben.

    // 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()
    

Beispiel

Mit dem folgenden Code wird veranschaulicht, wie Sie eine Sicherung einer Inhaltskomponente programmieren.

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

Siehe auch

Aufgaben

Gewusst wie: Programmgesteuerte Sicherung und Wiederherstellung einer einzelnen Websitesammlung

Gewusst wie: Programmgesteuertes Wiederherstellen von Inhalten

Gewusst wie: Erstellen einer Inhaltsklasse, die gesichert und wiederhergestellt werden kann

Gewusst wie: Erweitern des Hilfsprogramms "stsadm"

Referenz

Microsoft.SharePoint.Administration.Backup

Backup

Restore

Konzepte

Programmieren mit dem Sicherungs-/Wiederherstellungsobjektmodell von SharePoint Foundation

Weitere Ressourcen

Befehlszeilentool "Stsadm.exe"