Example #1
0
        internal void Deprovision(SyncDatabase db, SqlConnection connection, DbSyncScopeDescription scopeDesc)
        {
            this.GetDescriptionForTables(db.Tables, connection, ref scopeDesc);

            var provision = new SqlSyncScopeProvisioning(connection, scopeDesc);

            if (provision.ScopeExists(scopeDesc.ScopeName))
            {
                try
                {
                    var deprovision = new SqlSyncScopeDeprovisioning(connection);

                    Log.Info("[DistributedDb] Deprovision Scope [" + scopeDesc.ScopeName + "] Start", this);

                    deprovision.DeprovisionScope(scopeDesc.ScopeName);

                    Log.Info("[DistributedDb] Deprovision Scope [" + scopeDesc.ScopeName + "] End", this);
                }
                catch (Exception ex)
                {
                    Log.Error("[DistributedDb] Deprovision Scope [" + scopeDesc.ScopeName + "] Error", ex, this);
                }
            }
            else
            {
                Log.Info("[DistributedDb] Deprovision Scope [" + scopeDesc.ScopeName + "] Skipped", this);
            }
        }
Example #2
0
        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();
        }
Example #3
0
        internal void Provision(SyncDatabase db, SqlConnection connection, DbSyncScopeDescription scopeDesc)
        {
            var provision = new SqlSyncScopeProvisioning(connection, scopeDesc);

            if (!provision.ScopeExists(scopeDesc.ScopeName))
            {
                try
                {
                    Log.Info("[DistributedDb] Provision Scope [" + scopeDesc.ScopeName + "] Start", this);

                    provision.SetCreateTableDefault(DbSyncCreationOption.Skip);
                    provision.CommandTimeout = 3600;
                    provision.Apply();

                    Log.Info("[DistributedDb] Provision Scope [" + scopeDesc.ScopeName + "] End", this);
                }
                catch (Exception ex)
                {
                    Log.Error("[DistributedDb] Provision Scope [" + scopeDesc.ScopeName + "] Error", ex, this);
                }
            }
            else
            {
                Log.Info("[DistributedDb] Provision Scope [" + scopeDesc.ScopeName + "] Skipped", this);
            }
        }
 private static void Initialize
     (string table,
     string serverConnectionString,
     string clientConnectionString)
 {
     try
     {
         using (SqlConnection serverConnection = new
                                                 SqlConnection(serverConnectionString))
         {
             using (SqlConnection clientConnection = new
                                                     SqlConnection(clientConnectionString))
             {
                 DbSyncScopeDescription scopeDescription = new
                                                           DbSyncScopeDescription(table);
                 DbSyncTableDescription tableDescription =
                     SqlSyncDescriptionBuilder.GetDescriptionForTable(table,
                                                                      serverConnection);
                 scopeDescription.Tables.Add(tableDescription);
                 SqlSyncScopeProvisioning serverProvision = new
                                                            SqlSyncScopeProvisioning(serverConnection,
                                                                                     scopeDescription);
                 serverProvision.Apply();
                 SqlSyncScopeProvisioning clientProvision = new
                                                            SqlSyncScopeProvisioning(clientConnection,
                                                                                     scopeDescription);
                 clientProvision.Apply();
             }
         }
     }
     catch (Exception ex)
     {
         Common.WriteLog(System.DateTime.Now.ToString() + ": " + ex.ToString());
     }
 }
Example #5
0
        public void CreateScopeDescription(DbSyncScopeDescription scopeDescription)
        {
            Log("CreateScopeDescription: {0}", this.peerProvider.Connection.ConnectionString);
            SqlSyncScopeProvisioning prov = new SqlSyncScopeProvisioning((SqlConnection)this.peerProvider.Connection, scopeDescription);

            prov.Apply();
        }
        public DbSyncScopeDescription GetScopeDescription(string scopeName, string serverConnectionString)
        {
            this.peerProvider.Connection.ConnectionString = serverConnectionString;
            DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(scopeName, (SqlConnection)this.dbProvider.Connection);

            return(scopeDesc);
        }
Example #7
0
        static void Main(string[] args)
        {
            // 客户端的连接.
            // create a connection to the SyncExpressDB database
            SqlConnection clientConn = new SqlConnection(@"Data Source=.\SQLEXPRESS; Initial Catalog=SyncExpressDB; Trusted_Connection=Yes");

            // 服务端的连接.
            // create a connection to the SyncDB server database
            SqlConnection serverConn = new SqlConnection("Data Source=localhost; Initial Catalog=SyncDB; Integrated Security=True");

            // 从 服务器上, 获取 同步范围的数据.
            // get the description of ProductsScope from the SyncDB server database
            DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope("ProductsScope", serverConn);


            // 将同步范围的数据, 写入到客户端.
            // create server provisioning object based on the ProductsScope
            SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc);

            // starts the provisioning process
            clientProvision.Apply();


            // 该应用程序,运行完毕后, 会在 SQL Server Express 服务器上面, 创建这些表:
            // Products, Products_Tracking, schema_info, scope_config, scope_info
        }
Example #8
0
        private DbClientSync InitiateSyncScope(string scopeName, DbSyncScopeDescription scopeDescription, SyncDirectionOrder syncDirection)
        {
            Type type = Type.GetType(AppConfig.DbClientSyncClass);

            if (type == null)
            {
                FotoShoutUtils.Log.LogManager.Error(_logger, "The type of the database client sync is not supported.");
                return(null);
            }

            DbClientSync clientSync = (DbClientSync)Activator.CreateInstance(type);

            // clientSync.ServerConnection = AppConfig.ServerConnection;
            clientSync.ServerScopeDescription = scopeDescription;
            clientSync.Configure(AppConfig.SyncAction, scopeName, AppConfig.ClientConnection);

            if (string.IsNullOrEmpty(AppConfig.SyncAction) || AppConfig.SyncAction.Equals(FotoShoutUtils.Constants.ASV_SYNCACTION_PROVISION, StringComparison.InvariantCultureIgnoreCase))
            {
                // Asign sync direction
                clientSync.SyncDirection = syncDirection;

                // Register event handlers for db sync
                FotoShoutUtils.Log.LogManager.Info(_logger, "Registering event handlers for database sync parties...");
                clientSync.ApplyChangeFailed += new ApplyChangeFailedEventHandler(OnDbApplyChangeFailed);
                clientSync.ItemConflicting   += new FotoShoutUtils.Sync.Db.ItemConflictingEventHandler(OnDbItemConflicting);
                clientSync.ItemConstraint    += new FotoShoutUtils.Sync.Db.ItemConstraintEventHandler(OnDbItemConstraint);
                FotoShoutUtils.Log.LogManager.Info(_logger, "Successfully registered event handlers for database sync parties...");

                return(clientSync);
            }

            return(null);
        }
Example #9
0
        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();
            }
        }
