Partager via


SqlCeReplication.BeginSynchronize Method (AsyncCallback, OnStartTableUpload, OnStartTableDownload, OnSynchronization, Object)

Démarre une opération de synchronisation de données asynchrones. À la fin de la synchronisation, les délégués AsyncCallback sont appelés. Au cours de la synchronisation, des rapports d'état de synchronisation sont envoyés aux délégués SyncStatusReport.

Espace de noms: System.Data.SqlServerCe
Assembly: System.Data.SqlServerCe (dans system.data.sqlserverce.dll)

Syntaxe

'Déclaration
Public Function BeginSynchronize ( _
    onSyncCompletion As AsyncCallback, _
    onStartTableUpload As OnStartTableUpload, _
    onStartTableDownload As OnStartTableDownload, _
    onSynchronization As OnSynchronization, _
    state As Object _
) As IAsyncResult
public IAsyncResult BeginSynchronize (
    AsyncCallback onSyncCompletion,
    OnStartTableUpload onStartTableUpload,
    OnStartTableDownload onStartTableDownload,
    OnSynchronization onSynchronization,
    Object state
)
public:
IAsyncResult^ BeginSynchronize (
    AsyncCallback^ onSyncCompletion, 
    OnStartTableUpload^ onStartTableUpload, 
    OnStartTableDownload^ onStartTableDownload, 
    OnSynchronization^ onSynchronization, 
    Object^ state
)
public IAsyncResult BeginSynchronize (
    AsyncCallback onSyncCompletion, 
    OnStartTableUpload onStartTableUpload, 
    OnStartTableDownload onStartTableDownload, 
    OnSynchronization onSynchronization, 
    Object state
)
public function BeginSynchronize (
    onSyncCompletion : AsyncCallback, 
    onStartTableUpload : OnStartTableUpload, 
    onStartTableDownload : OnStartTableDownload, 
    onSynchronization : OnSynchronization, 
    state : Object
) : IAsyncResult

Paramètres

  • onSyncCompletion
    Délégué AsyncCallback implémenté par l'appelant et appelé à la fin de la synchronisation.
  • onStartTableUpload
    Délégué défini par l'utilisateur de l'événement qui est déclenché au début de la sauvegarde des modifications de table sur le serveur.
  • onStartTableDownload
    Délégué défini par l'utilisateur de l'événement qui est déclenché au début du téléchargement des modifications de table à partir du serveur.
  • onSynchronization
    Délégué défini par l'utilisateur qui utilise les événements de synchronisation en cours qui sont signalés pendant le travail du réconciliateur.
  • state
    Objet défini par l'utilisateur qui est retourné par la propriété AsyncState.

Valeur de retour

Interface IAsyncResult pour l'opération asynchrone qui a été démarrée en appelant cette fonction. Vous pouvez utiliser cette interface pour tester l'achèvement, ou attendre que la synchronisation soit terminée.

Remarques

Pour plus d'informations sur la synchronisation de données asynchrones dans SQL Server Compact 3.5, consultez la rubrique « Asynchronous Data Synchronization » de la documentation en ligne de SQL Server Compact 3.5.

Exemple

L'exemple suivant montre comment configurer la réplication SQL Server Compact 3.5 pour effectuer une synchronisation de données asynchrones.

' Imports System;
' Imports System.Data;
' Imports System.IO;
' Imports System.Data.SqlServerCe;
' Imports System.Windows.Forms;

