예제 #1
0
 ///<summary>Inserts one ReplicationServer into the database.  Provides option to use the existing priKey.</summary>
 internal static long Insert(ReplicationServer replicationServer,bool useExistingPK)
 {
     if(!useExistingPK && PrefC.RandomKeys) {
         replicationServer.ReplicationServerNum=ReplicationServers.GetKey("replicationserver","ReplicationServerNum");
     }
     string command="INSERT INTO replicationserver (";
     if(useExistingPK || PrefC.RandomKeys) {
         command+="ReplicationServerNum,";
     }
     command+="Descript,ServerId,RangeStart,RangeEnd,AtoZpath,UpdateBlocked,SlaveMonitor) VALUES(";
     if(useExistingPK || PrefC.RandomKeys) {
         command+=POut.Long(replicationServer.ReplicationServerNum)+",";
     }
     command+=
          "'"+POut.String(replicationServer.Descript)+"',"
         +    POut.Int   (replicationServer.ServerId)+","
         +    POut.Long  (replicationServer.RangeStart)+","
         +    POut.Long  (replicationServer.RangeEnd)+","
         +"'"+POut.String(replicationServer.AtoZpath)+"',"
         +    POut.Bool  (replicationServer.UpdateBlocked)+","
         +"'"+POut.String(replicationServer.SlaveMonitor)+"')";
     if(useExistingPK || PrefC.RandomKeys) {
         Db.NonQ(command);
     }
     else {
         replicationServer.ReplicationServerNum=Db.NonQ(command,true);
     }
     return replicationServer.ReplicationServerNum;
 }
예제 #2
0
 ///<summary>Inserts one ReplicationServer into the database.  Returns the new priKey.</summary>
 internal static long Insert(ReplicationServer replicationServer)
 {
     if(DataConnection.DBtype==DatabaseType.Oracle) {
         replicationServer.ReplicationServerNum=DbHelper.GetNextOracleKey("replicationserver","ReplicationServerNum");
         int loopcount=0;
         while(loopcount<100){
             try {
                 return Insert(replicationServer,true);
             }
             catch(Oracle.DataAccess.Client.OracleException ex){
                 if(ex.Number==1 && ex.Message.ToLower().Contains("unique constraint") && ex.Message.ToLower().Contains("violated")){
                     replicationServer.ReplicationServerNum++;
                     loopcount++;
                 }
                 else{
                     throw ex;
                 }
             }
         }
         throw new ApplicationException("Insert failed.  Could not generate primary key.");
     }
     else {
         return Insert(replicationServer,false);
     }
 }
예제 #3
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();
            }
        }
예제 #4
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();
        }
    }
예제 #5
0
        /*
         * ///<summary>Returns true if the given path is part of the image paths stored in the database list, false otherwise.</summary>
         * public static bool IsImagePath(string path){
         *      string imagePaths=PrefC.GetString(PrefName.DocPath");
         *      return IsImagePath(path,imagePaths);
         * }*/

        private void butOK_Click(object sender, System.EventArgs e)
        {
            //remember that user might be using a website or a linux box to store images, therefore must allow forward slashes.
            if (radioUseFolder.Checked)
            {
                if (textLocalPath.Text != "")
                {
                    if (ImageStore.GetValidPathFromString(textLocalPath.Text) == null)
                    {
                        MsgBox.Show(this, "The path override for this computer is invalid.  The folder must exist and must contain all 26 A through Z folders.");
                        return;
                    }
                }
                else if (textServerPath.Text != "")
                {
                    if (ImageStore.GetValidPathFromString(textServerPath.Text) == null)
                    {
                        MsgBox.Show(this, "The path override for this server is invalid.  The folder must exist and must contain all 26 A through Z folders.");
                        return;
                    }
                }
                else
                {
                    if (ImageStore.GetValidPathFromString(textDocPath.Text) == null)
                    {
                        MsgBox.Show(this, "The path is invalid.  The folder must exist and must contain all 26 A through Z folders.");
                        return;
                    }
                }
            }
            if (Prefs.UpdateBool(PrefName.AtoZfolderUsed, radioUseFolder.Checked)
                | Prefs.UpdateString(PrefName.DocPath, textDocPath.Text)
                | Prefs.UpdateString(PrefName.ExportPath, textExportPath.Text)
                | Prefs.UpdateString(PrefName.LetterMergePath, textLetterMergePath.Text))
            {
                DataValid.SetInvalid(InvalidType.Prefs);
            }
            if (ImageStore.LocalAtoZpath != textLocalPath.Text)           //if local path changed
            {
                ImageStore.LocalAtoZpath = textLocalPath.Text;
                //ComputerPref compPref=ComputerPrefs.GetForLocalComputer();
                ComputerPrefs.LocalComputer.AtoZpath = ImageStore.LocalAtoZpath;
                ComputerPrefs.Update(ComputerPrefs.LocalComputer);
            }
            if (ReplicationServers.GetAtoZpath() != textServerPath.Text)
            {
                ReplicationServer server = ReplicationServers.GetForLocalComputer();
                server.AtoZpath = textServerPath.Text;
                ReplicationServers.Update(server);
                DataValid.SetInvalid(InvalidType.ReplicationServers);
            }
            DialogResult = DialogResult.OK;
        }
