Пример #1
0
    //创建发布
    protected void Button4_Click(object sender, EventArgs e)
    {
        string publisherName     = SMO.publisherName;       // "rd01";//发布者名
        string publicationName   = SMO.publicationName;     // "HdHousePub";//发布名
        string publicationDbName = SMO.publicationDatabase; // "HdHouse";//发布的数据库名
        //创建连接
        ServerConnection    conn = new ServerConnection(publisherName);
        ReplicationDatabase replicationDatabase = new ReplicationDatabase();

        replicationDatabase.Name = publicationDbName;
        replicationDatabase.ConnectionContext = conn;
        if (!replicationDatabase.LoadProperties())
        {
            Label5.Text    = "请确定发布数据库" + publicationDbName + "已存在";
            TextBox3.Text += "请确定发布数据库" + publicationDbName + "已存在  \r\n";
            return;
        }

        if (!replicationDatabase.EnabledMergePublishing)
        {
            replicationDatabase.EnabledMergePublishing = true;
            replicationDatabase.CommitPropertyChanges();
        }

        MergePublication mergePub = new MergePublication();

        mergePub.ConnectionContext = conn;
        mergePub.DatabaseName      = publicationDbName;
        mergePub.Name = publicationName;
        //mergePub.SnapshotGenerationAgentProcessSecurity
        //mergePub.Attributes |= PublicationAttributes.;
        mergePub.Create();
        mergePub.CreateSnapshotAgent();
    }
Пример #2
0
        public void replication()
        {
            // Set the server and database names
            string distributionDbName = "TestDb";
            string publisherName      = "DESKTOP-9UAIISP\\MSSQLSERVER2017";
            string publicationDbName  = "TestMergeDb";

            DistributionDatabase  distributionDb;
            ReplicationServer     distributor;
            DistributionPublisher publisher;
            ReplicationDatabase   publicationDb;

            // Create a connection to the server using Windows Authentication.
            ServerConnection conn = new ServerConnection(publisherName, "sa", "Ads78ghj@2");

            try
            {
                // Connect to the server acting as the Distributor
                // and local Publisher.
                conn.Connect();

                // Define the distribution database at the Distributor,
                // but do not create it now.
                distributionDb = new DistributionDatabase(distributionDbName, conn);
                distributionDb.MaxDistributionRetention = 96;
                distributionDb.HistoryRetention         = 120;

                // Set the Distributor properties and install the Distributor.
                // This also creates the specified distribution database.
                distributor = new ReplicationServer(conn);
                distributor.InstallDistributor("sa", distributionDb);

                // Set the Publisher properties and install the Publisher.
                publisher = new DistributionPublisher(publisherName, conn);
                publisher.DistributionDatabase = distributionDb.Name;
                publisher.WorkingDirectory     = @"\\" + publisherName + @"\repldata";
                publisher.PublisherSecurity.WindowsAuthentication = true;
                publisher.Create();

                // Enable AdventureWorks2012 as a publication database.
                publicationDb = new ReplicationDatabase(publicationDbName, conn);

                publicationDb.EnabledTransPublishing = true;
                publicationDb.EnabledMergePublishing = true;
            }
            catch (Exception ex)
            {
                // Implement appropriate error handling here.
                throw new ApplicationException("An error occured when installing distribution and publishing.", ex);
            }
            finally
            {
                conn.Disconnect();
            }
        }
Пример #3
0
    //配置发布和分发服务器
    protected void Button5_Click(object sender, EventArgs e)
    {
        string distributionDbName = "distribution";
        string publisherName      = SMO.publisherName;       //"rd01";发布者服务器名
        string publicationDbName  = SMO.publicationDatabase; //"HdHouse";发布的数据库名

        DistributionDatabase  distributionDb;
        ReplicationServer     distributor;
        DistributionPublisher publisher;
        ReplicationDatabase   publicationDb;

        // Create a connection to the server using Windows Authentication.
        ServerConnection conn = new ServerConnection(publisherName);

        try
        {
            // Connect to the server acting as the Distributor
            // and local Publisher.
            conn.Connect();

            // Define the distribution database at the Distributor,
            // but do not create it now.
            distributionDb = new DistributionDatabase(distributionDbName, conn);
            distributionDb.MaxDistributionRetention = 96;
            distributionDb.HistoryRetention         = 120;

            // Set the Distributor properties and install the Distributor.
            // This also creates the specified distribution database.
            distributor = new ReplicationServer(conn);
            distributor.InstallDistributor((string)null, distributionDb);

            // Set the Publisher properties and install the Publisher.
            publisher = new DistributionPublisher(publisherName, conn);
            publisher.DistributionDatabase = distributionDb.Name;
            publisher.WorkingDirectory     = @"\\" + publisherName + @"\repldata";//用于访问快照文件的共享目录。
            publisher.PublisherSecurity.WindowsAuthentication = true;
            publisher.Create();

            // Enable AdventureWorks as a publication database.
            publicationDb = new ReplicationDatabase(publicationDbName, conn);

            publicationDb.EnabledTransPublishing = true;
            publicationDb.EnabledMergePublishing = true;
        }
        catch (Exception ex)
        {
            // Implement appropriate error handling here.
            throw new ApplicationException("An error occured when installing distribution and publishing.", ex);
            TextBox3.Text += "An error occured when installing distribution and publishing." + ex + " \r\n";
        }
        finally
        {
            conn.Disconnect();
        }
    }
