Example #1
0
        public static void Run(string[] args)
        {
            var options = new ServerOptions();
            if (!Parser.Default.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            var interopServer = new InteropServer(options);
            interopServer.Run();
        }
Example #2
0
        public static void Run(string[] args)
        {
            var options = new ServerOptions();
            if (!Parser.Default.ParseArguments(args, options))
            {
                Environment.Exit(1);
            }

            var workerServer = new QpsWorker(options);
            workerServer.RunAsync().Wait();
        }
Example #3
0
 public static string GetCorrectedString(this DicomDataset dataset, ServerOptions serverOptions, DicomTag dicomTag)
 {
     var result = dataset.Get<string>(dicomTag);
     if (serverOptions.Codepage > 0)
     {
         var dicomItem = dataset.FirstOrDefault(x => x.Tag == dicomTag);
         var bytes = ((DicomElement)dicomItem).Buffer.Data;
         result = Encoding.GetEncoding(serverOptions.Codepage).GetString(bytes);
         result = result.Replace('^', ' ');
     }
     return result;
 }
Example #4
0
        static void Main(string[] args)
        {
            ServerOptions serverOptions = new ServerOptions();

            serverOptions.ip       = "127.0.0.1";
            serverOptions.port     = 4444;
            serverOptions.protocol = Protocols.Tcp;

            Server          server   = new Server(serverOptions);
            IServerListener listener = new TCPListener(serverOptions.ip, serverOptions.port);

            server.AddListerner(listener);
            server.AddSerializer(new BinaryReader());

            stringPrinter print = new stringPrinter();

            server.AddObserver(print);

            server.Start();

            bool running = true;

            while (running)
            {
                int k;
                Int32.TryParse(Console.ReadLine(), out k);

                switch (k)
                {
                case (0):
                {
                    Object2DPacket p = new Object2DPacket();
                    p.objectID   = 23;
                    p.angle      = 360;
                    p.pos        = new Vec2(30, 40);
                    p.PacketType = PacketTypes.Object2D;

                    server.SendAll(p);
                    break;
                }

                case (1):
                {
                    server.SendAll("HELLO EVERYONE");
                    break;
                }

                case (2):
                {
                    server.SendAll(54);
                    break;
                }

                case (3):
                {
                    Object2DPacket p = new Object2DPacket();
                    p.objectID   = 23;
                    p.angle      = 360;
                    p.pos        = new Vec2(30, 40);
                    p.PacketType = PacketTypes.Object2D;

                    server.SendAll(p);
                    break;
                }

                case (9):
                {
                    running = false;
                    Console.WriteLine("Shut Down");
                    break;
                }
                }
            }
        }
Example #5
0
 public RabbitMQConnection(ServerOptions options, string virtualHost)
 {
     _serverOptions = options;
     _virtualHost   = virtualHost;
     _logger        = ObjectContainerFactory.ObjectContainer.Resolve <ILoggerFactory>().CreateLogger <RabbitMQConnection>();
 }
Example #6
0
 private QpsWorker(ServerOptions options)
 {
     this.options = options;
 }
 public FileController(IOptions <ServerOptions> serverOptions)
 {
     _serverOptions = serverOptions.Value;
 }
Example #8
0
        private void ReportCurrentChallenge(ICollection <PlayerRank> currentRankings, ChallengeListSingleInfo currentChallenge)
        {
            if (currentChallenge == null)
            {
                return;
            }

            ServerOptions serverOptions = GetServerOptionsCached(this);

            if (serverOptions == null)
            {
                return;
            }

            GameMode?currentGameMode = GetCurrentGameModeCached(this);

            if (!currentGameMode.HasValue)
            {
                return;
            }

            List <PlayerSettings> currentPlayers = Context.PlayerSettings.GetAllAsList();

            List <PlayerSettings>      nonSpectators   = currentPlayers.FindAll(player => !player.SpectatorStatus.IsSpectator);
            List <DedimaniaPlayerInfo> playersToReport = new List <DedimaniaPlayerInfo>();

            foreach (PlayerSettings playerSettings in nonSpectators)
            {
                playersToReport.Add(new DedimaniaPlayerInfo(playerSettings.Login, string.Empty, string.Empty, playerSettings.TeamID, playerSettings.SpectatorStatus.IsSpectator, playerSettings.LadderRanking, playerSettings.IsInOfficialMode));
            }

            int playersCount               = playersToReport.Count;
            int spectatorsCount            = currentPlayers.Count - playersCount;
            DedimaniaServerInfo serverInfo = new DedimaniaServerInfo(serverOptions.Name, serverOptions.Comment, serverOptions.Password.Length > 0, string.Empty, 0, Context.ServerInfo.ServerXMLRpcPort, playersCount, serverOptions.CurrentMaxPlayers, spectatorsCount, serverOptions.CurrentMaxSpectators, serverOptions.CurrentLadderMode, string.Empty);

            DedimaniaCurrentChallengeReply currentChallengeReply = null;

            try
            {
                currentChallengeReply = DedimaniaClient.CurrentChallenge(currentChallenge.UId, currentChallenge.Name, currentChallenge.Environnement, currentChallenge.Author, Context.ServerInfo.Version.GetShortName(), (int)currentGameMode.Value, serverInfo, (int)DedimaniaSettings.MAX_RECORDS_TO_REPORT, playersToReport.ToArray());
                IsDedimaniaResponsive = true;
            }
            catch (Exception ex)
            {
                Logger.ErrorToUI("Could not report current challenge: " + ex.Message);
                Logger.Error("Could not report current challenge: " + ex);
                IsDedimaniaResponsive = false;
            }

            if (currentChallengeReply != null)
            {
                FillRankingsFromDedimania(currentChallengeReply.Records, currentRankings);
                BestTime = Rankings.Length == 0 ? null : (uint?)Rankings[0].TimeOrScore;
            }
            else
            {
                Rankings = new DedimaniaRanking[] {};
                BestTime = null;

                if (IsDedimaniaResponsive)
                {
                    Logger.Debug("Error while calling CurrentChallenge!");
                }
            }

            OnRankingsChanged(Rankings);
        }
Example #9
0
 public MTCryptoService(ILogger <MTCryptoService> logger, ServerOptions serverOptions)
 {
     this.logger        = logger;
     this.serverOptions = serverOptions;
     this.ServerKey     = this.serverOptions.ServerKey;
 }
Example #10
0
        public static void SaveDicomToFile(DicomDataset dataset, string storagePath, 
            DicomFile dicomFile, ServerOptions serverOptions)
        {
            var pacientName = dataset.GetPacientName(serverOptions);
            var pacientDate = dataset.Get<DateTime>(DicomTag.PatientBirthDate);
            var imageDateTime = dataset.GetImageDateTime();

            var path = Path.GetFullPath(storagePath);
            path = Path.Combine(path, imageDateTime.Year.ToString("D4"));
            path = Path.Combine(path, imageDateTime.Month.ToString("D2"));
            path = Path.Combine(path, imageDateTime.ToShortDateString());

            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);

            string fileName = pacientName + " " + pacientDate.ToShortDateString() + " " + imageDateTime.ToLongTimeString() + ".dcm";
            fileName = Path.GetInvalidFileNameChars().Aggregate(fileName, (current, invalidChar) => current.Replace(invalidChar, '_'));
            fileName = Path.Combine(path, fileName);

            using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                dicomFile.Save(fileStream);
                fileStream.Flush();
            }

            var item = new QueueItem { FileName = fileName, Options = serverOptions };


            lock (BackgroundService.Services)
            {
                foreach (var queueService in BackgroundService.Services.OfType<QueueService>())
                    queueService.Enqueue(item);
            }

            try
            {
                if(Settings.Default.QueueNameList.Count > 0)
                {
                    foreach (var queueName in Settings.Default.QueueNameList)
                    {
                        if (!string.IsNullOrEmpty(queueName))
                        {
                            var name = queueName;
                            if (!name.Contains(@"\"))
                                name = @".\Private$\" + name;

                            System.Messaging.MessageQueue messageQueue;
                            if (System.Messaging.MessageQueue.Exists(name))
                                messageQueue = new System.Messaging.MessageQueue(name);
                            else
                                messageQueue = System.Messaging.MessageQueue.Create(name);

                            try
                            {
                                messageQueue.Send(item);
                            }
                            finally
                            {
                                messageQueue.Dispose();
                            }
                        }
                    }
                }
            }
            catch
            {
            }

        }
Example #11
0
        internal static void RunLog()
        {
            while (true)
            {
                try
                {
                    WriteCurrentText(true);

                    ConsoleKeyInfo cki = Console.ReadKey(true);
                    lock (lock_KeyObject)
                    {
                        switch (cki.Key)
                        {
                        case ConsoleKey.Enter:
                            string text = currentText;
                            if (text.Length > 0)
                            {
                                if (previousTexts.Count == MaxPreviousTexts)
                                {
                                    previousTexts.RemoveAt(previousTexts.Count - 1);
                                }

                                previousTexts.Insert(0, text);
                                WriteNewLine(text);

                                typedText.Clear();
                                currentText  = string.Empty;
                                cursorPos[0] = 0;

                                if (!ServerOptions.ProcessCmd(text) && OnCommand != null)
                                {
                                    OnCommand(text);
                                }
                            }
                            previousIndex = -1;
                            break;

                        case ConsoleKey.Escape:
                            typedText.Clear();
                            cursorPos[0]  = 0;
                            previousIndex = -1;
                            break;

                        case ConsoleKey.Backspace:
                            if (cursorPos[0] > 0 && cursorPos[0] <= currentText.Length)
                            {
                                typedText.Remove(cursorPos[0] - 1, 1);
                                cursorPos[0]--;
                            }
                            break;

                        case ConsoleKey.Delete:
                            if (cursorPos[0] >= 0 && cursorPos[0] < currentText.Length)
                            {
                                typedText.Remove(cursorPos[0], 1);
                            }
                            break;

                        case ConsoleKey.UpArrow:
                            if (previousTexts.Count > 0 && previousIndex < previousTexts.Count - 1)
                            {
                                previousIndex++;
                                typedText.Clear();
                                typedText.Append(previousTexts[previousIndex]);
                                cursorPos[0] = previousTexts[previousIndex].Length;
                            }
                            break;

                        case ConsoleKey.DownArrow:
                            if (previousIndex >= 0)
                            {
                                previousIndex--;
                            }
                            typedText.Clear();
                            if (previousIndex >= 0)
                            {
                                typedText.Append(previousTexts[previousIndex]);
                                cursorPos[0] = previousTexts[previousIndex].Length;
                            }
                            else
                            {
                                cursorPos[0] = 0;
                            }
                            break;

                        case ConsoleKey.LeftArrow:
                            if (cursorPos[0] > 0)
                            {
                                cursorPos[0]--;
                            }
                            break;

                        case ConsoleKey.RightArrow:
                            if (cursorPos[0] < currentText.Length)
                            {
                                cursorPos[0]++;
                            }
                            break;

                        default:
                            if (cki.KeyChar != '\0')
                            {
                                typedText.Insert(cursorPos[0], cki.KeyChar);
                                cursorPos[0]++;
                            }
                            break;
                        }
                    }
                }
                catch (Exception e)
                {
                    Logger.LogError(e);
                }
            }
        }
Example #12
0
 public AuthenticationFilterAttribute()
 {
     options = ServiceLocator.GetService <IOptions <ServerOptions> >()?.Value;
     logger  = ServiceLocator.GetService <ILogger <AuthenticationFilterAttribute> >();
 }
Example #13
0
 public RabbitMQBuilder AddGlobalServerOptions(ServerOptions serverOptions)
 {
     ServerOptions.Default = serverOptions;
     return(this);
 }
Example #14
0
 public AdminController(IOptions <ServerOptions> options, ILogger <AdminController> logger, ConfigHelper configHelper)
 {
     this.options      = options?.Value;
     this.logger       = logger;
     this.configHelper = configHelper;
 }
Example #15
0
 public void Init(ILifetimeScope scope, ServerOptions options = null)
 {
     _autofac = scope;
     server   = SocketFactory.CreateTcpServer(this, new Packet(typehandler), options);
     server.Open();
 }
Example #16
0
        private static async Task <int> Serve(ServerOptions options, ILoggerFactory loggerFactory)
        {
            Dacs7Client      client   = null;
            IPlcDataProvider provider = null;

            if (string.IsNullOrWhiteSpace(options.DataProvider) || options.DataProvider.Equals("Simulation", StringComparison.InvariantCultureIgnoreCase))
            {
                if (options.Tags != null)
                {
                    foreach (var item in options.Tags)
                    {
                        var ri = ReadItem.CreateFromTag(item);
                        Console.WriteLine($"Register tag {item}");

                        SimulationPlcDataProvider.Instance.Register(ri.Area, ri.NumberOfItems, ri.DbNumber);
                    }
                }
                Console.WriteLine("Using Simulation Provider!");
                provider = SimulationPlcDataProvider.Instance;
            }
            else if (options.DataProvider.Equals("Relay", StringComparison.InvariantCultureIgnoreCase))
            {
                client = new Dacs7Client(options.Address, PlcConnectionType.Pg, 5000, loggerFactory)
                {
                    MaxAmQCalled  = (ushort)options.MaxJobs,
                    MaxAmQCalling = (ushort)options.MaxJobs,
                    PduSize       = options.MaxPduSize
                };
                RelayPlcDataProvider.Instance.UseClient(client);
                Console.WriteLine("Using Relay Provider!");
                provider = RelayPlcDataProvider.Instance;
            }

            var server = new Dacs7Server(options.Port, provider, loggerFactory)
            {
                MaxAmQCalled  = (ushort)options.MaxJobs,
                MaxAmQCalling = (ushort)options.MaxJobs,
                PduSize       = (ushort)480
            };
            var logger = loggerFactory?.CreateLogger("Dacs7Cli.Serve");

            try
            {
                Console.WriteLine($"Started serving on port {options.Port} !");
                await server.ConnectAsync();

                if (client != null)
                {
                    await client.ConnectAsync();
                }

                Console.WriteLine("Please press any key to stop serving!");
                Console.ReadKey();
            }
            catch (Exception ex)
            {
                logger?.LogError($"An error occured in Serve: {ex.Message} - {ex.InnerException?.Message}");
                return(1);
            }
            finally
            {
                if (client != null)
                {
                    await client.DisconnectAsync();
                }
                await server.DisconnectAsync();
            }

            return(0);
        }
Example #17
0
 private InteropServer(ServerOptions options)
 {
     this.options = options;
 }
Example #18
0
            }             // ctor

            protected ServerOptions(ServerOptions options)
            {
                configurationFile = options.configurationFile;
                serviceName       = options.serviceName;
                Properties        = options.Properties; // use the reference
            }                                           // ctor