예제 #6
0
 internal protected override void HandleFailover(ReplicationServer server, Exception exception)
 {
     try
     {
         ExecuteCommand("threat report_error", server.Name);
     }
     catch (Exception ex)
     {
         MySqlTrace.LogError(-1, ex.ToString());
     }
     GetServerList();
     throw exception;
 }
예제 #7
0
        ///<summary>Updates one ReplicationServer in the database.</summary>
        public static void Update(ReplicationServer replicationServer)
        {
            string command = "UPDATE replicationserver SET "
                             + "Descript            = '" + POut.String(replicationServer.Descript) + "', "
                             + "ServerId            =  " + POut.Int(replicationServer.ServerId) + ", "
                             + "RangeStart          =  " + POut.Long(replicationServer.RangeStart) + ", "
                             + "RangeEnd            =  " + POut.Long(replicationServer.RangeEnd) + ", "
                             + "AtoZpath            = '" + POut.String(replicationServer.AtoZpath) + "', "
                             + "UpdateBlocked       =  " + POut.Bool(replicationServer.UpdateBlocked) + ", "
                             + "SlaveMonitor        = '" + POut.String(replicationServer.SlaveMonitor) + "' "
                             + "WHERE ReplicationServerNum = " + POut.Long(replicationServer.ReplicationServerNum);

            Db.NonQ(command);
        }
예제 #8
0
 ///<summary>Inserts one ReplicationServer into the database.  Returns the new priKey.  Doesn't use the cache.</summary>
 public static long InsertNoCache(ReplicationServer replicationServer)
 {
     if (DataConnection.DBtype == DatabaseType.MySql)
     {
         return(InsertNoCache(replicationServer, false));
     }
     else
     {
         if (DataConnection.DBtype == DatabaseType.Oracle)
         {
             replicationServer.ReplicationServerNum = DbHelper.GetNextOracleKey("replicationserver", "ReplicationServerNum");                  //Cacheless method
         }
         return(InsertNoCache(replicationServer, true));
     }
 }
