Partager via


Pocédure : sauvegarder du contenu par programme

Dernière modification : jeudi 4 novembre 2010

S’applique à : SharePoint Foundation 2010

Cette rubrique explique comment programmer une sauvegarde d'un composant de contenu SharePoint Foundation. Elle suppose que vous connaissez les notions présentées dans les articles Vue d’ensemble de la sauvegarde et restauration des données dans SharePoint Foundation et Programmation avec le modèle objet de sauvegarde/restauration de SharePoint Foundation.

Pour sauvegarder un composant de contenu

  1. Ajoutez une référence à Microsoft.SharePoint à votre projet Visual Studio. Ajoutez ensuite des instructions using pour les espaces de noms Microsoft.SharePoint.Administration et Microsoft.SharePoint.Administration.Backup à votre fichier de code.

  2. Dans la méthode Main, demandez à l'utilisateur de spécifier l'emplacement de stockage de la sauvegarde.

    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. Dans la méthode Main, créez un objet SPBackupSettings à l'aide de la méthode statique GetBackupSettings. Pour le premier paramètre, passez le chemin d'accès où la sauvegarde doit être stockée. Pour le second, passez une version de chaîne de l'une des valeurs de SPBackupMethodType.

    SPBackupSettings settings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full");
    
    Dim settings As SPBackupSettings = SPBackupRestoreSettings.GetBackupSettings(backupLocation, "Full")
    
  4. Demandez à l'utilisateur d'indiquer le composant de contenu à sauvegarder et affectez son nom à la propriété IndividualItem. Pour afficher une liste détaillée des noms des composants de votre batterie de serveurs qui peuvent être les objets des opérations de sauvegarde, exécutez la commande stsadm -o backup -showtree dans la ligne de commande du serveur ou consultez la page Opérations > Effectuer une sauvegarde dans l'application Administration centrale. Pour spécifier toute la batterie de serveurs, utilisez « Farm » en tant que nom. (Définir la propriété sur la valeur null permet de sélectionner également toute la batterie de serveurs pour la sauvegarde, à condition que vous utilisiez IndividualItem dans les lignes de code suivantes pour identifier le composant à sauvegarder par nom. Pour obtenir un exemple, reportez-vous à l'utilisation de la méthode FindItems() à l'étape 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. Vous pouvez éventuellement spécifier une ou plusieurs propriétés IsVerbose, UpdateProgress et BackupTheads(). (Pour plus d'informations sur ces propriétés, voir leur rubrique de référence respective.)

    settings.IsVerbose = true;
    settings.UpdateProgress = 10;
    settings.BackupThreads = 2;
    
    settings.IsVerbose = True
    settings.UpdateProgress = 10
    settings.BackupThreads = 2
    
  6. Créez l'opération de sauvegarde avec la méthode CreateBackupRestore(). (Un objet d'historique pour l'opération est également créé. Pour plus d'informations, voir SPBackupRestoreHistoryObject et SPBackupRestoreHistoryList.)

    Guid backup = SPBackupRestoreConsole.CreateBackupRestore(settings);
    
    Dim backup As Guid = SPBackupRestoreConsole.CreateBackupRestore(settings)
    
  7. Si votre interface utilisateur demande aux utilisateurs de taper un nom de composant et non de le sélectionner dans une liste, vous devez vous assurer que le nom entré correspond exactement à un composant. Ajoutez la ligne ci-après à votre méthode Main.

    SPBackupRestoreObject node = EnsureUniqueValidComponentName(settings, ref backup);
    
    Dim node As SPBackupRestoreObject = EnsureUniqueValidComponentName(settings, backup)
    
  8. Ajoutez l'implémentation suivante de votre méthode EnsureUniqueValidComponentName. Utilisez la méthode FindItems() pour récupérer une collection d'objets de contenu dont les noms correspondent à celui entré par l'utilisateur. S'il n'existe aucune correspondance, demandez à l'utilisateur de retaper un nom. S'il existe plusieurs correspondances, demandez à l'utilisateur d'être plus précis. Si le nom du composant qui a été entré par l'utilisateur est valide et non ambigu, obtenez une référence à l'objet SPBackupRestoreObject qui représente le composant que l'utilisateur souhaite restaurer.

    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. Dans la méthode Main, créez un indicateur Boolean, qui indiquera si l'espace disque est suffisant pour la sauvegarde, et une structure conditionnelle qui s'exécutera uniquement si votre méthode EnsureUniqueValidComponentName a renvoyé un nœud valide.

    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. Ajoutez l'implémentation suivante de votre méthode EnsureEnoughDiskSpace. Utilisez la méthode DiskSizeRequired() pour obtenir l'espace disque requis et la méthode DiskSize() pour déterminer l'espace disponible sur le disque de destination.

    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. Dans la méthode Main, créez une structure conditionnelle qui ne s'exécutera que si votre méthode EnsureEnoughDiskSpace renvoie la valeur 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
    
  12. Remplacez la ligne « TODO » de l'étape précédente par le code ci-après. Cela permet de définir l'opération comme étant l'opération active à l'aide de la méthode SetActive() et de vérifier le succès de l'opération. Si l'opération échoue, ce qui se produit lorsqu'une autre opération de restauration ou de sauvegarde est en cours, signalez une erreur dans l'interface utilisateur de votre application.

    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. Dans la branche de code qui s'exécute si l'appel de SetActive() réussit, exécutez l'opération avec la méthode Run(). Vérifiez la réussite de l'opération. Si l'opération échoue, affichez un message d'échec de l'opération dans votre interface utilisateur. Le code ci-après remplace la ligne « TODO » de l'étape précédente.

    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. Nettoyez la restauration à l'aide de la méthode Remove(). Ajoutez le code ci-après avant l'accolade fermante que vous avez inséré à l'étape 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()
    

Exemple

Le code ci-après montre comment programmer une sauvegarde d'un composant de contenu.

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

Voir aussi

Tâches

Procédure : sauvegarder et restaurer une seule collection de sites par programmation

Procédure : restaurer le contenu par programmation

Procédure : créer une classe de contenu qui peut être sauvegardée et restaurée

Procédure : étendre l'utilitaire STSADM

Référence

Microsoft.SharePoint.Administration.Backup

Backup

Restore

Concepts

Programmation avec le modèle objet de sauvegarde/restauration de SharePoint Foundation

Autres ressources

Outil en ligne de commande stsadm.exe