'/ <summary>
'/ Demonstrates the usage of asynchronous database synchronization
'/ </summary>
Public Class MyForm
    Inherits Form

    Private myUserInterfaceUpdateEvent As EventHandler
    Private tableName As String
    Private percentage As Integer
    Private eventStatus As SyncStatus
    Private repl As SqlCeReplication

    Friend Enum SyncStatus
        PercentComplete
        BeginUpload
        BeginDownload
        SyncComplete
    End Enum 'SyncStatus

    Public Sub New()
        ' InitializeComponent();
        Me.myUserInterfaceUpdateEvent = New EventHandler(AddressOf UserInterfaceUpdateEvent)

    End Sub 'New

    Private Sub UserInterfaceUpdateEvent(ByVal sender As Object, ByVal e As System.EventArgs)
        Select Case Me.eventStatus
            Case SyncStatus.BeginUpload
                'this.labelStatusValue.Text = "Began uploading table : " & tableName;

            Case SyncStatus.PercentComplete
                'this.labelStatusValue.Text = "Sync with SQL Server is " & percentage.ToString() & "% complete.";

            Case SyncStatus.BeginDownload
                'this.labelStatusValue.Text = "Began downloading table : " & tableName;

            Case SyncStatus.SyncComplete
                'this.labelStatusValue.Text = "Synchronization has completed successfully";
                'this.labelLastSyncValue.Text = GetLastSuccessfulSyncTime().ToString();
        End Select
    End Sub 'UserInterfaceUpdateEvent

    Public Sub SyncCompletedCallback(ByVal ar As IAsyncResult)
        Try
            Dim repl As SqlCeReplication = CType(ar.AsyncState, SqlCeReplication)

            repl.EndSynchronize(ar)
            repl.SaveProperties()

            Me.eventStatus = SyncStatus.SyncComplete
        Catch e As SqlCeException
            MessageBox.Show(e.Message)
        Finally
            ' NOTE: If you'd like to set Control properties from within this 
            ' method, you need to use Control.Invoke method in order to marshal
            ' the call to the UI thread; otherwise you might deadlock your 
            ' application; See Control.Invoke documentation for more information
            '
            Me.Invoke(Me.myUserInterfaceUpdateEvent)
        End Try

    End Sub 'SyncCompletedCallback

    Public Sub OnStartTableUploadCallback(ByVal ar As IAsyncResult, ByVal tableName As String)
        Me.tableName = tableName
        Me.eventStatus = SyncStatus.BeginUpload

        ' NOTE: If you'd like to set Control properties from within this 
        ' method, you need to use Control.Invoke method in order to marshal
        ' the call to the UI thread; otherwise you might deadlock your 
        ' application; See Control.Invoke documentation for more information
        '
        Me.Invoke(Me.myUserInterfaceUpdateEvent)

    End Sub 'OnStartTableUploadCallback

    Public Sub OnSynchronizationCallback(ByVal ar As IAsyncResult, ByVal percentComplete As Integer)
        Me.percentage = percentComplete
        Me.eventStatus = SyncStatus.PercentComplete

        ' NOTE: If you'd like to set Control properties from within this 
        ' method, you need to use Control.Invoke method in order to marshal
        ' the call to the UI thread; otherwise you might deadlock your 
        ' application; See Control.Invoke documentation for more information
        '
        Me.Invoke(Me.myUserInterfaceUpdateEvent)

    End Sub 'OnSynchronizationCallback

    Public Sub OnStartTableDownloadCallback(ByVal ar As IAsyncResult, ByVal tableName As String)
        Me.tableName = tableName
        Me.eventStatus = SyncStatus.BeginDownload

        ' NOTE: If you'd like to set Control properties from within this 
        ' method, you need to use Control.Invoke method in order to marshal
        ' the call to the UI thread; otherwise you might deadlock your 
        ' application; See Control.Invoke documentation for more information
        '
        Me.Invoke(Me.myUserInterfaceUpdateEvent)

    End Sub 'OnStartTableDownloadCallback

    Private Sub ButtonSynchronize_Click(ByVal sender As Object, ByVal e As System.EventArgs)
        Try
            Me.repl = New SqlCeReplication()
            repl.SubscriberConnectionString = "Data Source=Test.sdf"

            '
            'NOTE: when possible, prompt users to enter security 
            'credentials at runtime. If you store credentials in a file, 
            'you must secure the file to prevent unauthorized access.
            '
            If False = File.Exists("Test.sdf") Then
                repl.AddSubscription(AddOption.CreateDatabase)
                repl.PublisherSecurityMode = SecurityType.DBAuthentication
                repl.Publisher = "MyPublisher"
                repl.PublisherLogin = "PublisherLogin"
                repl.PublisherPassword = "<enterStrongPassword>"
                repl.PublisherDatabase = "AdventureWorksDW"
                repl.Publication = "AdventureWorksDW"
                repl.InternetUrl = "https://www.adventure-works.com/sqlmobile/sqlcesa35.dll"
                repl.InternetLogin = "InternetLogin"
                repl.InternetPassword = "<enterStrongPassword>"
                repl.Subscriber = "MySubscriber"
            Else
                repl.LoadProperties()
            End If

            Dim ar As IAsyncResult = repl.BeginSynchronize( _
                New AsyncCallback(AddressOf Me.SyncCompletedCallback), _
                New OnStartTableUpload(AddressOf Me.OnStartTableUploadCallback), _
                New OnStartTableDownload(AddressOf Me.OnStartTableDownloadCallback), _
                New OnSynchronization(AddressOf Me.OnSynchronizationCallback), repl)

        Catch ex As SqlCeException
            MessageBox.Show(ex.Message)
        End Try

    End Sub 'ButtonSynchronize_Click

    Public Function GetLastSuccessfulSyncTime() As DateTime
        Dim utcDateTime As DateTime
        Dim localDateTime As DateTime

        Dim conn As SqlCeConnection = Nothing
        Dim cmd As SqlCeCommand = Nothing

        Try
            conn = New SqlCeConnection("Data Source = Test.sdf")
            conn.Open()

            cmd = conn.CreateCommand()
            cmd.CommandText = "SELECT LastSuccessfulSync FROM __sysMergeSubscriptions " & _
                "WHERE Publication=@publication"

            cmd.Parameters.Add("@publication", SqlDbType.NVarChar, 4000)
            cmd.Parameters("@publication").Value = "AdventureWorksDW"

            utcDateTime = CType(cmd.ExecuteScalar(), DateTime)
            localDateTime = utcDateTime.ToLocalTime()

            Return localDateTime
        Finally
            conn.Close()
        End Try

    End Function 'GetLastSuccessfulSyncTime
