Exemple #1
0
        public async Task SyncThroughHttp()
        {
            using (var server = new KestrellTestServer())
            {
                var serverHandler = new RequestDelegate(async context =>
                {
                    SqlSyncProvider serverProvider      = new SqlSyncProvider(this.fixture.ServerConnectionString);
                    SyncConfiguration configuration     = new SyncConfiguration(this.fixture.Tables);
                    configuration.DownloadBatchSizeInKB = 500;

                    WebProxyServerProvider proxyServerProvider = new WebProxyServerProvider(serverProvider);
                    proxyServerProvider.Configuration          = configuration;

                    await proxyServerProvider.HandleRequestAsync(context);
                });

                var clientHandler = new ResponseDelegate(async(serviceUri) =>
                {
                    var proxyProvider  = new WebProxyClientProvider(new Uri(serviceUri));
                    var clientProvider = new SqlSyncProvider(this.fixture.Client1ConnectionString);

                    SyncAgent agent = new SyncAgent(clientProvider, proxyProvider);
                    var session     = await agent.SynchronizeAsync();

                    Assert.Equal(5, session.TotalChangesDownloaded);
                    Assert.Equal(0, session.TotalChangesUploaded);
                });

                await server.Run(serverHandler, clientHandler);
            }
        }
Exemple #2
0
        public async Task Initialize()
        {
            var serverHandler = new RequestDelegate(async context =>
            {
                //configuration.AddTable(fixture.Tables);
                serverProvider.SetConfiguration(configuration);
                proxyServerProvider.SerializationFormat = SerializationFormat.Json;

                await proxyServerProvider.HandleRequestAsync(context);
            });

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

                    var syncAgent = new SyncAgent(clientProvider, proxyClientProvider);
                    var session   = await syncAgent.SynchronizeAsync();

                    Assert.Equal(7, session.TotalChangesDownloaded);
                    Assert.Equal(0, session.TotalChangesUploaded);
                });
                await server.Run(serverHandler, clientHandler);
            }

            // check relation has been created on client :
            int foreignKeysCount;

            using (var sqlConnection = new SqlConnection(fixture.Client1ConnectionString))
            {
                var script = $@"Select count(*) from sys.foreign_keys where name = 'FK_ServiceTickets_Customers'";

                using (var sqlCmd = new SqlCommand(script, sqlConnection))
                {
                    sqlConnection.Open();
                    foreignKeysCount = (int)sqlCmd.ExecuteScalar();
                    sqlConnection.Close();
                }
            }
            Assert.Equal(1, foreignKeysCount);
        }
        public async Task Post()
        {
            // The [Authorize] class attribute is enough, since it prevents anyone to access
            // this controller without a Bearer token
            // Checking the scope is optional
            // Anyway you can have a more detailed control using the claims !
            string scope = (User.FindFirst("http://schemas.microsoft.com/identity/claims/scope"))?.Value;
            string user  = (User.FindFirst(ClaimTypes.NameIdentifier))?.Value;

            if (scope != "access_as_user")
            {
                this.HttpContext.Response.StatusCode = StatusCodes.Status401Unauthorized;
                return;
            }

            await webProxyServer.HandleRequestAsync(this.HttpContext);
        }
Exemple #4
0
        public async Task Post()
        {
            // Get the underline local provider
            var provider = webProxyServer.GetLocalProvider(this.HttpContext);

            provider.InterceptApplyChangesFailed(e =>
            {
                if (e.Conflict.RemoteRow.Table.TableName == "Region")
                {
                    e.Resolution = ConflictResolution.MergeRow;
                    e.FinalRow["RegionDescription"] = "Eastern alone !";
                }
                else
                {
                    e.Resolution = ConflictResolution.ServerWins;
                }
            });

            await webProxyServer.HandleRequestAsync(this.HttpContext);
        }
Exemple #5
0
        public async Task Initialize()
        {
            using (var server = new KestrellTestServer())
            {
                var serverHandler = new RequestDelegate(async context =>
                {
                    //configuration.AddTable(fixture.Tables);
                    serverProvider.SetConfiguration(configuration);
                    proxyServerProvider.SerializationFormat = SerializationFormat.Json;

                    await proxyServerProvider.HandleRequestAsync(context);
                });
                var clientHandler = new ResponseDelegate(async(serviceUri) =>
                {
                    proxyClientProvider.ServiceUri          = new Uri(serviceUri);
                    proxyClientProvider.SerializationFormat = SerializationFormat.Json;

                    var session = await agent.SynchronizeAsync();

                    Assert.Equal(50, session.TotalChangesDownloaded);
                    Assert.Equal(0, session.TotalChangesUploaded);
                });
                await server.Run(serverHandler, clientHandler);
            }
        }
 public async Task Post()
 {
     await webProxyServer.HandleRequestAsync(this.HttpContext);
 }
Exemple #7
0
 public async Task <HttpResponseMessage> Post()
 {
     return(await webProxyServer.HandleRequestAsync(this.Request, new HttpContextWrapper(HttpContext.Current)));
 }
        public async Task <ProviderRun> RunAsync(CoreProvider serverProvider, ProviderFixture <CoreProvider> serverFixture, string scopeName = null, string[] tables = null, SyncConfiguration conf = null,
                                                 bool reuseAgent = true)
        {
            // server proxy
            var proxyServerProvider = new WebProxyServerProvider(serverProvider);
            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, serverProvider, syncTables);
                }

                // copy conf settings
                if (conf != null)
                {
                    serverFixture.CopyConfiguration(this.Agent.Configuration, conf);
                }

                // Add Filers
                if (serverFixture.Filters != null && serverFixture.Filters.Count > 0)
                {
                    serverFixture.Filters.ForEach(f =>
                    {
                        if (!this.Agent.Configuration.Filters.Contains(f))
                        {
                            this.Agent.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)
            {
                // client handler
                using (var server = new KestrellTestServer())
                {
                    // server handler
                    var serverHandler = new RequestDelegate(async context =>
                    {
                        var syncConfiguration = new SyncConfiguration(syncTables);// set proxy conf
                        // copy conf settings

                        if (conf != null)
                        {
                            serverFixture.CopyConfiguration(syncConfiguration, conf);
                        }


                        // set proxy conf
                        proxyServerProvider.Configuration = syncConfiguration;

                        // test if <> directory name works
                        proxyServerProvider.Configuration.BatchDirectory = Path.Combine(proxyServerProvider.Configuration.BatchDirectory, "server");

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


                        // sync
                        try
                        {
                            this.BeginRun?.Invoke(proxyServerProvider.LocalProvider);
                            await proxyServerProvider.HandleRequestAsync(context);
                            this.EndRun?.Invoke(proxyServerProvider.LocalProvider);
                        }
                        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);
        }
Exemple #9
0
    public async static 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("Adv"));
        // 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,
            DownloadBatchSizeInKB  = 400,
            StoredProceduresPrefix = "s",
            StoredProceduresSuffix = "",
            TrackingTablesPrefix   = "t",
            TrackingTablesSuffix   = "",
        };


        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
                    {
                        CancellationTokenSource 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 int 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:
                                SyncContext ctx = new SyncContext(Guid.NewGuid());
                                SqlSyncProvider 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:
                                SqlSyncProvider clientSyncProvider = syncAgent.LocalProvider as SqlSyncProvider;
                                await clientSyncProvider.DeprovisionAsync(configuration, SyncProvision.All | SyncProvision.Table);
                                Console.WriteLine("Deprovision complete on client");
                                break;

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

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

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

                            case 9:
                                SqlSyncProvider 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);
        }
    }
Exemple #10
0
    /// <summary>
    /// Test syncking through Kestrell server
    /// </summary>
    private static async Task TestSyncThroughKestrellAsync()
    {
        var id = Guid.NewGuid();

        ConfigurationBuilder configurationBuilder = new ConfigurationBuilder();

        configurationBuilder.AddJsonFile("config.json", true);
        IConfiguration Configuration = configurationBuilder.Build();
        var            serverConfig  = Configuration["AppConfiguration:ServerConnectionString"];
        var            clientConfig  = Configuration["AppConfiguration:ClientConnectionString"];

        // Server side
        var serverHandler = new RequestDelegate(async context =>
        {
            // Create the internal provider
            SqlSyncProvider serverProvider = new SqlSyncProvider(serverConfig);
            // Create the configuration stuff
            ServiceConfiguration configuration  = new ServiceConfiguration(new string[] { "ServiceTickets" });
            configuration.DownloadBatchSizeInKB = 500;
            serverProvider.SetConfiguration(configuration);

            // Create the proxy provider
            WebProxyServerProvider proxyServerProvider = new WebProxyServerProvider(serverProvider, SerializationFormat.Json);

            serverProvider.SyncProgress += ServerProvider_SyncProgress;

            try
            {
                CancellationTokenSource cts = new CancellationTokenSource();
                //   cts.CancelAfter(60000);
                CancellationToken token = cts.Token;
                await proxyServerProvider.HandleRequestAsync(context, token);
            }
            catch (WebSyncException webSyncException)
            {
                Console.WriteLine("Proxy Server WebSyncException : " + webSyncException.Message);
            }
            catch (Exception e)
            {
                Console.WriteLine("Proxy Server Exception : " + e.Message);
                throw e;
            }
        });

        var clientHandler = new ResponseDelegate(async(serviceUri) =>
        {
            var proxyProvider  = new WebProxyClientProvider(new Uri(serviceUri), SerializationFormat.Json);
            var clientProvider = new SqlSyncProvider(clientConfig);

            SyncAgent agent = new SyncAgent(clientProvider, proxyProvider);

            agent.SyncProgress += Agent_SyncProgress;
            do
            {
                try
                {
                    CancellationTokenSource cts = new CancellationTokenSource();
                    //cts.CancelAfter(1000);
                    CancellationToken token = cts.Token;
                    var s = await agent.SynchronizeAsync(token);
                }
                catch (WebSyncException webSyncException)
                {
                    Console.WriteLine("Proxy Client WebSyncException : " + webSyncException.Message);
                }
                catch (Exception e)
                {
                    Console.WriteLine("Proxy Client Exception : " + e.Message);
                }

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


        await TestKestrelHttpServer.LaunchKestrellAsync(serverHandler, clientHandler);
    }