Example #10
0
        //FilteringSqlServerSync sqlServerSync = null;

        private bool InitializePhotoSyncProviders(EventTDO ev, string scopeName, string[] staticSyncTables, string[] dynamicSyncTables)
        {
            if (string.IsNullOrEmpty(AppConfig.PhotoDbServerSyncClass))
            {
                FotoShoutUtils.Log.LogManager.Error(_logger, "The type of the database server upload sync need to be defined in app config.");
                return(false);
            }

            //sqlServerSync = new FilteringSqlServerSync();
            //sqlServerSync.Configure(AppConfig.SyncAction, scopeName, AppConfig.ServerConnection, staticSyncTables, dynamicSyncTables);

            _sqlPhotoServerSync = new SqlServerSyncProviderProxy(AppConfig.SyncAction, scopeName, AppConfig.ServerConnection, staticSyncTables, dynamicSyncTables, AppConfig.PhotoDbServerSyncClass, SyncEngine.WFC_SERVICE_SQLSERVER);
            FotoShoutUtils.Log.LogManager.Info(_logger, "Server Upload Sync - " + _sqlPhotoServerSync.Ping());

            DbSyncScopeDescription scopeDescription = _sqlPhotoServerSync.GetScopeDescription(scopeName);

            //DbSyncScopeDescription scopeDescription = sqlServerSync.GetScopeDescription(scopeName);
            _sqlPhotoClientSync = InitiateSyncScope(scopeName, scopeDescription, (SyncDirectionOrder)Enum.Parse(typeof(SyncDirectionOrder), AppConfig.PhotoSyncDirection));
            if (_sqlPhotoClientSync != null)
            {
                _sqlPhotoClientSync.Synchronized += new FotoShoutUtils.Sync.Db.SynchronizedEventHandler(OnDbUploadSynchronized);
            }

            return(_sqlPhotoClientSync != null);
        }
 public bool compareDescriptions(DbSyncScopeDescription desc1, DbSyncScopeDescription desc2)
 {
     bool res;
     if (desc1.Tables.Count != desc2.Tables.Count) return false;
     DbSyncTableDescription table2;
     foreach (DbSyncTableDescription table1 in desc1.Tables)
     {
         res = false;
         for (int j = 0; j < desc2.Tables.Count; j++)
         {
             if (desc2.Tables[j].LocalName == table1.LocalName)
             {
                 res = true;
                 table2 = desc2.Tables[j];
                 if (table1.LocalName != table2.LocalName) return false;
                 if (table1.Columns.Count != table2.Columns.Count) return false;
                 for (int i = 0; i < table1.Columns.Count; i++)
                 {
                     if (table1.Columns[i].QuotedName != table2.Columns[i].QuotedName) return false;
                     if (table1.Columns[i].Size != table2.Columns[i].Size) return false;
                     if (table1.Columns[i].Type != table2.Columns[i].Type) return false;
                     if (table1.Columns[i].IsNullable != table2.Columns[i].IsNullable) return false;
                     if (table1.Columns[i].IsPrimaryKey != table2.Columns[i].IsPrimaryKey) return false;
                 }
             }
         }
         if (!res) return false;
     }
     return true;
 }
        private void ActualizarAnclaDeSincronizacion(int anclaActual, DbSyncScopeDescription ambito, IDbConnection conexionLocalSql)
        {
            string tablaAnclas = ObtenerNombreTablaAnclas();

            int    ultimaAnclaDeSincronizacion = ObtenerUltimaAnclaDeSincronizacion(ambito, conexionLocalSql);
            string comando = "";

            if (ultimaAnclaDeSincronizacion >= 0)
            {
                comando = "update " + tablaAnclas + " set  last_anchor_sync = " + anclaActual +
                          ", last_sync_datetime = getdate() where sync_scope_name = '" + ambito.ScopeName + "'" +
                          " and sync_remote_DataBase_name = '" + _nombreDeBaseRemota + "'";
            }
            else
            {
                comando = "insert into " + tablaAnclas +
                          " ( sync_scope_name, last_anchor_sync, last_sync_datetime, sync_remote_DataBase_name ) values " +
                          "('" + ambito.ScopeName + "'," + anclaActual.ToString() + ", getdate(), '" + _nombreDeBaseRemota + "' )";
            }

            using (SqlCommand consulta = new SqlCommand(comando, (SqlConnection)conexionLocalSql))
            {
                consulta.ExecuteNonQuery();
            }
        }
Example #13
0
        static void Main(string[] args)
        {
            string strscopename  = Properties.Settings.Default["ScopeName"].ToString();
            string strclientConn = Properties.Settings.Default["clientConn"].ToString();
            string strserverConn = Properties.Settings.Default["serverConn"].ToString();

            try
            {
                SqlConnection clientConn = new SqlConnection(@strclientConn);
                SqlConnection serverConn = new SqlConnection(@strserverConn);

                // Obtain the description of VLSummaryReport table from the server using the scope name
                DbSyncScopeDescription   scopeDesc       = SqlSyncDescriptionBuilder.GetDescriptionForScope(strscopename, serverConn);
                SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc);

                clientProvision.CommandTimeout = 180000;
                clientProvision.Apply();
                Console.WriteLine("Client Successfully Provisioned.");
                Console.ReadLine();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.Data.ToString());
                Console.ReadLine();
            }
        }
Example #14
0
        private static bool ProvisionSqlCe(SqlCeConnection con, Scope scope, DbConnection conToGetScopeDescr)
        {
            var sqlceProv = new SqlCeSyncScopeProvisioning(con);

            sqlceProv.ObjectPrefix = prefix;

            if (!sqlceProv.ScopeExists(scope.ToScopeString()))
            {
                var scopeDescr   = new DbSyncScopeDescription(scope.ToScopeString());
                var failedTables = AddTablesToScopeDescr(scope.ToTableNames(), scopeDescr, con);

                if (failedTables.Count > 0 && conToGetScopeDescr != null)
                {
                    Poster.PostMessage("GetScopeDescription for scope '{0}' from '{1}'", scope.ToScopeString(), conToGetScopeDescr.ConnectionString);
                    //use scope description from server to intitialize the client
                    scopeDescr = GetScopeDescription(scope, conToGetScopeDescr);
                }

                sqlceProv.PopulateFromScopeDescription(scopeDescr);

                sqlceProv.SetCreateTableDefault(DbSyncCreationOption.CreateOrUseExisting);
                sqlceProv.Apply();
                return(true);
            }
            return(false);
        }