End Class 'MyForm
// using System;
// using System.Data;
// using System.IO;
// using System.Data.SqlServerCe;
// using System.Windows.Forms;

/// <summary>
/// Demonstrates the usage of asynchronous database synchronization
/// </summary>
public class MyForm : Form
{
    private string tableName;
    private int percentage;
    private SyncStatus eventStatus;
    private SqlCeReplication repl;
    private EventHandler myUserInterfaceUpdateEvent;

    internal enum SyncStatus
    {
        PercentComplete,
        BeginUpload,
        BeginDownload,
        SyncComplete
    }

    public MyForm()
    {
        // InitializeComponent();
        this.myUserInterfaceUpdateEvent = new EventHandler(MyUserInterfaceUpdateEvent);
    }

    private void MyUserInterfaceUpdateEvent(object sender, System.EventArgs e)
    {
        switch (this.eventStatus)
        {
            case SyncStatus.BeginUpload:
                //this.labelStatusValue.Text = "Began uploading table : " + tableName;
                break;

            case SyncStatus.PercentComplete:
                //this.labelStatusValue.Text = "Sync with SQL Server is " + percentage.ToString() + "% complete.";
                break;

            case SyncStatus.BeginDownload:
                //this.labelStatusValue.Text = "Began downloading table : " + tableName;
                break;

            case SyncStatus.SyncComplete:
                //this.labelStatusValue.Text = "Synchronization has completed successfully";
                //this.labelLastSyncValue.Text = GetLastSuccessfulSyncTime().ToString();
                break;
        }
    }

    public void SyncCompletedCallback(IAsyncResult ar)
    {
        try
        {
            SqlCeReplication repl = (SqlCeReplication)ar.AsyncState;

            repl.EndSynchronize(ar);
            repl.SaveProperties();

            this.eventStatus = SyncStatus.SyncComplete;
        }
        catch (SqlCeException e)
        {
            MessageBox.Show(e.Message);
        }
        finally
        {
            // NOTE: If you'd like to set Control properties from within this 
            // method, you need to use Control.Invoke method in order to marshal
            // the call to the UI thread; otherwise you might deadlock your 
            // application; See Control.Invoke documentation for more information
            //
            this.Invoke(this.myUserInterfaceUpdateEvent);
        }
    }

    public void OnStartTableUploadCallback(IAsyncResult ar, string tableName)
    {
        this.tableName = tableName;
        this.eventStatus = SyncStatus.BeginUpload;

        // NOTE: If you'd like to set Control properties from within this 
        // method, you need to use Control.Invoke method in order to marshal
        // the call to the UI thread; otherwise you might deadlock your 
        // application; See Control.Invoke documentation for more information
        //
        this.Invoke(this.myUserInterfaceUpdateEvent);
    }

