Example #1
0
        //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();
        }
Example #2
0
        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();
            }
        }
Example #3
0
 protected virtual void ProvisionSyncScope(SqlSyncScopeProvisioning clientProvision, DbSyncScopeDescription serverScopeDescription, SqlSyncScopeProvisioningType provisionType)
 {
     if (serverScopeDescription != null)
     {
         // Create provisioning object
         if (!clientProvision.ScopeExists(serverScopeDescription.ScopeName))
         {
             clientProvision.PopulateFromScopeDescription(serverScopeDescription);
             if (provisionType == SqlSyncScopeProvisioningType.Scope)
             {
                 ApplyStaticFilters(clientProvision, serverScopeDescription.ScopeName);
             }
             clientProvision.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);
             // Start the provisioning process
             clientProvision.Apply();
         }
     }
 }
        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();
        }
Example #5
0
        private void CreateTemplate(string TableName, string filterColumn, string filterClause, SqlParameter param)
        {
            try
            {
                // Create a template named tableName + _Filter_Template
                scopeDesc = new DbSyncScopeDescription(TableName + "_Filter_Template");

                // Set a friendly description of the template.
                scopeDesc.UserComment = "Filter template for " + TableName + ".";

                // Definition for tables.
                tableDescription = SqlSyncDescriptionBuilder.GetDescriptionForTable(TableName, _serverConnection);
                scopeDesc.Tables.Add(tableDescription);

                // Create a provisioning object for "tableName_Filter_template" that can be used to create a template
                // from which filtered synchronization scopes can be created.
                serverTemplate = new SqlSyncScopeProvisioning(_serverConnection, scopeDesc, SqlSyncScopeProvisioningType.Template);

                AddFilter(TableName, filterColumn, filterClause, param);

                // create a new select changes stored proc for this scope
                serverTemplate.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);

                // Create the tableName_Filter_template" template in the database.
                if (!serverTemplate.TemplateExists(TableName + "_Filter_Template"))
                {
                    serverTemplate.Apply();
                    //Console.WriteLine(TableName + " filter template was created.");
                    Log.WriteLogs(TableName + " filter template was created.");
                }
                else
                {
                    //Console.WriteLine(TableName + " filter template was already exist.");
                    Log.WriteLogs(TableName + " filter template was already exist.");
                }
            }
            catch (Exception ex)
            {
                Log.WriteErrorLogs(ex);
            }
        }
        /// <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);
        }
        /// <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;
        }