Example #15
0
        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();
        }
        /// <summary>
        /// Check to see if the passed in  SqlSyncProvider needs Schema from server
        /// </summary>
        /// <param name="localProvider"></param>
        private void CheckIfProviderNeedsSchema(SqlSyncProvider localProvider)
        {
            if (localProvider != null)
            {
                SqlConnection            conn      = (SqlConnection)localProvider.Connection;
                SqlSyncScopeProvisioning sqlConfig = new SqlSyncScopeProvisioning(conn);
                string scopeName = localProvider.ScopeName;

                //if the scope does not exist in this store
                if (!sqlConfig.ScopeExists(scopeName))
                {
                    //create a reference to the server proxy
                    SqlSyncProviderProxy serverProxy = new SqlSyncProviderProxy("CardsScope",
                                                                                connString);

                    //retrieve the scope description from the server
                    DbSyncScopeDescription scopeDesc = serverProxy.GetScopeDescription();

                    serverProxy.Dispose();

                    //use scope description from server to intitialize the client
                    sqlConfig.PopulateFromScopeDescription(scopeDesc);
                    sqlConfig.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();
        }
Example #18
0
        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;
            }
        }
Example #19
0
        public static void ProvisionTableOnClient(string pScopeName, string pProviderConnectionString, string pClientConnectionString)
        {
            try
            {
                // create a connection to the SyncExpressDB database
                SqlConnection clientConn = new SqlConnection(pClientConnectionString);

                // create a connection to the SyncDB 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");

                // get the description of ProductsScope from the SyncDB server database
                DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(pScopeName, serverConn);

                // create server provisioning object based on the ProductsScope
                SqlSyncScopeProvisioning clientProvision = new SqlSyncScopeProvisioning(clientConn, scopeDesc);

                // starts the provisioning process
                clientProvision.Apply();
            }
            catch (Exception e)
            {
                string tempErrorMessage = "There was an exception whilst creating a client 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();
        }
Example #21
0
        private void ProvisionServer(string TableName)
        {
            try
            {
                // define a new scope named tableNameScope
                DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(TableName + _filter);
                // get the description of the tableName
                DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(TableName, _serverConnection);

                // add the table description to the sync scope definition
                scopeDesc.Tables.Add(tableDesc);

                // create a server scope provisioning object based on the tableNameScope
                SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(_serverConnection, scopeDesc);

                // start the provisioning process
                if (!serverProvision.ScopeExists(scopeDesc.ScopeName))
                {
                    serverProvision.Apply();
                    //Console.WriteLine("Server " + TableName + " was provisioned.");
                    Log.WriteLogs("Server " + TableName + " was provisioned.");
                }
                else
                {
                    //Console.WriteLine("Server " + TableName + " was already provisioned.");
                    Log.WriteLogs("Server " + TableName + " was already provisioned.");
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLogs(ex);
            }
        }
        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();
        }
        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();
        }
        private bool ElAmbitoTieneNovedades(DbSyncScopeDescription ambito, IDbConnection conexionLocalSql)
        {
            bool retorno = false;

            string tablaAnclas = ObtenerNombreTablaAnclas();
            int    anclaDeLaUltimaSincronizacion = ObtenerUltimaAnclaDeSincronizacion(ambito, conexionLocalSql);

            string     procedimientoAlmacenado = ambito.Tables[0].UnquotedGlobalName + "_selectchanges";
            SqlCommand cmd = new SqlCommand(procedimientoAlmacenado, (SqlConnection)conexionLocalSql)
            {
                CommandType = CommandType.StoredProcedure
            };

            cmd.Parameters.Add(new SqlParameter("@sync_min_timestamp", anclaDeLaUltimaSincronizacion));
            cmd.Parameters.Add(new SqlParameter("@sync_scope_local_id", 1));
            cmd.Parameters.Add(new SqlParameter("@sync_scope_restore_count", 1));
            cmd.Parameters.Add(new SqlParameter("@sync_update_peer_key", 1));

            SqlDataReader rdr = cmd.ExecuteReader();

            retorno = rdr.HasRows;
            rdr.Close();
            if (!retorno)
            {
                Loguear("El ambito: " + ambito.ScopeName + " no tiene novedades desde el ancla: " + anclaDeLaUltimaSincronizacion);
            }

            return(retorno);
        }
Example #25
0
        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());
            }
        }
Example #26
0
 protected override void DefineRemoteScope(DbSyncScopeDescription scopeDescription)
 {
     using (var connection = new SqlConnection(RemoteConfiguration.ConnectionString))
     {
         DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("currencies", connection);
         tableDesc.GlobalName = "currencies";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("products", connection);
         tableDesc.GlobalName = "products";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("product_cost", connection);
         tableDesc.GlobalName = "product_cost";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("certifications", connection);
         tableDesc.GlobalName = "certifications";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("certification_copies", connection);
         tableDesc.GlobalName = "certification_copies";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("appendix", connection);
         tableDesc.GlobalName = "appendix";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("appendix_series", connection);
         tableDesc.GlobalName = "appendix_series";
         scopeDescription.Tables.Add(tableDesc);
     }
 }
Example #27
0
 protected override void DefineLocalScope(DbSyncScopeDescription scopeDescription)
 {
     using (var connection = new SqlConnection(LocalConfiguration.ConnectionString))
     {
         DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable("obk_currencies", connection);
         tableDesc.GlobalName = "currencies";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("obk_products", connection);
         tableDesc.GlobalName = "products";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("obk_product_cost", connection);
         tableDesc.GlobalName = "product_cost";
         //tableDesc.Columns.Remove(tableDesc.Columns["cost_tenge"]);
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("obk_certifications", connection);
         tableDesc.GlobalName = "certifications";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("obk_certification_copies", connection);
         tableDesc.GlobalName = "certification_copies";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("obk_appendix", connection);
         tableDesc.GlobalName = "appendix";
         scopeDescription.Tables.Add(tableDesc);
         tableDesc            = SqlSyncDescriptionBuilder.GetDescriptionForTable("obk_appendix_series", connection);
         tableDesc.GlobalName = "appendix_series";
         scopeDescription.Tables.Add(tableDesc);
     }
 }
Example #28
0
        /// <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);
        }
        private void MantenerAprovisionamientoDeAmbitosEnHilos(ParametrosReplica parametros, string esquemaMetadataSyncFramework, string prefijoMetadataSyncFramework, List <DbSyncScopeDescription> Ambitos)
        {
            if (!(parametros.DesaprovisionarAmbitosEnServidorLocal || parametros.AprovisionarAmbitosEnServidorLocal || parametros.DesaprovisionarAmbitosEnServidorRemoto || parametros.AprovisionarAmbitosEnServidorRemoto))
            {
                return;
            }
            _semaphore = new Semaphore(parametros.HilosParaAprovisionar, parametros.HilosParaAprovisionar);

            foreach (DbSyncScopeDescription ambito in Ambitos)
            {
                DbSyncScopeDescription LocalAmbito = ambito;

                Thread t = new Thread(() =>
                {
                    MantenerAprovisionamientoDeAmbitos(parametros, esquemaMetadataSyncFramework, prefijoMetadataSyncFramework, LocalAmbito);
                });
                HilosEnEjecucion.Add(t);
                t.Start();
            }

            var threadCount = 1;

            while (threadCount > 0)
            {
                Thread.Sleep(500);
                threadCount = HilosEnEjecucion.FindAll(x => x.IsAlive).Count;
            }
        }
Example #30
0
        /// <summary>
        /// Kiểm tra có SCOPE chưa
        /// </summary>
        /// <param name="connectionString"></param>
        /// <param name="scope_name"></param>
        /// <returns></returns>
        public static int isHasScope(String connectionString, String scope_name, String[] tracking_tables)
        {
            SqlConnection serverConn = new SqlConnection(connectionString);

            if (!isExist(serverConn))
            {
                return(-1);
            }

            try
            {
                // define a new scope named ProductsScope
                DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(scope_name);
                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);
                }
                SqlSyncScopeProvisioning tmp = new SqlSyncScopeProvisioning(serverConn, scopeDesc);
                return(tmp.ScopeExists(scope_name)?1:-1);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
                return(-1);
            }
        }
Example #31
0
        /// <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);
        }
Example #32
0
        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);
        }
Example #33
0
        public DbSyncScopeDescription GetScopeDescription()
        {
            Log("GetSchema: {0}", this.peerProvider.Connection.ConnectionString);

            DbSyncScopeDescription scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(SyncUtils.ScopeName, (SqlConnection)this.dbProvider.Connection);

            return(scopeDesc);
        }
        private DbSyncScopeDescription CrearAmbito(String nombreDeAmbito, string TablaDentroDelAmbito, IDbConnection conexionSql)
        {
            DbSyncScopeDescription Ambito             = new DbSyncScopeDescription(nombreDeAmbito);
            DbSyncTableDescription descripcionDeTabla = SqlSyncDescriptionBuilder.GetDescriptionForTable(TablaDentroDelAmbito, (SqlConnection)conexionSql);

            Ambito.Tables.Add(descripcionDeTabla);
            return(Ambito);
        }
Example #35
0
        private static void Setup()
        {
            try
            {
                SqlConnection sqlServerConn = new SqlConnection(SqlLocalConnectionString); 
                SqlConnection sqlAzureConn = new SqlConnection(SqlAzureConnectionString);
                DbSyncScopeDescription myscope = new DbSyncScopeDescription(scopeName);

                DbSyncTableDescription Patient = SqlSyncDescriptionBuilder.GetDescriptionForTable("Patient", sqlServerConn);
                //DbSyncTableDescription Album = SqlSyncDescriptionBuilder.GetDescriptionForTable("Album", sqlServerConn);

                //Add the tables from above to scope
                myscope.Tables.Add(Patient);
                //   myscope.Tables.Add(Album);

                #region Setup Sql Server for sync
               
                SqlSyncScopeProvisioning sqlServerProv = new SqlSyncScopeProvisioning(sqlServerConn, myscope);
                if (!sqlServerProv.ScopeExists(scopeName))
                {
                    //Aapply the scope provisioning.
                    Console.WriteLine("Provisioning SQL Server for sync " + DateTime.Now);
                    sqlServerProv.Apply();
                    Console.WriteLine("Done Provisioning SQL Server for sync " + DateTime.Now);
                }
                else
                    Console.WriteLine("SQL Server Database server already provisioned for sync " + DateTime.Now);

                #endregion

                #region Setup Sql Azure for sync
                SqlSyncScopeProvisioning sqlAzureProv = new SqlSyncScopeProvisioning(sqlAzureConn, myscope);
                if (!sqlAzureProv.ScopeExists(scopeName))
                {
                    //Aapply the scope provisioning.
                    Console.WriteLine("Provisioning SQL Azure for sync " + DateTime.Now);
                    sqlAzureProv.Apply();
                    Console.WriteLine("Done Provisioning SQL Azure for sync " + DateTime.Now);
                }
                else
                    Console.WriteLine("SQL Azure Database server already provisioned for sync " + DateTime.Now);


                #endregion

                sqlAzureConn.Close();
                sqlServerConn.Close();
                

            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                
            }
        }
Example #36
0
 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();
 }
        private CodeCompileUnit GenerateSyncServiceCompileUnit(string prefix, string nameSpace, DbSyncScopeDescription desc)
        {
            CodeCompileUnit cc = new CodeCompileUnit();

            CodeNamespace scopeNs = new CodeNamespace(nameSpace);

            // Generate the SyncService<T> definition type.
            CodeTypeDeclaration wrapperEntity = new CodeTypeDeclaration(
                string.Format(Constants.ServiceCustomSyncServiceTypeFormat, string.IsNullOrEmpty(prefix) ? desc.ScopeName : prefix)
                );

            CodeTypeReference baseSyncType = new CodeTypeReference(Constants.ServiceSyncServiceBaseTypeFormat);
            baseSyncType.TypeArguments.Add(string.Format(Constants.ServiceOuterEntityNameFormat, string.IsNullOrEmpty(prefix) ? desc.ScopeName : prefix));
            wrapperEntity.BaseTypes.Add(baseSyncType);

            wrapperEntity.StartDirectives.Add(new CodeRegionDirective(CodeRegionMode.Start, "SyncService: Configuration and setup"));

            // Add the method InitializeService
            CodeMemberMethod initSvcMethod = new CodeMemberMethod();
            initSvcMethod.Name = "InitializeService";
            initSvcMethod.Attributes = MemberAttributes.Public | MemberAttributes.Static;
            initSvcMethod.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(Constants.ServiceISyncSvcConfigurationType), "config"));

            // Add comments for the following lines.
            foreach (string s in Constants.ServiceSyncSvcCommentLines)
            {
                initSvcMethod.Statements.Add(new CodeCommentStatement(s));
            }

            // Set the sync object schema. This is used when creating new scopes.
            // For SQL Azure, tables have to be explicitly referenced with the schema name.
            if (!String.IsNullOrEmpty(_syncObjectSchema))
            {
                foreach (string s in Constants.ServiceSyncSvcPreSchemaCommentLines)
                {
                    initSvcMethod.Statements.Add(new CodeCommentStatement(s));
                }

                CodeMethodInvokeExpression expr =
                    new CodeMethodInvokeExpression(new CodeVariableReferenceExpression("config"), 
                                                   Constants.ServiceSyncSvcInitializeService_SetSchemaMethodFormat, 
                                                   new CodeExpression[] { new CodePrimitiveExpression(_syncObjectSchema) });

                initSvcMethod.Statements.Add(expr);
            }

            wrapperEntity.Members.Add(initSvcMethod);
            wrapperEntity.EndDirectives.Add(new CodeRegionDirective(CodeRegionMode.End, string.Empty));

            scopeNs.Types.Add(wrapperEntity);
            cc.Namespaces.Add(scopeNs);

            return cc;
        }
        /// <summary>
        /// Generates thes following entities for the service.
        /// 1. An XXXEntities.cs file that contains the SyncScope attributed collection name and all the individual Entities that make that scope.
        /// 2. An .SVC file for the sync service.
        /// 3. The .svc.[Language] code behind file for the above .svc file generated.
        /// </summary>
        /// <param name="filePrefix"></param>
        /// <param name="nameSpace"></param>
        /// <param name="desc"></param>
        /// <param name="dirInfo"></param>
        /// <param name="option"></param>
        /// <param name="colsMappingInfo"></param>
        /// <param name="serviceUri"></param>
        public override void GenerateEntities(string filePrefix, string nameSpace, DbSyncScopeDescription desc, Dictionary<string, Dictionary<string, string>> colsMappingInfo,
            System.IO.DirectoryInfo dirInfo, CodeLanguage option, string serviceUri)
        {
            CodeCompileUnit cc = GenerateEntitiesCompileUnit(filePrefix, nameSpace, desc, colsMappingInfo);

            CodeDomUtility.SaveCompileUnitToFile(cc, option, CodeDomUtility.GenerateFileName(desc.ScopeName, dirInfo, filePrefix, "Entities", option));

            cc = GenerateSyncServiceCompileUnit(filePrefix, nameSpace, desc);

            // Generate the codebehing file for .svc file
            string codeBehindFilename = CodeDomUtility.GenerateFileName(desc.ScopeName, dirInfo, filePrefix, "SyncService.svc", option);
            CodeDomUtility.SaveCompileUnitToFile(cc, option, codeBehindFilename);

            // Generate the actual .SVC file.
            CodeDomUtility.SaveSVCFile(nameSpace, cc.Namespaces[0].Types[0].Name, codeBehindFilename, CodeDomUtility.GenerateFileName(desc.ScopeName, dirInfo, filePrefix, "SyncService", CodeLanguage.SVC), option);
        }
Example #39
0
        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 static CodeCompileUnit GenerateEntitiesFile(string nameSpace, DbSyncScopeDescription desc, Dictionary<string, Dictionary<string, string>> colsMappingInfo)
        {
            CodeCompileUnit entitiesCC = new CodeCompileUnit();

            CodeNamespace entityScopeNs = new CodeNamespace(nameSpace);

            // Generate the entities
            foreach (DbSyncTableDescription table in desc.Tables)
            {
                Dictionary<string, string> curTableMapping = null;
                colsMappingInfo.TryGetValue(table.UnquotedGlobalName, out curTableMapping);
                // Generate the actual entity
                CodeTypeDeclaration entityDecl = CodeDomUtility.GetEntityForTableDescription(table, true, curTableMapping);

                // Add the base type for the entity
                entityDecl.BaseTypes.Add(new CodeTypeReference(Constants.ClientIsolatedStoreOfflineEntity));
                entityScopeNs.Types.Add(entityDecl);

                foreach (CodeTypeMember member in entityDecl.Members)
                {
                    CodeMemberProperty prop = member as CodeMemberProperty;
                    if (prop != null)
                    {
                        // For each setter add the OnPropertyChanging and OnPropertyChanged lines
                        CodeStatement stmt = prop.SetStatements[0];
                        prop.SetStatements.Clear();

                        prop.SetStatements.Add(new CodeMethodInvokeExpression(
                            new CodeBaseReferenceExpression(), 
                            Constants.ClientCallOnPropertyChanging, 
                            new CodeSnippetExpression(string.Format(Constants.StringifyProperty, prop.Name)))
                            );
                        prop.SetStatements.Add(stmt);
                        prop.SetStatements.Add(new CodeMethodInvokeExpression(
                            new CodeBaseReferenceExpression(),
                            Constants.ClientCallOnPropertyChanged,
                            new CodeSnippetExpression(string.Format(Constants.StringifyProperty, prop.Name)))
                            );
                    }
                }
            }

            entitiesCC.Namespaces.Add(entityScopeNs);
            return entitiesCC;
        }
Example #41
0
        public bool SetupLocalServer()
        {
            var myscope = new DbSyncScopeDescription(_scopeName);
            var patient = SqlSyncDescriptionBuilder.GetDescriptionForTable("Patient", _sqlServerConn);
            myscope.Tables.Add(patient);

            var sqlServerProv = new SqlSyncScopeProvisioning(_sqlServerConn, myscope);

            if (!sqlServerProv.ScopeExists(_scopeName))
            {
                sqlServerProv.Apply();
                _sqlServerConn.Close();
                return true;
            }

            _sqlServerConn.Close();
            return false;
        }
        /// <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 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();
        }
Example #44
0
        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();
        }
Example #45
0
        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();
        }
Example #46
0
        private static DbSyncScopeDescription GetDbSyncScopeDescription(SelectedConfigSections selectedConfig)
        {
            DbSyncScopeDescription desc = new DbSyncScopeDescription(selectedConfig.SelectedSyncScope.Name);

            using (SqlConnection conn = new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()))
            {
                conn.Open();
                foreach (SyncTableConfigElement table in selectedConfig.SelectedSyncScope.SyncTables)
                {
                    DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(table.Name, conn);

                    // Ensure all specified columns do belong to the table on the server.
                    foreach (SyncColumnConfigElement colElem in table.SyncColumns)
                    {
                        if (tableDesc.Columns.Where((e) => e.UnquotedName.Equals(colElem.Name, StringComparison.OrdinalIgnoreCase)).FirstOrDefault() == null)
                        {
                            throw new InvalidOperationException(string.Format("Table '{0}' does not have a column '{1}' defined in the target database. Please check your SyncColumn definitions",
                                table.Name, colElem.Name));
                        }
                    }

                    List<DbSyncColumnDescription> columnsToRemove = new List<DbSyncColumnDescription>();

                    // Mark timestamp columns for removal
                    columnsToRemove.AddRange(tableDesc.Columns.Where(
                        e => ((SqlDbType)Enum.Parse(typeof(SqlDbType), e.Type, true)) == SqlDbType.Timestamp)
                        );

                    if (!table.IncludeAllColumns || table.SyncColumns.Count > 0)
                    {
                        //Users wants a subset of columns. Remove the ones they are not interested in
                        foreach (DbSyncColumnDescription columnDesc in tableDesc.Columns)
                        {
                            SyncColumnConfigElement configElement = table.SyncColumns.Cast<SyncColumnConfigElement>().FirstOrDefault((e) => e.Name.Equals(columnDesc.UnquotedName, StringComparison.InvariantCultureIgnoreCase));
                            if (configElement == null)
                            {
                                // Found a column that was not specified by the user. Remove it
                                columnsToRemove.Add(columnDesc);
                            }
                            else
                            {
                                columnDesc.IsNullable = configElement.IsNullable;
                                columnDesc.IsPrimaryKey = configElement.IsPrimaryKey;
                            }
                        }
                    }

                    // Remove columns marked for removal
                    columnsToRemove.ForEach((e) => tableDesc.Columns.Remove(e));

                    // Check to see that columns count is greater than 0
                    if (tableDesc.Columns.Count == 0)
                    {
                        throw new InvalidOperationException(
                            string.Format("SyncTable '{0}' has zero SyncColumns configured for sync. Either set IncludeAllColumns to true or specify atleast one SyncColumn.", table.Name));
                    }

                    // Fill in global name
                    if (!string.IsNullOrEmpty(table.GlobalName))
                    {
                        tableDesc.GlobalName = table.GlobalName;
                    }

                    desc.Tables.Add(tableDesc);
                }
            }

            return desc;
        }
        protected void loguearEstadisticas(SyncOperationStatistics estadisticas, DbSyncScopeDescription ambito)
        {
            string message = "";
            message = message + "\n\rEstadisticas de la replica de Sync Framework ambito " + ambito.ScopeName + " cant. tablas: " + ambito.Tables.Count + "";
            message = message + "\n\r\tHora de inicio:\t" + estadisticas.SyncStartTime.ToString();
            message = message + "\n\r\tHora de fin:\t" + estadisticas.SyncEndTime.ToString();
            message = message + "\n\r\tSubida cambios aplicados\t:" + estadisticas.UploadChangesApplied.ToString();
            message = message + "\n\r\tSubida cambios c/error\t:" + estadisticas.UploadChangesFailed.ToString();
            message = message + "\n\r\tSubida cambios Total\t:" + estadisticas.UploadChangesTotal.ToString();
            message = message + "\n\r\tBajada cambios aplicados\t:" + estadisticas.DownloadChangesApplied.ToString();
            message = message + "\n\r\tBajada cambios c/error\t:" + estadisticas.DownloadChangesFailed.ToString();
            message = message + "\n\r\tBajada cambios Total\t:" + estadisticas.DownloadChangesTotal.ToString();

            this.loguear("Estadisticas", message);
        }
        private void refreshScope(SqlSyncScopeProvisioning Provision, DbSyncScopeDescription currentDesc, SqlConnection CON)
        {
            // start the provisioning process
            if (Provision.ScopeExists(currentDesc.ScopeName))
            {
                DbSyncScopeDescription dbDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(currentDesc.ScopeName, CON);

                MessageBox.Show(currentDesc.Tables[0].Columns[1].QuotedName + ": " + currentDesc.Tables[0].Columns[1].Type + " <" + currentDesc.Tables[0].Columns[1].Size + ">\n" +
                    dbDesc.Tables[0].Columns[1].QuotedName + ": " + dbDesc.Tables[0].Columns[1].Type + " <" + dbDesc.Tables[0].Columns[1].Size + ">"
                    );

                if (!compareDescriptions(currentDesc, dbDesc) || true)
                {
                    if (MessageBox.Show("The Scope '" + currentDesc.ScopeName + "' is out of sync with the Database!\nShould the Scope be rewritten?\nWarning:\nAll Scope-Data (Trigger etc.) will be lost!",
                        "Warning,   Scope is invalid!", MessageBoxButtons.YesNo, MessageBoxIcon.Stop) == DialogResult.Yes)
                    {
                        SqlSyncScopeDeprovisioning DeProvision = new SqlSyncScopeDeprovisioning(CON);
                        DeProvision.DeprovisionScope(currentDesc.ScopeName);

                    }
                }
            }
        }
        private void ActualizarAnclaDeSincronizacion(int anclaActual, DbSyncScopeDescription ambito)
        {
            string tablaAnclas = this.ObtenerNombreTablaAnclas();

            int ultimaAnclaDeSincronizacion = this.ObtenerUltimaAnclaDeSincronizacion(ambito);
            string comando = "";
            if ( ultimaAnclaDeSincronizacion >= 0)
            {

                comando = "update " + tablaAnclas + " set  last_anchor_sync = " + anclaActual +
                        ", last_sync_datetime = getdate() where sync_scope_name = '" + ambito.ScopeName + "'" +
                         " and sync_remote_DataBase_name = '" + this.nombreDeBaseRemota + "'";

            }
            else
            {
                comando = "insert into " + tablaAnclas +
                    " ( sync_scope_name, last_anchor_sync, last_sync_datetime, sync_remote_DataBase_name ) values " +
                    "('" + ambito.ScopeName + "'," + anclaActual.ToString() + ", getdate(), '" + this.nombreDeBaseRemota + "' )";

            }

            using (SqlCommand consulta = new SqlCommand(comando, this.conexionLocalSql))
            {
                consulta.ExecuteNonQuery();
            }
        }
        private static CodeCompileUnit GenerateContextFile(string prefix, string nameSpace, DbSyncScopeDescription desc, string serviceUri)
        {
            CodeCompileUnit contextCC = new CodeCompileUnit();

            CodeNamespace ctxScopeNs = new CodeNamespace(nameSpace);

            // Generate the outer most entity
            CodeTypeDeclaration wrapperEntity = new CodeTypeDeclaration(
                string.Format(Constants.ClientContextClassNameFormat, string.IsNullOrEmpty(prefix) ? desc.ScopeName : prefix)
                );

            // Add SQLiteContext base type
            wrapperEntity.BaseTypes.Add(Constants.SQLiteContextBaseType);

            #region Generate the GetSchema method
            CodeMemberMethod getSchemaMethod = new CodeMemberMethod();
            getSchemaMethod.Name = Constants.ClientIsolatedStoreGetSchemaMethodName;
            getSchemaMethod.Attributes = MemberAttributes.Private | MemberAttributes.Final | MemberAttributes.Static;
            getSchemaMethod.ReturnType = new CodeTypeReference(Constants.SQLiteSchemaBaseType);

            // Add the line 'OfflineSchema schema = new OfflineSchema ()'
            CodeVariableDeclarationStatement initSchemaStmt = new CodeVariableDeclarationStatement(Constants.SQLiteSchemaBaseType, "schema");
            initSchemaStmt.InitExpression = new CodeObjectCreateExpression(Constants.SQLiteSchemaBaseType);
            getSchemaMethod.Statements.Add(initSchemaStmt);

            #endregion

            // Generate the entities
            foreach (DbSyncTableDescription table in desc.Tables)
            {
                string tableName = CodeDomUtility.SanitizeName(table.UnquotedGlobalName);
                CodeTypeReference icollReference = new CodeTypeReference(typeof(IEnumerable<>));

                // Generate the private field
                CodeTypeReference entityReference = new CodeTypeReference(tableName);
                icollReference.TypeArguments.Clear();
                icollReference.TypeArguments.Add(entityReference);

                #region Add this entity to the GetSchema method
                CodeMethodInvokeExpression expr = new CodeMethodInvokeExpression();
                expr.Method = new CodeMethodReferenceExpression();
                expr.Method.TargetObject = new CodeVariableReferenceExpression("schema");
                expr.Method.MethodName = "AddCollection";
                expr.Method.TypeArguments.Add(tableName);
                getSchemaMethod.Statements.Add(expr);
                #endregion

            }

            #region Add a const for the scopeName and default URL
            CodeMemberField scopeField = new CodeMemberField(typeof(string), "SyncScopeName");
            scopeField.Attributes = MemberAttributes.Const | MemberAttributes.Private;
            scopeField.InitExpression = new CodePrimitiveExpression(desc.ScopeName);
            wrapperEntity.Members.Add(scopeField);

            if (serviceUri != null)
            {
                CodeMemberField urlField = new CodeMemberField(typeof(Uri), "SyncScopeUri");
                urlField.Attributes = MemberAttributes.Static | MemberAttributes.Private;
                urlField.InitExpression = new CodeObjectCreateExpression(typeof(Uri), new CodePrimitiveExpression(serviceUri));
                wrapperEntity.Members.Add(urlField);
            }

            #endregion

            #region Add Constructor

            if (serviceUri != null)
            {
                // If serviceUri is present then add constructors with just the cachePath and 
                // cachePath with encryption algorithm specified

                // Add the constructor with just the cachepath
                CodeConstructor ctor1 = new CodeConstructor();
                ctor1.Attributes = MemberAttributes.Public;
                ctor1.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), Constants.ClientCachePathArgName));
                ctor1.ChainedConstructorArgs.Add(new CodeSnippetExpression(Constants.ClientIsolatedStoreCallCtorWithUri));
                wrapperEntity.Members.Add(ctor1);


            }

            // Add the constructor with no encryption
            CodeConstructor ctor = new CodeConstructor();
            ctor.Attributes = MemberAttributes.Public;
            ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(string), Constants.ClientCachePathArgName));
            ctor.Parameters.Add(new CodeParameterDeclarationExpression(typeof(Uri), Constants.ClientServiceUriArgName));
            ctor.BaseConstructorArgs.Add(
                new CodeMethodInvokeExpression(
                    new CodeMethodReferenceExpression(
                        new CodeSnippetExpression(wrapperEntity.Name), Constants.ClientIsolatedStoreGetSchemaMethodName),
                        new CodeParameterDeclarationExpression[] { }));
            ctor.BaseConstructorArgs.Add(new CodeSnippetExpression(Constants.ClientIsolatedStoreBaseCtor));
            wrapperEntity.Members.Add(ctor);

            #endregion


            getSchemaMethod.Statements.Add(new CodeMethodReturnStatement(new CodeSnippetExpression("schema")));
            wrapperEntity.Members.Add(getSchemaMethod);

            ctxScopeNs.Types.Add(wrapperEntity);
            contextCC.Namespaces.Add(ctxScopeNs);

            return contextCC;
        }
 private DbSyncScopeDescription CrearAmbito(String nombreDeAmbito, string TablaDentroDelAmbito, SqlConnection conexionSql)
 {
     DbSyncScopeDescription Ambito = new DbSyncScopeDescription(nombreDeAmbito);
     DbSyncTableDescription descripcionDeTabla = SqlSyncDescriptionBuilder.GetDescriptionForTable(TablaDentroDelAmbito, conexionSql);
     Ambito.Tables.Add(descripcionDeTabla);
     return Ambito;
 }
        private int ObtenerUltimaAnclaDeSincronizacion(DbSyncScopeDescription ambito)
        {
            string tablaAnclas = this.ObtenerNombreTablaAnclas();
            string comando = "select last_anchor_sync from " + tablaAnclas +
                " where sync_scope_name = '" + ambito.ScopeName + "'" +
                " and sync_remote_DataBase_name = '" + this.nombreDeBaseRemota + "'";

            int ancla = -1;
            using (SqlCommand consulta = new SqlCommand(comando, this.conexionLocalSql))
            {
                using (SqlDataReader reader = consulta.ExecuteReader())
                {
                    if (reader.Read())
                    {
                        ancla = reader.GetInt32(0);
                    }
                }
            }
            return ancla;
        }
        private void MantenerAprovisionamientoDeAmbitos(ParametrosReplica parametros, string esquemaMetadataSyncFramework, string prefijoMetadataSyncFramework, DbSyncScopeDescription ambito)
        {
            this.semaforo.WaitOne();
            this.HilosAprovisionando++;
            try
            {
                SqlConnection NuevaConexionLocalSql = null;
                SqlConnection NuevaConexionRemotoSql = null;
                SqlSyncScopeProvisioning proveedorDeAmbitoLocal = null;
                SqlSyncScopeProvisioning proveedorDeAmbitoRemoto = null;

                if (parametros.DesaprovisionarAmbitosEnServidorLocal || parametros.AprovisionarAmbitosEnServidorLocal)
                {
                    try{
                        NuevaConexionLocalSql = new SqlConnection(parametros.StringConnectionLocal);
                        NuevaConexionLocalSql.Open();
                    }
                    catch (Exception er){
                        this.loguear("Error al abrir conexión local al crear al aprovisionador!!: " + er.ToString());
                    }
                    proveedorDeAmbitoLocal = this.CrearProveedorDeAmbito(esquemaMetadataSyncFramework, prefijoMetadataSyncFramework, NuevaConexionLocalSql, ambito);
                    proveedorDeAmbitoLocal.CommandTimeout = parametros.TimeOut;
                }
                if (parametros.DesaprovisionarAmbitosEnServidorRemoto || parametros.AprovisionarAmbitosEnServidorRemoto)
                {
                    try
                    {
                        NuevaConexionRemotoSql = new SqlConnection(parametros.StringConnectionRemoto);
                        NuevaConexionRemotoSql.Open();
                    }
                    catch (Exception er)
                    {
                        this.loguear("Error al abrir conexión remota al crear al aprovisionador!!: " + er.ToString());
                    }
                    proveedorDeAmbitoRemoto = this.CrearProveedorDeAmbito(esquemaMetadataSyncFramework, prefijoMetadataSyncFramework, NuevaConexionRemotoSql, ambito);
                    proveedorDeAmbitoRemoto.CommandTimeout = parametros.TimeOut;
                }

                if ( parametros.DesaprovisionarAmbitosEnServidorLocal)
                    this.DesaprovicionarAmbito(NuevaConexionLocalSql, ambito, proveedorDeAmbitoLocal);

                if ( parametros.DesaprovisionarAmbitosEnServidorRemoto)
                    this.DesaprovicionarAmbito(NuevaConexionRemotoSql, ambito, proveedorDeAmbitoRemoto);

                if ( parametros.AprovisionarAmbitosEnServidorLocal  )
                    this.AprovicionarAmbito(ambito, proveedorDeAmbitoLocal);

                if ( parametros.AprovisionarAmbitosEnServidorRemoto)
                    this.AprovicionarAmbito(ambito, proveedorDeAmbitoRemoto);

                if (NuevaConexionLocalSql != null && NuevaConexionLocalSql.State == ConnectionState.Open)
                    NuevaConexionLocalSql.Close();

                if (NuevaConexionRemotoSql != null && NuevaConexionRemotoSql.State == ConnectionState.Open)
                    NuevaConexionRemotoSql.Close();
            }
            catch (Exception errorcito)
            {
                this.loguear("Error manteniendo ambitos!!: " + errorcito.ToString());
            }
            finally
            {
                this.semaforo.Release(1);
                this.HilosAprovisionando--;
            }
        }
 public abstract void GenerateEntities(string filePrefix, string nameSpace, DbSyncScopeDescription desc, Dictionary<string, Dictionary<string, string>> colsMappingInfo,
     DirectoryInfo dirInfo, CodeLanguage option, string serviceUri);
        private bool ElAmbitoTieneNovedades( DbSyncScopeDescription ambito)
        {
            bool retorno = false;

            string tablaAnclas = this.ObtenerNombreTablaAnclas();
            int anclaDeLaUltimaSincronizacion = this.ObtenerUltimaAnclaDeSincronizacion(ambito);

            string procedimientoAlmacenado = ambito.Tables[0].UnquotedGlobalName + "_selectchanges";
            SqlCommand cmd = new SqlCommand(procedimientoAlmacenado, this.conexionLocalSql);
            cmd.CommandType = CommandType.StoredProcedure;
            cmd.Parameters.Add(new SqlParameter("@sync_min_timestamp", anclaDeLaUltimaSincronizacion));
            cmd.Parameters.Add(new SqlParameter("@sync_scope_local_id", 1));
            cmd.Parameters.Add(new SqlParameter("@sync_scope_restore_count", 1 ));
            cmd.Parameters.Add(new SqlParameter("@sync_update_peer_key", 1));

            SqlDataReader rdr = cmd.ExecuteReader();
            retorno = rdr.HasRows;
            rdr.Close();
            if (!retorno)
            {
                this.loguear("El ambito: " + ambito.ScopeName + " no tiene novedades desde el ancla: " + anclaDeLaUltimaSincronizacion);
            }

            return retorno;
        }
        private void DesaprovicionarAmbito(SqlConnection conexionSql, DbSyncScopeDescription Ambito, SqlSyncScopeProvisioning proveedorDeAmbito)
        {
            SqlSyncScopeDeprovisioning DesaprovicionadorDeAmbito = new SqlSyncScopeDeprovisioning(conexionSql);
            DesaprovicionadorDeAmbito.ObjectSchema = this.esquemaMetadataSyncFramework;
            DesaprovicionadorDeAmbito.ObjectPrefix = this.prefijoMetadataSyncFramework;
            this.loguear("Se va a eliminar el ambito " + Ambito.ScopeName + " Inicio:\t" + DateTime.Now);
            lock(this.obj)
            {
                if (proveedorDeAmbito.ScopeExists(Ambito.ScopeName))
                    DesaprovicionadorDeAmbito.DeprovisionScope(Ambito.ScopeName);
            }

            this.loguear("Se elimino el ambito " + Ambito.ScopeName + " fin:\t" + DateTime.Now);
        }
 private SqlSyncScopeProvisioning CrearProveedorDeAmbito(String esquemaMetadataSyncFramework, String prefijoMetadataSyncFramework, SqlConnection conexionSql, DbSyncScopeDescription Ambito)
 {
     SqlSyncScopeProvisioning proveedorDeAmbito = new SqlSyncScopeProvisioning(conexionSql, Ambito);
     proveedorDeAmbito.ObjectSchema = esquemaMetadataSyncFramework;
     proveedorDeAmbito.ObjectPrefix = prefijoMetadataSyncFramework;
     return proveedorDeAmbito;
 }
Example #58
0
        public static void CreateDatabaseProvisionFilter(SqlConnection serverConn, SqlCeConnection clientConn, string scopeName, string filterName, string filterValue, Collection<string> columnsToInclude)
        {
            string filterTemplate = scopeName + "_filter_template";

            DbSyncScopeDescription scopeDesc = new DbSyncScopeDescription(filterTemplate);
            DbSyncTableDescription tableDesc = SqlSyncDescriptionBuilder.GetDescriptionForTable(scopeName.Replace("Scope", ""), columnsToInclude, serverConn);
            scopeDesc.Tables.Add(tableDesc);

            SqlSyncScopeProvisioning serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc, SqlSyncScopeProvisioningType.Template);
            serverProvision.Tables[scopeName.Replace("Scope", "")].AddFilterColumn(filterName);
            serverProvision.Tables[scopeName.Replace("Scope", "")].FilterClause = "[side].[" + filterName + "] = @" + filterName;
            SqlParameter parameter = new SqlParameter("@" + filterName, SqlDbType.NVarChar, 8);
            serverProvision.Tables[scopeName.Replace("Scope", "")].FilterParameters.Add(parameter);
            if (!serverProvision.TemplateExists(filterTemplate))
            {
                serverProvision.Apply();
            }

            serverProvision = new SqlSyncScopeProvisioning(serverConn, scopeDesc);
            serverProvision.PopulateFromTemplate(scopeName + "-" + filterName + filterValue, filterTemplate);
            serverProvision.Tables[scopeName.Replace("Scope", "")].FilterParameters["@" + filterName].Value = filterValue;
            if (!serverProvision.ScopeExists(scopeName + "-" + filterName + filterValue))
            {
                serverProvision.Apply();
            }

            scopeDesc = SqlSyncDescriptionBuilder.GetDescriptionForScope(scopeName + "-" + filterName + filterValue, serverConn);
            SqlCeSyncScopeProvisioning clientProvision = new SqlCeSyncScopeProvisioning(clientConn, scopeDesc);
            if (!clientProvision.ScopeExists(scopeName + "-" + filterName + filterValue))
            {
                try
                {
                    clientProvision.Apply();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error {0}", ex.Message);
                }
            }
        }
        private bool ExisteAmbito(string esquemaMetadataSyncFramework, string prefijoMetadataSyncFramework, SqlConnection conexionSql, DbSyncScopeDescription ambito)
        {
            Boolean resultado = false;

            SqlSyncScopeProvisioning serverConfig = new SqlSyncScopeProvisioning( conexionSql );
            serverConfig.ObjectPrefix = prefijoMetadataSyncFramework;
            serverConfig.ObjectSchema = esquemaMetadataSyncFramework;
            resultado = serverConfig.ScopeExists(ambito.ScopeName);
            return resultado;
        }
        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);
            }
        }