Пример #4
0
    //删除
    protected void Button15_Click(object sender, EventArgs e)
    {
        ServerConnection sconn = new ServerConnection(SMO.publisherName);

        try
        {
            MergePublication mpc = new MergePublication();
            mpc.Name              = SMO.publicationName;
            mpc.DatabaseName      = SMO.publicationDatabase;
            mpc.ConnectionContext = sconn;
            if (mpc.IsExistingObject)
            {
                mpc.Remove();
            }
            else
            {
                TextBox3.Text = "发布" + SMO.publicationName + "的定义不正确,或者发布不存在。\r\n";
            }
            ReplicationDatabase rld = new ReplicationDatabase();
            rld.ConnectionContext = sconn;
            rld.Name = SMO.publicationName;
            if (rld.LoadProperties())
            {
                rld.EnabledMergePublishing = false;
                rld.CommitPropertyChanges();
            }
            else
            {
                TextBox3.Text = "请验证" + SMO.publicationDatabase + "数据库是否存在。\r\n";
            }
        }
        catch (Exception ex)
        {
            throw new ApplicationException(String.Format(
                                               "The publication {0} 无法删除.", SMO.publicationName), ex);
        }
        finally
        {
            sconn.Disconnect();
        }
    }
Пример #5
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();
            }
        }
Пример #6
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();
                }
            }
        }
Пример #7
0
    //创建发布以允许使用 Web 同步
    protected void Button6_Click(object sender, EventArgs e)
    {
        // Set the Publisher, publication database, and publication names.
        string publisherName     = SMO.publisherName;       // TextBox8.Text; //"rd01";发布者服务器名
        string publicationName   = SMO.publicationName;     // TextBox4.Text; //"HdHousePub";发布名
        string publicationDbName = SMO.publicationDatabase; // TextBox5.Text;//"HdHouse";发布的数据库名
        string winLogin          = SMO.winLogin;            //TextBox6.Text;//"y";系统帐户
        string winPassword       = SMO.winPassword;         //TextBox7.Text;//"19870312";//该系统帐户密码!

        ReplicationDatabase publicationDb;
        MergePublication    publication;

        // Create a connection to the Publisher.
        ServerConnection conn = new ServerConnection(publisherName);

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

            // Enable the database for merge publication.
            publicationDb = new ReplicationDatabase(publicationDbName, conn);
            if (publicationDb.LoadProperties())
            {
                if (!publicationDb.EnabledMergePublishing)
                {
                    publicationDb.EnabledMergePublishing = true;
                }
            }
            else
            {
                // Do something here if the database does not exist.
                throw new ApplicationException(String.Format(
                                                   "The {0} database does not exist on {1}.",
                                                   publicationDb, publisherName));
            }

            // Set the required properties for the merge publication.
            publication = new MergePublication();
            publication.ConnectionContext = conn;
            publication.Name         = publicationName;
            publication.DatabaseName = publicationDbName;

            // Enable Web synchronization, if not already enabled.
            if ((publication.Attributes & PublicationAttributes.AllowWebSynchronization) == 0)
            {
                publication.Attributes |= PublicationAttributes.AllowWebSynchronization;
            }

            // Enable pull subscriptions, if not already enabled.
            if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
            {
                publication.Attributes |= PublicationAttributes.AllowPull;
            }

            // Enable Subscriber requested snapshot generation.
            publication.Attributes |= PublicationAttributes.AllowSubscriberInitiatedSnapshot;

            // Enable anonymous access for Subscribers that cannot make a direct connetion
            // to the Publisher.
            publication.Attributes |= PublicationAttributes.AllowAnonymous;

            // Specify the Windows account under which the Snapshot Agent job runs.
            // This account will be used for the local connection to the
            // Distributor and all agent connections that use Windows Authentication.
            publication.SnapshotGenerationAgentProcessSecurity.Login    = winLogin;
            publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

            // Explicitly set the security mode for the Publisher connection
            // Windows Authentication (the default).
            publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

            if (!publication.IsExistingObject)
            {
                // Create the merge publication and the Snapshot Agent job.
                publication.Create();
                publication.CreateSnapshotAgent();
            }
            else
            {
                //throw new ApplicationException(String.Format(
                //    "The {0} publication already exists.", publicationName));
                TextBox3.Text += String.Format("发布 {0} 已经存在  \r\n .", publicationName);
            }
        }

        catch (Exception ex)
        {
            // Implement custom application error handling here.
            throw new ApplicationException(String.Format(
                                               "The publication {0} could not be created.", publicationName), ex);
        }
        finally
        {
            conn.Disconnect();
        }
    }