Example #8
0
        public void Provision(String[] args)
        {
            ArgsParser parser = ArgsParser.ParseArgs(args);
            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = parser.ConfigFile }, ConfigurationUserLevel.None);
            SyncConfigurationSection syncConfig = config.GetSection(Constants.SyncConfigurationSectionName) as SyncConfigurationSection;

            SelectedConfigSections selectedConfig = FillDefaults(parser, syncConfig);
            DbSyncScopeDescription scopeDescription = GetDbSyncScopeDescription(selectedConfig);

            try
            {
                SqlSyncScopeProvisioning prov = new SqlSyncScopeProvisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()),
                                    scopeDescription, selectedConfig.SelectedSyncScope.IsTemplateScope ? SqlSyncScopeProvisioningType.Template : SqlSyncScopeProvisioningType.Scope);
                prov.CommandTimeout = 60;

                // Note: Deprovisioning does not work because of a bug in the provider when you set the ObjectSchema property to “dbo”. 
                // The workaround is to not set the property (it internally assumes dbo in this case) so that things work on deprovisioning.
                if (!String.IsNullOrEmpty(selectedConfig.SelectedSyncScope.SchemaName))
                {
                    prov.ObjectSchema = selectedConfig.SelectedSyncScope.SchemaName;
                }

                foreach (SyncTableConfigElement tableElement in selectedConfig.SelectedSyncScope.SyncTables)
                {
                    // Check and set the SchemaName for individual table if specified
                    if (!string.IsNullOrEmpty(tableElement.SchemaName))
                    {
                        prov.Tables[tableElement.GlobalName].ObjectSchema = tableElement.SchemaName;
                    }

                    prov.Tables[tableElement.GlobalName].FilterClause = tableElement.FilterClause;
                    foreach (FilterColumnConfigElement filterCol in tableElement.FilterColumns)
                    {
                        prov.Tables[tableElement.GlobalName].FilterColumns.Add(scopeDescription.Tables[tableElement.GlobalName].Columns[filterCol.Name]);
                    }
                    foreach (FilterParameterConfigElement filterParam in tableElement.FilterParameters)
                    {
                        CheckFilterParamTypeAndSize(filterParam);
                        prov.Tables[tableElement.GlobalName].FilterParameters.Add(new SqlParameter(filterParam.Name, (SqlDbType)Enum.Parse(typeof(SqlDbType), filterParam.SqlType, true)));
                        prov.Tables[tableElement.GlobalName].FilterParameters[filterParam.Name].Size = filterParam.DataSize;
                    }
                }

                // enable bulk procedures.
                prov.SetUseBulkProceduresDefault(selectedConfig.SelectedSyncScope.EnableBulkApplyProcedures);

                // Create a new set of enumeration stored procs per scope. 
                // Without this multiple scopes share the same stored procedure which is not desirable.
                prov.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);

                if (selectedConfig.SelectedSyncScope.IsTemplateScope)
                {
                    if (!prov.TemplateExists(selectedConfig.SelectedSyncScope.Name))
                    {
                        //Log("Provisioning Database {0} for template scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                        prov.Apply();
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("Database {0} already contains a template scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                            selectedConfig.SelectedSyncScope.Name));
                    }
                }
                else
                {
                    if (!prov.ScopeExists(selectedConfig.SelectedSyncScope.Name))
                    {
                        //Log("Provisioning Database {0} for scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                        prov.Apply();
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("Database {0} already contains a scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                            selectedConfig.SelectedSyncScope.Name));
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }

        }
Example #9
0
        private static void ProcessConfigFile(ArgsParser parser)
        {
            DbSyncScopeDescription scopeDescription;
            Dictionary <string, Dictionary <string, string> > tablesToColumnMappingsInfo = new Dictionary <string, Dictionary <string, string> >();

            if (string.IsNullOrEmpty(parser.ConfigFile))
            {
                LogArgsError("Required argument /scopeconfig is not specified.");
                return;
            }
            if (!System.IO.File.Exists(parser.ConfigFile))
            {
                LogArgsError("Unable to find scopeconfig file '" + parser.ConfigFile + "'");
                return;
            }

            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
            {
                ExeConfigFilename = parser.ConfigFile
            }, ConfigurationUserLevel.None);

            Log("Reading specified config file...");
            SyncConfigurationSection syncConfig = config.GetSection(Constants.SyncConfigurationSectionName) as SyncConfigurationSection;

            // ValidateConfigFile the config and the passed in input parameters
            ValidateConfigFile(parser, syncConfig);

            // Fill in the defaults value for the parser.
            SelectedConfigSections selectedConfig = FillDefaults(parser, syncConfig);


            Log("Generating DbSyncScopeDescription for scope {0}...", selectedConfig.SelectedSyncScope.Name);
            scopeDescription           = GetDbSyncScopeDescription(selectedConfig);
            tablesToColumnMappingsInfo = BuildColumnMappingInfo(selectedConfig);
            switch (parser.OperationMode)
            {
            case OperationMode.Provision:
                try
                {
                    SqlSyncScopeProvisioning prov = new SqlSyncScopeProvisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()),
                                                                                 scopeDescription, selectedConfig.SelectedSyncScope.IsTemplateScope ? SqlSyncScopeProvisioningType.Template : SqlSyncScopeProvisioningType.Scope);

                    // Note: Deprovisioning does not work because of a bug in the provider when you set the ObjectSchema property to “dbo”.
                    // The workaround is to not set the property (it internally assumes dbo in this case) so that things work on deprovisioning.
                    if (!String.IsNullOrEmpty(selectedConfig.SelectedSyncScope.SchemaName))
                    {
                        prov.ObjectSchema = selectedConfig.SelectedSyncScope.SchemaName;
                    }

                    foreach (SyncTableConfigElement tableElement in selectedConfig.SelectedSyncScope.SyncTables)
                    {
                        // Check and set the SchemaName for individual table if specified
                        if (!string.IsNullOrEmpty(tableElement.SchemaName))
                        {
                            prov.Tables[tableElement.GlobalName].ObjectSchema = tableElement.SchemaName;
                        }

                        prov.Tables[tableElement.GlobalName].FilterClause = tableElement.FilterClause;
                        foreach (FilterColumnConfigElement filterCol in tableElement.FilterColumns)
                        {
                            prov.Tables[tableElement.GlobalName].FilterColumns.Add(scopeDescription.Tables[tableElement.GlobalName].Columns[filterCol.Name]);
                        }
                        foreach (FilterParameterConfigElement filterParam in tableElement.FilterParameters)
                        {
                            CheckFilterParamTypeAndSize(filterParam);
                            prov.Tables[tableElement.GlobalName].FilterParameters.Add(new SqlParameter(filterParam.Name, (SqlDbType)Enum.Parse(typeof(SqlDbType), filterParam.SqlType, true)));
                            prov.Tables[tableElement.GlobalName].FilterParameters[filterParam.Name].Size = filterParam.DataSize;
                        }
                    }

                    // enable bulk procedures.
                    prov.SetUseBulkProceduresDefault(selectedConfig.SelectedSyncScope.EnableBulkApplyProcedures);

                    // Create a new set of enumeration stored procs per scope.
                    // Without this multiple scopes share the same stored procedure which is not desirable.
                    prov.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);

                    if (selectedConfig.SelectedSyncScope.IsTemplateScope)
                    {
                        if (!prov.TemplateExists(selectedConfig.SelectedSyncScope.Name))
                        {
                            Log("Provisioning Database {0} for template scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                            prov.Apply();
                        }
                        else
                        {
                            throw new InvalidOperationException(string.Format("Database {0} already contains a template scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                                                                              selectedConfig.SelectedSyncScope.Name));
                        }
                    }
                    else
                    {
                        if (!prov.ScopeExists(selectedConfig.SelectedSyncScope.Name))
                        {
                            Log("Provisioning Database {0} for scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                            prov.Apply();
                        }
                        else
                        {
                            throw new InvalidOperationException(string.Format("Database {0} already contains a scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                                                                              selectedConfig.SelectedSyncScope.Name));
                        }
                    }
                }
                catch (ConfigurationErrorsException)
                {
                    throw;
                }
                catch (InvalidOperationException)
                {
                    throw;
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("Unexpected error when executing the Provisioning command. See inner exception for details.", e);
                }
                break;

            case OperationMode.Deprovision:
                try
                {
                    SqlSyncScopeDeprovisioning deprov = new SqlSyncScopeDeprovisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()));

                    // Set the ObjectSchema property.
                    if (!String.IsNullOrEmpty(selectedConfig.SelectedSyncScope.SchemaName))
                    {
                        deprov.ObjectSchema = selectedConfig.SelectedSyncScope.SchemaName;
                    }

                    Log("Deprovisioning Database {0} for scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);

                    if (selectedConfig.SelectedSyncScope.IsTemplateScope)
                    {
                        deprov.DeprovisionTemplate(selectedConfig.SelectedSyncScope.Name);
                    }
                    else
                    {
                        deprov.DeprovisionScope(selectedConfig.SelectedSyncScope.Name);
                    }
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("Unexpected error when executing the Deprovisioning command. See inner exception for details.", e);
                }

                break;

            case OperationMode.Deprovisionstore:
                try
                {
                    SqlSyncScopeDeprovisioning deprov = new SqlSyncScopeDeprovisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()));

                    Log("Deprovisioning Store Database {0} ...", selectedConfig.SelectedTargetDatabase.Name);

                    deprov.DeprovisionStore();
                }
                catch (Exception e)
                {
                    throw new InvalidOperationException("Unexpected error when executing the Deprovisioning command. See inner exception for details.", e);
                }

                break;

            case OperationMode.Codegen:
                Log("Generating files...");
                EntityGenerator generator = EntityGeneratorFactory.Create(parser.CodeGenMode, selectedConfig.SelectedSyncScope.SchemaName);
                generator.GenerateEntities(parser.GeneratedFilePrefix,
                                           string.IsNullOrEmpty(parser.Namespace)
                        ? string.IsNullOrEmpty(parser.GeneratedFilePrefix) ? scopeDescription.ScopeName : parser.GeneratedFilePrefix
                        : parser.Namespace,
                                           scopeDescription, tablesToColumnMappingsInfo, parser.WorkingDirectory, parser.Language, null /*serviceUri*/);
                break;

            default:
                break;
            }
        }
Example #10
0
        private static void ProcessConfigFile(ArgsParser parser)
        {
            DbSyncScopeDescription scopeDescription;
            Dictionary<string, Dictionary<string, string>> tablesToColumnMappingsInfo = new Dictionary<string, Dictionary<string, string>>();

            if (string.IsNullOrEmpty(parser.ConfigFile))
            {
                LogArgsError("Required argument /scopeconfig is not specified.");
                return;
            }
            if (!System.IO.File.Exists(parser.ConfigFile))
            {
                LogArgsError("Unable to find scopeconfig file '" + parser.ConfigFile + "'");
                return;
            }

            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap() { ExeConfigFilename = parser.ConfigFile }, ConfigurationUserLevel.None);

            Log("Reading specified config file...");
            SyncConfigurationSection syncConfig = config.GetSection(Constants.SyncConfigurationSectionName) as SyncConfigurationSection;

            // ValidateConfigFile the config and the passed in input parameters
            ValidateConfigFile(parser, syncConfig);

            // Fill in the defaults value for the parser.
            SelectedConfigSections selectedConfig = FillDefaults(parser, syncConfig);


            Log("Generating DbSyncScopeDescription for scope {0}...", selectedConfig.SelectedSyncScope.Name);
            scopeDescription = GetDbSyncScopeDescription(selectedConfig);
            tablesToColumnMappingsInfo = BuildColumnMappingInfo(selectedConfig);
            switch (parser.OperationMode)
            {

                case OperationMode.Provision:
                    try
                    {


                        SqlSyncScopeProvisioning prov = new SqlSyncScopeProvisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()),
                                            scopeDescription, selectedConfig.SelectedSyncScope.IsTemplateScope ? SqlSyncScopeProvisioningType.Template : SqlSyncScopeProvisioningType.Scope);

                        // Note: Deprovisioning does not work because of a bug in the provider when you set the ObjectSchema property to “dbo”. 
                        // The workaround is to not set the property (it internally assumes dbo in this case) so that things work on deprovisioning.
                        if (!String.IsNullOrEmpty(selectedConfig.SelectedSyncScope.SchemaName))
                        {
                            prov.ObjectSchema = selectedConfig.SelectedSyncScope.SchemaName;
                        }

                        foreach (SyncTableConfigElement tableElement in selectedConfig.SelectedSyncScope.SyncTables)
                        {
                            // Check and set the SchemaName for individual table if specified
                            if (!string.IsNullOrEmpty(tableElement.SchemaName))
                            {
                                prov.Tables[tableElement.GlobalName].ObjectSchema = tableElement.SchemaName;
                            }

                            prov.Tables[tableElement.GlobalName].FilterClause = tableElement.FilterClause;
                            foreach (FilterColumnConfigElement filterCol in tableElement.FilterColumns)
                            {
                                prov.Tables[tableElement.GlobalName].FilterColumns.Add(scopeDescription.Tables[tableElement.GlobalName].Columns[filterCol.Name]);
                            }
                            foreach (FilterParameterConfigElement filterParam in tableElement.FilterParameters)
                            {
                                CheckFilterParamTypeAndSize(filterParam);
                                prov.Tables[tableElement.GlobalName].FilterParameters.Add(new SqlParameter(filterParam.Name, (SqlDbType)Enum.Parse(typeof(SqlDbType), filterParam.SqlType, true)));
                                prov.Tables[tableElement.GlobalName].FilterParameters[filterParam.Name].Size = filterParam.DataSize;
                            }
                        }

                        // enable bulk procedures.
                        prov.SetUseBulkProceduresDefault(selectedConfig.SelectedSyncScope.EnableBulkApplyProcedures);

                        // Create a new set of enumeration stored procs per scope. 
                        // Without this multiple scopes share the same stored procedure which is not desirable.
                        prov.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);

                        if (selectedConfig.SelectedSyncScope.IsTemplateScope)
                        {
                            if (!prov.TemplateExists(selectedConfig.SelectedSyncScope.Name))
                            {
                                Log("Provisioning Database {0} for template scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                                prov.Apply();
                            }
                            else
                            {
                                throw new InvalidOperationException(string.Format("Database {0} already contains a template scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                                    selectedConfig.SelectedSyncScope.Name));
                            }
                        }
                        else
                        {
                            if (!prov.ScopeExists(selectedConfig.SelectedSyncScope.Name))
                            {
                                Log("Provisioning Database {0} for scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                                prov.Apply();
                            }
                            else
                            {
                                throw new InvalidOperationException(string.Format("Database {0} already contains a scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                                    selectedConfig.SelectedSyncScope.Name));
                            }
                        }
                    }
                    catch (ConfigurationErrorsException)
                    {
                        throw;
                    }
                    catch (InvalidOperationException)
                    {
                        throw;
                    }
                    catch (Exception e)
                    {
                        throw new InvalidOperationException("Unexpected error when executing the Provisioning command. See inner exception for details.", e);
                    }
                    break;
                case OperationMode.Deprovision:
                    try
                    {
                        SqlSyncScopeDeprovisioning deprov = new SqlSyncScopeDeprovisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()));

                        // Set the ObjectSchema property.
                        if (!String.IsNullOrEmpty(selectedConfig.SelectedSyncScope.SchemaName))
                        {
                            deprov.ObjectSchema = selectedConfig.SelectedSyncScope.SchemaName;
                        }

                        Log("Deprovisioning Database {0} for scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);

                        if (selectedConfig.SelectedSyncScope.IsTemplateScope)
                        {
                            deprov.DeprovisionTemplate(selectedConfig.SelectedSyncScope.Name);
                        }
                        else
                        {
                            deprov.DeprovisionScope(selectedConfig.SelectedSyncScope.Name);

                        }
                    }
                    catch (Exception e)
                    {
                        throw new InvalidOperationException("Unexpected error when executing the Deprovisioning command. See inner exception for details.", e);
                    }

                    break;
                case OperationMode.Deprovisionstore:
                    try
                    {
                        SqlSyncScopeDeprovisioning deprov = new SqlSyncScopeDeprovisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()));

                        Log("Deprovisioning Store Database {0} ...", selectedConfig.SelectedTargetDatabase.Name);

                        deprov.DeprovisionStore();
                    }
                    catch (Exception e)
                    {
                        throw new InvalidOperationException("Unexpected error when executing the Deprovisioning command. See inner exception for details.", e);
                    }

                    break;
                case OperationMode.Codegen:
                    Log("Generating files...");
                    EntityGenerator generator = EntityGeneratorFactory.Create(parser.CodeGenMode, selectedConfig.SelectedSyncScope.SchemaName);
                    generator.GenerateEntities(parser.GeneratedFilePrefix,
                        string.IsNullOrEmpty(parser.Namespace)
                        ? string.IsNullOrEmpty(parser.GeneratedFilePrefix) ? scopeDescription.ScopeName : parser.GeneratedFilePrefix
                        : parser.Namespace,
                        scopeDescription, tablesToColumnMappingsInfo, parser.WorkingDirectory, parser.Language, null/*serviceUri*/);
                    break;
                default:
                    break;
            }
        }