Example #19
0
 public static  string GetPacientName(this DicomDataset dataset, ServerOptions serverOptions)
 {
     return dataset.GetCorrectedString(serverOptions, DicomTag.PatientName);
 }
Example #20
0
            }             // ctor

            public RunOptions(ServerOptions options)
                : base(options)
            {
            }             // ctor
Example #21
0
 public static void SetDefaultCacheServerOptions(this CoreServices services, ServerOptions options)
 {
     _init = true;
     _defaultServerOptions = options;
 }
Example #22
0
 public HttpClientHandler(IMessageFactory messageFactory, IConnectionChannelGroup group, ServerOptions Options)
 {
     this.channelGroup   = group;
     this.messageFactory = messageFactory;
     this.Options        = Options;
 }
Example #23
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IWebHostEnvironment env, ILoggerFactory log)
        {
            ServerOptions serverOptions = Configuration.GetSection("ServerOptions").Get <ServerOptions>();

            app.UseRouting();

            Action <IApplicationBuilder> configure = subdir =>
            {
                subdir.UseRouting();
                subdir.UseDeveloperExceptionPage();
                subdir.UseDefaultFiles();
                subdir.UseStaticFiles();
                subdir.UseSpaStaticFiles();

                subdir.UseWebSockets();

                subdir.UseEndpoints(e =>
                {
                    e.MapHub <NotificationsHub>("/hubs/notifications");

                    e.MapControllers();
                    if (env.IsDevelopment())
                    {
                        e.MapToVueCliProxy(
                            "{*path}",
                            new SpaOptions {
                            SourcePath = Path.Join(env.ContentRootPath, "ClientApp")
                        },
                            npmScript: "serve",
                            regex: "Compiled successfully",
                            forceKill: true,
                            port: 8123
                            );
                    }
                });



                Smtp4devDbContext context = subdir.ApplicationServices.GetService <Smtp4devDbContext>();
                if (!context.Database.IsInMemory())
                {
                    context.Database.Migrate();
                }

                subdir.ApplicationServices.GetService <Smtp4devServer>().TryStart();
                subdir.ApplicationServices.GetService <ImapServer>().TryStart();
            };

            if (!string.IsNullOrEmpty(serverOptions.BasePath) && serverOptions.BasePath != "/")
            {
                RewriteOptions rewrites = new RewriteOptions();
                rewrites.AddRedirect("^" + serverOptions.BasePath.TrimEnd('/') + "$", serverOptions.BasePath.TrimEnd('/') + "/");;
                rewrites.AddRedirect("^(/)?$", serverOptions.BasePath.TrimEnd('/') + "/");;
                app.UseRewriter(rewrites);

                app.Map(serverOptions.BasePath, configure);
            }
            else
            {
                configure(app);
            }
        }
