Ejemplo n.º 1
0
        private void WebSyncOptions_Load(object sender, EventArgs e)
        {
            passwordTextBox.Text = string.Empty;

            try
            {
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();

                mergePullSub = new MergePullSubscription(subscriptionDatabase,
                                                         publisherServer, publicationDatabase, publicationName,
                                                         subscriberConn);

                mergePullSub.Load();

                if (mergePullSub.UseWebSynchronization)
                {
                    enableWebSyncChkBox.Checked = true;
                    useWebSync = true;
                }

                if (string.IsNullOrEmpty(mergePullSub.InternetUrl) == false)
                {
                    webSyncUrlTexBox.Text = mergePullSub.InternetUrl;
                }
                else
                {
                    webSyncUrlTexBox.Text = webSynchronizationUrl;
                }

                if (string.IsNullOrEmpty(mergePullSub.InternetLogin) == false)
                {
                    userNameTextBox.Text = mergePullSub.InternetLogin;
                }
                else
                {
                    if (Environment.UserDomainName.Length != 0)
                    {
                        userNameTextBox.Text = Environment.UserDomainName
                                               + @"\" + Environment.UserName;
                    }
                    else
                    {
                        userNameTextBox.Text = Environment.UserName;
                    }
                }

                if (mergePullSub.UseWebSynchronization == false)
                {
                    userNameTextBox.Enabled = false;
                    passwordTextBox.Enabled = false;
                }
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
                this.Close();
            }
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Check that the subscription exists and create it if needed.
        /// </summary>
        public void CheckSubscription()
        {
            try
            {
                // We need connections to the Publisher and Distributor.
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();
            }
            catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionCannotConnectLocal,
                    Properties.Resources.ExceptionSqlServerError,
                    ExceptionMessageBoxButtons.OK);
                emb.InnerException = ex;
                emb.Show(this);

                // Shutdown the application because we can't continue.
                Application.Exit();
            }

            // Create the subscription database using SMO if it does not exist.
            Server subServer = new Server(subscriberConn);

            // Instantiate a pull subscription object.
            mergePullSub = new MergePullSubscription();

            // Set the properties needed to create the subscription.
            mergePullSub.ConnectionContext = subscriberConn;
            mergePullSub.PublicationName   = publicationName;
            mergePullSub.PublisherName     = publisherServer;
            mergePullSub.PublicationDBName = publicationDatabase;
            mergePullSub.DatabaseName      = subscriptionDatabase;

            if (subServer.Databases.Contains(subscriptionDatabase))
            {
                // If the database exists, check for replication objects.
                if (mergePullSub.IsExistingObject)
                {
                    if (mergePullSub.UseWebSynchronization)
                    {
                        this.UseWebSynchronization = true;
                    }
                    this.Close();
                    return;
                }
            }

            CreateSubscription();
        }
Ejemplo n.º 3
0
        public void CreateSubscription()
        {
            // The publication must support anonymous Subscribers, pull
            // subscriptions, and Web synchronization.
            // Define the Publisher, publication, and databases.
            string publicationName = "HdHouse-Pub";
            string publisherName = PublisherInstance;
            string subscriberName = SubscriberInstance;
            string subscriptionDbName = "HdHouseReplica";
            string publicationDbName = "HdHouse";
            string hostname = "RD03";
            string webSyncUrl = "https://" + PublisherInstance + "/hdhouse-dbpub/replisapi.dll";

            //Create the Subscriber connection.
            ServerConnection conn = new ServerConnection(subscriberName);

            // Create the objects that we need.
            MergePullSubscription subscription;

            try
            {
                // Connect to the Subscriber.
                conn.Connect();

                // Define the pull subscription.
                subscription = new MergePullSubscription();
                subscription.ConnectionContext = conn;
                subscription.PublisherName = publisherName;
                subscription.PublicationName = publicationName;
                subscription.PublicationDBName = publicationDbName;
                subscription.DatabaseName = subscriptionDbName;
                subscription.HostName = hostname;

                // Specify an anonymous Subscriber type since we can't
                // register at the Publisher with a direct connection.
                subscription.SubscriberType = MergeSubscriberType.Anonymous;

                // Specify the Windows login credentials for the Merge Agent job.
                subscription.SynchronizationAgentProcessSecurity.Login = WinLogin;
                subscription.SynchronizationAgentProcessSecurity.Password = WinPassword;

                // Enable Web synchronization.
                subscription.UseWebSynchronization = true;
                subscription.InternetUrl = webSyncUrl;

                // Specify the same Windows credentials to use when connecting to the
                // Web server using HTTPS Basic Authentication.
                subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
                subscription.InternetLogin = WinLogin;
                subscription.InternetPassword = WinPassword;

                // Create the subscription database using SMO if it does not exist.
                ReplicationDatabase replDatabase;
                Database newDatabase;
                Server subServer = new Server(conn);

                replDatabase = new ReplicationDatabase(
                    subscription.DatabaseName, conn);
                newDatabase = subServer.Databases[replDatabase.Name];

                // Create the subscription database.
                if (subServer.Databases.Contains(replDatabase.Name) == false)
                {
                    //currentStatusTextBox.Text += statusCreateDatabase
                    //    + Environment.NewLine;
                    //Application.DoEvents();
                    newDatabase = new Database(subServer, replDatabase.Name);
                    newDatabase.Create();
                }

                replDatabase.Load();
                replDatabase.EnabledMergePublishing = false;
                replDatabase.CommitPropertyChanges();

                // Ensure that we create a job for this subscription.
                subscription.CreateSyncAgentByDefault = true;

                // Create the pull subscription at the Subscriber.
                subscription.Create();

                // 订阅创建成功,进行初始化同步

            }
            catch (Exception ex)
            {
                // Implement the appropriate error handling here.
                throw new ApplicationException(String.Format(
                    "The subscription to {0} could not be created.", publicationName), ex);
            }
            finally
            {
                conn.Disconnect();
            }
        }
