Exemplo n.º 1
0
        private static async Task CreateSnapshotAsync()
        {
            // [Required]: Get a connection string to your server data source
            var connectionString = configuration.GetSection("ConnectionStrings")["SqlConnection"];

            // [Required] Tables involved in the sync process:
            var tables = new string[] { "ProductCategory", "ProductModel", "Product",
                                        "Address", "Customer", "CustomerAddress", "SalesOrderHeader", "SalesOrderDetail" };

            var syncOptions = new SyncOptions
            {
                SnapshotsDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "Snapshots"),
                BatchSize          = 2000,
            };

            var syncSetup = new SyncSetup(tables);

            // Using the Progress pattern to handle progession during the synchronization
            var progress = new SynchronousProgress <ProgressArgs>(s => Console.WriteLine($"{s.Source}:\t{s.Message}"));

            var provider = new SqlSyncProvider(connectionString);

            var orchestrator = new RemoteOrchestrator(provider, syncOptions, syncSetup);

            var snap = await orchestrator.CreateSnapshotAsync(progress : progress);
        }
Exemplo n.º 2
0
    /// <summary>
    /// Launch a simple sync, over TCP network, each sql server (client and server are reachable through TCP cp
    /// </summary>
    /// <returns></returns>
    private static async Task SynchronizeAsync()
    {
        // Create 2 Sql Sync providers
        var serverProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(serverDbName));
        var clientProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(clientDbName));

        // Tables involved in the sync process:
        var tables = allTables;

        // Creating an agent that will handle all the process
        var agent = new SyncAgent(clientProvider, serverProvider, tables);

        // Using the Progress pattern to handle progession during the synchronization
        var progress = new Progress <ProgressArgs>(s => Console.WriteLine($"[client]: {s.Context.SyncStage}:\t{s.Message}"));


        // Setting configuration options
        agent.SetConfiguration(s =>
        {
            s.ScopeInfoTableName     = "tscopeinfo";
            s.SerializationFormat    = Dotmim.Sync.Enumerations.SerializationFormat.Binary;
            s.StoredProceduresPrefix = "s";
            s.StoredProceduresSuffix = "";
            s.TrackingTablesPrefix   = "t";
            s.TrackingTablesSuffix   = "";
        });

        agent.SetOptions(opt =>
        {
            opt.BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "sync");
            opt.BatchSize         = 100;
            opt.CleanMetadatas    = true;
            opt.UseBulkOperations = true;
            opt.UseVerboseErrors  = false;
        });


        do
        {
            Console.Clear();
            Console.WriteLine("Sync Start");
            try
            {
                // Launch the sync process
                var s1 = await agent.SynchronizeAsync(progress);

                // Write results
                Console.WriteLine(s1);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


            //Console.WriteLine("Sync Ended. Press a key to start again, or Escapte to end");
        } while (Console.ReadKey().Key != ConsoleKey.Escape);

        Console.WriteLine("End");
    }
Exemplo n.º 3
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            // [Required]: Handling multiple sessions
            services.AddMemoryCache();

            // [Required]: Get a connection string to your server data source
            var connectionString = Configuration.GetSection("ConnectionStrings")["SqlConnection"];

            // Sync options
            var options = new SyncOptions
            {
                SnapshotsDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "Snapshots"),
                BatchSize          = 2000,
            };

            // [Required] Tables involved in the sync process:
            var tables = new string[] { "ProductCategory", "ProductModel", "Product",
                                        "Address", "Customer", "CustomerAddress", "SalesOrderHeader", "SalesOrderDetail" };

            var setup = new SyncSetup(tables);

            // add a SqlSyncProvider acting as the server hub
            services.AddSyncServer <SqlSyncProvider>(connectionString, setup, options);
        }
Exemplo n.º 4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // Mandatory to be able to handle multiple sessions
            services.AddMemoryCache();

            // Get a connection string for your server data source
            var connectionString = Configuration.GetConnectionString("OtherConnection");

            services.AddSingleton <ContosoContext>();

            // Sync options
            var syncOptions = new SyncOptions
            {
                SnapshotsDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "Snapshots"),
                BatchDirectory     = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "Server"),
                BatchSize          = 10000,
            };

            // Create the setup used for your sync process
            var tables = new string[] { "SyncLog" };

            //var tables = new string[] {"ProductDescription", "ProductCategory",
            //                        "ProductModel", "Product",
            //                        "Address", "Customer", "CustomerAddress",
            //                        "SalesOrderHeader", "SalesOrderDetail" };

            var setup = new SyncSetup(tables);

            // add a SqlSyncProvider acting as the server hub
            services.AddSyncServer <SqlSyncProvider>(connectionString, setup, syncOptions);
        }