Example #24
0
        public bool Configure <TPackageInfo>(ServerOptions options, IServiceCollection services = null, IPipelineFilterFactory <TPackageInfo> pipelineFilterFactory = null, Func <IAppSession, TPackageInfo, Task> packageHandler = null)
            where TPackageInfo : class
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            Options = options;

            if (services == null)
            {
                services = new ServiceCollection();
            }

            // prepare service collections
            _serviceCollection = services.AddOptions(); // activate options

            // build service provider
            _serviceProvider = services.BuildServiceProvider();

            // initialize logger factory
            LoggerFactory = _serviceProvider.GetService <ILoggerFactory>();

            _logger = LoggerFactory.CreateLogger("SuperSocket");

            if (pipelineFilterFactory == null)
            {
                pipelineFilterFactory = _serviceProvider.GetService <IPipelineFilterFactory <TPackageInfo> >();
            }

            if (pipelineFilterFactory == null)
            {
                throw new ArgumentNullException(nameof(pipelineFilterFactory));
            }

            var listenerFactory = _serviceProvider.GetService <IListenerFactory>();

            if (listenerFactory == null)
            {
                listenerFactory = new TcpSocketListenerFactory();
            }

            _listeners = new List <IListener>();

            foreach (var l in options.Listeners)
            {
                var listener = listenerFactory.CreateListener <TPackageInfo>(l, LoggerFactory, pipelineFilterFactory);
                listener.NewClientAccepted += OnNewClientAccept;

                if (packageHandler != null)
                {
                    _sessionInitializer = (s) =>
                    {
                        if (s.Channel is IChannel <TPackageInfo> channel)
                        {
                            channel.PackageReceived += async(ch, p) =>
                            {
                                try
                                {
                                    await packageHandler(s, p);
                                }
                                catch (Exception e)
                                {
                                    OnSessionError(s, e);
                                }
                            };
                        }
                    };
                }

                _listeners.Add(listener);
            }

            return(_configured = true);
        }