Ejemplo n.º 4
0
        private void WebSyncOptions_Load(object sender, EventArgs e)
        {
            passwordTextBox.Text = string.Empty;

            try
            {
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();

                mergePullSub = new MergePullSubscription(subscriptionDatabase,
                    publisherServer, publicationDatabase, publicationName,
                    subscriberConn);

                mergePullSub.Load();

                if (mergePullSub.UseWebSynchronization)
                {
                    enableWebSyncChkBox.Checked = true;
                    useWebSync = true;
                }

                if (string.IsNullOrEmpty(mergePullSub.InternetUrl) == false)
                {
                    webSyncUrlTexBox.Text = mergePullSub.InternetUrl;
                }
                else
                {
                    webSyncUrlTexBox.Text = webSynchronizationUrl;
                }

                if (string.IsNullOrEmpty(mergePullSub.InternetLogin) == false)
                {
                    userNameTextBox.Text = mergePullSub.InternetLogin;
                }
                else
                {
                    if (Environment.UserDomainName.Length != 0)
                    {
                        userNameTextBox.Text = Environment.UserDomainName
                            + @"\" + Environment.UserName;
                    }
                    else
                    {
                        userNameTextBox.Text = Environment.UserName;
                    }
                }

                if (mergePullSub.UseWebSynchronization == false)
                {
                    userNameTextBox.Enabled = false;
                    passwordTextBox.Enabled = false;
                }

            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
                this.Close();
            }
        }