Пример #8
0
    //创建发布以允许使用 Web 同步
    protected void Button6_Click(object sender, EventArgs e)
    {
        // Set the Publisher, publication database, and publication names.
        string publisherName = SMO.publisherName;// TextBox8.Text; //"rd01";发布者服务器名
        string publicationName = SMO.publicationName;// TextBox4.Text; //"HdHousePub";发布名
        string publicationDbName = SMO.publicationDatabase;// TextBox5.Text;//"HdHouse";发布的数据库名
        string winLogin = SMO.winLogin;//TextBox6.Text;//"y";系统帐户
        string winPassword = SMO.winPassword; //TextBox7.Text;//"19870312";//该系统帐户密码!

        ReplicationDatabase publicationDb;
        MergePublication publication;

        // Create a connection to the Publisher.
        ServerConnection conn = new ServerConnection(publisherName);

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

            // Enable the database for merge publication.
            publicationDb = new ReplicationDatabase(publicationDbName, conn);
            if (publicationDb.LoadProperties())
            {
                if (!publicationDb.EnabledMergePublishing)
                {
                    publicationDb.EnabledMergePublishing = true;
                }
            }
            else
            {
                // Do something here if the database does not exist.
                throw new ApplicationException(String.Format(
                    "The {0} database does not exist on {1}.",
                    publicationDb, publisherName));
            }

            // Set the required properties for the merge publication.
            publication = new MergePublication();
            publication.ConnectionContext = conn;
            publication.Name = publicationName;
            publication.DatabaseName = publicationDbName;

            // Enable Web synchronization, if not already enabled.
            if ((publication.Attributes & PublicationAttributes.AllowWebSynchronization) == 0)
            {
                publication.Attributes |= PublicationAttributes.AllowWebSynchronization;
            }

            // Enable pull subscriptions, if not already enabled.
            if ((publication.Attributes & PublicationAttributes.AllowPull) == 0)
            {
                publication.Attributes |= PublicationAttributes.AllowPull;
            }

            // Enable Subscriber requested snapshot generation.
            publication.Attributes |= PublicationAttributes.AllowSubscriberInitiatedSnapshot;

            // Enable anonymous access for Subscribers that cannot make a direct connetion
            // to the Publisher.
            publication.Attributes |= PublicationAttributes.AllowAnonymous;

            // Specify the Windows account under which the Snapshot Agent job runs.
            // This account will be used for the local connection to the
            // Distributor and all agent connections that use Windows Authentication.
            publication.SnapshotGenerationAgentProcessSecurity.Login = winLogin;
            publication.SnapshotGenerationAgentProcessSecurity.Password = winPassword;

            // Explicitly set the security mode for the Publisher connection
            // Windows Authentication (the default).
            publication.SnapshotGenerationAgentPublisherSecurity.WindowsAuthentication = true;

            if (!publication.IsExistingObject)
            {
                // Create the merge publication and the Snapshot Agent job.
                publication.Create();
                publication.CreateSnapshotAgent();
            }
            else
            {
                //throw new ApplicationException(String.Format(
                //    "The {0} publication already exists.", publicationName));
                TextBox3.Text += String.Format("发布 {0} 已经存在  \r\n .", publicationName);
            }
        }

        catch (Exception ex)
        {
            // Implement custom application error handling here.
            throw new ApplicationException(String.Format(
                "The publication {0} could not be created.", publicationName), ex);
        }
        finally
        {
            conn.Disconnect();
        }
    }