Example #25
0
 public Server(ServerOptions options)
 {
     listener.Prefixes.Add("http://" + options.Host +  ":" + options.Port + "/");
     this.options = options;
 }
Example #26
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task StartAsync(IEventLoopGroup BossGroup, IEventLoopGroup WorkerGroup, ServerOptions Options, AppFunc app)
        {
            X509Certificate2 tlsCertificate = null;

            if (Options.IsSsl)
            {
                tlsCertificate = new X509Certificate2(Path.Combine(_environment.ContentRootPath, Options.CertificatePath), Options.CertificateToken);
            }

            var bootstrap = new ServerBootstrap();
            var appKey    = AttributeKey <AppFunc> .ValueOf(Constants.AppAttributeKey);

            bootstrap.Group(BossGroup, WorkerGroup)
            .Channel <TcpServerSocketChannel>()
            .Option(ChannelOption.SoBacklog, 8192)        //设置channelconfig
            .Handler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                pipeline.AddLast(new LoggingHandler($"{Options.Name}-CONN"));
                this.Handler(channel, this._serviceProvider, Options);
            }))
            .ChildAttribute <AppFunc>(appKey, app)
            .ChildHandler(new ActionChannelInitializer <IChannel>(channel =>
            {
                IChannelPipeline pipeline = channel.Pipeline;
                if (tlsCertificate != null)
                {
                    pipeline.AddLast(TlsHandler.Server(tlsCertificate));
                }
                pipeline.AddLast("encoder", new HttpResponseEncoder());
                pipeline.AddLast("decoder", new HttpRequestDecoder(4096, 8192, 8192, false));

                pipeline.AddLast(ActivatorUtilities.CreateInstance <HttpClientHandler>(this._serviceProvider, Options));
                this.ChildHandler(channel, this._serviceProvider, Options);
            }));

            BoundChannel = await bootstrap.BindAsync(IPAddress.IPv6Any, Options.Port);

            _logger.LogInformation($"{Options.Name}-启动完成");
        }