Ejemplo n.º 5
0
        private void CreateSubscription()
        {
            ReplicationDatabase replDatabase;
            Server   subServer;
            Database newDatabase;
            MergeSynchronizationAgent syncAgent;
            ReplicationServer         Subscriber;
            BusinessLogicHandler      insertUpdateHandler;
            Boolean isRegistered = false;

            this.Show();
            Application.DoEvents();

            // We need to collect valid Windows credentials to be able to
            //  store Web synchronization information in the database.
            LogonUser    logon    = new LogonUser();
            DialogResult dr       = logon.ShowDialog(this);
            string       username = logon.UserName;
            string       password = logon.Password;

            if (dr == DialogResult.OK)
            {
                //try
                //{
                //    // Create connections to the Publisher and Distributor.
                //    publisherConn = new ServerConnection(publisherServer);
                //    publisherConn.Connect();
                //}
                //catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
                //{
                //    ExceptionMessageBox emb = new ExceptionMessageBox(
                //        Properties.Resources.ExceptionCannotConnectPublisher,
                //        Properties.Resources.ExceptionSqlServerError,
                //        ExceptionMessageBoxButtons.OK);
                //    emb.InnerException = ex;
                //    emb.Show(this);

                //    // Shutdown the application because we can't continue.
                //    Application.Exit();
                //}

                try
                {
                    // Make the connection and get the subscription properties.
                    subscriberConn = new ServerConnection(subscriberServer);
                    subscriberConn.Connect();
                }
                catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
                {
                    ExceptionMessageBox emb = new ExceptionMessageBox(
                        Properties.Resources.ExceptionCannotConnectLocal,
                        Properties.Resources.ExceptionSqlServerError,
                        ExceptionMessageBoxButtons.OK);
                    emb.InnerException = ex;
                    emb.Show(this);

                    // Shutdown the application because we can't continue.
                    Application.Exit();
                }

                // Instantiate a pull subscription object.
                mergePullSub = new MergePullSubscription();

                // Set the required properties needed to create the subscription.
                mergePullSub.ConnectionContext = subscriberConn;
                mergePullSub.PublicationName   = publicationName;
                mergePullSub.PublisherName     = publisherServer;
                mergePullSub.PublicationDBName = publicationDatabase;
                mergePullSub.DatabaseName      = subscriptionDatabase;
                // Specify an anonymous Subscriber type since we can't
                // register at the Publisher with a direct connection.
                mergePullSub.SubscriberType = MergeSubscriberType.Anonymous;
                // Enable Web synchronization.
                mergePullSub.UseWebSynchronization = true;
                mergePullSub.InternetUrl           = Properties.Settings.Default.WebSynchronizationUrl;

                // Specify the same Windows credentials to use when connecting to the
                // Web server using HTTPS Basic Authentication.
                mergePullSub.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
                //mergePullSub.InternetLogin = username;
                //mergePullSub.InternetPassword = password;
                mergePullSub.InternetLogin    = internetLogin;
                mergePullSub.InternetPassword = internetPassword;

                // Create the subscription database using SMO if it does not exist.
                subServer = new Server(subscriberConn);

                replDatabase = new ReplicationDatabase(
                    mergePullSub.DatabaseName, subscriberConn);
                newDatabase = subServer.Databases[replDatabase.Name];

                // Create the subscription database.
                if (subServer.Databases.Contains(replDatabase.Name) == false)
                {
                    currentStatusTextBox.Text += statusCreateDatabase
                                                 + Environment.NewLine;
                    Application.DoEvents();
                    newDatabase = new Database(subServer, replDatabase.Name);
                    newDatabase.Create();
                }

                replDatabase.Load();
                replDatabase.EnabledMergePublishing = false;
                replDatabase.CommitPropertyChanges();

                // This is needed so that we can store Web synchronization
                // information in the MSsubscription_properties table and access this
                // information using the MergePullSubscription class. For a SQL Server 2005
                // Subscriber an agent job will be created. For a SQL Server 2005 Express Edition
                // Subscriber, only the meta data will be created because this edition does not
                // support SQL Server Agent.
                mergePullSub.CreateSyncAgentByDefault = true;

                // Set the process security which is required for the agent job.
                mergePullSub.SynchronizationAgentProcessSecurity.Login    = username;
                mergePullSub.SynchronizationAgentProcessSecurity.Password = password;

                // Set the HostName property.
                mergePullSub.HostName = subscriberHostName;

                // 调用 远程接口注册该订阅

                /*DBCenterWebService service = new DBCenterWebService();
                 * SubscriptionInfo info = new SubscriptionInfo();
                 * info.subscriberName = mergePullSub.Name;
                 * info.subscriptionDbName = mergePullSub.DatabaseName;
                 * service.CreateSubscriptionRequest(info);*/

                //if (!mergePub.SnapshotAvailable)
                //{
                //    throw new ApplicationException(
                //        Properties.Resources.ExceptionSalesDataNotAvailable
                //        + Environment.NewLine
                //        + Properties.Resources.ExceptionContactTechSupport);
                //}

                // Define the handler for inserts and updates at the Subscriber.
                Subscriber          = new ReplicationServer(subscriberConn);
                insertUpdateHandler = new BusinessLogicHandler();
                insertUpdateHandler.FriendlyName       = handlerFriendlyName;
                insertUpdateHandler.DotNetAssemblyName = "BusinessLogic.dll";
                insertUpdateHandler.DotNetClassName    = "Microsoft.Samples.SqlServer.CustomBusinessLogicHandler";
                insertUpdateHandler.IsDotNetAssembly   = true;

                try
                {
                    // Create the pull subscription.
                    currentStatusTextBox.Text += statusCreateSubscription
                                                 + Environment.NewLine;
                    Application.DoEvents();
                    mergePullSub.Create();

                    mergePullSub.Refresh();

                    // Get the Merge Agent for synchronous execution.
                    syncAgent = mergePullSub.SynchronizationAgent;

                    // We have to set these because of an RMO bug.
                    // Remove for RTM.
                    syncAgent.DistributorSecurityMode = SecurityMode.Integrated;
                    syncAgent.PublisherSecurityMode   = SecurityMode.Integrated;
                    syncAgent.SubscriberSecurityMode  = SecurityMode.Integrated;

                    // Generate a troubleshooting log file.
                    syncAgent.OutputVerboseLevel = outputLevel;
                    syncAgent.Output             = outputLogFile;

                    // Define the event handler.
                    syncAgent.Status
                        += new AgentCore.StatusEventHandler(Sync_Status);

                    currentStatusTextBox.Text += statusInitialize
                                                 + Environment.NewLine;
                    Application.DoEvents();

                    // Start the Merge Agent synchronously to apply the initial snapshot.
                    syncAgent.Synchronize();

                    // Make sure that the initialization was successful.
                    mergePullSub.Refresh();
                    if (mergePullSub.LastAgentStatus
                        != ReplicationStatus.Succeeded)
                    {
                        throw new SubscriptionInitializationException(
                                  Properties.Resources.ExceptionSubscriptionNotSync);
                    }
                    currentStatusTextBox.Text += statusSuccess.ToString()
                                                 + Environment.NewLine;
                    statusProgressBar.Value = 100;
                }

                catch (Exception ex)
                {
                    currentStatusTextBox.Text += statusFail.ToString()
                                                 + Environment.NewLine;
                    statusProgressBar.Value = 0;

                    // If an exception occurs, undo subscription registration at both
                    // the Publisher and Subscriber and remove the handler registration.
                    mergePullSub.Remove();

                    if (isRegistered)
                    {
                        Subscriber.UnregisterBusinessLogicHandler(insertUpdateHandler);
                        isRegistered = false;
                    }

                    throw new SubscriptionCreationException(
                              Properties.Resources.ExceptionSubscriptionNotCreated,
                              ex);
                }

                finally
                {
                    closeButton.Enabled = true;
                    subscriberConn.Disconnect();
                    //publisherConn.Disconnect();
                }
            }
            else
            {
                // If we can't create the subscription, close the application.
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionSubscriptionNotCreated);
                emb.Buttons = ExceptionMessageBoxButtons.RetryCancel;
                DialogResult drRetry = emb.Show(this);

                if (drRetry == DialogResult.Retry)
                {
                    this.CreateSubscription();
                }
                else
                {
                    Application.Exit();
                }
            }
        }