예제 #9
0
        public void Replication_Generate_Scripts(string BaseScriptFile, string PublicationServer)
        {
            dynamic ServerConnection = new ServerConnection(PublicationServer);

            try
            {
                // connect to publisher
                ServerConnection.LoginSecure = true;
                ServerConnection.Connect();
                string Filename = string.Empty;

                ScriptOptions _so = ScriptOptions.Creation | ScriptOptions.IncludeAll ^ ScriptOptions.IncludeReplicationJobs;

                dynamic ReplicationServer    = new ReplicationServer(ServerConnection);
                dynamic ReplicationDatabases = ReplicationServer.ReplicationDatabases;

                foreach (ReplicationDatabase rdb in ReplicationDatabases)
                {
                    if (rdb.HasPublications)
                    {
                        foreach (TransPublication tp in rdb.TransPublications)
                        {
                            Filename = BaseScriptFile + "_" + tp.Name;
                            FileInfo _fi = new FileInfo(Filename);
                            if (_fi.Extension != "sql")
                            {
                                Filename += ".sql";
                            }

                            if (_fi.FullName.Length > 260)
                            {
                                Filename = Filename.Substring(0, 256) + ".sql";
                            }

                            System.IO.File.WriteAllText(Filename, tp.Script(_so));
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
            finally
            {
                ServerConnection.Disconnect();
            }
        }
        public FabricServer(Guid serverUuid, string groupId, string host, int port, FabricServerModeEnum mode, FabricServerStatusEnum status, float weight, string user, string passowrd)
        {
            ServerUuid = serverUuid;
            GroupId    = groupId;
            Host       = host;
            Port       = port;
            Mode       = mode;
            Status     = status;
            Weight     = weight;

            ReplicationServerInstance = new ReplicationServer(
                serverUuid.ToString(),
                mode == FabricServerModeEnum.Read_Write || mode == FabricServerModeEnum.Write_only,
                string.Format("server={0};port={1};uid={2};password={3};", host, port, user, passowrd)
                );
        }
		///<summary>Converts a DataTable to a list of objects.</summary>
		public static List<ReplicationServer> TableToList(DataTable table){
			List<ReplicationServer> retVal=new List<ReplicationServer>();
			ReplicationServer replicationServer;
			for(int i=0;i<table.Rows.Count;i++) {
				replicationServer=new ReplicationServer();
				replicationServer.ReplicationServerNum= PIn.Long  (table.Rows[i]["ReplicationServerNum"].ToString());
				replicationServer.Descript            = PIn.String(table.Rows[i]["Descript"].ToString());
				replicationServer.ServerId            = PIn.Int   (table.Rows[i]["ServerId"].ToString());
				replicationServer.RangeStart          = PIn.Long  (table.Rows[i]["RangeStart"].ToString());
				replicationServer.RangeEnd            = PIn.Long  (table.Rows[i]["RangeEnd"].ToString());
				replicationServer.AtoZpath            = PIn.String(table.Rows[i]["AtoZpath"].ToString());
				replicationServer.UpdateBlocked       = PIn.Bool  (table.Rows[i]["UpdateBlocked"].ToString());
				replicationServer.SlaveMonitor        = PIn.String(table.Rows[i]["SlaveMonitor"].ToString());
				retVal.Add(replicationServer);
			}
			return retVal;
		}
예제 #12
0
        internal protected override ReplicationServer GetServer(bool isMaster, MySqlConnectionStringBuilder settings)
        {
            if (fabricConnection == null)
            {
                if (servers.Count == 0)
                {
                    throw new MySqlFabricException(Properties.Resources.errorNoFabricSettings);
                }

                username = settings.UserID;
                password = settings.Password;

                fabricConnection = new MySqlConnection(servers[0].ConnectionString);
            }
            bool hasChanged = false;

            if (groupIdProperty != settings.FabricGroup)
            {
                hasChanged = true;
            }
            groupIdProperty = settings.FabricGroup;
            if (modeProperty != (FabricServerModeEnum?)settings.FabricServerMode)
            {
                hasChanged = true;
            }
            modeProperty = (FabricServerModeEnum?)settings.FabricServerMode;
            if (tableProperty != settings.ShardingTable)
            {
                hasChanged = true;
            }
            tableProperty = settings.ShardingTable;
            if (keyProperty != settings.ShardingKey)
            {
                hasChanged = true;
            }
            keyProperty = settings.ShardingKey;

            if (hasChanged)
            {
                GetServerList();
                lastServer = GetServer(isMaster);
            }

            return(lastServer);
        }
예제 #13
0
        public bool Go(string serverName, string dbname)
        {
            bool result = true;

            ServerConnection subscriberConn = new ServerConnection(serverName);

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

                ReplicationServer replserv = new ReplicationServer(subscriberConn);

                foreach (SubscriberSubscription subscription in replserv.EnumSubscriberSubscriptions(dbname, 2))
                {
                    if (!string.IsNullOrEmpty(dbname))
                    {
                        if (dbname != subscription.SubscriptionDBName)
                        {
                            continue;
                        }
                    }

                    if (!SynchronizeSubscription(subscription, serverName))
                    {
                        result = false;
                    }
                }
            }
            catch (Exception ex)
            {
                result = false;
                Log(ex.Message);
            }
            finally
            {
                subscriberConn.Disconnect();
            }

            Info.DateEnd = DateTime.Now;
            Log(string.Format("Merge process ended at: {0}", Info.DateEnd));

            return(result);
        }
예제 #14
0
        ///<summary>Inserts one ReplicationServer into the database.  Provides option to use the existing priKey.  Doesn't use the cache.</summary>
        public static long InsertNoCache(ReplicationServer replicationServer, bool useExistingPK)
        {
            bool   isRandomKeys = Prefs.GetBoolNoCache(PrefName.RandomPrimaryKeys);
            string command      = "INSERT INTO replicationserver (";

            if (!useExistingPK && isRandomKeys)
            {
                replicationServer.ReplicationServerNum = ReplicationServers.GetKeyNoCache("replicationserver", "ReplicationServerNum");
            }
            if (isRandomKeys || useExistingPK)
            {
                command += "ReplicationServerNum,";
            }
            command += "Descript,ServerId,RangeStart,RangeEnd,AtoZpath,UpdateBlocked,SlaveMonitor) VALUES(";
            if (isRandomKeys || useExistingPK)
            {
                command += POut.Long(replicationServer.ReplicationServerNum) + ",";
            }
            command +=
                DbHelper.ParamChar + "paramDescript,"
                + POut.Int(replicationServer.ServerId) + ","
                + POut.Long(replicationServer.RangeStart) + ","
                + POut.Long(replicationServer.RangeEnd) + ","
                + "'" + POut.String(replicationServer.AtoZpath) + "',"
                + POut.Bool(replicationServer.UpdateBlocked) + ","
                + "'" + POut.String(replicationServer.SlaveMonitor) + "')";
            if (replicationServer.Descript == null)
            {
                replicationServer.Descript = "";
            }
            OdSqlParameter paramDescript = new OdSqlParameter("paramDescript", OdDbType.Text, POut.StringParam(replicationServer.Descript));

            if (useExistingPK || isRandomKeys)
            {
                Db.NonQ(command, paramDescript);
            }
            else
            {
                replicationServer.ReplicationServerNum = Db.NonQ(command, true, "ReplicationServerNum", "replicationServer", paramDescript);
            }
            return(replicationServer.ReplicationServerNum);
        }
예제 #15
0
        ///<summary>Updates one ReplicationServer in the database.</summary>
        public static void Update(ReplicationServer replicationServer)
        {
            string command = "UPDATE replicationserver SET "
                             + "Descript            =  " + DbHelper.ParamChar + "paramDescript, "
                             + "ServerId            =  " + POut.Int(replicationServer.ServerId) + ", "
                             + "RangeStart          =  " + POut.Long(replicationServer.RangeStart) + ", "
                             + "RangeEnd            =  " + POut.Long(replicationServer.RangeEnd) + ", "
                             + "AtoZpath            = '" + POut.String(replicationServer.AtoZpath) + "', "
                             + "UpdateBlocked       =  " + POut.Bool(replicationServer.UpdateBlocked) + ", "
                             + "SlaveMonitor        = '" + POut.String(replicationServer.SlaveMonitor) + "' "
                             + "WHERE ReplicationServerNum = " + POut.Long(replicationServer.ReplicationServerNum);

            if (replicationServer.Descript == null)
            {
                replicationServer.Descript = "";
            }
            OdSqlParameter paramDescript = new OdSqlParameter("paramDescript", OdDbType.Text, POut.StringParam(replicationServer.Descript));

            Db.NonQ(command, paramDescript);
        }
예제 #16
0
        ///<summary>Converts a DataTable to a list of objects.</summary>
        public static List <ReplicationServer> TableToList(DataTable table)
        {
            List <ReplicationServer> retVal = new List <ReplicationServer>();
            ReplicationServer        replicationServer;

            for (int i = 0; i < table.Rows.Count; i++)
            {
                replicationServer = new ReplicationServer();
                replicationServer.ReplicationServerNum = PIn.Long(table.Rows[i]["ReplicationServerNum"].ToString());
                replicationServer.Descript             = PIn.String(table.Rows[i]["Descript"].ToString());
                replicationServer.ServerId             = PIn.Int(table.Rows[i]["ServerId"].ToString());
                replicationServer.RangeStart           = PIn.Long(table.Rows[i]["RangeStart"].ToString());
                replicationServer.RangeEnd             = PIn.Long(table.Rows[i]["RangeEnd"].ToString());
                replicationServer.AtoZpath             = PIn.String(table.Rows[i]["AtoZpath"].ToString());
                replicationServer.UpdateBlocked        = PIn.Bool(table.Rows[i]["UpdateBlocked"].ToString());
                replicationServer.SlaveMonitor         = PIn.String(table.Rows[i]["SlaveMonitor"].ToString());
                retVal.Add(replicationServer);
            }
            return(retVal);
        }
예제 #17
0
        internal protected override ReplicationServer GetServer(bool isMaster)
        {
            if (string.IsNullOrEmpty(groupIdProperty) && string.IsNullOrEmpty(tableProperty))
            {
                throw new MySqlFabricException(Properties.Resources.errorNotGroupNorTable);
            }

            FabricServerModeEnum mode = modeProperty.HasValue ? modeProperty.Value
        : (isMaster ? FabricServerModeEnum.Read_Write : FabricServerModeEnum.Read_only);

            lock (_lockObject)
            {
                /*
                 * Pick a server using this algorithm.
                 *
                 * */
                if (string.IsNullOrEmpty(tableProperty))
                {
                    return(GetServerByGroup(mode, groupIdProperty));
                }
                else
                {
                    ReplicationServer server = GetServerByShard(mode);
                    // Ensure the database is the current shard db.
                    string[] db     = tableProperty.Split('.');
                    string   conStr = server.ConnectionString;
                    if (conStr.IndexOf("database=" + db[0] + ";") == -1)
                    {
                        MySqlConnectionStringBuilder msb = new MySqlConnectionStringBuilder(conStr);
                        msb.Database            = db[0];
                        server.ConnectionString = msb.ToString();
                    }
                    // return server
                    return(server);
                }
            }
        }
예제 #18
0
        ///<summary>Updates one ReplicationServer in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
        public static void Update(ReplicationServer replicationServer, ReplicationServer oldReplicationServer)
        {
            string command = "";

            if (replicationServer.Descript != oldReplicationServer.Descript)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Descript = '" + POut.String(replicationServer.Descript) + "'";
            }
            if (replicationServer.ServerId != oldReplicationServer.ServerId)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "ServerId = " + POut.Int(replicationServer.ServerId) + "";
            }
            if (replicationServer.RangeStart != oldReplicationServer.RangeStart)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "RangeStart = " + POut.Long(replicationServer.RangeStart) + "";
            }
            if (replicationServer.RangeEnd != oldReplicationServer.RangeEnd)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "RangeEnd = " + POut.Long(replicationServer.RangeEnd) + "";
            }
            if (replicationServer.AtoZpath != oldReplicationServer.AtoZpath)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "AtoZpath = '" + POut.String(replicationServer.AtoZpath) + "'";
            }
            if (replicationServer.UpdateBlocked != oldReplicationServer.UpdateBlocked)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "UpdateBlocked = " + POut.Bool(replicationServer.UpdateBlocked) + "";
            }
            if (replicationServer.SlaveMonitor != oldReplicationServer.SlaveMonitor)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "SlaveMonitor = '" + POut.String(replicationServer.SlaveMonitor) + "'";
            }
            if (command == "")
            {
                return;
            }
            command = "UPDATE replicationserver SET " + command
                      + " WHERE ReplicationServerNum = " + POut.Long(replicationServer.ReplicationServerNum);
            Db.NonQ(command);
        }