Пример #9
0
    //配置发布和分发服务器
    protected void Button5_Click(object sender, EventArgs e)
    {
        string distributionDbName = "distribution";
        string publisherName =SMO.publisherName;//"rd01";发布者服务器名
        string publicationDbName = SMO.publicationDatabase; //"HdHouse";发布的数据库名

        DistributionDatabase distributionDb;
        ReplicationServer distributor;
        DistributionPublisher publisher;
        ReplicationDatabase publicationDb;

        // Create a connection to the server using Windows Authentication.
        ServerConnection conn = new ServerConnection(publisherName);

        try
        {
            // Connect to the server acting as the Distributor
            // and local Publisher.
            conn.Connect();

            // Define the distribution database at the Distributor,
            // but do not create it now.
            distributionDb = new DistributionDatabase(distributionDbName, conn);
            distributionDb.MaxDistributionRetention = 96;
            distributionDb.HistoryRetention = 120;

            // Set the Distributor properties and install the Distributor.
            // This also creates the specified distribution database.
            distributor = new ReplicationServer(conn);
            distributor.InstallDistributor((string)null, distributionDb);

            // Set the Publisher properties and install the Publisher.
            publisher = new DistributionPublisher(publisherName, conn);
            publisher.DistributionDatabase = distributionDb.Name;
            publisher.WorkingDirectory = @"\\" + publisherName + @"\repldata";//用于访问快照文件的共享目录。
            publisher.PublisherSecurity.WindowsAuthentication = true;
            publisher.Create();

            // Enable AdventureWorks as a publication database.
            publicationDb = new ReplicationDatabase(publicationDbName, conn);

            publicationDb.EnabledTransPublishing = true;
            publicationDb.EnabledMergePublishing = true;
        }
        catch (Exception ex)
        {
            // Implement appropriate error handling here.
            throw new ApplicationException("An error occured when installing distribution and publishing.", ex);
            TextBox3.Text += "An error occured when installing distribution and publishing." + ex + " \r\n";
        }
        finally
        {
            conn.Disconnect();
        }
    }
Пример #10
0
    //创建发布
    protected void Button4_Click(object sender, EventArgs e)
    {
        string publisherName = SMO.publisherName;// "rd01";//发布者名
        string publicationName = SMO.publicationName;// "HdHousePub";//发布名
        string publicationDbName = SMO.publicationDatabase;// "HdHouse";//发布的数据库名
        //创建连接
        ServerConnection conn = new ServerConnection(publisherName);
        ReplicationDatabase replicationDatabase = new ReplicationDatabase();
        replicationDatabase.Name = publicationDbName;
        replicationDatabase.ConnectionContext = conn;
        if (!replicationDatabase.LoadProperties())
        {
            Label5.Text = "请确定发布数据库" + publicationDbName + "已存在";
            TextBox3.Text += "请确定发布数据库" + publicationDbName + "已存在  \r\n";
            return;
        }

        if (!replicationDatabase.EnabledMergePublishing)
        {
            replicationDatabase.EnabledMergePublishing = true;
            replicationDatabase.CommitPropertyChanges();
        }

        MergePublication mergePub = new MergePublication();
        mergePub.ConnectionContext = conn;
        mergePub.DatabaseName = publicationDbName;
        mergePub.Name = publicationName;
        //mergePub.SnapshotGenerationAgentProcessSecurity
        //mergePub.Attributes |= PublicationAttributes.;
        mergePub.Create();
        mergePub.CreateSnapshotAgent();
    }
Пример #11
0
 //删除
 protected void Button15_Click(object sender, EventArgs e)
 {
     ServerConnection sconn = new ServerConnection(SMO.publisherName);
     try
     {
         MergePublication mpc = new MergePublication();
         mpc.Name = SMO.publicationName;
         mpc.DatabaseName = SMO.publicationDatabase;
         mpc.ConnectionContext = sconn;
         if (mpc.IsExistingObject)
         {
             mpc.Remove();
         }
         else
         {
             TextBox3.Text = "发布" + SMO.publicationName + "的定义不正确,或者发布不存在。\r\n";
         }
         ReplicationDatabase rld = new ReplicationDatabase();
         rld.ConnectionContext = sconn;
         rld.Name = SMO.publicationName;
         if (rld.LoadProperties())
         {
             rld.EnabledMergePublishing = false;
             rld.CommitPropertyChanges();
         }
         else
         {
             TextBox3.Text = "请验证" + SMO.publicationDatabase + "数据库是否存在。\r\n";
         }
     }
     catch (Exception ex)
     {
         throw new ApplicationException(String.Format(
             "The publication {0} 无法删除.", SMO.publicationName), ex);
     }
     finally
     {
         sconn.Disconnect();
     }
 }
Пример #12
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();
            }
        }
Пример #13
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();
                }
            }
        }