Ejemplo n.º 6
0
        public void ReinitializeSubscriptionWithUpload()
        {
            MergeSynchronizationAgent syncAgent;

            try
            {
                // Make the connection and get the subscription properties.
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();
            }
            catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionCannotConnectLocal,
                    Properties.Resources.ExceptionSqlServerError,
                    ExceptionMessageBoxButtons.OK);
                emb.InnerException = ex;
                emb.Show(this);

                // Shutdown the application because we can't continue.
                Application.Exit();
            }

            mergePullSub = new MergePullSubscription();

            // Set the properties needed to get the subscription.
            mergePullSub.ConnectionContext = subscriberConn;
            mergePullSub.PublicationName   = publicationName;
            mergePullSub.PublisherName     = publisherServer;
            mergePullSub.PublicationDBName = publicationDatabase;
            mergePullSub.DatabaseName      = subscriptionDatabase;

            // Load the properties of the existing subscription.
            if (!mergePullSub.LoadProperties())
            {
                throw new ApplicationException(
                          Properties.Resources.ExceptionProblemLocalData
                          + Environment.NewLine
                          + Properties.Resources.ExceptionContactTechSupport);
            }

            // Check to make sure that the Merge Agent isn't already running.
            if (mergePullSub.LastAgentStatus
                != (ReplicationStatus.Running | ReplicationStatus.Starting))
            {
                // Mark the subscription for reinitialization after uploading.
                mergePullSub.Reinitialize(true);

                // Get the Merge Agent for synchronous execution.
                syncAgent = mergePullSub.SynchronizationAgent;

                // Define the event handler.
                syncAgent.Status
                    += new AgentCore.StatusEventHandler(Sync_Status);

                syncAgent.Output             = outputLogFile;
                syncAgent.OutputVerboseLevel = outputLevel;

                // Start the Merge Agent Job.
                try
                {
                    currentStatusTextBox.Text = statusReinitialize
                                                + Environment.NewLine;
                    syncAgent.Synchronize();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(
                              Properties.Resources.ExceptionCouldNotReInit
                              + Environment.NewLine
                              + Properties.Resources.ExceptionContactTechSupport, ex);
                }
                finally
                {
                    statusProgressBar.Value = 100;
                    closeButton.Enabled     = true;
                    subscriberConn.Disconnect();
                }
            }
            else
            {
                currentStatusTextBox.Text
                    = Properties.Resources.StatusSubscriptionAlreadySync;
                closeButton.Enabled = true;
            }
        }
Ejemplo n.º 7
0
        public void SynchronizeSubscriptionUploadOnly()
        {
            MergeSynchronizationAgent syncAgent;

            try
            {
                // Make the connection and get the subscription properties.
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();
            }
            catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionCannotConnectLocal,
                    Properties.Resources.ExceptionSqlServerError,
                    ExceptionMessageBoxButtons.OK);
                emb.InnerException = ex;
                emb.Show(this);

                // Shutdown the application because we can't continue.
                Application.Exit();
            }

            mergePullSub = new MergePullSubscription();

            // Set the properties needed to get the subscription.
            mergePullSub.ConnectionContext = subscriberConn;
            mergePullSub.PublicationName   = publicationName;
            mergePullSub.PublisherName     = publisherServer;
            mergePullSub.PublicationDBName = publicationDatabase;
            mergePullSub.DatabaseName      = subscriptionDatabase;

            // Load the properties of the existing subscription.
            if (!mergePullSub.LoadProperties())
            {
                throw new ApplicationException(
                          Properties.Resources.ExceptionProblemLocalData
                          + Environment.NewLine
                          + Properties.Resources.ExceptionContactTechSupport);
            }

            // Get the Merge Agent for synchronous execution.
            syncAgent = mergePullSub.SynchronizationAgent;

            // Specify an upload-only exchange type.
            syncAgent.ExchangeType = MergeExchangeType.Upload;

            // Generate a troubleshooting log file.
            syncAgent.Output             = outputLogFile;
            syncAgent.OutputVerboseLevel = outputLevel;

            // Define the event handler.
            syncAgent.Status += new AgentCore.StatusEventHandler(Sync_Status);

            // Start the Merge Agent Job.
            try
            {
                syncAgent.Synchronize();
            }
            catch (Exception ex)
            {
                statusProgressBar.Value = 0;
                throw new ApplicationException(
                          Properties.Resources.ExceptionMergeAgentFailedSync,
                          ex);
            }
            finally
            {
                closeButton.Enabled = true;
                subscriberConn.Disconnect();
            }
        }