예제 #19
0
        private void LoadSubscriptionProperties(string subscriber)
        {
            int subTextLength = 40;
            string subId;

            try
            {
                // Get default values from the current SQL Server
                ServerConnection serverConnection = new ServerConnection(subscriber);
                serverConnection.Connect();
                ReplicationServer replServer = new ReplicationServer(serverConnection);

                // Get the subscriptions on this Subscriber.
                availableSubscriptions =
                    replServer.EnumSubscriberSubscriptions(null,
                    Convert.ToInt32(SubscriptionType.Both,
                    System.Globalization.CultureInfo.InvariantCulture));

                // Enumerate all subscriptions
                this.subscriptionsComboBox.BeginUpdate();

                // Empty the combo box
                this.subscriptionsComboBox.Items.Clear();
                this.subscriptionsComboBox.Text = string.Empty;

                foreach (SubscriberSubscription subscriberSubscription
                    in availableSubscriptions)
                {
                    // Only get subscriptions to merge publications.
                    if (subscriberSubscription.Type == PublicationType.Merge)
                    {
                        subId = "[" + subscriberSubscription.SubscriptionDBName
                            + "]-[" + subscriberSubscription.PublisherName
                            + " ].[" + subscriberSubscription.PublicationDBName
                            + "]:" + subscriberSubscription.PublicationName;

                        subscriberSubscription.UserData = subId;
                        this.subscriptionsComboBox.Items.Add(subscriberSubscription.UserData);

                        if (subId.Length > subTextLength)
                        {
                            subTextLength = subId.Length;
                        }
                    }
                }

                this.subscriptionsComboBox.DropDownWidth = Convert.ToInt32(subTextLength * 5.6);

                // Set to the first item to get subscription properties.
                if (this.subscriptionsComboBox.Items.Count > 0)
                {
                    this.subscriptionsComboBox.SelectedIndex = 0;
                }

                this.subscriptionsComboBox.EndUpdate();
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
            }
        }
예제 #20
0
 ///<summary>Updates one ReplicationServer in the database.</summary>
 internal static void Update(ReplicationServer replicationServer)
 {
     string command="UPDATE replicationserver SET "
         +"Descript            = '"+POut.String(replicationServer.Descript)+"', "
         +"ServerId            =  "+POut.Int   (replicationServer.ServerId)+", "
         +"RangeStart          =  "+POut.Long  (replicationServer.RangeStart)+", "
         +"RangeEnd            =  "+POut.Long  (replicationServer.RangeEnd)+", "
         +"AtoZpath            = '"+POut.String(replicationServer.AtoZpath)+"', "
         +"UpdateBlocked       =  "+POut.Bool  (replicationServer.UpdateBlocked)+", "
         +"SlaveMonitor        = '"+POut.String(replicationServer.SlaveMonitor)+"' "
         +"WHERE ReplicationServerNum = "+POut.Long(replicationServer.ReplicationServerNum);
     Db.NonQ(command);
 }
예제 #21
0
 ///<summary>Updates one ReplicationServer in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.</summary>
 internal static void Update(ReplicationServer replicationServer,ReplicationServer oldReplicationServer)
 {
     string command="";
     if(replicationServer.Descript != oldReplicationServer.Descript) {
         if(command!=""){ command+=",";}
         command+="Descript = '"+POut.String(replicationServer.Descript)+"'";
     }
     if(replicationServer.ServerId != oldReplicationServer.ServerId) {
         if(command!=""){ command+=",";}
         command+="ServerId = "+POut.Int(replicationServer.ServerId)+"";
     }
     if(replicationServer.RangeStart != oldReplicationServer.RangeStart) {
         if(command!=""){ command+=",";}
         command+="RangeStart = "+POut.Long(replicationServer.RangeStart)+"";
     }
     if(replicationServer.RangeEnd != oldReplicationServer.RangeEnd) {
         if(command!=""){ command+=",";}
         command+="RangeEnd = "+POut.Long(replicationServer.RangeEnd)+"";
     }
     if(replicationServer.AtoZpath != oldReplicationServer.AtoZpath) {
         if(command!=""){ command+=",";}
         command+="AtoZpath = '"+POut.String(replicationServer.AtoZpath)+"'";
     }
     if(replicationServer.UpdateBlocked != oldReplicationServer.UpdateBlocked) {
         if(command!=""){ command+=",";}
         command+="UpdateBlocked = "+POut.Bool(replicationServer.UpdateBlocked)+"";
     }
     if(replicationServer.SlaveMonitor != oldReplicationServer.SlaveMonitor) {
         if(command!=""){ command+=",";}
         command+="SlaveMonitor = '"+POut.String(replicationServer.SlaveMonitor)+"'";
     }
     if(command==""){
         return;
     }
     command="UPDATE replicationserver SET "+command
         +" WHERE ReplicationServerNum = "+POut.Long(replicationServer.ReplicationServerNum);
     Db.NonQ(command);
 }
예제 #22
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();
                }
            }
        }
예제 #23
0
        private void LoadSubscriptionProperties(string subscriber)
        {
            int    subTextLength = 40;
            string subId;

            try
            {
                // Get default values from the current SQL Server
                ServerConnection serverConnection = new ServerConnection(subscriber);
                serverConnection.Connect();
                ReplicationServer replServer = new ReplicationServer(serverConnection);

                // Get the subscriptions on this Subscriber.
                availableSubscriptions =
                    replServer.EnumSubscriberSubscriptions(null,
                                                           Convert.ToInt32(SubscriptionType.Both,
                                                                           System.Globalization.CultureInfo.InvariantCulture));

                // Enumerate all subscriptions
                this.subscriptionsComboBox.BeginUpdate();

                // Empty the combo box
                this.subscriptionsComboBox.Items.Clear();
                this.subscriptionsComboBox.Text = string.Empty;

                foreach (SubscriberSubscription subscriberSubscription
                         in availableSubscriptions)
                {
                    // Only get subscriptions to merge publications.
                    if (subscriberSubscription.Type == PublicationType.Merge)
                    {
                        subId = "[" + subscriberSubscription.SubscriptionDBName
                                + "]-[" + subscriberSubscription.PublisherName
                                + " ].[" + subscriberSubscription.PublicationDBName
                                + "]:" + subscriberSubscription.PublicationName;

                        subscriberSubscription.UserData = subId;
                        this.subscriptionsComboBox.Items.Add(subscriberSubscription.UserData);

                        if (subId.Length > subTextLength)
                        {
                            subTextLength = subId.Length;
                        }
                    }
                }

                this.subscriptionsComboBox.DropDownWidth = Convert.ToInt32(subTextLength * 5.6);

                // Set to the first item to get subscription properties.
                if (this.subscriptionsComboBox.Items.Count > 0)
                {
                    this.subscriptionsComboBox.SelectedIndex = 0;
                }

                this.subscriptionsComboBox.EndUpdate();
            }
            catch (Exception ex)
            {
                ExceptionMessageBox emb = new ExceptionMessageBox(ex);
                emb.Show(this);
            }
        }