Example #27
0
 private InteropServer(ServerOptions options)
 {
     this.options = options;
 }
Example #28
0
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <ServerOptions>(Configuration.GetSection("ServerOptions"));
            services.Configure <RelayOptions>(Configuration.GetSection("RelayOptions"));

            ServerOptions serverOptions = Configuration.GetSection("ServerOptions").Get <ServerOptions>();

            services.AddDbContext <Smtp4devDbContext>(opt =>
            {
                if (string.IsNullOrEmpty(serverOptions.Database))
                {
                    Console.WriteLine("Using in memory database.");
                    opt.UseInMemoryDatabase("main");
                }
                else
                {
                    if (serverOptions.RecreateDb && File.Exists(serverOptions.Database))
                    {
                        Console.WriteLine("Deleting Sqlite database.");
                        File.Delete(serverOptions.Database);
                    }

                    Console.WriteLine("Using Sqlite database at " + Path.GetFullPath(serverOptions.Database));
                    opt.UseSqlite($"Data Source='{serverOptions.Database}'");
                }
            }, ServiceLifetime.Transient, ServiceLifetime.Singleton);

            services.AddSingleton <Smtp4devServer>();
            services.AddSingleton <ImapServer>();
            services.AddSingleton <IMessagesRepository>(sp => sp.GetService <Smtp4devServer>());
            services.AddSingleton <Func <Smtp4devDbContext> >(sp => (() => sp.GetService <Smtp4devDbContext>()));

            services.AddSingleton <Func <RelayOptions, SmtpClient> >((relayOptions) =>
            {
                if (!relayOptions.IsEnabled)
                {
                    return(null);
                }

                SmtpClient result = new SmtpClient();

                if (!relayOptions.ValidateSSLCertificate) //
                {
                    result.ServerCertificateValidationCallback = (sender, certificate, chain, errors) => true;
                }

                result.Connect(relayOptions.SmtpServer, relayOptions.SmtpPort);

                if (!string.IsNullOrEmpty(relayOptions.Login))
                {
                    result.Authenticate(relayOptions.Login, relayOptions.Password);
                }

                return(result);
            });


            services.AddSignalR();
            services.AddSingleton <NotificationsHub>();

            services.AddControllers();

            services.AddSpaStaticFiles(o => o.RootPath = "ClientApp");
        }