Ejemplo n.º 8
0
        private bool SynchronizeSubscription(SubscriberSubscription subscriptionparameters, string serverName)
        {
            bool             result = true;
            ServerConnection conn   = null;

            try
            {
                conn = new ServerConnection(serverName);
                // Connect to the Subscriber.
                conn.Connect();

                if (!conn.IsOpen)
                {
                    return(false);
                }

                // Define the pull subscription.
                MergePullSubscription subscription = new MergePullSubscription();
                subscription.ConnectionContext = conn;
                subscription.DatabaseName      = subscriptionparameters.SubscriptionDBName;
                subscription.PublisherName     = subscriptionparameters.PublisherName;
                subscription.PublicationDBName = subscriptionparameters.PublicationDBName;
                subscription.PublicationName   = subscriptionparameters.PublicationName;

                // If the pull subscription exists, then start the synchronization.
                if (subscription.LoadProperties())
                {
                    // Get the agent for the subscription.
                    MergeSynchronizationAgent agent = subscription.SynchronizationAgent;

                    agent.UseInteractiveResolver = true;
                    agent.InternetTimeout        = 600;
                    //if (File.Exists(@"c:\DotNet\tosi2010-09-01.zip"))
                    //{
                    //    DateTime dt = DateTime.Now;
                    //    agent.Output =
                    //        string.Format(@"c:\DotNet\out_{0}_{1}_{2}_{3}_{4}.txt", dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute);
                    //    agent.OutputVerboseLevel = 2;
                    //}

                    // Synchronously start the Merge Agent for the subscription.
                    agent.Status += OnAgentStatusEventHandler;
                    agent.Synchronize();

                    Info.ConflittiPub = agent.PublisherConflicts;
                    Info.ConflittiSub = agent.SubscriberConflicts;
                    Info.ModificheSub = agent.SubscriberChanges;
                    Info.ModifichePub = agent.PublisherChanges;

                    if (agent.PublisherConflicts > 0 || agent.SubscriberConflicts > 0)
                    {
                        Log("**************************************");
                        Log(string.Format("Conflitti: pub: {0}, sub: {1}",
                                          agent.PublisherConflicts,
                                          agent.SubscriberConflicts
                                          ));
                    }
                }
                else
                {
                    // Do something here if the pull subscription does not exist.
                    throw new ApplicationException(String.Format(
                                                       "La sottoscrizione '{0}' non esiste sul server {1}",
                                                       subscriptionparameters.PublicationName, conn.ServerInstance));
                }
            }
            catch (ComErrorException comErrorEx)
            {
                result = false;
                throw new ApplicationException(
                          "Impossibile connettersi al server di pubblicazione, " +
                          "verificare la connessione di rete e che la sottoscrizione " +
                          "sia stata creata correttamnte.", comErrorEx);
            }
            catch (Exception ex)
            {
                result = false;
                // Implement appropriate error handling here.
                throw new ApplicationException("The subscription could not be " +
                                               "synchronized. Verify that the subscription has " +
                                               "been defined correctly.", ex);
            }
            finally
            {
                if (conn != null)
                {
                    conn.Disconnect();
                }
            }

            Info.Result = result;
            return(result);
        }