    public void OnSynchronizationCallback(IAsyncResult ar, int percentComplete)
    {
        this.percentage = percentComplete;
        this.eventStatus = SyncStatus.PercentComplete;

        // NOTE: If you'd like to set Control properties from within this 
        // method, you need to use Control.Invoke method in order to marshal
        // the call to the UI thread; otherwise you might deadlock your 
        // application; See Control.Invoke documentation for more information
        //
        this.Invoke(this.myUserInterfaceUpdateEvent);
    }

    public void OnStartTableDownloadCallback(IAsyncResult ar, string tableName)
    {
        this.tableName = tableName;
        this.eventStatus = SyncStatus.BeginDownload;

        // NOTE: If you'd like to set Control properties from within this 
        // method, you need to use Control.Invoke method in order to marshal
        // the call to the UI thread; otherwise you might deadlock your 
        // application; See Control.Invoke documentation for more information
        //
        this.Invoke(this.myUserInterfaceUpdateEvent);
    }

    private void ButtonSynchronize_Click(object sender, System.EventArgs e)
    {
        try
        {
            this.repl = new SqlCeReplication();
            repl.SubscriberConnectionString = "Data Source=Test.sdf";

            if (false == File.Exists("Test.sdf"))
            {
                //NOTE: when possible, prompt users to enter security 
                //credentials at runtime. If you store credentials in a file, 
                //you must secure the file to prevent unauthorized access.
                //
                repl.AddSubscription(AddOption.CreateDatabase);
                repl.PublisherSecurityMode = SecurityType.DBAuthentication;
                repl.Publisher = "MyPublisher";
                repl.PublisherLogin = "PublisherLogin";
                repl.PublisherPassword = "<enterStrongPassword>";
                repl.PublisherDatabase = "AdventureWorksDW";
                repl.Publication = "AdventureWorksDW";
                repl.InternetUrl = "https://www.adventure-works.com/sqlmobile/sqlcesa35.dll";
                repl.InternetLogin = "MyInternetLogin";
                repl.InternetPassword = "<enterStrongPassword>";
                repl.Subscriber = "MySubscriber";
            }
            else
            {
                repl.LoadProperties();
            }

            IAsyncResult ar = repl.BeginSynchronize(
                new AsyncCallback(this.SyncCompletedCallback),
                new OnStartTableUpload(this.OnStartTableUploadCallback),
                new OnStartTableDownload(this.OnStartTableDownloadCallback),
                new OnSynchronization(this.OnSynchronizationCallback), 
                repl);
        }
        catch (SqlCeException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public DateTime GetLastSuccessfulSyncTime()
    {
        DateTime utcDateTime;
        DateTime localDateTime;
        SqlCeConnection conn = null;
        SqlCeCommand cmd = null;

        try
        {
            conn = new SqlCeConnection("Data Source = Test.sdf");
            conn.Open();

            cmd = conn.CreateCommand();
            cmd.CommandText = "SELECT LastSuccessfulSync FROM __sysMergeSubscriptions " +
                "WHERE Publication=@publication";

            cmd.Parameters.Add("@publication", SqlDbType.NVarChar, 4000);
            cmd.Parameters["@publication"].Value = "AdventureWorksDW";

            utcDateTime = (DateTime)cmd.ExecuteScalar();
            localDateTime = utcDateTime.ToLocalTime();

            return localDateTime;
        }
        finally
        {
            conn.Close();
        }
    }
}

Sécurité des threads

Tout membre statique public (Partagé dans Microsoft Visual Basic) de ce type sont thread-safe. Tous les membres de l'instance ne sont pas garantis comme sûrs.

Plateformes

Plateformes de développement

Windows Vista, Windows Mobile 5.0, Windows XP Professional with Service Pack 2 (SP2), Windows Server 2003, Windows Mobile 2003 for Pocket PC, Windows CE 5.0
Informations sur la version
.NET Framework et NET Compact Framework
Pris en charge dans 3.5
.NET Framework
Pris en charge dans 3.0
.NET Compact Framework et .Net Framework
Pris en charge dans 2.0

Voir aussi

Référence

SqlCeReplication Class
SqlCeReplication Members
System.Data.SqlServerCe Namespace