Example #29
0
        public void EmbeddedSamples()
        {
            #region embedded_example
            EmbeddedServer.Instance.StartServer();
            using (var store = EmbeddedServer.Instance.GetDocumentStore("Embedded"))
            {
                using (var session = store.OpenSession())
                {
                    // Your code here
                }
            }
            #endregion

            #region start_server
            // Start RavenDB Embedded Server with default options
            EmbeddedServer.Instance.StartServer();
            #endregion

            #region start_server_with_options

            EmbeddedServer.Instance.StartServer(new ServerOptions
            {
                DataDirectory = "C:\\RavenData",
                ServerUrl     = "http://127.0.0.1:8080"
            });

            #endregion

            #region start_server_with_server_directory_option

            EmbeddedServer.Instance.StartServer(new ServerOptions
            {
                ServerDirectory = @"C:\RavenDB\Server"
            });

            #endregion

            #region get_document_store

            EmbeddedServer.Instance.GetDocumentStore("Embedded");

            #endregion

            #region get_document_store_with_database_options

            var databaseOptions = new DatabaseOptions(new DatabaseRecord
            {
                DatabaseName = "Embedded"
            });
            EmbeddedServer.Instance.GetDocumentStore(databaseOptions);
            #endregion

            #region open_in_browser
            EmbeddedServer.Instance.OpenStudioInBrowser();
            #endregion

            #region security
            var serverOptions = new ServerOptions();
            serverOptions.Secured(
                certificate: "PathToServerCertificate",
                certPassword: "******");
            #endregion

            #region security2
            var serverOptionsWithExec = new ServerOptions();
            var certificate           = new X509Certificate2();
            serverOptionsWithExec.Secured(
                certLoadExec: "powershell",
                certExecArgs: "C:\\secrets\\give_me_cert.ps1",
                serverCertThumbprint: certificate.Thumbprint,
                clientCert: certificate);
            #endregion

            #region run_with_dotnet_path
            EmbeddedServer.Instance.StartServer(new ServerOptions
            {
                FrameworkVersion = "2.1.2",
                DotNetPath       = "PATH_TO_DOTNET_EXEC"
            });
            #endregion
        }
 public GatewayController(IGatewayService gatewayService, ServerOptions options)
 {
     this.gatewayService = gatewayService;
     this.options        = options;
 }