Example #11
0
        private static void Provision(SelectedConfigSections selectedConfig, DbSyncScopeDescription scopeDescription, bool script, DirectoryInfo workingDirectory)
        {
            try
            {
                SqlSyncScopeProvisioning prov =
                    new SqlSyncScopeProvisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()),
                                                 scopeDescription,
                                                 selectedConfig.SelectedSyncScope.IsTemplateScope
                            ? SqlSyncScopeProvisioningType.Template
                            : SqlSyncScopeProvisioningType.Scope);

                // Note: Deprovisioning does not work because of a bug in the provider when you set the ObjectSchema property to “dbo”.
                // The workaround is to not set the property (it internally assumes dbo in this case) so that things work on deprovisioning.
                if (!String.IsNullOrEmpty(selectedConfig.SelectedSyncScope.SchemaName))
                {
                    prov.ObjectSchema = selectedConfig.SelectedSyncScope.SchemaName;
                }

                foreach (SyncTableConfigElement tableElement in selectedConfig.SelectedSyncScope.SyncTables)
                {
                    // Check and set the SchemaName for individual table if specified
                    if (!string.IsNullOrEmpty(tableElement.SchemaName))
                    {
                        prov.Tables[tableElement.GlobalName].ObjectSchema = tableElement.SchemaName;
                    }

                    prov.Tables[tableElement.GlobalName].FilterClause = tableElement.FilterClause;
                    foreach (FilterColumnConfigElement filterCol in tableElement.FilterColumns)
                    {
                        prov.Tables[tableElement.GlobalName].FilterColumns.Add(
                            scopeDescription.Tables[tableElement.GlobalName].Columns[filterCol.Name]);
                    }
                    foreach (FilterParameterConfigElement filterParam in tableElement.FilterParameters)
                    {
                        CheckFilterParamTypeAndSize(filterParam);
                        prov.Tables[tableElement.GlobalName].FilterParameters.Add(new SqlParameter(filterParam.Name,
                                                                                                   (SqlDbType)Enum.Parse(typeof(SqlDbType), filterParam.SqlType, true)));
                        prov.Tables[tableElement.GlobalName].FilterParameters[filterParam.Name].Size = filterParam.DataSize;
                    }
                }

                // enable bulk procedures.
                prov.SetUseBulkProceduresDefault(selectedConfig.SelectedSyncScope.EnableBulkApplyProcedures);

                // Create a new set of enumeration stored procs per scope.
                // Without this multiple scopes share the same stored procedure which is not desirable.
                prov.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);

                if (selectedConfig.SelectedSyncScope.IsTemplateScope)
                {
                    if (!script)
                    {
                        if (!prov.TemplateExists(selectedConfig.SelectedSyncScope.Name))
                        {
                            Log("Provisioning Database {0} for template scope {1}...",
                                selectedConfig.SelectedTargetDatabase.Name,
                                selectedConfig.SelectedSyncScope.Name);
                            prov.Apply();
                        }
                        else
                        {
                            throw new InvalidOperationException(
                                      string.Format(
                                          "Database {0} already contains a template scope {1}. Please deprovision the scope and retry.",
                                          selectedConfig.SelectedTargetDatabase.Name,
                                          selectedConfig.SelectedSyncScope.Name));
                        }
                    }
                    else
                    {
                        SaveScript("provision.sql", prov.Script(), workingDirectory);
                    }
                }
                else
                {
                    if (!script)
                    {
                        if (!prov.ScopeExists(selectedConfig.SelectedSyncScope.Name))
                        {
                            Log("Provisioning Database {0} for scope {1}...", selectedConfig.SelectedTargetDatabase.Name,
                                selectedConfig.SelectedSyncScope.Name);


                            prov.Apply();
                        }
                        else
                        {
                            throw new InvalidOperationException(
                                      string.Format(
                                          "Database {0} already contains a scope {1}. Please deprovision the scope and retry.",
                                          selectedConfig.SelectedTargetDatabase.Name,
                                          selectedConfig.SelectedSyncScope.Name));
                        }
                    }
                    else
                    {
                        SaveScript("provision.sql", prov.Script(), workingDirectory);
                    }
                }
            }
            catch (ConfigurationErrorsException)
            {
                throw;
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            catch (Exception e)
            {
                throw new InvalidOperationException(
                          "Unexpected error when executing the Provisioning command. See inner exception for details.", e);
            }
        }
