// This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();
            services.AddMemoryCache();

            services.AddSingleton(Configuration);

            var connectionString = Configuration.GetConnectionString("DefaultConnection");
            var syncSetup        = new SyncSetup(new string[] { "Customer" });

            services.AddSingleton(syncSetup);
            var snapshotDirectoryName = "snapshots";
            var snapshotDirectory     = Path.Combine(Environment.CurrentDirectory, snapshotDirectoryName);
            var syncOptions           = new SyncOptions
            {
                SnapshotsDirectory = snapshotDirectory,
                BatchSize          = 500
            };

            services.AddTransient(x => new SyncOptions
            {
                SnapshotsDirectory = snapshotDirectory,
                BatchSize          = 500
            });
            var webServerOptions = new WebServerOptions();

            services.AddSyncServer <SqlSyncProvider>(connectionString, syncSetup, syncOptions, webServerOptions);
        }
        public static void Send(this Response response, Socket socket, WebServerOptions serverOptions)
        {
            var logger = serverOptions.Logger;

            logger.Debug("Start sending response");
            var messageBytes = new byte[0];

            var constantHeaders = $@"HTTP/1.1 {response.ResponseCode.GetValue()} {response.ResponseCode.GetMessage()}
Server: {serverOptions.ServerName}
Content-Type: {response.ContentType}";

            if (response.Type == ResponseType.Text)
            {
                var message = $@"{constantHeaders}

{response.Body}
";
                messageBytes = Encoding.ASCII.GetBytes(message);
            }

            if (response.Type == ResponseType.Binary)
            {
                var message = $@"{constantHeaders}

";
                messageBytes = Encoding.ASCII.GetBytes(message);
                messageBytes = messageBytes.Concat(response.Bytes).ToArray();
            }
            logger.Debug($"Sending {messageBytes.Length} bytes to socket");
            socket.Send(messageBytes);
            logger.Debug($"Sent {messageBytes.Length} bytes to socket");
        }
Exemple #3
0
        public async Task OpenWebServerHttps_RetrievesIndex()
        {
            if (SwanRuntime.OS != Swan.OperatingSystem.Windows)
            {
                Assert.Ignore("Only Windows");
            }

            ServicePointManager.ServerCertificateValidationCallback = ValidateCertificate;

            var options = new WebServerOptions()
                          .WithUrlPrefix(HttpsUrl)
                          .WithAutoLoadCertificate()
                          .WithMode(HttpListenerMode.EmbedIO);

            using (var webServer = new WebServer(options))
            {
                webServer.OnAny(ctx => ctx.SendStringAsync(DefaultMessage, MimeType.PlainText, Encoding.UTF8));

                var dump = webServer.RunAsync();

                using (var httpClientHandler = new HttpClientHandler())
                {
                    httpClientHandler.ServerCertificateCustomValidationCallback = ValidateCertificate;
                    using (var httpClient = new HttpClient(httpClientHandler))
                    {
                        Assert.AreEqual(DefaultMessage, await httpClient.GetStringAsync(HttpsUrl));
                    }
                }
            }
        }
Exemple #4
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddControllers();

            services.AddDistributedMemoryCache();
            services.AddSession(options => options.IdleTimeout = TimeSpan.FromMinutes(30));

            // [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" };

            // To add a converter, create an instance and add it to the special WebServerOptions
            var webServerOptions = new WebServerOptions();

            webServerOptions.Converters.Add(new CustomConverter());
            webServerOptions.SerializerFactories.Add(new CustomMessagePackSerializerFactory());

            var options = new SyncOptions {
            };

            // [Required]: Add a SqlSyncProvider acting as the server hub.
            services.AddSyncServer <SqlSyncChangeTrackingProvider>(connectionString, tables, options, webServerOptions);
        }
Exemple #5
0
        /// <summary>
        /// Habilitar API local para configuración
        /// </summary>
        public DeviceServerCore EnableApi()
        {
            if (WebServer == null)
            {
                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12 | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls;

                var configuration    = ConfigurationManager.Get <IWebServerConfiguration>();
                var sslConfiguration = ConfigurationManager.Get <ISSLConfiguration>();

                WebServerOptions opts = ConfigureWebServer(configuration, sslConfiguration);
                WebServer = new WebServer(opts);

                WebServer.RegisterModule(new WebApiModule());
                WebServer.Module <WebApiModule>().RegisterController <SystemController>();

                if (configuration.EnableFilesModule)
                {
                    if (Directory.Exists(configuration.FilesModulePath))
                    {
                        Debug.WriteLine(this, "Habilitando modulo de archivos para el WebServer", VerbosityLevel.Debug);
                        WebServer.RegisterModule(new StaticFilesModule(configuration.FilesModulePath));
                    }
                    else
                    {
                        Debug.WriteLine(this, "La ruta al directorio de archivos estaticos no es correcta", VerbosityLevel.Debug);
                    }
                }

                WebServer.RunAsync();
            }
            return(this);
        }
Exemple #6
0
        public OneDasConsole(IOptions <WebServerOptions> options)
        {
            _webServerOptions       = options.Value;
            _syncLock_UpdateConsole = new object();

            Console.CursorVisible = false;
        }
        public async Task OpenWebServerHttps_RetrievesIndex()
        {
            if (Runtime.OS != Swan.OperatingSystem.Windows)
            {
                Assert.Ignore("Only Windows");
            }

            // bypass certification validation
            System.Net.ServicePointManager.ServerCertificateValidationCallback = (s, c, cert, x) => true;

            var options = new WebServerOptions(HttpsUrl)
            {
                AutoLoadCertificate = true,
                Mode = HttpListenerMode.EmbedIO,
            };

            using (var webServer = new WebServer(options))
            {
                webServer.OnAny((ctx, ct) => ctx.HtmlResponseAsync(DefaultMessage, cancellationToken: ct));

                webServer.RunAsync();

                using (var httpClientHandler = new HttpClientHandler())
                {
#if !NET452
                    httpClientHandler.ServerCertificateCustomValidationCallback = (s, c, cert, x) => true;
#endif
                    using (var httpClient = new HttpClient(httpClientHandler))
                    {
                        Assert.AreEqual(DefaultMessage, await httpClient.GetStringAsync(HttpsUrl));
                    }
                }
            }
        }
Exemple #8
0
    internal static async Task <(ServerURLs, IWebHost)> StartAsync(WebServerOptions options, ILogger logger, CancellationToken token)
    {
        string[]? urls = new string[] { $"http://127.0.0.1:{options.Port}", "https://127.0.0.1:0" };

        IWebHostBuilder builder = new WebHostBuilder()
                                  .UseKestrel()
                                  .UseStartup <WebServerStartup>()
                                  .ConfigureLogging(logging =>
        {
            logging.AddConsole().AddFilter(null, LogLevel.Warning);
        })
                                  .ConfigureServices((ctx, services) =>
        {
            if (options.WebServerUseCors)
            {
                services.AddCors(o => o.AddPolicy("AnyCors", builder =>
                {
                    builder.AllowAnyOrigin()
                    .AllowAnyMethod()
                    .AllowAnyHeader()
                    .WithExposedHeaders("*");
                }));
            }
            services.AddSingleton(logger);
            services.AddSingleton(Options.Create(options));
            services.AddRouting();
        })
                                  .UseUrls(urls);

        if (options.ContentRootPath != null)
        {
            builder.UseContentRoot(options.ContentRootPath);
        }

        IWebHost?host = builder.Build();
        await host.StartAsync(token);

        ICollection <string>?addresses = host.ServerFeatures
                                         .Get <IServerAddressesFeature>()?
                                         .Addresses;

        string?ipAddress =
            addresses?
            .Where(a => a.StartsWith("http:", StringComparison.InvariantCultureIgnoreCase))
            .Select(a => new Uri(a))
            .Select(uri => uri.ToString())
            .FirstOrDefault();

        string?ipAddressSecure =
            addresses?
            .Where(a => a.StartsWith("https:", StringComparison.OrdinalIgnoreCase))
            .Select(a => new Uri(a))
            .Select(uri => uri.ToString())
            .FirstOrDefault();

        return(ipAddress == null || ipAddressSecure == null
            ? throw new InvalidOperationException("Failed to determine web server's IP address or port")
            : (new ServerURLs(ipAddress, ipAddressSecure), host));
    }
Exemple #9
0
        public SimpleWebServer(WebServerOptions options)
        {
            _options  = options ?? throw new ArgumentNullException(nameof(options));
            _listener = new HttpListener();
            _listener = new HttpListener();
            _thread   = new Thread(Listen);

            _listener.Prefixes.Add($"http://{_options.Host}:{_options.Port}/");
        }
Exemple #10
0
        public SillyWebServer(WebServerOptions options)
        {
            _options  = options ?? throw new ArgumentNullException(nameof(options));
            _listener = new HttpListener();
            _thread   = new Thread(Listen);
            _lock     = new MonitorLock((_handleThreads as ICollection).SyncRoot);

            _listener.Prefixes.Add($"http://{_options.Host}:{_options.Port}/");
        }
        public static IServiceCollection AddSyncServer(this IServiceCollection serviceCollection, IConfiguration configuration, Type providerType,
                                                       string connectionString, string scopeName = SyncOptions.DefaultScopeName, SyncSetup setup = null, SyncOptions options = null, WebServerOptions webServerOptions = null)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            // Create default web server options
            if (webServerOptions == null)
            {
                webServerOptions = new WebServerOptions();
            }

            options ??= new SyncOptions();
            setup = setup ?? throw new ArgumentNullException(nameof(setup));

            var serviceProvider = serviceCollection.BuildServiceProvider();

            serviceCollection.AddMemoryCache();

            // Get all registered server providers with schema and options
            var webServerManager = serviceProvider.GetService <WebServerManager>();

            // On first time, inject the singleton in the service collection provider
            if (webServerManager == null)
            {
                var cache = serviceProvider.GetService <IMemoryCache>();
#if NET5_0 || NETCOREAPP3_1
                var env = serviceProvider.GetService <IWebHostEnvironment>();
#elif NETSTANDARD
                var env = serviceProvider.GetService <IHostingEnvironment>();
#endif
                webServerManager = new WebServerManager(cache, env);
                serviceCollection.AddSingleton(webServerManager);
            }

            // Check if we don't have already added this scope name provider to the remote orchestrator list
            if (webServerManager.Contains(scopeName))
            {
                throw new ArgumentException($"Orchestrator with scope name {scopeName} already exists in the service collection");
            }

            // Create provider
            var provider = (CoreProvider)Activator.CreateInstance(providerType);
            provider.ConnectionString = connectionString;

            // Create orchestrator
            var webServerOrchestrator = new WebServerOrchestrator(provider, options, webServerOptions, setup, webServerManager.Cache, scopeName);

            // add it to the singleton collection
            webServerManager.Add(webServerOrchestrator);

            return(serviceCollection);
        }
Exemple #12
0
        public void OpenWebServerHttpsWithoutCert_ThrowsInvalidOperation()
        {
            if (SwanRuntime.OS != Swan.OperatingSystem.Windows)
            {
                Assert.Ignore("Only Windows");
            }

            var options = new WebServerOptions()
                          .WithUrlPrefix(HttpsUrl)
                          .WithAutoRegisterCertificate();

            Assert.Throws <InvalidOperationException>(() => new WebServer(options).Void());
        }
        public void OpenWebServerHttpsWithLinuxOrMac_ThrowsInvalidOperation()
        {
            if (Runtime.OS == Swan.OperatingSystem.Windows)
            {
                Assert.Ignore("Ignore Windows");
            }

            var options = new WebServerOptions(HttpsUrl)
            {
                AutoLoadCertificate = true,
            };

            Assert.Throws <InvalidOperationException>(() => new WebServer(options));
        }
Exemple #14
0
        public void OpenWebServerHttpsWithInvalidStore_ThrowsInvalidOperation()
        {
            if (SwanRuntime.OS != Swan.OperatingSystem.Windows)
            {
                Assert.Ignore("Only Windows");
            }

            var options = new WebServerOptions()
                          .WithUrlPrefix(HttpsUrl)
                          .WithCertificate(new X509Certificate2())
                          .WithAutoRegisterCertificate();

            Assert.Throws <System.Security.Cryptography.CryptographicException>(() => _ = new WebServer(options));
        }
Exemple #15
0
        public void OpenWebServerHttpsWithLinuxOrMac_ThrowsInvalidOperation()
        {
            if (SwanRuntime.OS == Swan.OperatingSystem.Windows)
            {
                Assert.Ignore("Ignore Windows");
            }

            Assert.Throws <PlatformNotSupportedException>(() => {
                var options = new WebServerOptions()
                              .WithUrlPrefix(HttpsUrl)
                              .WithAutoLoadCertificate();

                new WebServer(options).Void();
            });
        }
Exemple #16
0
 public WebClientHub(
     OneDasEngine engine,
     OneDasPackageManager packageManager,
     ClientPushService clientPushService,
     IExtensionFactory extensionFactory,
     ILoggerFactory loggerFactory,
     IOneDasProjectSerializer projectSerializer,
     IOptions <WebServerOptions> options)
 {
     _engine            = engine;
     _packageManager    = packageManager;
     _clientPushService = clientPushService;
     _extensionFactory  = extensionFactory;
     _webServerLogger   = loggerFactory.CreateLogger("WebServer");
     _projectSerializer = projectSerializer;
     _webServerOptions  = options.Value;
 }
        /// <summary>
        /// Creates the web server.
        /// </summary>
        /// <param name="urls">The urls.</param>
        /// <returns></returns>
        private IWebServer CreateWebServer(string[] urls)
        {
            //remove built in console logger and register the override that wraps serilog
#if DEBUG
            Logger.UnregisterLogger <ConsoleLogger>();
#endif
            Logger.RegisterLogger(new WebServerLogger(Log.Logger));

            WebServerOptions options = new WebServerOptions();
            options.WithUrlPrefixes(urls);
            options.WithMode(HttpListenerMode.EmbedIO);
            var server = new EmbedIO.WebServer(options);

            server.WithWebApi("/api", m => m
                              .WithController(() => _controller));

            return(server);
        }
Exemple #18
0
        public WebServer(IUnityContainer container, string pathStaticFiles = null, bool developmentMode = false)
        {
            var config = container.Resolve <Config>();

            scheduler = container.Resolve <IScheduler>();
            shutdown  = container.IsRegistered <IShutdown>() ? container.Resolve <IShutdown>() : null;

            var options = new WebServerOptions()
                          .WithMode(HttpListenerMode.Microsoft)
                          .WithUrlPrefix(config.HostingURI);

            var frontendSettings = new
            {
                appName   = getApplicationName(),
                apiUrl    = $"{config.HostingURI}/api",
                isService = shutdown == null
            };

            server = new EmbedServer(options);

            // Из-за отсутствия обработчика ошибок в EmbedIO приходится использовать такой странный способ проверки занятости префикса
            // Конкретнее: https://github.com/unosquare/embedio/blob/3.1.3/src/EmbedIO/WebServerBase%601.cs#L208
            // Проверяется только токен отмены, а все ошибки включая запуск HttpListener будут проигнорированы без всякого сообщения
            server.Listener.Start();
            server.Listener.Stop();

            if (developmentMode)
            {
                server.WithCors();
            }

            server.WithModule(nameof(WebSocketStatus), new WebSocketStatus(scheduler, "/ws-status"));

            server.WithWebApi("/api", m => m.WithController(() => new JobController(shutdown, scheduler)))
            .WithModule(new ActionModule("/settings.json", HttpVerbs.Get, ctx => ctx.SendDataAsync(frontendSettings)));

            if (pathStaticFiles != null)
            {
                server.WithStaticFolder("/", pathStaticFiles, true);
            }

            server.StateChanged += (s, e) => logger.Debug($"New State: {e.NewState}");
            server.RunAsync();
        }
Exemple #19
0
        /// <summary>
        /// Crear configuración para el servidor WebServer en base a la configuración provista
        /// </summary>
        /// <param name="configuration">Estructura de configuración</param>
        private WebServerOptions ConfigureWebServer(IWebServerConfiguration serverConfiguration, ISSLConfiguration configuration)
        {
            WebServerOptions opts;
            List <string>    urlPrefixes = new List <string>
            {
                $"http://*:{serverConfiguration.HttpPort}/"
            };

            if (configuration.Secure && Helper.SSL.Status == SSLCertificateStatus.Loaded)
            {
                urlPrefixes.Add($"https://*:{serverConfiguration.HttpsPort}/");
                opts = new WebServerOptions(urlPrefixes.ToArray())
                {
                    Certificate = Helper.SSL.GlobalCertificate
                };
            }
            else
            {
                opts = new WebServerOptions(urlPrefixes.ToArray());
            }
            return(opts);
        }
Exemple #20
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);
        }
        private static WebServer StartWebServerOnAvailablePort(out Uri serverUri, Action <IHttpContext> handler)
        {
            var module = new SimpleModule(handler);

            for (int port = 10000; ; port++)
            {
                var options = new WebServerOptions()
                              .WithUrlPrefix($"http://*:{port}")
                              .WithMode(HttpListenerMode.EmbedIO);
                var server = new WebServer(options).WithModule(module);
                try
                {
                    _ = server.RunAsync();
                }
                catch (HttpListenerException)
                {
                    continue;
                }
                serverUri = new Uri(string.Format("http://localhost:{0}", port));
                return(server);
            }
        }
Exemple #22
0
        private static WebServer CreateWebServer(string url)
        {
            // Opções do servidor
            var options = new WebServerOptions();

            options.WithUrlPrefix(url);

            // Criação do servidor
            var server = new WebServer(options);

            server.WithCors(ConfigurationManager.AppSettings["origin"]);
            server.HandleUnhandledException(CustomExceptionHandler.ResponseForUnhandledException);
            server.HandleHttpException(CustomExceptionHandler.ResponseForHttpException);

            // Criação do módulo de API
            var module = new WebApiModule("/");

            module.WithController <SatController>();
            server.WithModule(module);

            return(server);
        }
Exemple #23
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);
        }
 public static IServiceCollection AddSyncServer <TProvider>(this IServiceCollection serviceCollection, IConfiguration configuration, string connectionString, SyncSetup setup = null, SyncOptions options = null, WebServerOptions webServerOptions = null) where TProvider : CoreProvider, new()
 => serviceCollection.AddSyncServer(configuration, typeof(TProvider), connectionString, SyncOptions.DefaultScopeName, setup, options, webServerOptions);
 public static IServiceCollection AddSyncServer <TProvider>(this IServiceCollection serviceCollection, string connectionString, string[] tables, WebServerOptions options = null) where TProvider : CoreProvider, new()
 => serviceCollection.AddSyncServer(typeof(TProvider), connectionString, new SyncSetup(tables), options);