Example #31
0
 public bool Configure <TPackageInfo, TPipelineFilter>(ServerOptions options, IServiceCollection services = null, Action <IAppSession, TPackageInfo> packageHandler = null)
     where TPackageInfo : class
     where TPipelineFilter : IPipelineFilter <TPackageInfo>, new()
 {
     return(Configure <TPackageInfo>(options, services, new DefaultPipelineFilterFactory <TPackageInfo, TPipelineFilter>(), packageHandler: packageHandler));
 }
Example #32
0
 public WebSocketClientHandler(IConnectionChannelGroup group, ServerOptions Options)
 {
     this.channelGroup = group;
     this.Options      = Options;
 }
Example #33
0
 private static ServerOptions ParseArguments(string[] args)
 {
     var options = new ServerOptions();
     foreach (string arg in args)
     {
         ParseArgument(arg, options);
         if (options.help)
         {
             break;
         }
     }
     return options;
 }
Example #34
0
 private QpsWorker(ServerOptions options)
 {
     this.options = options;
 }
Example #35
0
        private static void ParseArgument(string arg, ServerOptions options)
        {
            Match match;
            match = Regex.Match(arg, "--port=(.*)");
            if (match.Success)
            {
                options.port = int.Parse(match.Groups[1].Value.Trim());
                return;
            }

            match = Regex.Match(arg, "--use_tls=(.*)");
            if (match.Success)
            {
                options.useTls = bool.Parse(match.Groups[1].Value.Trim());
                return;
            }

            Console.WriteLine(string.Format("Unrecognized argument \"{0}\"", arg));
            options.help = true;
        }