Exemplo n.º 5
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            services.AddMemoryCache();

            var connectionString = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];

            services.AddSyncServer <SqlSyncProvider>(connectionString,
                                                     c =>
            {
                var tables = new string[] { "ProductCategory",
                                            "ProductDescription", "ProductModel",
                                            "Product", "ProductModelProductDescription",
                                            "Address", "Customer", "CustomerAddress",
                                            "SalesOrderHeader", "SalesOrderDetail" };
                c.Add(tables);
                c.ScopeInfoTableName     = "tscopeinfo";
                c.SerializationFormat    = Dotmim.Sync.Enumerations.SerializationFormat.Binary;
                c.StoredProceduresPrefix = "s";
                c.StoredProceduresSuffix = "";
                c.TrackingTablesPrefix   = "t";
                c.TrackingTablesSuffix   = "";
            }, options =>
            {
                options.BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "server");
                options.BatchSize      = 100;
            });
        }
Exemplo n.º 6
0
    private static async Task TestSync()
    {
        //CreateDatabase("NW1", true);
        var serverProvider = new SqlSyncProvider(GetDatabaseConnectionString("AdventureWorks"));
        var clientProvider = new SqlSyncProvider(GetDatabaseConnectionString("Client"));

        // Tables involved in the sync process:
        var tables = new string[] { "ProductCategory",
                                    "ProductDescription", "ProductModel",
                                    "Product", "ProductModelProductDescription",
                                    "Address", "Customer", "CustomerAddress",
                                    "SalesOrderHeader", "SalesOrderDetail" };

        var agent = new SyncAgent(clientProvider, serverProvider, tables);

        agent.Configuration.StoredProceduresPrefix = "sp";
        agent.Configuration.TrackingTablesPrefix   = "sync";
        agent.Configuration.ScopeInfoTableName     = "syncscope";
        agent.Configuration.SerializationFormat    = SerializationFormat.Binary;

        agent.Options = new SyncOptions
        {
            BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "test"),
            BatchSize         = 1000,
            CleanMetadatas    = true,
            UseBulkOperations = true,
            UseVerboseErrors  = false
        };

        do
        {
            Console.Clear();
            Console.WriteLine("Sync Start");
            try
            {
                var cts   = new CancellationTokenSource();
                var token = cts.Token;

                var s1 = await agent.SynchronizeAsync(SyncType.ReinitializeWithUpload, token);

                Console.WriteLine(s1);
            }
            catch (SyncException e)
            {
                Console.WriteLine(e.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine("UNKNOW EXCEPTION : " + e.Message);
            }


            //Console.WriteLine("Sync Ended. Press a key to start again, or Escapte to end");
        } while (Console.ReadKey().Key != ConsoleKey.Escape);

        Console.WriteLine("End");
    }
Exemplo n.º 7
0
        private static async Task SynchronizeAsync()
        {
            // Database script used for this sample : https://github.com/Mimetis/Dotmim.Sync/blob/master/CreateAdventureWorks.sql

            var serverOrchestrator = new WebRemoteOrchestrator("https://localhost:44342/api/sync");

            // Second provider is using plain old Sql Server provider, relying on triggers and tracking tables to create the sync environment
            var clientProvider = new SqlSyncProvider(clientConnectionString);

            // Set the web server Options
            var options = new SyncOptions
            {
                BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "client")
            };

            // Creating an agent that will handle all the process
            var agent = new SyncAgent(clientProvider, serverOrchestrator, options);

            var progress = new SynchronousProgress <ProgressArgs>(
                pa => Console.WriteLine($"{pa.ProgressPercentage:p}\t {pa.Message}"));

            var parameters = new SyncParameters
            {
                { "City", "Toronto" },
                // Because I've specified that "postal" could be null,
                // I can set the value to DBNull.Value (and the get all postal code in Toronto city)
                { "postal", DBNull.Value }
            };

            do
            {
                try
                {
                    // Launch the sync process
                    var s1 = await agent.SynchronizeAsync(progress);

                    // Write results
                    Console.WriteLine(s1);
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.Message);
                }
            } while (Console.ReadKey().Key != ConsoleKey.Escape);

            Console.WriteLine("End");
        }
Exemplo n.º 8
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_2);

            // Mandatory to be able to handle multiple sessions
            services.AddMemoryCache();

            // Get a connection string for your server data source
            var connectionString = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];

            // Set the web server Options
            var options = new WebServerOptions()
            {
                BatchDirectory     = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "server"),
                SnapshotsDirectory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Snapshots")
            };


            // Create the setup used for your sync process
            var tables = new string[] { "ProductCategory",
                                        "ProductDescription", "ProductModel",
                                        "Product", "ProductModelProductDescription",
                                        "Address", "Customer", "CustomerAddress",
                                        "SalesOrderHeader", "SalesOrderDetail" };

            var setup = new SyncSetup(tables)
            {
                // optional :
                StoredProceduresPrefix = "server",
                StoredProceduresSuffix = "",
                TrackingTablesPrefix   = "server",
                TrackingTablesSuffix   = ""
            };

            setup.Filters.Add("ProductDescriptionFilter", "ProductDescriptionId");

            // add a SqlSyncProvider acting as the server hub
            services.AddSyncServer <SqlSyncProvider>(connectionString, setup, options);
        }
Exemplo n.º 9
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc();

            // Mandatory to be able to handle multiple sessions
            services.AddMemoryCache();

            // Get a connection string for your server data source
            var connectionString = Configuration.GetSection("ConnectionStrings")["DefaultConnection"];

            // Set the web server Options
            var options = new WebServerOptions()
            {
                BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "server"),
            };

            // Create the setup used for your sync process
            var tables = new string[] { "Employee" };

            var setup = new SyncSetup(tables);

            // add a SqlSyncProvider acting as the server hub
            services.AddSyncServer <SqlSyncProvider>(connectionString, setup, options);
        }
Exemplo n.º 10
0
    public static async Task SyncHttpThroughKestellAsync()
    {
        // server provider
        var serverProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(serverDbName));

        // client provider
        var client1Provider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(clientDbName));
        // proxy client provider
        var proxyClientProvider = new WebProxyClientProvider();

        var tables = new string[] { "ProductCategory",
                                    "ProductDescription", "ProductModel",
                                    "Product", "ProductModelProductDescription",
                                    "Address", "Customer", "CustomerAddress",
                                    "SalesOrderHeader", "SalesOrderDetail" };

        var configuration = new Action <SyncConfiguration>(conf =>
        {
            conf.ScopeName              = "AdventureWorks";
            conf.ScopeInfoTableName     = "tscopeinfo";
            conf.SerializationFormat    = Dotmim.Sync.Enumerations.SerializationFormat.Binary;
            conf.StoredProceduresPrefix = "s";
            conf.StoredProceduresSuffix = "";
            conf.TrackingTablesPrefix   = "t";
            conf.TrackingTablesSuffix   = "";
            conf.Add(tables);
        });


        var optionsClient = new Action <SyncOptions>(opt =>
        {
            opt.BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "client");
            opt.BatchSize         = 100;
            opt.CleanMetadatas    = true;
            opt.UseBulkOperations = true;
            opt.UseVerboseErrors  = false;
        });

        var optionsServer = new Action <SyncOptions>(opt =>
        {
            opt.BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "server");
            opt.BatchSize         = 100;
            opt.CleanMetadatas    = true;
            opt.UseBulkOperations = true;
            opt.UseVerboseErrors  = false;
        });



        var serverHandler = new RequestDelegate(async context =>
        {
            var proxyServerProvider = WebProxyServerProvider.Create(context, serverProvider, configuration, optionsServer);

            await proxyServerProvider.HandleRequestAsync(context);
        });

        using (var server = new KestrellTestServer())
        {
            var clientHandler = new ResponseDelegate(async(serviceUri) =>
            {
                proxyClientProvider.ServiceUri = new Uri(serviceUri);

                var syncAgent = new SyncAgent(client1Provider, proxyClientProvider);

                do
                {
                    Console.Clear();
                    Console.WriteLine("Sync Start");
                    try
                    {
                        var cts = new CancellationTokenSource();

                        Console.WriteLine("--------------------------------------------------");
                        Console.WriteLine("1 : Normal synchronization.");
                        Console.WriteLine("2 : Synchronization with reinitialize");
                        Console.WriteLine("3 : Synchronization with upload and reinitialize");
                        Console.WriteLine("--------------------------------------------------");
                        Console.WriteLine("What's your choice ? ");
                        Console.WriteLine("--------------------------------------------------");
                        var choice = Console.ReadLine();

                        if (int.TryParse(choice, out var choiceNumber))
                        {
                            Console.WriteLine($"You choose {choice}. Start operation....");
                            switch (choiceNumber)
                            {
                            case 1:
                                var s1 = await syncAgent.SynchronizeAsync(cts.Token);
                                Console.WriteLine(s1);
                                break;

                            case 2:
                                s1 = await syncAgent.SynchronizeAsync(SyncType.Reinitialize, cts.Token);
                                Console.WriteLine(s1);
                                break;

                            case 3:
                                s1 = await syncAgent.SynchronizeAsync(SyncType.ReinitializeWithUpload, cts.Token);
                                Console.WriteLine(s1);
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    catch (SyncException e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("UNKNOW EXCEPTION : " + e.Message);
                    }


                    Console.WriteLine("--------------------------------------------------");
                    Console.WriteLine("Press a key to choose again, or Escapte to end");
                } while (Console.ReadKey().Key != ConsoleKey.Escape);
            });
            await server.Run(serverHandler, clientHandler);
        }
    }
Exemplo n.º 11
0
    /// <summary>
    /// Launch a simple sync, over TCP network, each sql server (client and server are reachable through TCP cp
    /// </summary>
    /// <returns></returns>
    private static async Task SynchronizeExistingTablesAsync()
    {
        string serverName = "ServerTablesExist";
        string clientName = "ClientsTablesExist";

        await DbHelper.EnsureDatabasesAsync(serverName);

        await DbHelper.EnsureDatabasesAsync(clientName);

        // Create 2 Sql Sync providers
        var serverProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(serverName));
        var clientProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(clientName));

        // Tables involved in the sync process:
        var tables = allTables;

        // Creating an agent that will handle all the process
        var agent = new SyncAgent(clientProvider, serverProvider, tables);

        // Using the Progress pattern to handle progession during the synchronization
        var progress = new Progress <ProgressArgs>(s => Console.WriteLine($"[client]: {s.Context.SyncStage}:\t{s.Message}"));



        // Setting configuration options
        agent.SetConfiguration(s =>
        {
            s.ScopeInfoTableName     = "tscopeinfo";
            s.SerializationFormat    = Dotmim.Sync.Enumerations.SerializationFormat.Binary;
            s.StoredProceduresPrefix = "s";
            s.StoredProceduresSuffix = "";
            s.TrackingTablesPrefix   = "t";
            s.TrackingTablesSuffix   = "";
        });

        agent.SetOptions(opt =>
        {
            opt.BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "sync");
            opt.BatchSize         = 100;
            opt.CleanMetadatas    = true;
            opt.UseBulkOperations = true;
            opt.UseVerboseErrors  = false;
        });


        var remoteProvider = agent.RemoteProvider as CoreProvider;

        var dpAction = new Action <DatabaseProvisionedArgs>(args =>
        {
            Console.WriteLine($"-- [InterceptDatabaseProvisioned] -- ");

            var sql = $"Update tscopeinfo set scope_last_sync_timestamp = 0 where [scope_is_local] = 1";

            var cmd         = args.Connection.CreateCommand();
            cmd.Transaction = args.Transaction;
            cmd.CommandText = sql;

            cmd.ExecuteNonQuery();
        });

        remoteProvider.InterceptDatabaseProvisioned(dpAction);

        agent.LocalProvider.InterceptDatabaseProvisioned(dpAction);

        do
        {
            Console.Clear();
            Console.WriteLine("Sync Start");
            try
            {
                // Launch the sync process
                var s1 = await agent.SynchronizeAsync(progress);

                // Write results
                Console.WriteLine(s1);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


            //Console.WriteLine("Sync Ended. Press a key to start again, or Escapte to end");
        } while (Console.ReadKey().Key != ConsoleKey.Escape);

        Console.WriteLine("End");
    }
Exemplo n.º 12
0
    /// <summary>
    /// Test a client syncing through a web api
    /// </summary>
    private static async Task SyncThroughWebApiAsync()
    {
        var clientProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(clientDbName));

        var handler = new HttpClientHandler {
            AutomaticDecompression = DecompressionMethods.GZip
        };
        var client = new HttpClient(handler)
        {
            Timeout = TimeSpan.FromMinutes(5)
        };

        var proxyClientProvider = new WebClientOrchestrator("http://localhost:52288/api/Sync", null, null, client);



        // ----------------------------------
        // Client side
        // ----------------------------------
        var clientOptions = new SyncOptions
        {
            ScopeInfoTableName = "client_scopeinfo",
            BatchDirectory     = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "sync_client"),
            BatchSize          = 50,
            CleanMetadatas     = true,
            UseBulkOperations  = true,
            UseVerboseErrors   = false,
        };

        var clientSetup = new SyncSetup
        {
            StoredProceduresPrefix = "cli",
            StoredProceduresSuffix = "",
            TrackingTablesPrefix   = "cli",
            TrackingTablesSuffix   = "",
            TriggersPrefix         = "",
            TriggersSuffix         = "",
        };


        var agent = new SyncAgent(clientProvider, proxyClientProvider, clientSetup, clientOptions);

        Console.WriteLine("Press a key to start (be sure web api is running ...)");
        Console.ReadKey();
        do
        {
            Console.Clear();
            Console.WriteLine("Web sync start");
            try
            {
                var progress = new SynchronousProgress <ProgressArgs>(pa => Console.WriteLine($"{pa.Context.SessionId} - {pa.Context.SyncStage}\t {pa.Message}"));

                var s = await agent.SynchronizeAsync(progress);

                Console.WriteLine(s);
            }
            catch (SyncException e)
            {
                Console.WriteLine(e.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("UNKNOW EXCEPTION : " + e.Message);
            }


            Console.WriteLine("Sync Ended. Press a key to start again, or Escapte to end");
        } while (Console.ReadKey().Key != ConsoleKey.Escape);

        Console.WriteLine("End");
    }
Exemplo n.º 13
0
    private static async Task SyncProductCategoryAsync()
    {
        // Create 2 Sql Sync providers
        var serverProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(serverDbName));
        var clientProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(clientDbName));
        // specific Setup with only 2 tables, and one filtered
        var setup = new SyncSetup(new string[] { "ProductCategory" });

        // Creating an agent that will handle all the process
        var agent = new SyncAgent(clientProvider, serverProvider, setup);

        // Using the Progress pattern to handle progession during the synchronization
        var progress = new SynchronousProgress <ProgressArgs>(s =>
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"{s.Context.SyncStage}:\t{s.Message}");
            Console.ResetColor();
        });

        var remoteProgress = new SynchronousProgress <ProgressArgs>(s =>
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine($"{s.Context.SyncStage}:\t{s.Message}");
            Console.ResetColor();
        });

        agent.AddRemoteProgress(remoteProgress);

        agent.Options.BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "syncproduct");
        agent.Options.BatchSize         = 10;
        agent.Options.CleanMetadatas    = true;
        agent.Options.UseBulkOperations = true;
        agent.Options.DisableConstraintsOnApplyChanges = false;

        do
        {
            Console.Clear();
            Console.WriteLine("Sync Start");
            try
            {
                // Launch the sync process
                if (!agent.Parameters.Contains("City"))
                {
                    agent.Parameters.Add("City", "Toronto");
                }

                if (!agent.Parameters.Contains("postal"))
                {
                    agent.Parameters.Add("postal", DBNull.Value);
                }


                var s1 = await agent.SynchronizeAsync(progress);

                // Write results
                Console.WriteLine(s1);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


            //Console.WriteLine("Sync Ended. Press a key to start again, or Escapte to end");
        } while (Console.ReadKey().Key != ConsoleKey.Escape);

        Console.WriteLine("End");
    }
Exemplo n.º 14
0
    private static async Task SynchronizeWithSyncAgent2Async()
    {
        // Create 2 Sql Sync providers
        var serverProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString("AdventureWorks"));
        var clientProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString("Client"));

        // Tables involved in the sync process:
        var tables = new string[] { "ProductCategory", "ProductModel", "Product" };

        // Creating an agent that will handle all the process
        var agent = new SyncAgent(clientProvider, serverProvider, tables);

        // Using the Progress pattern to handle progession during the synchronization
        var progress = new SynchronousProgress <ProgressArgs>(s =>
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"{s.Context.SyncStage}:\t{s.Message}");
            Console.ResetColor();
        });

        var remoteProgress = new SynchronousProgress <ProgressArgs>(s =>
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"{s.Context.SyncStage}:\t{s.Message}");
            Console.ResetColor();
        });

        agent.AddRemoteProgress(remoteProgress);

        // Setting configuration options
        agent.Schema.StoredProceduresPrefix = "s";
        agent.Schema.StoredProceduresSuffix = "";
        agent.Schema.TrackingTablesPrefix   = "t";
        agent.Schema.TrackingTablesSuffix   = "";

        agent.Options.ScopeInfoTableName = "tscopeinfo";
        agent.Options.BatchDirectory     = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "sync");
        //agent.Options.BatchSize = 100;
        agent.Options.CleanMetadatas    = true;
        agent.Options.UseBulkOperations = true;
        agent.Options.UseVerboseErrors  = false;

        agent.LocalOrchestrator.OnTransactionOpen(to =>
        {
            var dt = DateTime.Now;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"Transaction Opened\t {dt.ToLongTimeString()}.{dt.Millisecond}");
            Console.ResetColor();
        });
        agent.LocalOrchestrator.OnTransactionCommit(to =>
        {
            var dt = DateTime.Now;
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"Transaction Commited\t {dt.ToLongTimeString()}.{dt.Millisecond}");
            Console.ResetColor();
        });


        agent.RemoteOrchestrator.OnTransactionOpen(to =>
        {
            var dt = DateTime.Now;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Transaction Opened\t {dt.ToLongTimeString()}.{dt.Millisecond}");
            Console.ResetColor();
        });
        agent.RemoteOrchestrator.OnTransactionCommit(to =>
        {
            var dt = DateTime.Now;
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"Transaction Commited\t {dt.ToLongTimeString()}.{dt.Millisecond}");
            Console.ResetColor();
        });

        do
        {
            Console.Clear();
            Console.WriteLine("Sync Start");
            try
            {
                // Launch the sync process
                var s1 = await agent.SynchronizeAsync(SyncType.Normal, CancellationToken.None, progress);

                // Write results
                Console.WriteLine(s1);
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }


            //Console.WriteLine("Sync Ended. Press a key to start again, or Escapte to end");
        } while (Console.ReadKey().Key != ConsoleKey.Escape);

        Console.WriteLine("End");
    }
Exemplo n.º 15
0
        public async Task <ProviderRun> RunAsync(ProviderFixture serverFixture, string[] tables = null,
                                                 Action <SyncConfiguration> conf = null, bool reuseAgent = true)
        {
            // server proxy
            var proxyClientProvider = new WebProxyClientProvider();

            var syncTables = tables ?? serverFixture.Tables;

            // local test, through tcp
            if (this.NetworkType == NetworkType.Tcp)
            {
                // create agent
                if (this.Agent == null || !reuseAgent)
                {
                    this.Agent = new SyncAgent(this.ClientProvider, serverFixture.ServerProvider, syncTables);
                }

                // copy conf settings
                if (conf != null)
                {
                    this.Agent.SetConfiguration(conf);
                }

                // Add Filers
                if (serverFixture.Filters != null && serverFixture.Filters.Count > 0)
                {
                    serverFixture.Filters.ForEach(f =>
                    {
                        if (!this.Agent.LocalProvider.Configuration.Filters.Contains(f))
                        {
                            this.Agent.LocalProvider.Configuration.Filters.Add(f);
                        }
                    });
                }

                // Add Filers values
                if (serverFixture.FilterParameters != null && serverFixture.FilterParameters.Count > 0)
                {
                    foreach (var syncParam in serverFixture.FilterParameters)
                    {
                        if (!this.Agent.Parameters.Contains(syncParam))
                        {
                            this.Agent.Parameters.Add(syncParam);
                        }
                    }
                }

                // sync
                try
                {
                    this.BeginRun?.Invoke(this.Agent.RemoteProvider);
                    this.Results = await this.Agent.SynchronizeAsync();

                    this.EndRun?.Invoke(this.Agent.RemoteProvider);
                }
                catch (Exception ex)
                {
                    this.Exception = ex;
                    Console.WriteLine(ex);
                }
            }

            // -----------------------------------------------------------------------
            // HTTP
            // -----------------------------------------------------------------------

            // tests through http proxy
            if (this.NetworkType == NetworkType.Http)
            {
                using (var server = new KestrellTestServer())
                {
                    // server handler
                    var serverHandler = new RequestDelegate(async context =>
                    {
                        // test if <> directory name works
                        var options = new Action <SyncOptions>(o => o.BatchDirectory = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "server"));

                        // sync
                        try
                        {
                            var proxyServerProvider = WebProxyServerProvider.Create(
                                context, serverFixture.ServerProvider, conf, options);

                            var serverProvider = proxyServerProvider.GetLocalProvider(context);

                            serverProvider.Configuration.Add(syncTables);

                            this.BeginRun?.Invoke(serverProvider);
                            await proxyServerProvider.HandleRequestAsync(context);
                            this.EndRun?.Invoke(serverProvider);
                        }
                        catch (Exception ew)
                        {
                            Console.WriteLine(ew);
                        }
                    });

                    var clientHandler = new ResponseDelegate(async(serviceUri) =>
                    {
                        // create agent
                        if (this.Agent == null || !reuseAgent)
                        {
                            this.Agent = new SyncAgent(this.ClientProvider, proxyClientProvider);
                        }

                        if (serverFixture.FilterParameters != null && serverFixture.FilterParameters.Count > 0)
                        {
                            foreach (var syncParam in serverFixture.FilterParameters)
                            {
                                if (!this.Agent.Parameters.Contains(syncParam))
                                {
                                    this.Agent.Parameters.Add(syncParam);
                                }
                            }
                        }

                        ((WebProxyClientProvider)this.Agent.RemoteProvider).ServiceUri = new Uri(serviceUri);

                        try
                        {
                            this.Results = await this.Agent.SynchronizeAsync();
                        }
                        catch (Exception ew)
                        {
                            this.Exception = ew;
                            Console.WriteLine(ew);
                        }
                    });
                    await server.Run(serverHandler, clientHandler);
                }
            }
            return(this);
        }
Exemplo n.º 16
0
    private static async Task TestDeleteWithoutBulkAsync()
    {
        var cs = DBHelper.GetDatabaseConnectionString(serverProductCategoryDbName);
        var cc = DBHelper.GetDatabaseConnectionString(clientDbName);

        // Create 2 Sql Sync providers
        var serverProvider   = new SqlSyncProvider(cs);
        var serverConnection = new SqlConnection(cs);

        //var clientProvider = new SqlSyncProvider(cc);
        //var clientConnection = new SqlConnection(cc);

        var clientProvider   = new SqliteSyncProvider("advworks2.db");
        var clientConnection = new SqliteConnection(clientProvider.ConnectionString);

        // Creating an agent that will handle all the process
        var agent = new SyncAgent(clientProvider, serverProvider, new string[] { "ProductCategory" });

        // Using the Progress pattern to handle progession during the synchronization
        var progress = new SynchronousProgress <ProgressArgs>(s =>
        {
            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine($"{s.Context.SyncStage}:\t{s.Message}");
            Console.ResetColor();
        });

        var remoteProgress = new SynchronousProgress <ProgressArgs>(s =>
        {
            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine($"{s.Context.SyncStage}:\t{s.Message}");
            Console.ResetColor();
        });

        // agent.AddRemoteProgress(remoteProgress);

        agent.Options.BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "sync");
        agent.Options.BatchSize         = 0;
        agent.Options.UseBulkOperations = false;
        agent.Options.DisableConstraintsOnApplyChanges = false;
        agent.Options.ConflictResolutionPolicy         = ConflictResolutionPolicy.ClientWins;

        Console.WriteLine("Sync Start");
        var s1 = await agent.SynchronizeAsync(progress);

        Console.WriteLine(s1);

        Console.WriteLine("Insert product category on Server");
        var id = InsertOneProductCategoryId(serverConnection, "GLASSES");

        Console.WriteLine("Update Done.");

        Console.WriteLine("Update product category on Server");
        UpdateOneProductCategoryId(serverConnection, id, "OVERGLASSES");
        Console.WriteLine("Update Done.");

        Console.WriteLine("Sync Start");
        s1 = await agent.SynchronizeAsync(progress);

        Console.WriteLine(s1);

        Console.WriteLine("End");
    }
Exemplo n.º 17
0
    public static async Task SyncHttpThroughKestellAsync()
    {
        // server provider
        var serverProvider = new SqlSyncProvider(GetDatabaseConnectionString("AdventureWorks"));
        // proxy server based on server provider
        var proxyServerProvider = new WebProxyServerProvider(serverProvider);

        // client provider
        var client1Provider = new SqlSyncProvider(GetDatabaseConnectionString("Client"));
        // proxy client provider
        var proxyClientProvider = new WebProxyClientProvider();

        var tables = new string[] { "ProductCategory",
                                    "ProductDescription", "ProductModel",
                                    "Product", "ProductModelProductDescription",
                                    "Address", "Customer", "CustomerAddress",
                                    "SalesOrderHeader", "SalesOrderDetail" };

        var configuration = new SyncConfiguration(tables)
        {
            ScopeName              = "AdventureWorks",
            ScopeInfoTableName     = "tscopeinfo",
            SerializationFormat    = Dotmim.Sync.Enumerations.SerializationFormat.Binary,
            StoredProceduresPrefix = "s",
            StoredProceduresSuffix = "",
            TrackingTablesPrefix   = "t",
            TrackingTablesSuffix   = "",
        };

        var optionsClient = new SyncOptions
        {
            BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "client"),
            BatchSize         = 400,
            CleanMetadatas    = true,
            UseBulkOperations = true,
            UseVerboseErrors  = false
        };

        var optionsServer = new SyncOptions
        {
            BatchDirectory    = Path.Combine(SyncOptions.GetDefaultUserBatchDiretory(), "server"),
            BatchSize         = 400,
            CleanMetadatas    = false,
            UseBulkOperations = true,
            UseVerboseErrors  = false
        };


        var serverHandler = new RequestDelegate(async context =>
        {
            proxyServerProvider.Configuration = configuration;

            await proxyServerProvider.HandleRequestAsync(context);
        });

        using (var server = new KestrellTestServer())
        {
            var clientHandler = new ResponseDelegate(async(serviceUri) =>
            {
                proxyClientProvider.ServiceUri = new Uri(serviceUri);

                var syncAgent = new SyncAgent(client1Provider, proxyClientProvider);

                do
                {
                    Console.Clear();
                    Console.WriteLine("Sync Start");
                    try
                    {
                        var cts = new CancellationTokenSource();

                        Console.WriteLine("--------------------------------------------------");
                        Console.WriteLine("1 : Normal synchronization.");
                        Console.WriteLine("2 : Fill configuration from server side");
                        Console.WriteLine("3 : Synchronization with reinitialize");
                        Console.WriteLine("4 : Synchronization with upload and reinitialize");
                        Console.WriteLine("5 : Deprovision everything from client side (tables included)");
                        Console.WriteLine("6 : Deprovision everything from client side (tables not included)");
                        Console.WriteLine("7 : Deprovision everything from server side (tables not included)");
                        Console.WriteLine("8 : Provision everything on the client side (tables included)");
                        Console.WriteLine("9 : Provision everything on the server side (tables not included)");
                        Console.WriteLine("10 : Insert datas on client");
                        Console.WriteLine("--------------------------------------------------");
                        Console.WriteLine("What's your choice ? ");
                        Console.WriteLine("--------------------------------------------------");
                        var choice = Console.ReadLine();

                        if (int.TryParse(choice, out var choiceNumber))
                        {
                            Console.WriteLine($"You choose {choice}. Start operation....");
                            switch (choiceNumber)
                            {
                            case 1:
                                var s1 = await syncAgent.SynchronizeAsync(cts.Token);
                                Console.WriteLine(s1);
                                break;

                            case 2:
                                var ctx = new SyncContext(Guid.NewGuid());
                                var syncConfigProvider      = new SqlSyncProvider(GetDatabaseConnectionString("AdventureWorks"));
                                (ctx, configuration.Schema) = await syncConfigProvider.EnsureSchemaAsync(ctx, new Dotmim.Sync.Messages.MessageEnsureSchema
                                {
                                    Schema = configuration.Schema,
                                    SerializationFormat = Dotmim.Sync.Enumerations.SerializationFormat.Json
                                });
                                break;

                            case 3:
                                s1 = await syncAgent.SynchronizeAsync(SyncType.Reinitialize, cts.Token);
                                Console.WriteLine(s1);
                                break;

                            case 4:
                                s1 = await syncAgent.SynchronizeAsync(SyncType.ReinitializeWithUpload, cts.Token);
                                Console.WriteLine(s1);
                                break;

                            case 5:
                                var clientSyncProvider = syncAgent.LocalProvider as SqlSyncProvider;
                                await clientSyncProvider.DeprovisionAsync(configuration, SyncProvision.All | SyncProvision.Table);
                                Console.WriteLine("Deprovision complete on client");
                                break;

                            case 6:
                                var client2SyncProvider = syncAgent.LocalProvider as SqlSyncProvider;
                                await client2SyncProvider.DeprovisionAsync(configuration, SyncProvision.All);
                                Console.WriteLine("Deprovision complete on client");
                                break;

                            case 7:
                                var remoteSyncProvider = new SqlSyncProvider(GetDatabaseConnectionString("AdventureWorks"));
                                await remoteSyncProvider.DeprovisionAsync(configuration, SyncProvision.All);
                                Console.WriteLine("Deprovision complete on remote");
                                break;

                            case 8:
                                var clientSyncProvider2 = syncAgent.LocalProvider as SqlSyncProvider;
                                await clientSyncProvider2.ProvisionAsync(configuration, SyncProvision.All | SyncProvision.Table);
                                Console.WriteLine("Provision complete on client");
                                break;

                            case 9:
                                var remoteSyncProvider2 = new SqlSyncProvider(GetDatabaseConnectionString("AdventureWorks"));
                                await remoteSyncProvider2.ProvisionAsync(configuration, SyncProvision.All);
                                Console.WriteLine("Provision complete on remote");
                                break;

                            case 10:
                                var c       = GetDatabaseConnectionString("Adv");
                                var catId   = await InsertProductCategory(c);
                                var modelId = await InsertProductModel(c);
                                await InsertProduct(c, catId, modelId);
                                Console.WriteLine("Inserted a model, a category and a product.");
                                break;

                            default:
                                break;
                            }
                        }
                    }
                    catch (SyncException e)
                    {
                        Console.WriteLine(e.ToString());
                    }
                    catch (Exception e)
                    {
                        Console.WriteLine("UNKNOW EXCEPTION : " + e.Message);
                    }


                    Console.WriteLine("--------------------------------------------------");
                    Console.WriteLine("Press a key to choose again, or Escapte to end");
                } while (Console.ReadKey().Key != ConsoleKey.Escape);
            });
            await server.Run(serverHandler, clientHandler);
        }
    }