Exemple #26
0
    public static async Task SyncHttpThroughKestellAsync()
    {
        // server provider
        // Create 2 Sql Sync providers
        var serverProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(serverDbName));
        var clientProvider = new SqlSyncProvider(DbHelper.GetDatabaseConnectionString(clientDbName));


        // ----------------------------------
        // Client side
        // ----------------------------------
        var clientOptions = new SyncOptions {
            BatchSize = 500
        };

        var proxyClientProvider = new WebClientOrchestrator();

        // ----------------------------------
        // Web Server side
        // ----------------------------------
        var setup = new SyncSetup(allTables)
        {
            ScopeName = "all_tables_scope",
            StoredProceduresPrefix = "s",
            StoredProceduresSuffix = "",
            TrackingTablesPrefix   = "t",
            TrackingTablesSuffix   = "",
            TriggersPrefix         = "",
            TriggersSuffix         = "t"
        };

        // snapshot directory
        var directory = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile), "Snapshots");

        // ----------------------------------
        // Create a snapshot
        // ----------------------------------
        Console.ForegroundColor = ConsoleColor.Yellow;
        Console.WriteLine($"Creating snapshot");
        var remoteOrchestrator = new RemoteOrchestrator(serverProvider);
        await remoteOrchestrator.CreateSnapshotAsync(new SyncContext(), setup, directory, 500, CancellationToken.None);

        Console.WriteLine($"Done.");
        Console.ResetColor();


        // ----------------------------------
        // Insert a value after snapshot created
        // ----------------------------------
        using (var c = serverProvider.CreateConnection())
        {
            var command = c.CreateCommand();
            command.CommandText = "INSERT INTO [dbo].[ProductCategory] ([Name]) VALUES ('Bikes revolution');";
            c.Open();
            command.ExecuteNonQuery();
            c.Close();
        }

        var webServerOptions = new WebServerOptions {
            SnapshotsDirectory = directory
        };

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

        agent.Options = clientOptions;

        var configureServices = new Action <IServiceCollection>(services =>
        {
            services.AddSyncServer <SqlSyncProvider>(serverProvider.ConnectionString, setup, webServerOptions);
        });

        var serverHandler = new RequestDelegate(async context =>
        {
            var webProxyServer = context.RequestServices.GetService(typeof(WebProxyServerOrchestrator)) as WebProxyServerOrchestrator;
            await webProxyServer.HandleRequestAsync(context);
        });

        using (var server = new KestrellTestServer(configureServices))
        {
            var clientHandler = new ResponseDelegate(async(serviceUri) =>
            {
                proxyClientProvider.ServiceUri = serviceUri;
                do
                {
                    Console.Clear();
                    Console.WriteLine("Web sync start");
                    try
                    {
                        var progress = new SynchronousProgress <ProgressArgs>(pa => Console.WriteLine($"{pa.Context.SyncStage}\t {pa.Message}"));
                        var s        = await agent.SynchronizeAsync(progress);
                        Console.WriteLine(s);
                    }
                    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);
            });
            await server.Run(serverHandler, clientHandler);
        }
    }
        /// <summary>
        /// Add the server provider (inherited from CoreProvider) and register in the DI a WebProxyServerProvider.
        /// Use the WebProxyServerProvider in your controller, by inject it.
        /// </summary>
        /// <param name="providerType">Provider inherited from CoreProvider (SqlSyncProvider, MySqlSyncProvider, OracleSyncProvider) Should have [CanBeServerProvider=true] </param>
        /// <param name="serviceCollection">services collections</param>
        /// <param name="connectionString">Provider connection string</param>
        /// <param name="setup">Configuration server side. Adding at least tables to be synchronized</param>
        /// <param name="options">Options, not shared with client, but only applied locally. Can be null</param>

        public static IServiceCollection AddSyncServer(this IServiceCollection serviceCollection, Type providerType,
                                                       string connectionString, SyncSetup setup = null, WebServerOptions options = null)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }

            //serviceCollection.AddOptions();

            // create cache instance
            var webServerProperties = new WebServerProperties
            {
                ProviderType     = providerType,
                Options          = options ?? new WebServerOptions(),
                ConnectionString = connectionString,
                Setup            = setup
            };

            // Add this to the service pool injection
            serviceCollection.AddSingleton(webServerProperties);

            // Add this to the service pool injection
            serviceCollection.AddScoped <WebProxyServerOrchestrator>();

            return(serviceCollection);
        }