Example #36
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="services"></param>
        public ServerBootstrap(IServiceProvider services)
        {
            if (services == null)
            {
                throw new ArgumentNullException(nameof(services));
            }
            var options = new ServerOptions();
            var types   = GetTypeInfos(options as ServerOptions);
            var list    = new List <JobExecutor>();

            foreach (var type in types)
            {
                foreach (var method in type.DeclaredMethods)
                {
                    var attribute = method.GetCustomAttribute <ScheduleAttribute>();
                    if (attribute != null)
                    {
                        if (string.IsNullOrEmpty(attribute.Name))
                        {
                            throw new CustomAttributeFormatException("Crontab name is empty");
                        }
                        var arr = attribute.Schedule.Split('|');
                        if (arr.Length == 0)
                        {
                            throw new CustomAttributeFormatException($"Crontab '{attribute.Name}' does not have any schedule");
                        }
                        var schedules = new JobSchedule[arr.Length];
                        for (int i = 0; i < arr.Length; i++)
                        {
                            if (JobSchedule.TryParse(arr[i], out JobSchedule schedule))
                            {
                                schedules[i] = schedule;
                            }
                            else
                            {
                                throw new CustomAttributeFormatException($"Crontab '{attribute.Name}' schedule '{arr[i]}' format error");
                            }
                        }
                        var name = attribute.Name;
                        if (string.IsNullOrEmpty(name))
                        {
                            name = method.Name;
                        }
                        var item = new JobExecutor(name, services, cts.Token, type, method, schedules, attribute.AllowConcurrentExecution, attribute.RunImmediately);
                        if (!executorDict.ContainsKey(item.Name))
                        {
                            executorDict.Add(item.Name, item);
                            if (attribute.AutoEnable)
                            {
                                item.Enable();
                            }
                        }
                        else
                        {
                            throw new CustomAttributeFormatException($"Crontab '{item.Name}' name is duplicate");
                        }
                    }
                }
            }

            var dt = DateTime.Now;

            dt = new DateTime(dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, 0);
            var next = dt.AddMinutes(1);
            var due  = Convert.ToInt32(Math.Ceiling((next - DateTime.Now).TotalMilliseconds));

            Task.Factory.StartNew(async() => {
                try
                {
                    await Task.Delay(due, cts.Token);
                    Execute();
                }
                catch (Exception ex)
                {
                    LogAgent.Error(ex.ToString());
                }
            }, cts.Token);
        }
 /// <summary>
 /// Set new server options using the struct passed as parameters. This struct must contain the following fields : Name, Comment, Password, PasswordForSpectator, NextMaxPlayers, NextMaxSpectators, IsP2PUpload, IsP2PDownload, NextLadderMode, NextVehicleNetQuality, NextCallVoteTimeOut, CallVoteRatio, AllowMapDownload, AutoSaveReplays, and optionally for forever: RefereePassword, RefereeMode, AutoSaveValidationReplays, HideServer, UseChangingValidationSeed, ClientInputsMaxLatency, DisableHorns, DisableServiceAnnounces, KeepPlayerSlots, ServerPlugin. Only available to Admin. A change of NextMaxPlayers, NextMaxSpectators, NextLadderMode, NextVehicleNetQuality, NextCallVoteTimeOut or UseChangingValidationSeed requires a map restart to be taken into account.
 /// </summary>
 /// <param name="options"></param>
 /// <returns></returns>
 public async Task <bool> SetServerOptionsAsync(ServerOptions options) =>
 (bool)XmlRpcTypes.ToNativeValue <bool>(
     await CallOrFaultAsync("SetServerOptions", options)
     );
        static void Main(string[] args)
        {
            Console.WriteLine("Select RavenDB data directory from the open file dialog...");

            var openFile = new OpenFileDialog
            {
                Title           = "Select Raven Database Directory",
                Multiselect     = false,
                ValidateNames   = false,
                CheckFileExists = false,
                CheckPathExists = false,
                FileName        = "Select Directory"
            };
            var openFileResult = openFile.ShowDialog();

            if (openFileResult != DialogResult.OK)
            {
                Console.WriteLine("Cancelled");
                return;
            }

            var directory = Path.GetDirectoryName(openFile.FileName);

            var dbDirectory = Path.Combine(directory, "DB");

            Directory.CreateDirectory(dbDirectory);
            var logsDirectory = Path.Combine(directory, "Logs");

            Directory.CreateDirectory(logsDirectory);

            if (!Directory.Exists(directory) || !Directory.Exists(dbDirectory) || !Directory.Exists(logsDirectory))
            {
                Console.WriteLine("Not a RavenDB database. Exiting.");
                return;
            }

            Console.Write("Enter port / click enter for 8080: ");
            if (!int.TryParse(Console.ReadLine(), out int port))
            {
                port = 8080;
            }

            var serverOptions = new ServerOptions
            {
                AcceptEula      = true,
                DataDirectory   = dbDirectory,
                LogsPath        = logsDirectory,
                ServerUrl       = $"http://localhost:{port}",
                CommandLineArgs = new List <string>
                {
                    $"--License={CommandLineArgumentEscaper.EscapeSingleArg(ReadLicense())}",
                }
            };

            EmbeddedServer.Instance.StartServer(serverOptions);
            var databaseOptions = new DatabaseOptions("Embedded")
            {
                Conventions = new DocumentConventions
                {
                    SaveEnumsAsIntegers = true
                },
                DatabaseRecord =
                {
                    Expiration   = new ExpirationConfiguration
                    {
                        Disabled = false
                    }
                }
            };

            using (var documentStore = EmbeddedServer.Instance
                                       .GetDocumentStore(databaseOptions))
            {
                Console.WriteLine($"Database initialized. Serving at {serverOptions.ServerUrl}");
                Console.WriteLine("Press enter to exit...");

                EmbeddedServer.Instance.OpenStudioInBrowser();
                Console.ReadLine();
                Console.WriteLine("Shutting down...");

                documentStore.Dispose();

                Console.WriteLine();
                Console.WriteLine();
                Console.WriteLine("Press enter to exit.");
                Console.ReadLine();
            }
        }
 public void UseOptions(ServerOptions options) => Options = options;
Example #40
0
 public void Configure(ServerOptions <TPackage> options)
 {
     options.ApplicationServices = _services;
 }