static void Main(string[] args) { //create connection to the server DB SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=SyncDB; Integrated Security=True"); // define the OrdersScope-NC filtered scope // this scope filters records in the Orders table with OriginState set to NC" DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("OrdersScope-NC"); // get the description of the Orders table and add it to the scope DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("Orders", serverConn); scopeDesc.Tables.Add(tableDesc); // create server provisioning object SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // no need to create the Orders table since it already exists, // so use the Skip parameter serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // set the filter column on the Orders table to OriginState serverProvision.Tables["Orders"].AddFilterColumn("OriginState"); // set the filter value to NC serverProvision.Tables["Orders"].FilterClause = "[side].[OriginState] = 'NC'"; // start the provisioning process serverProvision.Apply(); }
private static void createScope(SqlConnection connection) { var scopeDesc = new DbSyncScopeDescription("SyncScope"); // Definition for Customer. DbSyncTableDescription customerDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable("Company", connection); scopeDesc.Tables.Add(customerDescription); customerDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable("Contact", connection); scopeDesc.Tables.Add(customerDescription); // Create a provisioning object for "SyncScope". We specify that // base tables should not be created (They already exist in SyncSamplesDb_SqlPeer1), // and that all synchronization-related objects should be created in a // database schema named "Sync". If you specify a schema, it must already exist // in the database. var serverConfig = new SqlSyncScopeProvisioning(scopeDesc); serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); // Configure the scope and change-tracking infrastructure. serverConfig.Apply(connection); connection.Close(); }
internal void ProvisionTriggerAndProcedureUpdates(SyncDatabase db, SqlConnection connection, DbSyncScopeDescription scopeDesc) { var provision = new SqlSyncScopeProvisioning(connection, scopeDesc); if (provision.ScopeExists(scopeDesc.ScopeName)) { try { Log.Info("[DistributedDb] Provision Scope Trigger And Procedure Updates [" + scopeDesc.ScopeName + "] Start", this); provision.SetCreateTableDefault(DbSyncCreationOption.Skip); provision.CommandTimeout = 3600; provision.ApplyTriggerAndProcedureUpdates(connection); Log.Info("[DistributedDb] Provision Scope Trigger And Procedure Updates [" + scopeDesc.ScopeName + "] End", this); } catch (Exception ex) { Log.Error("[DistributedDb] Provision Scope Trigger And Procedure Updates [" + scopeDesc.ScopeName + "] Error", ex, this); } } else { Log.Info("[DistributedDb] Provision Scope Trigger And Procedure Updates [" + scopeDesc.ScopeName + "] Skipped", this); } }
public void ActivateSqlSync() { SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=Balda; Integrated Security=True"); // Определить новую область с именем ProductsScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("BaldaScope"); // Получаем описание таблицы Изделия из SyncDB dtabase DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("Dictionary", serverConn); // Добавить описание таблицы для определения синхронизации области видимости scopeDesc.Tables.Add(tableDesc); // List<DbSyncTableDescription> tableDescD = new List<DbSyncTableDescription>(); for (int i = 3; i < MaxLengthWord; i++) { scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Dictionary" + i, serverConn)); } // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); }
public void ProvisionServer() { SqlConnection serverConn = new SqlConnection(sServerConnection); DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(sScope); DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("CUSTOMER", serverConn); scopeDesc.Tables.Add(tableDesc); DbSyncTableDescription productDescription2 = SqlSyncDescriptionBuilder.GetDescriptionForTable("MOB", serverConn); scopeDesc.Tables.Add(productDescription2); SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); if (!serverProvision.ScopeExists(sScope)) { serverProvision.Apply(); } }
void provsisonDB(SqlConnection clientConn) { try { DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("CardsScope"); // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("cards", clientConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); } catch (Exception exc) { Console.WriteLine(exc.ToString()); logger.Error(exc.ToString()); } }
/// <summary> /// Configure the SqlSyncprovider. Note that this method assumes you have a direct /// conection to the server as this is more of a design time use case vs. runtime /// use case. We think of provisioning the server as something that occurs before /// an application is deployed whereas provisioning the client is somethng that /// happens during runtime (on intitial sync) after the application is deployed. /// </summary> /// <param name="hostName"></param> /// <returns></returns> public SqlSyncProvider ConfigureSqlSyncProvider(string scopeName) { var provider = new SqlSyncProvider(); provider.ScopeName = scopeName; provider.Connection = new SqlConnection(conString); provider.ObjectSchema = "dbo"; // create anew scope description and add the appropriate tables to this scope var scopeDesc = new DbSyncScopeDescription(scopeName); // class to be used to provision the scope defined above var serverConfig = new SqlSyncScopeProvisioning((SqlConnection)provider.Connection); serverConfig.ObjectSchema = "dbo"; //determine if this scope already exists on the server and if not go ahead //and provision if (!serverConfig.ScopeExists(scopeName)) { // note that it is important to call this after the tables have been added // to the scope serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); //provision the server serverConfig.Apply(); } return(provider); }
/// <summary> /// Configure the SqlSyncprovider. Note that this method assumes you have a direct conection /// to the server as this is more of a design time use case vs. runtime use case. We think /// of provisioning the server as something that occurs before an application is deployed whereas /// provisioning the client is somethng that happens during runtime (on intitial sync) after the /// application is deployed. /// /// </summary> /// <param name="hostName"></param> /// <returns></returns> public SqlSyncProvider ConfigureSqlSyncProvider(string scopeName, string hostName) { SqlSyncProvider provider = new SqlSyncProvider(); provider.ApplyChangeFailed += new EventHandler <DbApplyChangeFailedEventArgs>(Provider_ApplyingChanges); provider.ScopeName = scopeName; SqlConn conn = new SqlConn(); provider.Connection = new SqlConnection(conn.connString); MakeBackUp(); //create anew scope description and add the appropriate tables to this scope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("CardsScope"); //class to be used to provision the scope defined above SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning((SqlConnection)provider.Connection); //determine if this scope already exists on the server and if not go ahead and provision if (!serverConfig.ScopeExists("CardsScope")) { //add the approrpiate tables to this scope scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("[" + conn.schema + "].[cards]", (System.Data.SqlClient.SqlConnection)provider.Connection)); //note that it is important to call this after the tables have been added to the scope serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); //provision the server serverConfig.Apply(); } conn.close(); return(provider); }
public static void ProvisionTableOnProvider(string pScopeName, string pTableName, string pProviderConnectionString) { try { // connect to server database SqlConnection serverConn = new SqlConnection(pProviderConnectionString); // connection string for Eskimos test // SqlConnection serverConn = new SqlConnection("Data Source=q6.2eskimos.com; Initial Catalog=EskLeeTest; uid=test ; pwd=test1test"); // define a new scope named ProductsScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(pScopeName); // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(pTableName, serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); serverProvision.Apply(); } catch (Exception e) { string tempErrorMessage = "There was an exception whilst creating a provider provision: " + e; Debug.WriteLine(tempErrorMessage); Logs.ProvisioningLog.WriteLine(tempErrorMessage); throw e; } }
public void ProvisionServer(SqlConnection serverConnection = null) { var serverConn = serverConnection ?? SqlConnectionFactory.DefaultServerConnection; var deprovisionScope = new SqlSyncScopeDeprovisioning(serverConn); deprovisionScope.DeprovisionScope("FullScope"); // define a new scope var scopeDesc = new DbSyncScopeDescription("FullScope"); // add the table description to the sync scope definition foreach (var table in DbInfo.Tables) //TODO: view (oder JOINs) synchronisieren? scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable(table.Name, serverConn)); //TODO: Server-Event feuern sobald ein Client synchronisiert // create a server scope provisioning object based on the ProductScope var serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting); // start the provisioning process if (!serverProvision.ScopeExists(scopeDesc.ScopeName)) serverProvision.Apply(); }
public static bool ConfigureSqlSyncProvider(ProvisionStruct provisionStruct) { SqlSyncProvider provider = null; bool returnVal = false; try { provider = new SqlSyncProvider(); provider.ScopeName = provisionStruct.scopeName; provider.Connection = new SqlConnection(provisionStruct.connectionString); //create a new scope description and add the appropriate tables to this scope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(provider.ScopeName); if (provisionStruct.tableNames != null) { foreach (var tableName in provisionStruct.tableNames) { var info = SqlSyncDescriptionBuilder.GetDescriptionForTable(tableName, (SqlConnection)provider.Connection); //FixPrimaryKeysForTable(info); scopeDesc.Tables.Add(info); } } //class to be used to provision the scope defined above SqlSyncScopeProvisioning serverConfig = null; serverConfig = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)provider.Connection); if (serverConfig.ScopeExists(provisionStruct.scopeName)) { return(false); } if (!serverConfig.ScopeExists(provisionStruct.scopeName)) { //note that it is important to call this after the tables have been added to the scope serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); //provision the server serverConfig.Apply(); returnVal = true; } } catch { throw; } finally { //provider.Dispose(); } return(returnVal); }
static void Main(string[] args) { SqlConnection serverConn = new SqlConnection(@"Data Source=.\SQL2008; Initial Catalog=SyncDB; Integrated Security=true"); DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("ProductsScope"); DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("Products", serverConn); scopeDesc.Tables.Add(tableDesc); SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); serverProvision.Apply(); }
//Get Data From Client Provision public static void ProvisionClient() { SqlConnection serverConn = new SqlConnection(sServerConnection); SqlConnection clientConn = new SqlConnection(sClientConnection); //Drop scope_Info Table string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='scope_info') DROP table scope_info"; clientConn.Open(); SqlCommand cmd = new SqlCommand(cmdText, clientConn); cmd.ExecuteScalar(); clientConn.Close(); List <string> tables = new List <string>(); // tables.Add("Accounts"); // Add Tables in List // tables.Add("Drinks"); // tables.Add("Roles"); // tables.Add("Tables"); tables.Add("Toppings"); var scopeDesc = new DbSyncScopeDescription("MainScope"); foreach (var tbl in tables) //Add Tables in Scope { scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable(tbl, clientConn)); } SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc); //Provisioning //skip creating the user tables clientProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); //skip creating the change tracking tables clientProvision.SetCreateTrackingTableDefault(DbSyncCreationOption.Skip); //skip creating the change tracking triggers clientProvision.SetCreateTriggersDefault(DbSyncCreationOption.Skip); //skip creating the insert/update/delete/selectrow SPs including those for metadata clientProvision.SetCreateProceduresDefault(DbSyncCreationOption.Skip); //create new SelectChanges SPs for selecting changes for the new scope //the new SelectChanges SPs will have a guid suffix clientProvision.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create); clientProvision.Apply(); }
static void Main(string[] args) { SqlConnection serverConn = new SqlConnection(@"Data Source=.\SQL2008; Initial Catalog=SyncDB; Integrated Security=true"); DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("OrdersScope-NC"); DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("Orders", serverConn); scopeDesc.Tables.Add(tableDesc); SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); serverProvision.Tables["Orders"].AddFilterColumn("OriginState"); serverProvision.Tables["Orders"].FilterClause = "[side].[OriginState] = 'NC'"; serverProvision.Apply(); }
protected virtual void ProvisionSyncScope(SqlSyncScopeProvisioning serverProvision, string syncScope, ICollection <string> syncTables, SqlConnection serverConnect, SqlSyncScopeProvisioningType provisionType) { // Create a sync scope if it is not existed yet if (!string.IsNullOrEmpty(syncScope) && syncTables != null && syncTables.Any()) { // Check if the sync scope or template exists if (provisionType == SqlSyncScopeProvisioningType.Scope && serverProvision.ScopeExists(syncScope)) { return; } if (provisionType == SqlSyncScopeProvisioningType.Template && serverProvision.TemplateExists(syncScope)) { return; } // Define a new sync scope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(syncScope); // Generate and add table descriptions to the sync scope foreach (string tblName in syncTables) { // Get the description of a specific table DbSyncTableDescription tblDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(tblName, serverConnect); // add the table description to the sync scope scopeDesc.Tables.Add(tblDesc); } // Set the scope description from which the database should be provisioned serverProvision.PopulateFromScopeDescription(scopeDesc); if (provisionType == SqlSyncScopeProvisioningType.Template) { serverProvision.ObjectSchema = "Sync"; // apply dynamic filters ApplyDynamicFilters(serverProvision, syncScope); } else { // apply static filters ApplyStaticFilters(serverProvision, syncScope); } // Indicate that the base table already exists and does not need to be created serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); serverProvision.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create); // start the provisioning process serverProvision.Apply(); } }
static void Main(string[] args) { // Defines the sync scope name const string scopeName = "UserScope"; // Creates a connexion to the server database. string SqlConnString = @"Data Source='.\SQLEXPRESS';Initial Catalog=gtd;Integrated Security=True"; SqlConnection serverConn = new SqlConnection(SqlConnString); // Remove the previous scope from the Sql Server database (no support for updating a scope). SqlSyncScopeDeprovisioning sqlDepro = new SqlSyncScopeDeprovisioning(serverConn); sqlDepro.DeprovisionScope(scopeName); // Defines a new synchronization scope named UserScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scopeName); // Gets the description of the Users table from the gtd database DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("Users", serverConn); // Adds the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); // Gets the description of the other tables from the gtd base and add them to the sync scope. DbSyncTableDescriptionCollection otherTables = new DbSyncTableDescriptionCollection(); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Tasks", serverConn)); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Lists", serverConn)); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Projects", serverConn)); //otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Tasks_Lists", serverConn)); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Tasks_Tasks", serverConn)); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Lists_Tasks", serverConn)); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Projects_Tasks", serverConn)); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Projects_Lists", serverConn)); otherTables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Projects_Lists_Tasks", serverConn)); foreach (var table in otherTables) { scopeDesc.Tables.Add(table); } // Creates a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // Skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // Starts the provisioning process serverProvision.Apply(); }
private void AprovicionarAmbito(DbSyncScopeDescription Ambito, SqlSyncScopeProvisioning proveedorDeAmbito) { if (proveedorDeAmbito.ScopeExists(Ambito.ScopeName)) { Loguear("El ambito " + Ambito.ScopeName + " ya existe!!"); } else { Loguear("Se va a crear el ambito " + Ambito.ScopeName); proveedorDeAmbito.PopulateFromScopeDescription(Ambito); proveedorDeAmbito.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting); proveedorDeAmbito.Apply(); Loguear("Se creo el ambito " + Ambito.ScopeName); } }
private void setupScopeToolStripMenuItem_Click(object sender, EventArgs e) { #if (DEBUG) SqlConnection clientConn = new SqlConnection(Program.str_debug_clientConn); #else SqlConnection clientConn = new SqlConnection(Program.str_release_clientConn); #endif SqlConnection serverConn = new SqlConnection(Program.str_serverConn); // define a new scope named PayPalSyncScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("PayPalSyncScope"); // get the description of the tblpaypal table from SERVER database DbSyncTableDescription tblpaypalDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("tblpaypal", serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tblpaypalDesc); // create a server scope provisioning object based on the PayPalSyncScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); Console.WriteLine("Server Successfully Provisioned."); // get the description of SyncScope from the server database DbSyncScopeDescription scopeDesc2 = SqlSyncDescriptionBuilder.GetDescriptionForScope("PayPalSyncScope", serverConn); // create server provisioning object based on the SyncScope SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc2); // starts the provisioning process clientProvision.Apply(); DialogResult result = DotNetPerls.BetterDialog.ShowDialog( "Trans2Summa3060", //titleString "Client and Server Successfully Provisioned.", //bigString null, //smallString null, //leftButton "OK", //rightButton global::Trans2Summa3060.Properties.Resources.Message_info); //iconSet }
/// <summary> /// Configure the SqlSyncprovider. Note that this method assumes you have a direct conection /// to the server as this is more of a design time use case vs. runtime use case. We think /// of provisioning the server as something that occurs before an application is deployed whereas /// provisioning the client is somethng that happens during runtime (on intitial sync) after the /// application is deployed. /// /// </summary> /// <param name="hostName"></param> /// <returns></returns> public SqlSyncProvider ConfigureSqlSyncProvider(string hostName) { SqlSyncProvider provider = new SqlSyncProvider(); provider.ScopeName = SyncUtils.ScopeName; provider.Connection = new SqlConnection(SyncUtils.GenerateSqlConnectionString(hostName, SyncUtils.FirstPeerDBName, null, null, true)); //create a new scope description and add the appropriate tables to this scope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(SyncUtils.ScopeName); //class to be used to provision the scope defined above SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)provider.Connection); //determine if this scope already exists on the server and if not go ahead and provision //Note that provisioning of the server is oftentimes a design time scenario and not something //that would be exposed into a client side app as it requires DDL permissions on the server. //However, it is demonstrated here for purposes of completentess. // //Note the default assumption is that SQL Server is installed as localhost. If it's not, //please replace Environment.MachineName with the correct instance name in //SqlSharingForm.SqlSharingForm_Shown(). if (!serverConfig.ScopeExists(SyncUtils.ScopeName)) { //add the approrpiate tables to this scope scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("orders", (System.Data.SqlClient.SqlConnection)provider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("order_details", (System.Data.SqlClient.SqlConnection)provider.Connection)); //note that it is important to call this after the tables have been added to the scope serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); //provision the server serverConfig.Apply(); } //Register the BatchSpooled and BatchApplied events. These are fired when a provider is either enumerating or applying changes in batches. provider.BatchApplied += new EventHandler <DbBatchAppliedEventArgs>(provider_BatchApplied); provider.BatchSpooled += new EventHandler <DbBatchSpooledEventArgs>(provider_BatchSpooled); return(provider); }
public static void SetUp(string _pTableName) { // Connection to SQL Server database SqlConnection serverConn = new SqlConnection(ServerConnString); // Connection to SQL client database SqlConnection clientConn = new SqlConnection(ClientConnString); // Create a scope named "product" and add tables to it. Console.WriteLine(_pTableName); DbSyncScopeDescription productScope = new DbSyncScopeDescription(_pTableName + "_SCOP"); // Define the Products table. DbSyncTableDescription productDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable(_pTableName, serverConn); // Add the Table to the scope object. productScope.Tables.Add(productDescription); // Create a provisioning object for "product" and apply it to the on-premise database if one does not exist. SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, productScope); serverProvision.ObjectSchema = ".dbo"; serverProvision.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create); serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); serverProvision.SetCreateProceduresDefault(DbSyncCreationOption.CreateOrUseExisting); serverProvision.SetCreateTrackingTableDefault(DbSyncCreationOption.CreateOrUseExisting); serverProvision.SetCreateTriggersDefault(DbSyncCreationOption.CreateOrUseExisting); if (!serverProvision.ScopeExists(_pTableName + "_SCOP")) { serverProvision.Apply(); } // Provision the SQL client database from the on-premise SQL Server database if one does not exist. SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, productScope); if (!clientProvision.ScopeExists(_pTableName + "_SCOP")) { clientProvision.Apply(); } // Shut down database connections. serverConn.Close(); serverConn.Dispose(); clientConn.Close(); clientConn.Dispose(); }
/// <summary> /// Configure the SqlSyncprovider. Note that this method assumes you have a direct conection /// to the server as this is more of a design time use case vs. runtime use case. We think /// of provisioning the server as something that occurs before an application is deployed whereas /// provisioning the client is somethng that happens during runtime (on intitial sync) after the /// application is deployed. /// /// </summary> /// <param name="hostName"></param> /// <returns></returns> public SqlSyncProvider ConfigureSqlSyncProvider(string hostName) { SqlSyncProvider provider = new SqlSyncProvider(); provider.ScopeName = SyncUtils.ScopeName; SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(); builder.DataSource = hostName; builder.IntegratedSecurity = true; builder.InitialCatalog = "peer1"; builder.ConnectTimeout = 1; provider.Connection = new SqlConnection(builder.ToString()); //create a new scope description and add the appropriate tables to this scope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(SyncUtils.ScopeName); //class to be used to provision the scope defined above SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)provider.Connection); //determine if this scope already exists on the server and if not go ahead and provision if (!serverConfig.ScopeExists(SyncUtils.ScopeName)) { //add the approrpiate tables to this scope scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("orders", (System.Data.SqlClient.SqlConnection)provider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("order_details", (System.Data.SqlClient.SqlConnection)provider.Connection)); //note that it is important to call this after the tables have been added to the scope serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); //provision the server serverConfig.Apply(); } //Register the BatchSpooled and BatchApplied events. These are fired when a provider is either enumerating or applying changes in batches. provider.BatchApplied += new EventHandler <DbBatchAppliedEventArgs>(provider_BatchApplied); provider.BatchSpooled += new EventHandler <DbBatchSpooledEventArgs>(provider_BatchSpooled); return(provider); }
//Set Data To Server Provision public static void ProvisionServer() { SqlConnection serverConn = new SqlConnection(sServerConnection); string cmdText = @"IF EXISTS(SELECT * FROM INFORMATION_SCHEMA.TABLES WHERE TABLE_NAME='scope_info') DROP table scope_info"; serverConn.Open(); SqlCommand cmd = new SqlCommand(cmdText, serverConn); cmd.ExecuteScalar(); serverConn.Close(); List <string> tables = new List <string>(); // tables.Add("Accounts"); // Add Tables in List // tables.Add("Drinks"); // tables.Add("Roles"); // tables.Add("Tables"); tables.Add("Toppings"); var scopeDesc = new DbSyncScopeDescription("MainScope"); foreach (var tbl in tables) { scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable(tbl, serverConn)); } SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // Create Provision From All Tables //skip creating the user tables serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); //skip creating the change tracking tables serverProvision.SetCreateTrackingTableDefault(DbSyncCreationOption.Skip); //skip creating the change tracking triggers serverProvision.SetCreateTriggersDefault(DbSyncCreationOption.Skip); //skip creating the insert/update/delete/selectrow SPs including those for metadata serverProvision.SetCreateProceduresDefault(DbSyncCreationOption.Skip); serverProvision.Apply(); }
private void ApplyProvision(DbSynchronizerConfiguration configuration, Action <DbSyncScopeDescription> defineScope) { using (var connection = new SqlConnection(configuration.ConnectionString)) { var provision = new SqlSyncScopeProvisioning(connection) { ObjectPrefix = configuration.ObjectPrefix ?? string.Empty, ObjectSchema = configuration.ObjectSchema ?? string.Empty, }; if (!provision.ScopeExists(configuration.ScopeName)) { var scopeDescription = new DbSyncScopeDescription(configuration.ScopeName); defineScope(scopeDescription); provision.SetCreateTableDefault(DbSyncCreationOption.Skip); provision.PopulateFromScopeDescription(scopeDescription); provision.Apply(); } } }
void provsisonDB(SqlConnection serverConn) { DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("CardsScope"); // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("cards", serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); }
private static bool ProvisionSqlServer(SqlConnection con, Scope scope) { var sqlProv = new SqlSyncScopeProvisioning(con); sqlProv.ObjectSchema = prefix; if (!sqlProv.ScopeExists(scope.ToScopeString())) { var scopeDescr = new DbSyncScopeDescription(scope.ToScopeString()); AddTablesToScopeDescr(scope.ToTableNames(), scopeDescr, con); sqlProv.PopulateFromScopeDescription(scopeDescr); sqlProv.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting); sqlProv.Apply(); return(true); } return(false); }
/// <summary> /// Cài đặt Sync SCOPE ở database chỉ định, /// yêu cầu bắt buộc phải có cấu trúc CSDL trước, /// Nếu Server có Scope trùng tên rồi thì không làm gì cả /// </summary> /// <param name="connectionString"></param> /// <param name="scopeName"></param> /// <param name="tracking_tables"></param> public static int setup_sync_scope(String connectionString, String scope_name, String[] tracking_tables) { SqlConnection serverConn = new SqlConnection(connectionString); try { DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scope_name); // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = null; foreach (String item in tracking_tables) { //parse tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(item, serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); } // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); return(1); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return(-1); } finally { serverConn.Dispose(); } }
/// <summary> /// Configure the SqlSyncprovider. Note that this method assumes you have a direct conection /// to the server as this is more of a design time use case vs. runtime use case. We think /// of provisioning the server as something that occurs before an application is deployed whereas /// provisioning the client is somethng that happens during runtime (on intitial sync) after the /// application is deployed. /// /// </summary> /// <param name="hostName"></param> /// <returns></returns> public SqlSyncProvider ConfigureSqlSyncProvider(string ScopeName, string serverConnectionString, Guid clientId) { SqlSyncProvider provider = new SqlSyncProvider(); provider.ScopeName = ScopeName; provider.Connection = new SqlConnection(); provider.Connection.ConnectionString = serverConnectionString; DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(ScopeName); SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)provider.Connection); if (!serverConfig.ScopeExists(ScopeName)) { serverConfig.ObjectSchema = "dbo."; scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Client", (System.Data.SqlClient.SqlConnection)provider.Connection)); serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); serverConfig.Tables["Client"].AddFilterColumn("ClientId"); serverConfig.Tables["Client"].FilterClause = "[side].[ClientId] = '" + clientId + "'"; //Create new selectchanges procedure for our scope serverConfig.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create); //provision the server serverConfig.Apply(); } //Register the BatchSpooled and BatchApplied events. These are fired when a provider is either enumerating or applying changes in batches. provider.BatchApplied += new EventHandler <DbBatchAppliedEventArgs>(provider_BatchApplied); provider.BatchSpooled += new EventHandler <DbBatchSpooledEventArgs>(provider_BatchSpooled); return(provider); }
static void Main(string[] args) { SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=SyncDB; Integrated Security=True"); // define a new scope named ProductsScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("ProductsScope"); // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("Products", serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); }
/// <summary> /// Configure the SqlSyncprovider. Note that this method assumes you have a direct conection /// to the server as this is more of a design time use case vs. runtime use case. We think /// of provisioning the server as something that occurs before an application is deployed whereas /// provisioning the client is somethng that happens during runtime (on intitial sync) after the /// application is deployed. /// /// </summary> /// <param name="hostName"></param> /// <returns></returns> public SqlSyncProvider ConfigureSqlSyncProvider(string ScopeName, string serverConnectionString, Guid clientId) { SqlSyncProvider provider = new SqlSyncProvider(); provider.ScopeName = ScopeName; provider.Connection = new SqlConnection(); provider.Connection.ConnectionString = serverConnectionString; DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(ScopeName); SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)provider.Connection); if (!serverConfig.ScopeExists(ScopeName)) { serverConfig.ObjectSchema = "dbo."; scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Client", (System.Data.SqlClient.SqlConnection)provider.Connection)); serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); serverConfig.Tables["Client"].AddFilterColumn("ClientId"); serverConfig.Tables["Client"].FilterClause = "[side].[ClientId] = '" + clientId + "'"; //Create new selectchanges procedure for our scope serverConfig.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create); //provision the server serverConfig.Apply(); } //Register the BatchSpooled and BatchApplied events. These are fired when a provider is either enumerating or applying changes in batches. provider.BatchApplied += new EventHandler<DbBatchAppliedEventArgs>(provider_BatchApplied); provider.BatchSpooled += new EventHandler<DbBatchSpooledEventArgs>(provider_BatchSpooled); return provider; }
private static void ProvisioningRemote() { var connectionRemote = new SqlConnection(@"Data Source=davamixsample.database.windows.net;Initial Catalog=sampleDB;Integrated Security=False;User ID=davamix;Password=Aztroline13;Connect Timeout=60;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False"); var descriptionScope = new DbSyncScopeDescription("ProductScope"); var tableDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable("SalesLT.Product", connectionRemote); descriptionScope.Tables.Add(tableDescription); var provisionRemote = new SqlSyncScopeProvisioning(connectionRemote, descriptionScope); provisionRemote.SetCreateTableDefault(DbSyncCreationOption.Skip); try { provisionRemote.Apply(); } catch (Exception ex) { Console.WriteLine($"[ERROR] {ex.Message}"); throw; } }
private static void Main(string[] args) { SyncOrchestrator sync = new SyncOrchestrator(); string scopeName = "test"; SqlConnection localData = new SqlConnection(@"Data Source=nipun;Initial Catalog=ClientData;Integrated Security=True;"); SqlConnection serverData = new SqlConnection(@"Data Source=nipun;Initial Catalog=ServerData;Integrated Security=True;"); SqlSyncProvider localProvider = new SqlSyncProvider(scopeName, localData); SqlSyncProvider serverProvider = new SqlSyncProvider(scopeName, serverData); SqlSyncScopeProvisioning scopeProvisionLocal = new SqlSyncScopeProvisioning(localData); if (!scopeProvisionLocal.ScopeExists(scopeName)) { DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scopeName); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("abc", localData)); scopeProvisionLocal.PopulateFromScopeDescription(scopeDesc); scopeProvisionLocal.SetCreateTableDefault(DbSyncCreationOption.Skip); scopeProvisionLocal.Apply(); } SqlSyncScopeProvisioning scopeProvisionRemote = new SqlSyncScopeProvisioning(serverData); if (!scopeProvisionRemote.ScopeExists(scopeName)) { DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(scopeName, localData); scopeProvisionRemote.PopulateFromScopeDescription(scopeDesc); scopeProvisionRemote.Apply(); } SqlSyncScopeProvisioning romve = new SqlSyncScopeProvisioning(localData); sync.LocalProvider = localProvider; sync.RemoteProvider = serverProvider; SyncOperationStatistics stats = sync.Synchronize(); Console.WriteLine("Update Data:\t\t {0}", stats.UploadChangesApplied); Console.WriteLine("Update Data ChangesFailed:\t\t {0}", stats.UploadChangesFailed); Console.WriteLine("Update Data Changes:\t\t {0}", stats.UploadChangesTotal); Console.ReadLine(); }
static void Main(string[] args) { string strscopename = Properties.Settings.Default["ScopeName"].ToString(); string strserverConn = Properties.Settings.Default["serverConn"].ToString(); string strsyncTableEID = Properties.Settings.Default["syncTableEID"].ToString(); string strsyncTableVL = Properties.Settings.Default["syncTableVL"].ToString(); try { // connect to server database (The Public IP) SqlConnection serverConn = new SqlConnection(strserverConn); // define a new scope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(strscopename); // get the description of the VLSummaryReport table from SERVER database DbSyncTableDescription syncTableEID = SqlSyncDescriptionBuilder.GetDescriptionForTable(strsyncTableEID, serverConn); DbSyncTableDescription syncTableVL = SqlSyncDescriptionBuilder.GetDescriptionForTable(strsyncTableVL, serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(syncTableEID); scopeDesc.Tables.Add(syncTableVL); // create a server scope provisioning object based on the VLSyncScopeAlert SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); serverProvision.Apply(); Console.WriteLine("Server Successfully Provisioned."); Console.ReadLine(); } catch (Exception ex) { Console.WriteLine(ex.Message + ex.Data.ToString()); Console.ReadLine(); } }
static void Main(string[] args) { SqlConnection serverConn = new SqlConnection(@"Data Source=localhost; Initial Catalog=G:\htmlconvertsql\match_analysis_pdm.mdf; Integrated Security=True"); // define a new scope named ProductsScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("match_analysisScope"); string[] tableList = new string[]{ "live_Aibo", "live_okoo", "live_Table", "live_Table_lib", "match_analysis_collection", "match_analysis_result", "match_table_xpath", "result_tb", "result_tb_lib"}; DbSyncTableDescription tableDesc; for (int i = 0; i < tableList.Length; i++) { // get the description of the Products table from SyncDB dtabase tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(tableList[i], serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); } // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); }
static void Main(string[] args) { // 服务器连接. // connect to server database SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=SyncDB; Integrated Security=True"); // 定义一个 同步范围 // define a new scope named ProductsScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("ProductsScope"); // 同步范围 增加一个表. // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("Products", serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); // 将同步范围定义的信息,更新到数据库上面去. // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); // 该应用程序,运行完毕后, 会在 服务器上面, 创建这些表: // Products_Tracking, schema_info, scope_config, scope_info }
public void refreshServerScope(int SellerID) { //define Scope DbSyncScopeDescription currentDesc = new DbSyncScopeDescription(DbInfo.ScopeName(SellerID)); //add the tables to the scope discription (defined in DBTable) foreach (DbTable table in DbInfo.Tables) currentDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable(table.Name,table.Columns, ServerCON)); // create a server scope provisioning object SqlSyncScopeProvisioning Provision = new SqlSyncScopeProvisioning(ServerCON, currentDesc); // so use the Skip parameter Provision.SetCreateTableDefault(DbSyncCreationOption.Skip); // set the filter column on the Orders table to OriginState Provision.Tables["sellers"].AddFilterColumn("ID"); // set the filter value to NC Provision.Tables["sellers"].FilterClause = "[side].[ID] != 2"; //Provision.Tables["sellers"].ObjectSchema refreshScope(Provision,currentDesc, ServerCON); if (!Provision.ScopeExists(currentDesc.ScopeName)) Provision.Apply(); }
public static void CreateDatabaseProvision(SqlConnection serverConn, SqlCeConnection clientConn, string scopeName) { DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scopeName); DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(scopeName.Replace("Scope", ""), serverConn); scopeDesc.Tables.Add(tableDesc); SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); if (!serverProvision.ScopeExists(scopeName)) { serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); serverProvision.Apply(); } SqlCeSyncScopeProvisioning clientProvision = new SqlCeSyncScopeProvisioning(clientConn, scopeDesc); if (!clientProvision.ScopeExists(scopeName)) { clientProvision.Apply(); } }
private void AprovicionarAmbito(DbSyncScopeDescription Ambito, SqlSyncScopeProvisioning proveedorDeAmbito) { if (proveedorDeAmbito.ScopeExists(Ambito.ScopeName)) { this.loguear("El ambito " + Ambito.ScopeName + " ya existe!! Inicio:\t" + DateTime.Now); } else { this.loguear("Se va a crear el ambito " + Ambito.ScopeName + " Inicio:\t" + DateTime.Now); proveedorDeAmbito.PopulateFromScopeDescription(Ambito); proveedorDeAmbito.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting); proveedorDeAmbito.Apply(); this.loguear("Se creo el ambito " + Ambito.ScopeName + " fin:\t" + DateTime.Now); } }
/// <summary> /// Cài đặt Sync SCOPE ở database chỉ định, /// yêu cầu bắt buộc phải có cấu trúc CSDL trước, /// Nếu Server có Scope trùng tên rồi thì không làm gì cả /// </summary> /// <param name="connectionString"></param> /// <param name="scopeName"></param> /// <param name="tracking_tables"></param> public static int setup_sync_scope(String connectionString, String scope_name, String[] tracking_tables) { SqlConnection serverConn = new SqlConnection(connectionString); try { DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scope_name); // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = null; foreach (String item in tracking_tables) { //parse tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(item, serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); } // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); return 1; } catch (Exception ex) { Debug.WriteLine(ex.ToString()); return -1; } finally { serverConn.Dispose(); } }
public static void ProvisionDatabase(SqlConnection destination, SqlConnection master, string scopeName, string srid) { bool oneway = false; if (scopeName == "OneWay") { oneway = true; } bool isSlave = false; if (!destination.ConnectionString.Equals(master.ConnectionString)) { isSlave = true; } DbSyncScopeDescription scopeDescription = new DbSyncScopeDescription(scopeName); SqlSyncScopeProvisioning destinationConfig = new SqlSyncScopeProvisioning(destination); if (destinationConfig.ScopeExists(scopeName)) { return; } // TODO: Retrieve actual sync tables IList<SpatialColumnInfo> twowaytableList = new List<SpatialColumnInfo>(); twowaytableList.Add(new SpatialColumnInfo { TableName = "WaterJobs" }); twowaytableList.Add(new SpatialColumnInfo { TableName = "SewerJobs" }); twowaytableList.Add(new SpatialColumnInfo { TableName = "ParkAssets" }); // TODO: Retrieve actual sync tables IList<SpatialColumnInfo> onewaytableList = new List<SpatialColumnInfo>(); onewaytableList.Add(new SpatialColumnInfo { TableName = "WaterFittings" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "WaterMains" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "WaterMeters" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "WaterServices" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "SewerNodes" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "SewerPipes" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "RoadLabels" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "Cadastre" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "AddressNumbers" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "Towns" }); onewaytableList.Add(new SpatialColumnInfo { TableName = "LocalityBoundaries" }); if (isSlave) { destination.Open(); if (!oneway) { DropTables(destination, twowaytableList); } else { DropTables(destination, onewaytableList); } destination.Close(); } DbSyncColumnDescription identityColumn = null; DbSyncColumnDescription geometryColumn = null; if (!oneway) { foreach (SpatialColumnInfo spatialTable in twowaytableList) { DbSyncTableDescription table = SqlSyncDescriptionBuilder.GetDescriptionForTable(spatialTable.TableName, master); if (table.PkColumns.Count() != 1 || table.PkColumns.First().Type != "uniqueidentifier") { try { table.Columns["UniqueID"].IsPrimaryKey = true; table.PkColumns.FirstOrDefault().IsPrimaryKey = false; } catch (Exception) { throw new DataSyncException("Tables require a column called 'UniqueID' of type 'uniqueidentifier' to be used with spatial syncing." + "\nThe UniqueID column should also have a default value of newid() and a UNIQUE, NONCLUSTERED index."); } } foreach (DbSyncColumnDescription item in table.NonPkColumns) { if (item.AutoIncrementStepSpecified) { identityColumn = item; spatialTable.IdentityColumn = item.UnquotedName; continue; } if (!item.Type.Contains("geometry")) { continue; } spatialTable.GeometryColumn = item.UnquotedName; geometryColumn = item; geometryColumn.ParameterName += "_was_geometry"; geometryColumn.Type = "nvarchar"; geometryColumn.Size = "max"; geometryColumn.SizeSpecified = true; } if (geometryColumn == null || identityColumn == null) { throw new DataSyncException("Spatial tables must contain a geometry column and an identity column."); } table.Columns.Remove(identityColumn); if (destination.Equals(master)) { destinationConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); } else { identityColumn.IsPrimaryKey = true; destinationConfig.SetCreateTableDefault(DbSyncCreationOption.Create); } scopeDescription.Tables.Add(table); } } if (oneway) { foreach (var spatialTable in onewaytableList) { DbSyncTableDescription table = SqlSyncDescriptionBuilder.GetDescriptionForTable(spatialTable.TableName, master); spatialTable.IdentityColumn = table.PkColumns.FirstOrDefault().UnquotedName; foreach (DbSyncColumnDescription item in table.NonPkColumns) { if (!item.Type.Contains("geometry")) { continue; } spatialTable.GeometryColumn = item.UnquotedName; geometryColumn = item; geometryColumn.ParameterName += "_was_geometry"; geometryColumn.Type = "nvarchar"; geometryColumn.Size = "max"; geometryColumn.SizeSpecified = true; } if (geometryColumn == null) { throw new DataSyncException("Spatial tables must contain a geometry column and an identity column."); } scopeDescription.Tables.Add(table); } } //It is important to call this after the tables have been added to the scope destinationConfig.PopulateFromScopeDescription(scopeDescription); //provision the server destinationConfig.Apply(); destination.Open(); if (!oneway) { foreach (SpatialColumnInfo spatialTable in twowaytableList) { string tableName = spatialTable.TableName; SqlCommand command = destination.CreateCommand(); if (isSlave) { command.CommandText = string.Format("ALTER TABLE [{0}] ADD [{1}] int IDENTITY(1,1) NOT NULL", tableName, spatialTable.IdentityColumn); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] DROP CONSTRAINT PK_{0}", tableName); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT PK_{0} PRIMARY KEY CLUSTERED ([{1}])", tableName, spatialTable.IdentityColumn); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] ADD UNIQUE (UniqueID)", tableName); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [DF_{0}_UniqueID] DEFAULT (newid()) FOR [UniqueID]", tableName); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] ALTER COLUMN [{1}] geometry", tableName, spatialTable.GeometryColumn); command.ExecuteNonQuery(); command.CommandText = string.Format("CREATE SPATIAL INDEX [SIndex_{0}_{1}] ON [{0}]([{1}]) USING GEOMETRY_GRID WITH (BOUNDING_BOX =(300000, 6700000, 500000, 7000000), GRIDS =(LEVEL_1 = MEDIUM,LEVEL_2 = MEDIUM,LEVEL_3 = MEDIUM,LEVEL_4 = MEDIUM), CELLS_PER_OBJECT = 16, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]", tableName, spatialTable.GeometryColumn); command.ExecuteNonQuery(); } try { command.CommandText = string.Format("CREATE TRIGGER [dbo].[{0}_GEOMSRID_trigger]\nON [dbo].[{0}]\nAFTER INSERT, UPDATE\nAS UPDATE [dbo].[{0}] SET [{1}].STSrid = {2}\nFROM [dbo].[{0}]\nJOIN inserted\nON [dbo].[{0}].[UniqueID] = inserted.[UniqueID] AND inserted.[{1}] IS NOT NULL", spatialTable.TableName, spatialTable.GeometryColumn, srid); command.ExecuteNonQuery(); } catch (SqlException ex) { if (!ex.Message.StartsWith("There is already")) { throw; } } Server server = new Server(destination.DataSource); Database db = server.Databases[destination.Database]; foreach (StoredProcedure sp in db.StoredProcedures.Cast<StoredProcedure>().Where(sp => sp.Name.Equals(tableName + "_selectchanges", StringComparison.InvariantCultureIgnoreCase) || sp.Name.Equals(tableName + "_selectrow", StringComparison.InvariantCultureIgnoreCase))) { sp.TextBody = sp.TextBody.Replace(string.Format("[{0}]", spatialTable.GeometryColumn), string.Format("[{0}].STAsText() as [{0}]", spatialTable.GeometryColumn)); sp.Alter(); } } } else { foreach (SpatialColumnInfo spatialTable in onewaytableList) { string tableName = spatialTable.TableName; SqlCommand command = destination.CreateCommand(); if (isSlave) { command.CommandText = string.Format("ALTER TABLE [{0}] ALTER COLUMN [{1}] geometry", tableName, spatialTable.GeometryColumn); command.ExecuteNonQuery(); command.CommandText = string.Format("CREATE SPATIAL INDEX [SIndex_{0}_{1}] ON [{0}]([{1}]) USING GEOMETRY_GRID WITH (BOUNDING_BOX =(300000, 6700000, 500000, 7000000), GRIDS =(LEVEL_1 = MEDIUM,LEVEL_2 = MEDIUM,LEVEL_3 = MEDIUM,LEVEL_4 = MEDIUM), CELLS_PER_OBJECT = 16, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]", tableName, spatialTable.GeometryColumn); command.ExecuteNonQuery(); } try { command.CommandText = string.Format("CREATE TRIGGER [dbo].[{0}_GEOMSRID_trigger]\nON [dbo].[{0}]\nAFTER INSERT, UPDATE\nAS UPDATE [dbo].[{0}] SET [{1}].STSrid = {2}\nFROM [dbo].[{0}]\nJOIN inserted\nON [dbo].[{0}].[{3}] = inserted.[{3}] AND inserted.[{1}] IS NOT NULL", spatialTable.TableName, spatialTable.GeometryColumn, srid, spatialTable.IdentityColumn); command.ExecuteNonQuery(); } catch (SqlException ex) { if (!ex.Message.StartsWith("There is already")) { throw; } } Server server = new Server(destination.DataSource); Database db = server.Databases[destination.Database]; foreach (StoredProcedure sp in db.StoredProcedures.Cast<StoredProcedure>() .Where(sp => sp.Name.Equals(tableName + "_selectchanges", StringComparison.InvariantCultureIgnoreCase) || sp.Name.Equals(tableName + "_selectrow", StringComparison.InvariantCultureIgnoreCase))) { sp.TextBody = sp.TextBody.Replace(string.Format("[{0}]", spatialTable.GeometryColumn), string.Format("[{0}].STAsText() as [{0}]", spatialTable.GeometryColumn)); sp.Alter(); } } } }
public static void ProvisionTable(SqlConnection master, SqlConnection destination, string tableName, int srid, bool oneWayOnly) { bool isSlave = false; if (!destination.ConnectionString.Equals(master.ConnectionString)) { isSlave = true; } DbSyncScopeDescription scopeDescription = new DbSyncScopeDescription(tableName); SqlSyncScopeProvisioning destinationConfig = new SqlSyncScopeProvisioning(destination); if (destinationConfig.ScopeExists(tableName)) { throw new SyncConstraintConflictNotAllowedException(@"Scope already exists. Please deprovision scope first."); } DbSyncTableDescription table = SqlSyncDescriptionBuilder.GetDescriptionForTable(tableName, master); DbSyncColumnDescription uniqueColumn = table.Columns.Where(f => f.Type == "uniqueidentifier").FirstOrDefault(); DbSyncColumnDescription geometryColumn = table.Columns.Where(f => f.Type.EndsWith("geometry")).FirstOrDefault(); DbSyncColumnDescription identityColumn = table.Columns.Where(f => f.AutoIncrementStepSpecified).FirstOrDefault(); DbSyncColumnDescription joinColumn = table.PkColumns.FirstOrDefault(); if (table.PkColumns.Count() != 1) { throw new SyncException(@"Table must have a single primary key column to be used with synchronisation."); } if (uniqueColumn != null && !uniqueColumn.IsPrimaryKey && !oneWayOnly) { table.PkColumns.FirstOrDefault().IsPrimaryKey = false; uniqueColumn.IsPrimaryKey = true; joinColumn = uniqueColumn; } if (geometryColumn != null) { geometryColumn.ParameterName += "_was_geometry"; geometryColumn.Type = "nvarchar"; geometryColumn.Size = "max"; geometryColumn.SizeSpecified = true; } if (identityColumn != null && identityColumn != joinColumn) { table.Columns.Remove(identityColumn); } destinationConfig.SetCreateTableDefault(isSlave ? DbSyncCreationOption.Create : DbSyncCreationOption.Skip); scopeDescription.Tables.Add(table); //It is important to call this after the tables have been added to the scope destinationConfig.PopulateFromScopeDescription(scopeDescription); //provision the server destinationConfig.Apply(); destination.Open(); SqlCommand command = destination.CreateCommand(); if (isSlave && identityColumn != null && identityColumn != joinColumn) { command.CommandText = string.Format("ALTER TABLE [{0}] ADD {1} int IDENTITY(1,1) NOT NULL", tableName, identityColumn.QuotedName); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] DROP CONSTRAINT PK_{0}", tableName); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT PK_{0} PRIMARY KEY CLUSTERED ({1})", tableName, identityColumn.QuotedName); command.ExecuteNonQuery(); } if (uniqueColumn != null && isSlave && uniqueColumn == joinColumn) { command.CommandText = string.Format("ALTER TABLE [{0}] ADD UNIQUE ({1})", tableName, uniqueColumn.QuotedName); command.ExecuteNonQuery(); command.CommandText = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [DF_{0}_{2}] DEFAULT (newid()) FOR {1}", tableName, uniqueColumn.QuotedName, uniqueColumn.UnquotedName.Replace(' ', '_')); command.ExecuteNonQuery(); } if (geometryColumn == null) { return; } if (isSlave) { command.CommandText = string.Format("ALTER TABLE [{0}] ALTER COLUMN {1} geometry", tableName, geometryColumn.QuotedName); command.ExecuteNonQuery(); try { command.CommandText = string.Format("CREATE SPATIAL INDEX [ogr_{2}_sidx] ON [{0}]({1}) USING GEOMETRY_GRID WITH (BOUNDING_BOX =(300000, 6700000, 500000, 7000000), GRIDS =(LEVEL_1 = MEDIUM,LEVEL_2 = MEDIUM,LEVEL_3 = MEDIUM,LEVEL_4 = MEDIUM), CELLS_PER_OBJECT = 16, PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]", tableName, geometryColumn.QuotedName, geometryColumn.UnquotedName); command.ExecuteNonQuery(); } catch (SqlException sqlException) { if (!sqlException.Message.Contains("already exists")) { throw; } } } command.CommandText = string.Format("IF EXISTS (SELECT * FROM sys.triggers WHERE object_id = OBJECT_ID(N'[dbo].[{0}_GEOMSRID_trigger]')) DROP TRIGGER [dbo].[{0}_GEOMSRID_trigger]", tableName); command.ExecuteNonQuery(); command.CommandText = string.Format("CREATE TRIGGER [dbo].[{0}_GEOMSRID_trigger]\nON [dbo].[{0}]\nAFTER INSERT, UPDATE\nAS UPDATE [dbo].[{0}] SET [{1}].STSrid = {2}\nFROM [dbo].[{0}]\nJOIN inserted\nON [dbo].[{0}].{3} = inserted.{3} AND inserted.[{1}] IS NOT NULL", tableName, geometryColumn.UnquotedName, srid, joinColumn.QuotedName); command.ExecuteNonQuery(); Server server = new Server(destination.DataSource); Database db = server.Databases[destination.Database]; foreach (StoredProcedure sp in db.StoredProcedures.Cast<StoredProcedure>().Where(sp => sp.Name.Equals(tableName + "_selectchanges", StringComparison.InvariantCultureIgnoreCase) || sp.Name.Equals(tableName + "_selectrow", StringComparison.InvariantCultureIgnoreCase))) { sp.TextBody = sp.TextBody.Replace(geometryColumn.QuotedName, string.Format("{0}.STAsText() as {0}", geometryColumn.QuotedName)); sp.Alter(); } }
public bool Sync(SqlConnection clientConnection) { // ServerSideSync String scope = "VideoScope"; SqlSyncProvider serverProvider = new SqlSyncProvider(); serverProvider.ScopeName = scope; serverProvider.Connection = new SqlConnection(); serverProvider.Connection.ConnectionString = @"Data Source = (localdb)\MSSQLLocalDB; Initial Catalog = MoviesDB; Integrated Security = True; Connect Timeout = 30; Encrypt = False; TrustServerCertificate = True; ApplicationIntent = ReadWrite; MultiSubnetFailover = False"; //Config of the Scope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scope); SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning((System.Data.SqlClient.SqlConnection)serverProvider.Connection); if (!serverConfig.ScopeExists(scope)) { serverProvider.ObjectSchema = "dbo."; scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Actor", (System.Data.SqlClient.SqlConnection)serverProvider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Director", (System.Data.SqlClient.SqlConnection)serverProvider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Genre", (System.Data.SqlClient.SqlConnection)serverProvider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("Movie", (System.Data.SqlClient.SqlConnection)serverProvider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieActor", (System.Data.SqlClient.SqlConnection)serverProvider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieDirector", (System.Data.SqlClient.SqlConnection)serverProvider.Connection)); scopeDesc.Tables.Add(SqlSyncDescriptionBuilder.GetDescriptionForTable("MovieGenre", (System.Data.SqlClient.SqlConnection)serverProvider.Connection)); serverConfig.PopulateFromScopeDescription(scopeDesc); //indicate that the base table already exists and does not need to be created serverConfig.SetCreateTableDefault(DbSyncCreationOption.Skip); //provision the server serverConfig.Apply(); } //ClientSideSyncserverConfig // create the sync orhcestrator SyncOrchestrator syncOrchestrator = new SyncOrchestrator(); syncOrchestrator.LocalProvider = serverProvider; // set the remote provider of orchestrator to a server sync provider associated with // the ProductsScope in the SyncDB server database syncOrchestrator.RemoteProvider = new SqlSyncProvider(scope, clientConnection); // set the direction of sync session to Upload and Download syncOrchestrator.Direction = SyncDirectionOrder.Upload; // execute the synchronization process SyncOperationStatistics syncStats = syncOrchestrator.Synchronize(); // print statistics Console.WriteLine("Start Time: " + syncStats.SyncStartTime); Console.WriteLine("Total Changes Uploaded: " + syncStats.UploadChangesTotal); Console.WriteLine("Total Changes Downloaded: " + syncStats.DownloadChangesTotal); Console.WriteLine("Complete Time: " + syncStats.SyncEndTime); Console.WriteLine(String.Empty); return(false); }
public static void ServerProvision() { if (serverConn.State == ConnectionState.Closed) serverConn.Open(); List<string> tables = new List<string>(); DataTable dt = serverConn.GetSchema("Tables"); foreach (DataRow row in dt.Rows) { string tablename = (string)row[2]; if (tablename == "SystemIdsSet") continue; tables.Add(tablename); } // define a new scope named ProductsScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("AllSyncScope"); foreach (string table in tables) { // get the description of the Products table from SyncDB dtabase DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(table, serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(tableDesc); } // create a server scope provisioning object based on the ProductScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); }
//TODO: run for all required tables public void setServer() { // define a new scope named MySyncScope DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription("MySyncScope"); // get the description of the CUSTOMER & PRODUCT table from SERVER database DbSyncTableDescription questionsTableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("questions", serverConn); DbSyncTableDescription answersTableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("answers", serverConn); // add the table description to the sync scope definition scopeDesc.Tables.Add(questionsTableDesc); scopeDesc.Tables.Add(answersTableDesc); // create a server scope provisioning object based on the MySyncScope SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc); // skipping the creation of table since table already exists on server serverProvision.SetCreateTableDefault(DbSyncCreationOption.Skip); // start the provisioning process serverProvision.Apply(); Console.WriteLine("Server Successfully Provisioned."); Console.ReadLine(); }