Exemple #28
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        private static async Task Main(string[] args)
        {
            var url = args.Length > 0 ? args[0] : "http://*:8877";

            AppDbContext.InitDatabase();

            var ctSource = new CancellationTokenSource();

            ctSource.Token.Register(() => "Shutting down".Info(nameof(Main)));

            // Set a task waiting for press key to exit
#pragma warning disable 4014
            Task.Run(() =>
#pragma warning restore 4014
            {
                // Wait for any key to be pressed before disposing of our web server.
                Console.ReadLine();

                ctSource.Cancel();
            }, ctSource.Token);

            var webOptions = new WebServerOptions(url)
            {
                Mode = HttpListenerMode.EmbedIO
            };

            // Our web server is disposable.
            using (var server = new WebServer(webOptions))
            {
                // First, we will configure our web server by adding Modules.
                // Please note that order DOES matter.
                // ================================================================================================
                // If we want to enable sessions, we simply register the LocalSessionModule
                // Beware that this is an in-memory session storage mechanism so, avoid storing very large objects.
                // You can use the server.GetSession() method to get the SessionInfo object and manipulate it.
                server.RegisterModule(new LocalSessionModule());

                // Set the CORS Rules
                server.RegisterModule(new CorsModule(
                                          // Origins, separated by comma without last slash
                                          "http://unosquare.github.io,http://run.plnkr.co",
                                          // Allowed headers
                                          "content-type, accept",
                                          // Allowed methods
                                          "post"));

                // Register the static files server. See the html folder of this project. Also notice that
                // the files under the html folder have Copy To Output Folder = Copy if Newer
                server.RegisterModule(new StaticFilesModule(HtmlRootPath));

                // Register the Web Api Module. See the Setup method to find out how to do it
                // It registers the WebApiModule and registers the controller(s) -- that's all.
                server.WithWebApiController <PeopleController>(true);

                // Register the WebSockets module. See the Setup method to find out how to do it
                // It registers the WebSocketsModule and registers the server for the given paths(s)
                server.RegisterModule(new WebSocketsModule());
                server.Module <WebSocketsModule>().RegisterWebSocketsServer <WebSocketsChatServer>();
                server.Module <WebSocketsModule>().RegisterWebSocketsServer <WebSocketsTerminalServer>();

                server.RegisterModule(new FallbackModule((ctx, ct) => ctx.JsonResponseAsync(new { Message = "Error" }, ct)));

                // Fire up the browser to show the content!
                var browser = new Process
                {
                    StartInfo = new ProcessStartInfo(url.Replace("*", "localhost"))
                    {
                        UseShellExecute = true
                    }
                };

                browser.Start();

                // Once we've registered our modules and configured them, we call the RunAsync() method.
                if (!ctSource.IsCancellationRequested)
                {
                    await server.RunAsync(ctSource.Token);
                }

                // Clean up
                "Bye".Info(nameof(Program));
                Terminal.Flush();
            }
        }
 public static IServiceCollection AddSyncServer <TProvider>(this IServiceCollection serviceCollection, string connectionString, string[] tables = default, SyncOptions options = null, WebServerOptions webServerOptions = null) where TProvider : CoreProvider, new()
 => serviceCollection.AddSyncServer(typeof(TProvider), connectionString, SyncOptions.DefaultScopeName, new SyncSetup(tables), options, webServerOptions);
        /// <summary>
        /// Add the server provider (inherited from CoreProvider) and register in the DI a WebServerAgent.
        /// Use the WebServerAgent in your controller, by inject it.
        /// </summary>
        /// <param name="providerType">Provider inherited from CoreProvider (SqlSyncProvider, MySqlSyncProvider, OracleSyncProvider) Should have [CanBeServerProvider=true] </param>
        /// <param name="serviceCollection">services collections</param>
        /// <param name="connectionString">Provider connection string</param>
        /// <param name="setup">Configuration server side. Adding at least tables to be synchronized</param>
        /// <param name="options">Options, not shared with client, but only applied locally. Can be null</param>

        public static IServiceCollection AddSyncServer(this IServiceCollection serviceCollection, Type providerType,
                                                       string connectionString, string scopeName = SyncOptions.DefaultScopeName, SyncSetup setup = null, SyncOptions options = null, WebServerOptions webServerOptions = null)
        {
            if (string.IsNullOrWhiteSpace(connectionString))
            {
                throw new ArgumentNullException(nameof(connectionString));
            }


            webServerOptions ??= new WebServerOptions();
            options ??= new SyncOptions();
            setup = setup ?? throw new ArgumentNullException(nameof(setup));

            // Create provider
            var provider = (CoreProvider)Activator.CreateInstance(providerType);

            provider.ConnectionString = connectionString;

            // Create orchestrator
            //var webServerAgent = new WebServerAgent(provider, setup, options, webServerOptions, scopeName);
            serviceCollection.AddScoped(sp => new WebServerAgent(provider, setup, options, webServerOptions, scopeName));

            return(serviceCollection);
        }