Example #12
0
        public void Provision(String[] args)
        {
            ArgsParser parser = ArgsParser.ParseArgs(args);

            System.Configuration.Configuration config = ConfigurationManager.OpenMappedExeConfiguration(new ExeConfigurationFileMap()
            {
                ExeConfigFilename = parser.ConfigFile
            }, ConfigurationUserLevel.None);
            SyncConfigurationSection syncConfig = config.GetSection(Constants.SyncConfigurationSectionName) as SyncConfigurationSection;

            SelectedConfigSections selectedConfig   = FillDefaults(parser, syncConfig);
            DbSyncScopeDescription scopeDescription = GetDbSyncScopeDescription(selectedConfig);

            try
            {
                SqlSyncScopeProvisioning prov = new SqlSyncScopeProvisioning(new SqlConnection(selectedConfig.SelectedTargetDatabase.GetConnectionString()),
                                                                             scopeDescription, selectedConfig.SelectedSyncScope.IsTemplateScope ? SqlSyncScopeProvisioningType.Template : SqlSyncScopeProvisioningType.Scope);
                prov.CommandTimeout = 60;

                // Note: Deprovisioning does not work because of a bug in the provider when you set the ObjectSchema property to “dbo”.
                // The workaround is to not set the property (it internally assumes dbo in this case) so that things work on deprovisioning.
                if (!String.IsNullOrEmpty(selectedConfig.SelectedSyncScope.SchemaName))
                {
                    prov.ObjectSchema = selectedConfig.SelectedSyncScope.SchemaName;
                }

                foreach (SyncTableConfigElement tableElement in selectedConfig.SelectedSyncScope.SyncTables)
                {
                    // Check and set the SchemaName for individual table if specified
                    if (!string.IsNullOrEmpty(tableElement.SchemaName))
                    {
                        prov.Tables[tableElement.GlobalName].ObjectSchema = tableElement.SchemaName;
                    }

                    prov.Tables[tableElement.GlobalName].FilterClause = tableElement.FilterClause;
                    foreach (FilterColumnConfigElement filterCol in tableElement.FilterColumns)
                    {
                        prov.Tables[tableElement.GlobalName].FilterColumns.Add(scopeDescription.Tables[tableElement.GlobalName].Columns[filterCol.Name]);
                    }
                    foreach (FilterParameterConfigElement filterParam in tableElement.FilterParameters)
                    {
                        CheckFilterParamTypeAndSize(filterParam);
                        prov.Tables[tableElement.GlobalName].FilterParameters.Add(new SqlParameter(filterParam.Name, (SqlDbType)Enum.Parse(typeof(SqlDbType), filterParam.SqlType, true)));
                        prov.Tables[tableElement.GlobalName].FilterParameters[filterParam.Name].Size = filterParam.DataSize;
                    }
                }

                // enable bulk procedures.
                prov.SetUseBulkProceduresDefault(selectedConfig.SelectedSyncScope.EnableBulkApplyProcedures);

                // Create a new set of enumeration stored procs per scope.
                // Without this multiple scopes share the same stored procedure which is not desirable.
                prov.SetCreateProceduresForAdditionalScopeDefault(DbSyncCreationOption.Create);

                if (selectedConfig.SelectedSyncScope.IsTemplateScope)
                {
                    if (!prov.TemplateExists(selectedConfig.SelectedSyncScope.Name))
                    {
                        //Log("Provisioning Database {0} for template scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                        prov.Apply();
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("Database {0} already contains a template scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                                                                          selectedConfig.SelectedSyncScope.Name));
                    }
                }
                else
                {
                    if (!prov.ScopeExists(selectedConfig.SelectedSyncScope.Name))
                    {
                        //Log("Provisioning Database {0} for scope {1}...", selectedConfig.SelectedTargetDatabase.Name, selectedConfig.SelectedSyncScope.Name);
                        prov.Apply();
                    }
                    else
                    {
                        throw new InvalidOperationException(string.Format("Database {0} already contains a scope {1}. Please deprovision the scope and retry.", selectedConfig.SelectedTargetDatabase.Name,
                                                                          selectedConfig.SelectedSyncScope.Name));
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }