Partager via


Procédure : Personnaliser le déploiement pour scénarios déconnectés

Dernière modification : mercredi 22 septembre 2010

S’applique à : SharePoint Server 2010

Le déploiement de contenu fonctionne correctement lorsqu’une bonne connexion entre la batterie de serveurs source et la batterie de serveurs de destination est toujours disponible. Toutefois, une connexion fiable, fonctionnelle entre une batterie de création source et une batterie de destination de production n’est pas toujours disponible. Par exemple, des barrières géographiques, des pare-feu qui empêchent l’accès ou des coupures réseau sont autant de situations dans lesquelles l’utilisation d’une connexion réseau pour le transport d’un package d’exportation vers une batterie de destination de production n’est pas fiable. Dans ces situations, Microsoft recommande de travailler avec le modèle objet Microsoft SharePoint Server 2010 et l’API de migration de contenu SharePoint Foundation pour effectuer par programme les étapes d’exportation et d’importation de la migration de contenu et trouver une autre façon de transporter le package d’exportation vers la batterie de destination de production et d’exécuter le code personnalisé d’importation.

Comme il est décrit dans Déploiement de contenu entre serveurs, chaque déploiement de contenu comprend trois étapes: : exportation, transport et importation. Dans ce scénario, le transport est géré manuellement, et pas par programme. Par exemple, vous pourriez transporter le package de contenu exporté sur des supports portables ou utiliser un client FTP pour transférer les données vers un partage de fichiers indépendant à partir duquel vous pouvez procéder à l'importation.

Exporter un package de contenu à l'aide de l'API de migration du contenu

  1. Appelez l'API de migration de contenu avec les options que vous souhaitez spécifier.

  2. Stockez un jeton de modification.

  3. L'application exécute l'exportation, recherche des exceptions et signale ces dernières le cas échéant. Si l'exécution aboutit, l'application crée le package exporté avec le nom fourni et le stocke à l'emplacement fourni.

Notes

Une fois l'exportation terminée et après que vous avez créé un package de contenu, vous pouvez transporter le package exporté en utilisant FTP, un support portable et ainsi de suite. Une fois que vous avez transporté les données dans un emplacement de fichier auquel le processus d'importation peut accéder, vous pouvez commencer l'importation.

Importer un package de contenu à l'aide de l'API de migration du contenu

  1. Localisez le fichier que vous avez créé à l'aide du modèle objet pendant l'exportation. Si vous utilisez l'exemple de code fourni, le nom de fichier est export.cmp.

  2. Exécutez le code d'importation. Le code d'importation effectue les opérations suivantes :

    1. Crée un objet SPImportSettings avec les propriétés définies dans le code.

    2. Crée un nouvel objet SPImport et gère les jetons de modification de pré-importation et de post-importation, la gestion des versions du contenu, les paramètres de cache et la planification pour le contenu nouvellement déployé.

    Notes

    Pour des raisons de performances, SharePoint Server 2010 n’appelle pas de récepteurs d’événements par défaut. Par défaut, les écouteurs ne se déclenchent pas lorsque le déploiement de contenu crée du contenu. Toutefois, si vous utilisez des applications tierces ou du code personnalisé qui requiert le déclenchement de récepteurs d’événements durant l’importation, vous pouvez affecter la valeur false à la propriété SuppressAfterEvents. Lorsque cet indicateur est défini, vous pouvez rencontrer des problèmes de performances significatifs, mais tout le contenu spécifié dans l’importation est reçu.

    Notes

    Vous appelez l'API de migration de contenu sur le serveur source et définissez des options spécifiques, telles que la propriété RetainObjectIdentity, à true.

Exemple

Pour vous aider à utiliser l’API de migration de contenu SharePoint Foundation avec la fonctionnalité de déploiement de contenu SharePoint Server 2010, cette rubrique comprend un exemple de code qui utilise l’API de migration de contenu avec le déploiement de contenu SharePoint Server 2010. L’exemple montre comment la fonctionnalité de déploiement de contenu interagit avec l’API de migration de contenu pour créer une exportation, les concepts et la syntaxe requis lors de l’utilisation de l’API de migration de contenu pour effectuer l’exportation, l’importation et le chemin d’accès, ainsi que la définition de tâche et les étapes d’exécution de déploiement de contenu SharePoint Server 2010.

L'exemple de code est divisé en deux applications plus petites : une application d'exportation et une application d'importation.

using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.SharePoint.Deployment;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Publishing;
using Microsoft.SharePoint.Publishing.Administration;

/* Note: Before running this sample code, or any custom deployment solution, disable auto-spawning for the Variations feature
 * on your source site if it is enabled.
 **/
namespace CustomDeployment
{
    class Program
    {
        private static SavedCacheSettings savedCacheSettings;
        private static string sourceUrl = "http://samplesource/";
        private static string destinationUrl = "http://sampledestination/";
        private static string destinationRootWebUrl;

        static void Main(string[] args)
        {
            // This region defines content deployment export settings,
            // runs the export, and catches an exceptions during export
            // and outputs them.
            #region Export

            try
            {
                SPExportSettings exportSettings = new SPExportSettings();
                // Turn on extra output for testing
                exportSettings.CommandLineVerbose = true; 
                // The name of the file targeted by the export
                exportSettings.BaseFileName = "export.cmp"; 
                // The directory on the file system in which
                // to put the exported package
                exportSettings.FileLocation = @"%temp%"; 
                // If the file exists, overwrite it
                exportSettings.OverwriteExistingDataFile = true;
                // Export all security settings; change this if needed
                exportSettings.IncludeSecurity = SPIncludeSecurity.All;
                // The URL of the site being exported
                exportSettings.SiteUrl = sourceUrl;
                // The last major and minor versions
                exportSettings.IncludeVersions = SPIncludeVersions.LastMajorAndMinor;
                // Compress the exported file
                exportSettings.FileCompression = true; 
                // Create a new export object with the correct settings
                SPExport export = new SPExport(exportSettings); 
                // Optionally add event handlers to the export
                // object for:
                    // Started
                    // ProgressUpdated
                    // Completed
                    // Canceled
                    // Error
                    // Compressing
                // Run the export
                   export.Run(); 
                   }
                // Catch any exceptions during export and output them
                   catch (Exception ex) 
                   {
                   Console.Error.Write(ex.ToString());
                   throw;
                }
            #endregion //Export

            // This region defines import settings, creates a new
            // SPImportObject with those settings, manages versioning
            // and caching, and applies appropriate conditions if the
            // object is a Web site or root Web site
            #region Import
            try
            {
                SPImportSettings importSettings = new SPImportSettings();
                // Turn on extra output for testing
                importSettings.CommandLineVerbose = true; 
                // IMPORTANT: retains object IDs
                importSettings.RetainObjectIdentity = true; 
                // The directory of the file being imported
                importSettings.FileLocation = @"%temp%"; 
                // The name of the file being imported
                importSettings.BaseFileName = "export.cmp";
                // The URL of the site into which content is being imported
                importSettings.SiteUrl = destinationUrl; 
                //Import all the security settings from the package
                importSettings.IncludeSecurity = SPIncludeSecurity.All;
                // Retain author name during import; change if needed
                importSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ImportAll;
                // Don't fire event receivers during import; 
                // change if needed
                importSettings.SuppressAfterEvents = true;
                // Add new versions when importing items that 
                // already exist
                importSettings.UpdateVersions = SPUpdateVersions.Append; 
                // Create a new import object with specified settings
                SPImport import = new SPImport(importSettings); 
                // Turn down caching during the import
                  SiteCacheSettingsWriter.UpdateCacheSettingsDuringImport(importSettings.SiteUrl, true); 
                // Save the cache settings to restore after 
                // the import finishes
                savedCacheSettings = SiteCacheSettingsWriter.SaveCacheSettingsBeforeImport(importSettings.SiteUrl);
                // Change tokens for pre-import and post-import
                SPChangeToken startChangeToken, endChangeToken; 
                using (SPSite destinationSite = new SPSite(importSettings.SiteUrl))
                {
                    // Get the change token from the destination site
                    startChangeToken = destinationSite.CurrentChangeToken; 
                    // Save the root Web URL for future use
                    destinationRootWebUrl = destinationSite.RootWeb.ServerRelativeUrl; 
                }

                import.ObjectImported += new EventHandler<SPObjectImportedEventArgs>(import_ObjectImported);
                // Optionally add event handlers to the 
                // import object for:
                    // Started
                    // ProgressUpdated
                    // Completed
                    // Cancelled
                    // Error
                    // Uncompressing

                // Run the import
                import.Run();

                using (SPSite destinationSite = new SPSite(importSettings.SiteUrl))
                {
                    // Get the change token from the
                    // destination site AFTER import
                    endChangeToken = destinationSite.CurrentChangeToken; 

                    // Enable scheduling of the items just deployed
                    ScheduledItem.EnableSchedulingOnDeployedItems(destinationSite, startChangeToken, endChangeToken, "Succeeded");
                }
            }
            // Catch any exceptions during import and output them
            catch (Exception ex) 
            {
                Console.Error.Write(ex.ToString());
                throw;
            }
            finally
            {
                // Update the cache settings because import is done
                SiteCacheSettingsWriter.UpdateCacheSettingsDuringImport(destinationUrl, false);
            }
            #endregion
        }

        private static void import_ObjectImported(object sender, SPObjectImportedEventArgs e)
        {
            // Is the imported object a Web site?
            if ((e != null) && (e.Type == SPDeploymentObjectType.Web))
            {
                // Is the imported object the root Web site?
                if (string.Compare(e.TargetUrl, destinationRootWebUrl, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // The root Web site is being imported, so restore
                    // the cache-related root Web site properties.
                    SiteCacheSettingsWriter.RestoreCacheSettingsOnImport(destinationUrl, savedCacheSettings);
                }
            }

            return;
        }
    }
}
Imports System
Imports System.Collections.Generic
Imports System.Text
Imports Microsoft.SharePoint.Deployment
Imports Microsoft.SharePoint
Imports Microsoft.SharePoint.Publishing
Imports Microsoft.SharePoint.Publishing.Administration

' Note: Before running this sample code, or any custom deployment solution, disable auto-spawning for the Variations feature
' * on your source site if it is enabled.
' *
Namespace CustomDeployment
    Friend Class Program
        Private Shared savedCacheSettings As SavedCacheSettings
        Private Shared sourceUrl As String = "http://samplesource/"
        Private Shared destinationUrl As String = "http://sampledestination/"
        Private Shared destinationRootWebUrl As String

        Shared Sub Main(ByVal args() As String)
            ' This region defines content deployment export settings,
            ' runs the export, and catches an exceptions during export
            ' and outputs them.
'            #Region "Export"

            Try
                Dim exportSettings As New SPExportSettings()
                ' Turn on extra output for testing
                exportSettings.CommandLineVerbose = True
                ' The name of the file targeted by the export
                exportSettings.BaseFileName = "export.cmp"
                ' The directory on the file system in which
                ' to put the exported package
                exportSettings.FileLocation = "%temp%"
                ' If the file exists, overwrite it
                exportSettings.OverwriteExistingDataFile = True
                ' Export all security settings; change this if needed
                exportSettings.IncludeSecurity = SPIncludeSecurity.All
                ' The URL of the site being exported
                exportSettings.SiteUrl = sourceUrl
                ' The last major and minor versions
                exportSettings.IncludeVersions = SPIncludeVersions.LastMajorAndMinor
                ' Compress the exported file
                exportSettings.FileCompression = True
                ' Create a new export object with the correct settings
                Dim export As New SPExport(exportSettings)
                ' Optionally add event handlers to the export
                ' object for:
                    ' Started
                    ' ProgressUpdated
                    ' Completed
                    ' Canceled
                    ' Error
                    ' Compressing
                ' Run the export
                   export.Run()
                ' Catch any exceptions during export and output them
                   Catch ex As Exception
                   Console.Error.Write(ex.ToString())
                   Throw
                   End Try
'            #End Region 'Export

            ' This region defines import settings, creates a new
            ' SPImportObject with those settings, manages versioning
            ' and caching, and applies appropriate conditions if the
            ' object is a Web site or root Web site
'            #Region "Import"
            Try
                Dim importSettings As New SPImportSettings()
                ' Turn on extra output for testing
                importSettings.CommandLineVerbose = True
                ' IMPORTANT: retains object IDs
                importSettings.RetainObjectIdentity = True
                ' The directory of the file being imported
                importSettings.FileLocation = "%temp%"
                ' The name of the file being imported
                importSettings.BaseFileName = "export.cmp"
                ' The URL of the site into which content is being imported
                importSettings.SiteUrl = destinationUrl
                'Import all the security settings from the package
                importSettings.IncludeSecurity = SPIncludeSecurity.All
                ' Retain author name during import; change if needed
                importSettings.UserInfoDateTime = SPImportUserInfoDateTimeOption.ImportAll
                ' Don't fire event receivers during import; 
                ' change if needed
                importSettings.SuppressAfterEvents = True
                ' Add new versions when importing items that 
                ' already exist
                importSettings.UpdateVersions = SPUpdateVersions.Append
                ' Create a new import object with specified settings
                Dim import As New SPImport(importSettings)
                ' Turn down caching during the import
                  SiteCacheSettingsWriter.UpdateCacheSettingsDuringImport(importSettings.SiteUrl, True)
                ' Save the cache settings to restore after 
                ' the import finishes
                savedCacheSettings = SiteCacheSettingsWriter.SaveCacheSettingsBeforeImport(importSettings.SiteUrl)
                ' Change tokens for pre-import and post-import
                Dim startChangeToken, endChangeToken As SPChangeToken
                Using destinationSite As New SPSite(importSettings.SiteUrl)
                    ' Get the change token from the destination site
                    startChangeToken = destinationSite.CurrentChangeToken
                    ' Save the root Web URL for future use
                    destinationRootWebUrl = destinationSite.RootWeb.ServerRelativeUrl
                End Using

                AddHandler import.ObjectImported, AddressOf import_ObjectImported
                ' Optionally add event handlers to the 
                ' import object for:
                    ' Started
                    ' ProgressUpdated
                    ' Completed
                    ' Cancelled
                    ' Error
                    ' Uncompressing

                ' Run the import
                import.Run()

                Using destinationSite As New SPSite(importSettings.SiteUrl)
                    ' Get the change token from the
                    ' destination site AFTER import
                    endChangeToken = destinationSite.CurrentChangeToken

                    ' Enable scheduling of the items just deployed
                    ScheduledItem.EnableSchedulingOnDeployedItems(destinationSite, startChangeToken, endChangeToken, "Succeeded")
                End Using
            ' Catch any exceptions during import and output them
            Catch ex As Exception
                Console.Error.Write(ex.ToString())
                Throw
            Finally
                ' Update the cache settings because import is done
                SiteCacheSettingsWriter.UpdateCacheSettingsDuringImport(destinationUrl, False)
            End Try
'            #End Region
        End Sub

        Private Shared Sub import_ObjectImported(ByVal sender As Object, ByVal e As SPObjectImportedEventArgs)
            ' Is the imported object a Web site?
            If (e IsNot Nothing) AndAlso (e.Type = SPDeploymentObjectType.Web) Then
                ' Is the imported object the root Web site?
                If String.Compare(e.TargetUrl, destinationRootWebUrl, StringComparison.OrdinalIgnoreCase) = 0 Then
                    ' The root Web site is being imported, so restore
                    ' the cache-related root Web site properties.
                    SiteCacheSettingsWriter.RestoreCacheSettingsOnImport(destinationUrl, savedCacheSettings)
                End If
            End If

            Return
        End Sub
    End Class
End Namespace

Voir aussi

Tâches

Procédure : Déployer du contenu entre des serveurs

Référence

Web

Concepts

Déploiement de contenu entre serveurs