Ejemplo n.º 9
0
        // This event handler initiates the synchronization
        private void syncBackgroundWorker_DoWork()
        {
            // Connect to the Subscriber and synchronize

            // Create a connection to the Subscriber.
            ServerConnection conn = new ServerConnection(subscriberName);

            // Merge pull subscription
            MergePullSubscription subscription;

            try
            {
                // Connect to the Subscriber.
                conn.Connect();

                // Define the pull subscription.
                subscription = new MergePullSubscription();
                subscription.ConnectionContext = conn;
                subscription.DatabaseName      = subscriptionDbName;
                subscription.PublisherName     = publisherName;
                subscription.PublicationDBName = publicationDbName;
                subscription.PublicationName   = publicationName;

                // If the pull subscription exists, then start the synchronization.
                if (subscription.LoadProperties())
                {
                    // Get the agent for the subscription.
                    agent = subscription.SynchronizationAgent;

                    // Set the required properties that could not be returned
                    // from the MSsubscription_properties table.
                    agent.PublisherSecurityMode   = SecurityMode.Integrated;
                    agent.DistributorSecurityMode = SecurityMode.Integrated;
                    agent.Distributor             = publisherName;

                    // Enable verbose merge agent output to file.
                    agent.OutputVerboseLevel = 4;
                    agent.Output             = "C:\\TEMP\\mergeagent.log";

                    // Handle the Status event
                    //agent.Status += new AgentCore.StatusEventHandler(agent_Status);

                    // Synchronously start the Merge Agent for the subscription.
                    agent.Synchronize();
                }
                else
                {
                    // Do something here if the pull subscription does not exist.
                    throw new ApplicationException(String.Format(
                                                       "A subscription to '{0}' does not exist on {1}",
                                                       publicationName, subscriberName));
                }
            }
            catch (Exception ex)
            {
                // Implement appropriate error handling here.
                throw new ApplicationException("The subscription could not be " +
                                               "synchronized. Verify that the subscription has " +
                                               "been defined correctly.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
        }
Ejemplo n.º 10
0
        public void CreateSubscription()
        {
            // The publication must support anonymous Subscribers, pull
            // subscriptions, and Web synchronization.
            // Define the Publisher, publication, and databases.
            string publicationName    = "HdHouse-Pub";
            string publisherName      = PublisherInstance;
            string subscriberName     = SubscriberInstance;
            string subscriptionDbName = "HdHouseReplica";
            string publicationDbName  = "HdHouse";
            string hostname           = "RD03";
            string webSyncUrl         = "https://" + PublisherInstance + "/hdhouse-dbpub/replisapi.dll";

            //Create the Subscriber connection.
            ServerConnection conn = new ServerConnection(subscriberName);

            // Create the objects that we need.
            MergePullSubscription subscription;

            try
            {
                // Connect to the Subscriber.
                conn.Connect();

                // Define the pull subscription.
                subscription = new MergePullSubscription();
                subscription.ConnectionContext = conn;
                subscription.PublisherName     = publisherName;
                subscription.PublicationName   = publicationName;
                subscription.PublicationDBName = publicationDbName;
                subscription.DatabaseName      = subscriptionDbName;
                subscription.HostName          = hostname;

                // Specify an anonymous Subscriber type since we can't
                // register at the Publisher with a direct connection.
                subscription.SubscriberType = MergeSubscriberType.Anonymous;

                // Specify the Windows login credentials for the Merge Agent job.
                subscription.SynchronizationAgentProcessSecurity.Login    = WinLogin;
                subscription.SynchronizationAgentProcessSecurity.Password = WinPassword;

                // Enable Web synchronization.
                subscription.UseWebSynchronization = true;
                subscription.InternetUrl           = webSyncUrl;

                // Specify the same Windows credentials to use when connecting to the
                // Web server using HTTPS Basic Authentication.
                subscription.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
                subscription.InternetLogin        = WinLogin;
                subscription.InternetPassword     = WinPassword;

                // Create the subscription database using SMO if it does not exist.
                ReplicationDatabase replDatabase;
                Database            newDatabase;
                Server subServer = new Server(conn);

                replDatabase = new ReplicationDatabase(
                    subscription.DatabaseName, conn);
                newDatabase = subServer.Databases[replDatabase.Name];

                // Create the subscription database.
                if (subServer.Databases.Contains(replDatabase.Name) == false)
                {
                    //currentStatusTextBox.Text += statusCreateDatabase
                    //    + Environment.NewLine;
                    //Application.DoEvents();
                    newDatabase = new Database(subServer, replDatabase.Name);
                    newDatabase.Create();
                }

                replDatabase.Load();
                replDatabase.EnabledMergePublishing = false;
                replDatabase.CommitPropertyChanges();


                // Ensure that we create a job for this subscription.
                subscription.CreateSyncAgentByDefault = true;

                // Create the pull subscription at the Subscriber.
                subscription.Create();

                // 订阅创建成功,进行初始化同步
            }
            catch (Exception ex)
            {
                // Implement the appropriate error handling here.
                throw new ApplicationException(String.Format(
                                                   "The subscription to {0} could not be created.", publicationName), ex);
            }
            finally
            {
                conn.Disconnect();
            }
        }
Ejemplo n.º 11
0
        private void CreateSubscription()
        {
            ReplicationDatabase replDatabase;
            Server subServer;
            Database newDatabase;
            MergeSynchronizationAgent syncAgent;
            ReplicationServer Subscriber;
            BusinessLogicHandler insertUpdateHandler;
            Boolean isRegistered = false;

            this.Show();
            Application.DoEvents();

            // We need to collect valid Windows credentials to be able to
               //  store Web synchronization information in the database.
            LogonUser logon = new LogonUser();
            DialogResult dr = logon.ShowDialog(this);
            string username = logon.UserName;
            string password = logon.Password;

            if (dr == DialogResult.OK)
            {
                //try
                //{
                //    // Create connections to the Publisher and Distributor.
                //    publisherConn = new ServerConnection(publisherServer);
                //    publisherConn.Connect();
                //}
                //catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
                //{
                //    ExceptionMessageBox emb = new ExceptionMessageBox(
                //        Properties.Resources.ExceptionCannotConnectPublisher,
                //        Properties.Resources.ExceptionSqlServerError,
                //        ExceptionMessageBoxButtons.OK);
                //    emb.InnerException = ex;
                //    emb.Show(this);

                //    // Shutdown the application because we can't continue.
                //    Application.Exit();
                //}

                try
                {
                    // Make the connection and get the subscription properties.
                    subscriberConn = new ServerConnection(subscriberServer);
                    subscriberConn.Connect();
                }
                catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
                {
                    ExceptionMessageBox emb = new ExceptionMessageBox(
                        Properties.Resources.ExceptionCannotConnectLocal,
                        Properties.Resources.ExceptionSqlServerError,
                        ExceptionMessageBoxButtons.OK);
                    emb.InnerException = ex;
                    emb.Show(this);

                    // Shutdown the application because we can't continue.
                    Application.Exit();
                }

                // Instantiate a pull subscription object.
                mergePullSub = new MergePullSubscription();

                // Set the required properties needed to create the subscription.
                mergePullSub.ConnectionContext = subscriberConn;
                mergePullSub.PublicationName = publicationName;
                mergePullSub.PublisherName = publisherServer;
                mergePullSub.PublicationDBName = publicationDatabase;
                mergePullSub.DatabaseName = subscriptionDatabase;
                // Specify an anonymous Subscriber type since we can't
                // register at the Publisher with a direct connection.
                mergePullSub.SubscriberType = MergeSubscriberType.Anonymous;
                // Enable Web synchronization.
                mergePullSub.UseWebSynchronization = true;
                mergePullSub.InternetUrl = Properties.Settings.Default.WebSynchronizationUrl;

                // Specify the same Windows credentials to use when connecting to the
                // Web server using HTTPS Basic Authentication.
                mergePullSub.InternetSecurityMode = AuthenticationMethod.BasicAuthentication;
                //mergePullSub.InternetLogin = username;
                //mergePullSub.InternetPassword = password;
                mergePullSub.InternetLogin = internetLogin;
                mergePullSub.InternetPassword = internetPassword;

                // Create the subscription database using SMO if it does not exist.
                subServer = new Server(subscriberConn);

                replDatabase = new ReplicationDatabase(
                    mergePullSub.DatabaseName, subscriberConn);
                newDatabase = subServer.Databases[replDatabase.Name];

                // Create the subscription database.
                if (subServer.Databases.Contains(replDatabase.Name) == false)
                {
                    currentStatusTextBox.Text += statusCreateDatabase
                        + Environment.NewLine;
                    Application.DoEvents();
                    newDatabase = new Database(subServer, replDatabase.Name);
                    newDatabase.Create();
                }

                replDatabase.Load();
                replDatabase.EnabledMergePublishing = false;
                replDatabase.CommitPropertyChanges();

                // This is needed so that we can store Web synchronization
                // information in the MSsubscription_properties table and access this
                // information using the MergePullSubscription class. For a SQL Server 2005
                // Subscriber an agent job will be created. For a SQL Server 2005 Express Edition
                // Subscriber, only the meta data will be created because this edition does not
                // support SQL Server Agent.
                mergePullSub.CreateSyncAgentByDefault = true;

                // Set the process security which is required for the agent job.
                mergePullSub.SynchronizationAgentProcessSecurity.Login = username;
                mergePullSub.SynchronizationAgentProcessSecurity.Password = password;

                // Set the HostName property.
                mergePullSub.HostName = subscriberHostName;

                // 调用 远程接口注册该订阅
                /*DBCenterWebService service = new DBCenterWebService();
                SubscriptionInfo info = new SubscriptionInfo();
                info.subscriberName = mergePullSub.Name;
                info.subscriptionDbName = mergePullSub.DatabaseName;
                service.CreateSubscriptionRequest(info);*/

                //if (!mergePub.SnapshotAvailable)
                //{
                //    throw new ApplicationException(
                //        Properties.Resources.ExceptionSalesDataNotAvailable
                //        + Environment.NewLine
                //        + Properties.Resources.ExceptionContactTechSupport);
                //}

                // Define the handler for inserts and updates at the Subscriber.
                Subscriber = new ReplicationServer(subscriberConn);
                insertUpdateHandler = new BusinessLogicHandler();
                insertUpdateHandler.FriendlyName = handlerFriendlyName;
                insertUpdateHandler.DotNetAssemblyName = "BusinessLogic.dll";
                insertUpdateHandler.DotNetClassName = "Microsoft.Samples.SqlServer.CustomBusinessLogicHandler";
                insertUpdateHandler.IsDotNetAssembly = true;

                try
                {
                    // Create the pull subscription.
                    currentStatusTextBox.Text += statusCreateSubscription
                        + Environment.NewLine;
                    Application.DoEvents();
                    mergePullSub.Create();

                    mergePullSub.Refresh();

                    // Get the Merge Agent for synchronous execution.
                    syncAgent = mergePullSub.SynchronizationAgent;

                    // We have to set these because of an RMO bug.
                    // Remove for RTM.
                    syncAgent.DistributorSecurityMode = SecurityMode.Integrated;
                    syncAgent.PublisherSecurityMode = SecurityMode.Integrated;
                    syncAgent.SubscriberSecurityMode = SecurityMode.Integrated;

                    // Generate a troubleshooting log file.
                    syncAgent.OutputVerboseLevel = outputLevel;
                    syncAgent.Output = outputLogFile;

                    // Define the event handler.
                    syncAgent.Status
                        += new AgentCore.StatusEventHandler(Sync_Status);

                    currentStatusTextBox.Text += statusInitialize
                        + Environment.NewLine;
                    Application.DoEvents();

                    // Start the Merge Agent synchronously to apply the initial snapshot.
                    syncAgent.Synchronize();

                    // Make sure that the initialization was successful.
                    mergePullSub.Refresh();
                    if (mergePullSub.LastAgentStatus
                        != ReplicationStatus.Succeeded)
                    {
                        throw new SubscriptionInitializationException(
                            Properties.Resources.ExceptionSubscriptionNotSync);
                    }
                    currentStatusTextBox.Text += statusSuccess.ToString()
                        + Environment.NewLine;
                    statusProgressBar.Value = 100;
                }

                catch (Exception ex)
                {
                    currentStatusTextBox.Text += statusFail.ToString()
                        + Environment.NewLine;
                    statusProgressBar.Value = 0;

                    // If an exception occurs, undo subscription registration at both
                    // the Publisher and Subscriber and remove the handler registration.
                    mergePullSub.Remove();

                    if (isRegistered)
                    {
                        Subscriber.UnregisterBusinessLogicHandler(insertUpdateHandler);
                        isRegistered = false;
                    }

                    throw new SubscriptionCreationException(
                        Properties.Resources.ExceptionSubscriptionNotCreated,
                        ex);
                }

                finally
                {
                    closeButton.Enabled = true;
                    subscriberConn.Disconnect();
                    //publisherConn.Disconnect();
                }
            }
            else
            {
                // If we can't create the subscription, close the application.
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionSubscriptionNotCreated);
                emb.Buttons = ExceptionMessageBoxButtons.RetryCancel;
                DialogResult drRetry = emb.Show(this);

                if (drRetry == DialogResult.Retry)
                {
                    this.CreateSubscription();
                }
                else
                {
                    Application.Exit();
                }
            }
        }
Ejemplo n.º 12
0
        public void SynchronizeSubscriptionUploadOnly()
        {
            MergeSynchronizationAgent syncAgent;

            try
            {
                // Make the connection and get the subscription properties.
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();
            }
            catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionCannotConnectLocal,
                    Properties.Resources.ExceptionSqlServerError,
                    ExceptionMessageBoxButtons.OK);
                emb.InnerException = ex;
                emb.Show(this);

                // Shutdown the application because we can't continue.
                Application.Exit();
            }

            mergePullSub = new MergePullSubscription();

            // Set the properties needed to get the subscription.
            mergePullSub.ConnectionContext = subscriberConn;
            mergePullSub.PublicationName = publicationName;
            mergePullSub.PublisherName = publisherServer;
            mergePullSub.PublicationDBName = publicationDatabase;
            mergePullSub.DatabaseName = subscriptionDatabase;

            // Load the properties of the existing subscription.
            if (!mergePullSub.LoadProperties())
            {
                throw new ApplicationException(
                    Properties.Resources.ExceptionProblemLocalData
                    + Environment.NewLine
                    + Properties.Resources.ExceptionContactTechSupport);
            }

            // Get the Merge Agent for synchronous execution.
            syncAgent = mergePullSub.SynchronizationAgent;

            // Specify an upload-only exchange type.
            syncAgent.ExchangeType = MergeExchangeType.Upload;

            // Generate a troubleshooting log file.
            syncAgent.Output = outputLogFile;
            syncAgent.OutputVerboseLevel = outputLevel;

            // Define the event handler.
            syncAgent.Status += new AgentCore.StatusEventHandler(Sync_Status);

            // Start the Merge Agent Job.
            try
            {
                syncAgent.Synchronize();
            }
            catch (Exception ex)
            {
                statusProgressBar.Value = 0;
                throw new ApplicationException(
                    Properties.Resources.ExceptionMergeAgentFailedSync,
                    ex);
            }
            finally
            {
                closeButton.Enabled = true;
                subscriberConn.Disconnect();
            }
        }