예제 #24
0
 public override void _Ready()
 {
     Instance = this;
 }
 ///<summary>Inserts one ReplicationServer into the database.  Returns the new priKey.  Doesn't use the cache.</summary>
 public static long InsertNoCache(ReplicationServer replicationServer)
 {
     return(InsertNoCache(replicationServer, false));
 }
예제 #26
0
        ///<summary>Updates one ReplicationServer in the database.  Uses an old object to compare to, and only alters changed fields.  This prevents collisions and concurrency problems in heavily used tables.  Returns true if an update occurred.</summary>
        public static bool Update(ReplicationServer replicationServer, ReplicationServer oldReplicationServer)
        {
            string command = "";

            if (replicationServer.Descript != oldReplicationServer.Descript)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "Descript = " + DbHelper.ParamChar + "paramDescript";
            }
            if (replicationServer.ServerId != oldReplicationServer.ServerId)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "ServerId = " + POut.Int(replicationServer.ServerId) + "";
            }
            if (replicationServer.RangeStart != oldReplicationServer.RangeStart)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "RangeStart = " + POut.Long(replicationServer.RangeStart) + "";
            }
            if (replicationServer.RangeEnd != oldReplicationServer.RangeEnd)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "RangeEnd = " + POut.Long(replicationServer.RangeEnd) + "";
            }
            if (replicationServer.AtoZpath != oldReplicationServer.AtoZpath)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "AtoZpath = '" + POut.String(replicationServer.AtoZpath) + "'";
            }
            if (replicationServer.UpdateBlocked != oldReplicationServer.UpdateBlocked)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "UpdateBlocked = " + POut.Bool(replicationServer.UpdateBlocked) + "";
            }
            if (replicationServer.SlaveMonitor != oldReplicationServer.SlaveMonitor)
            {
                if (command != "")
                {
                    command += ",";
                }
                command += "SlaveMonitor = '" + POut.String(replicationServer.SlaveMonitor) + "'";
            }
            if (command == "")
            {
                return(false);
            }
            if (replicationServer.Descript == null)
            {
                replicationServer.Descript = "";
            }
            OdSqlParameter paramDescript = new OdSqlParameter("paramDescript", OdDbType.Text, POut.StringParam(replicationServer.Descript));

            command = "UPDATE replicationserver SET " + command
                      + " WHERE ReplicationServerNum = " + POut.Long(replicationServer.ReplicationServerNum);
            Db.NonQ(command, paramDescript);
            return(true);
        }
예제 #27
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();
        }
    }
 public ReplicationBackuper(ReplicationServer replicationServer)
 {
     this.replicationServer = replicationServer ?? throw new ArgumentNullException(nameof(replicationServer));
     this.dirPath           = PathBuilder.Build(this.replicationServer);
 }
예제 #29
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();
                }
            }
        }