Ejemplo n.º 13
0
        public void ReinitializeSubscriptionWithUpload()
        {
            MergeSynchronizationAgent syncAgent;

            try
            {
                // Make the connection and get the subscription properties.
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();
            }
            catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionCannotConnectLocal,
                    Properties.Resources.ExceptionSqlServerError,
                    ExceptionMessageBoxButtons.OK);
                emb.InnerException = ex;
                emb.Show(this);

                // Shutdown the application because we can't continue.
                Application.Exit();
            }

            mergePullSub = new MergePullSubscription();

            // Set the properties needed to get the subscription.
            mergePullSub.ConnectionContext = subscriberConn;
            mergePullSub.PublicationName = publicationName;
            mergePullSub.PublisherName = publisherServer;
            mergePullSub.PublicationDBName = publicationDatabase;
            mergePullSub.DatabaseName = subscriptionDatabase;

            // Load the properties of the existing subscription.
            if (!mergePullSub.LoadProperties())
            {
                throw new ApplicationException(
                    Properties.Resources.ExceptionProblemLocalData
                    + Environment.NewLine
                    + Properties.Resources.ExceptionContactTechSupport);
            }

            // Check to make sure that the Merge Agent isn't already running.
            if (mergePullSub.LastAgentStatus
                != (ReplicationStatus.Running | ReplicationStatus.Starting))
            {
                // Mark the subscription for reinitialization after uploading.
                mergePullSub.Reinitialize(true);

                // Get the Merge Agent for synchronous execution.
                syncAgent = mergePullSub.SynchronizationAgent;

                // Define the event handler.
                syncAgent.Status
                    += new AgentCore.StatusEventHandler(Sync_Status);

                syncAgent.Output = outputLogFile;
                syncAgent.OutputVerboseLevel = outputLevel;

                // Start the Merge Agent Job.
                try
                {
                    currentStatusTextBox.Text = statusReinitialize
                        + Environment.NewLine;
                    syncAgent.Synchronize();
                }
                catch (Exception ex)
                {
                    throw new ApplicationException(
                        Properties.Resources.ExceptionCouldNotReInit
                        + Environment.NewLine
                        + Properties.Resources.ExceptionContactTechSupport, ex);
                }
                finally
                {
                    statusProgressBar.Value = 100;
                    closeButton.Enabled = true;
                    subscriberConn.Disconnect();
                }
            }
            else
            {
                currentStatusTextBox.Text
                    = Properties.Resources.StatusSubscriptionAlreadySync;
                closeButton.Enabled = true;
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Check that the subscription exists and create it if needed.
        /// </summary>
        public void CheckSubscription()
        {
            try
            {
                // We need connections to the Publisher and Distributor.
                subscriberConn = new ServerConnection(subscriberServer);
                subscriberConn.Connect();
            }
            catch (Microsoft.SqlServer.Replication.ConnectionFailureException ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(
                    Properties.Resources.ExceptionCannotConnectLocal,
                    Properties.Resources.ExceptionSqlServerError,
                    ExceptionMessageBoxButtons.OK);
                emb.InnerException = ex;
                emb.Show(this);

                // Shutdown the application because we can't continue.
                Application.Exit();
            }

            // Create the subscription database using SMO if it does not exist.
            Server subServer = new Server(subscriberConn);

            // Instantiate a pull subscription object.
            mergePullSub = new MergePullSubscription();

            // Set the properties needed to create the subscription.
            mergePullSub.ConnectionContext = subscriberConn;
            mergePullSub.PublicationName = publicationName;
            mergePullSub.PublisherName = publisherServer;
            mergePullSub.PublicationDBName = publicationDatabase;
            mergePullSub.DatabaseName = subscriptionDatabase;

            if (subServer.Databases.Contains(subscriptionDatabase))
            {
                // If the database exists, check for replication objects.
                if (mergePullSub.IsExistingObject)
                {
                    if (mergePullSub.UseWebSynchronization)
                    {
                        this.UseWebSynchronization = true;
                    }
                    this.Close();
                    return;
                }
            }

            CreateSubscription();
        }