Esempio n. 1
0
        public MJpegServer(ILog log, MJpegServerSettings settings)
        {
            _log = log;
            _settings = settings;
            if (settings.SourceSettings.GetFormat() != ImageFormat.Jpeg)
            {
                throw new InvalidDataException("Expected input image format is jpeg!");
            }
            _serverSource = ServerSourceFactory.Create(_log, settings.SourceSettings);

            var sourcei = _serverSource.GetSource();
            try
            {
                _cache = sourcei.PrepareSourceServerCache();
                _serverSource.SetCache(_cache);
            }
            finally
            {
                _serverSource.DisposeClient(sourcei);
            }

            _server = new WebServer(log, _settings.Uri);
            _server.IncomingRequest += HandleRequest;
            _server.Start();
        }
Esempio n. 2
0
		/// <summary>
		/// Gets the IIS worker process name.
		/// </summary>
		public static string GetWorkerProcessName(WebServer webServer)
		{
			if (webServer == WebServer.IISExpress) {
				return GetIISExpressWorkerProcessName();
			}
			return GetIISWorkerProcessName();
		}
Esempio n. 3
0
        public static void Main()
        {
            var webServerUrl = Resources.GetServerAddress();

            var webServer = new WebServer(webServerUrl);
            webServer.RegisterModule(new LocalSessionModule() { Expiration = TimeSpan.FromSeconds(6) });
            webServer.RegisterModule(new FallbackModule((ws, ctx) =>
            {
                return ctx.JsonResponse(new { Message = "OK" });
            }));

            webServer.RunAsync();

            var rnd = new Random();

            Parallel.ForEach(Enumerable.Range(0, 50), async (s, t, l) =>
            {
                await Task.Delay(TimeSpan.FromSeconds(rnd.Next(1, 10)));

                using (var webClient = new HttpClient())
                {
                    var data = await webClient.GetStringAsync(webServerUrl);
                    data.Info();
                }
            });

            Console.ReadKey();
        }
Esempio n. 4
0
        public void WebserverCanBeDisposed()
        {
            var cts = new CancellationTokenSource();
            var instance = new WebServer("http://localhost:" + DefaultPort);
            var task = instance.RunAsync(cts.Token);

            cts.Cancel();

            try
            {
                //Thread.Sleep(2000);
                task.Wait();
            }
            catch (AggregateException e)
            {
                var baseEx = e.GetBaseException();
                if (baseEx is OperationCanceledException)
                {
                    instance.Dispose();
                    return;
                }

                Assert.Fail($"Must have thrown OperationCanceledException and trhew '{baseEx.GetType().ToString()}' instead.");
            }
            catch (Exception ex)
            {
                Assert.Fail($"Must have thrown AggregateException and threw '{ex.GetType().ToString()}' instead.");
            }
        }
Esempio n. 5
0
 public void Init()
 {
     WebServerUrl = Resources.GetServerAddress();
     WebServer = new WebServer(WebServerUrl)
         .WithWebApiController<TestController>();
     WebServer.RunAsync();
 }
Esempio n. 6
0
 public static void updateSettings(int webServerPort, int controlServerPort, string webServerRoot, string[] webServerDefaultPages, bool webServerDirectoryBrowsing)
 {
     webServer.close();
     controlServer.close();
     webServer = new WebServer(webServerPort, webServerRoot, webServerDefaultPages, webServerDirectoryBrowsing);
     controlServer = new ControlServer(controlServerPort);
 }
Esempio n. 7
0
 public void WebServerDefaultConstructor()
 {
     var instance = new WebServer();
     Assert.AreEqual(instance.Log.GetType(), typeof (NullLog), "Default log is NullLog");
     Assert.IsNotNull(instance.Listener, "It has a HttpListener");
     Assert.IsNotNull(Constants.DefaultMimeTypes, "It has MimeTypes");
 }
Esempio n. 8
0
            public bool GetPeople(WebServer server, HttpListenerContext context)
            {
                try
                {
                    // read the last segment
                    var lastSegment = context.Request.Url.Segments.Last();

                    // if it ends with a / means we need to list people
                    if (lastSegment.EndsWith("/"))
                        return context.JsonResponse(RestApiSample.People);

                    // otherwise, we need to parse the key and respond with the entity accordingly
                    int key = 0;
                    if (int.TryParse(lastSegment, out key) && People.Any(p => p.Key == key))
                    {
                        return context.JsonResponse(People.FirstOrDefault(p => p.Key == key));
                    }

                    throw new KeyNotFoundException("Key Not Found: " + lastSegment);
                }
                catch (Exception ex)
                {
                    // here the error handler will respond with a generic 500 HTTP code a JSON-encoded object
                    // with error info. You will need to handle HTTP status codes correctly depending on the situation.
                    // For example, for keys that are not found, ou will need to respond with a 404 status code.
                    return HandleError(context, ex, (int) HttpStatusCode.InternalServerError);
                }
            }
Esempio n. 9
0
        public void WebserverCanBeDisposed()
        {
            var cts = new CancellationTokenSource();
            var instance = new WebServer("http://localhost:" + DefaultPort);
            var task = instance.RunAsync(cts.Token);

            cts.Cancel();

            try
            {
                Thread.Sleep(2000);
                task.Wait();
            }
            catch (AggregateException e)
            {
                if (e.GetBaseException() is OperationCanceledException)
                {
                    instance.Dispose();
                    return;
                }

                Assert.Fail("Must fail because of an OperationCanceledException");
            }

            Assert.Fail("Must throw an AggregateException");
        }
Esempio n. 10
0
        public bool GetPeople(WebServer server, HttpListenerContext context)
        {
            try
            {
                // read the last segment
                var lastSegment = context.Request.Url.Segments.Last();

                // if it ends with a / means we need to list people
                if (lastSegment.EndsWith("/"))
                    return context.JsonResponse(PeopleRepository.Database);

                // otherwise, we need to parse the key and respond with the entity accordingly
                int key;

                if (int.TryParse(lastSegment, out key) && PeopleRepository.Database.Any(p => p.Key == key))
                {
                    return context.JsonResponse(PeopleRepository.Database.FirstOrDefault(p => p.Key == key));
                }

                throw new KeyNotFoundException("Key Not Found: " + lastSegment);
            }
            catch (Exception ex)
            {
                context.Response.StatusCode = (int)System.Net.HttpStatusCode.InternalServerError;
                return context.JsonResponse(ex);
            }
        }
Esempio n. 11
0
        public void FindOlderThanTest()
        {
            var webServer = new WebServer("http://mss.alkotorg.com");
            var webConnectionFactory = new WebConnectionFactory(webServer, "manager", "423200");
            var target = new WebRepository<StatusDto>(webConnectionFactory);
            IQueryObject<StatusDto, IDictionary<string, object>, WebConnection> actual = target.Find().UpdatedAfter(new DateTime(2013, 04, 24, 8, 15, 0));

            foreach (var statusDto in actual.ToArray())
            {
                Console.Write(statusDto.Id.ToString(CultureInfo.InvariantCulture) + '\t');
                Console.Write(statusDto.Validity.ToString() + '\t');
                Console.Write(statusDto.Name + '\n');
            }

            Assert.AreEqual(4, actual.ToArray().Length);

            actual = target.Find().UpdatedAfter(new DateTime(2013, 04, 24, 8, 16, 0));

            foreach (var statusDto in actual.ToArray())
            {
                Console.Write(statusDto.Id.ToString(CultureInfo.InvariantCulture) + '\t');
                Console.Write(statusDto.Validity.ToString() + '\t');
                Console.Write(statusDto.Name + '\n');
            }

            Assert.AreEqual(0, actual.ToArray().Length);
        }
Esempio n. 12
0
 public void ShouldStart()
 {
     using (var webServer = new WebServer(null))
     {
         webServer.Start();
         Thread.Sleep(1000);
     }
 }
Esempio n. 13
0
 public void Init()
 {
     WebServerUrl = Resources.GetServerAddress();
     WebServer =
         new WebServer(WebServerUrl, RoutingStrategy.Regex)
             .WithWebApiController<TestRegexController>();
     WebServer.RunAsync();
 }
Esempio n. 14
0
        public static void Main()
        {
            Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].EnableDhcp();
            WebServer webServer = new WebServer();
            webServer.ListenForRequest();

            Debug.Print("End");
        }
Esempio n. 15
0
 public void OpenTest()
 {
     var webServer = new WebServer("http://mss.alkotorg.com");
     string username = "******";
     string password = "******";
     var target = new WebConnection(webServer, username, password);
     target.Open();
 }
Esempio n. 16
0
 public static void Main(string[] args)
 {
     Console.WriteLine("Serenity Console Mode, starting up...");
     WebServer server = new WebServer();
     server.Start();
     Console.WriteLine("Server shutting down. Press any key...");
     Console.ReadLine();
 }
Esempio n. 17
0
		public EMServer()
		{
			InitializeComponent();

			server = new WebServer();
			ConnectionString = ConfigLoader.LoadConnectionString();
			//btServerStart_Click(null, null);
		}
Esempio n. 18
0
        public void Init()
        {
            WebServerUrl = Resources.GetServerAddress();
            Thread.CurrentThread.CurrentCulture = new CultureInfo("ko");

            WebServer = new WebServer(WebServerUrl).WithWebApiController<TestController>();
            WebServer.RunAsync();
        }
Esempio n. 19
0
        public void Init()
        {
            RootPath = TestHelper.SetupStaticFolder();

            WebServer = new WebServer(Resources.ServerAddress, Logger);
            WebServer.RegisterModule(new LocalSessionModule());
            WebServer.RegisterModule(new StaticFilesModule(RootPath));
            WebServer.RunAsync();
        }
Esempio n. 20
0
        public void WebServerConstructorWithPortParam()
        {
            var instance = new WebServer(DefaultPort);

            Assert.AreEqual(instance.UrlPrefixes.Count, 1, "It has one URL Prefix");
            Assert.IsTrue(
                instance.UrlPrefixes.First().Contains(DefaultPort.ToString(CultureInfo.InvariantCulture)),
                "Construct with port number is correct");
        }
Esempio n. 21
0
        public void Init()
        {
            WebServerUrl = Resources.GetServerAddress();
            RootPath = TestHelper.SetupStaticFolder();

            WebServer = new WebServer(WebServerUrl);
            WebServer.RegisterModule(new LocalSessionModule() { Expiration = WaitTimeSpan });
            WebServer.RegisterModule(new StaticFilesModule(RootPath));
            WebServer.RunAsync();
        }
Esempio n. 22
0
        /// <summary>
        /// Here we add the WebApiModule to our Web Server and register our controller classes.
        /// You can register as many controller classes as you would like
        /// We also add some records to our People list
        /// </summary>
        /// <param name="server">The server.</param>
        public static void Setup(WebServer server)
        {
            foreach (var person in People)
            {
                person.PhotoUrl = GetGravatarUrl(person.EmailAddress);
            }

            server.RegisterModule(new WebApiModule());
            server.Module<WebApiModule>().RegisterController<PeopleController>();
        }
Esempio n. 23
0
 /// <summary>
 /// Setups the specified server.
 /// </summary>
 /// <param name="server">The server.</param>
 public static void Setup(WebServer server, bool useGzip)
 {
     server.RegisterModule(new StaticFilesModule(HtmlRootPath));
     // The static files module will cache small files in ram until it detects they have been modified.
     server.Module<StaticFilesModule>().UseRamCache = false;
     server.Module<StaticFilesModule>().DefaultExtension = ".html";
     server.Module<StaticFilesModule>().UseGzip = useGzip;
     // We don't need to add the line below. The default document is always index.html.
     //server.Module<StaticFilesWebModule>().DefaultDocument = "index.html";
 }
Esempio n. 24
0
        public void Init()
        {
            WebServerUrl = Resources.GetServerAddress();
            RootPath = TestHelper.SetupStaticFolder();

            WebServer = new WebServer(WebServerUrl);
            WebServer.RegisterModule(new StaticFilesModule(RootPath) { UseRamCache = true });
            WebServer.RegisterModule(new FallbackModule("/index.html"));
            WebServer.RunAsync();
        }
Esempio n. 25
0
        public void WebServerConstructorWithPortAndLogParam()
        {
            var instance = new WebServer(DefaultPort, new TestConsoleLog());

            Assert.AreEqual(instance.UrlPrefixes.Count, 1, "It has one URL Prefix");
            Assert.IsTrue(
                instance.UrlPrefixes.First().Contains(DefaultPort.ToString(CultureInfo.InvariantCulture)),
                "Port number is correct");
            Assert.AreEqual(instance.Log.GetType(), typeof (TestConsoleLog), "Log type is correct");
        }
        public void Init()
        {
            WebServerUrl = Resources.GetServerAddress();
            TestHelper.SetupStaticFolder();

            var additionalPaths = InstancesNames.ToDictionary(x => "/" + x, TestHelper.SetupStaticFolderInstance);

            WebServer = new WebServer(WebServerUrl);
            WebServer.RegisterModule(new StaticFilesModule(additionalPaths) {UseRamCache = true});
            WebServer.RunAsync();
        }
Esempio n. 27
0
 static void Main(string[] args)
 {
     WebServer ws = new WebServer(SendResponse, "http://localhost:8080/test/");
     WebServer info = new WebServer(SendInfo, "http://localhost:8080/info/");
     ws.Run();
     info.Run();
     Console.WriteLine("A ShitSensor webserver. Press a key to quit.");
     Console.ReadKey();
     ws.Stop();
     info.Stop();
 }
Esempio n. 28
0
        public void RegisterAndUnregisterModule()
        {
            var instance = new WebServer();
            instance.RegisterModule(new LocalSessionModule());

            Assert.AreEqual(instance.Modules.Count, 1, "It has one module");

            instance.UnregisterModule(typeof (LocalSessionModule));

            Assert.AreEqual(instance.Modules.Count, 0, "It has not modules");
        }
Esempio n. 29
0
 public void ServerTimeTest()
 {
     WebServer webServer = new WebServer("http://mss.alkotorg.com");
     string username = "******";
     string password = "******";
     WebConnection target = new WebConnection(webServer, username, password);
     target.Open();
     DateTime actual = target.ServerTime();
     Console.WriteLine("Server time - \"{0}\"", actual);
     Assert.IsNotNull(actual);
 }
        internal HttpContext(WebServer server, TcpClient client)
        {
            if (server == null)
                throw new ArgumentNullException(nameof(server));

            if (client == null)
                throw new ArgumentNullException(nameof(client));

            Server = server;

            Client = client;
        }
Esempio n. 31
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 = "http://localhost:8787/";

            if (args.Length > 0)
            {
                url = args[0];
            }

            AppDbContext.InitDatabase();

            var ctSource = new CancellationTokenSource();

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

            // 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);


            // Our web server is disposable.
            using (var server = new WebServer(url))
            {
                // 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 manupulate 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
                StaticFilesSample.Setup(server, useGzip: Runtime.IsUsingMonoRuntime == false);

                // 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>();

                // 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)
                WebSocketsSample.Setup(server);

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

                // Fire up the browser to show the content!
                var browser = new System.Diagnostics.Process
                {
                    StartInfo = new System.Diagnostics.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);
                }

                "Bye".Info();
            }
        }
Esempio n. 32
0
        /// <summary>
        /// Generates an Owin App
        /// </summary>
        /// <param name="webServer"></param>
        /// <param name="owinApp"></param>
        /// <returns></returns>
        public static WebServer UseOwin(this WebServer webServer, Func <IAppBuilder, IAppBuilder> owinApp)
        {
            webServer.RegisterModule(new OwinModule(owinApp));

            return(webServer);
        }
Esempio n. 33
0
 public MediaWebServer(IPAddress ipAddress, ushort port)
 {
     UrlPrefix = Invariant($"http://{ipAddress}:{port}/");
     server    = new WebServer(UrlPrefix, RoutingStrategy.Wildcard);
     server.RegisterModule(inMemoryFileSystem);
 }
Esempio n. 34
0
        public WebBgMusicForm()
        {
            this.Opacity = 0;
            Awesomium.Core.WebPreferences prefs = new Awesomium.Core.WebPreferences();
            prefs.FileAccessFromFileURL      = true;
            prefs.UniversalAccessFromFileURL = true;
            prefs.WebGL = true;
            string configFolder = System.Environment.GetFolderPath(System.Environment.SpecialFolder.ApplicationData) + @"\mute.fm";

            Awesomium.Core.WebSession session = Awesomium.Core.WebCore.CreateWebSession(configFolder + @"\Awesomium", prefs);

            InitializeComponent();

            this.webControl1 = new Awesomium.Windows.Forms.WebControl();
            this.dockBrowserControl.Controls.Add(this.webControl1);
            //
            // webControl1
            //
            this.webControl1.Dock     = System.Windows.Forms.DockStyle.Fill;
            this.webControl1.Location = new System.Drawing.Point(20, 20);
            this.webControl1.Name     = "webControl1";
            // TODO: Code generation for 'this.webControl1.NativeView' failed because of Exception 'Invalid Primitive Type: System.IntPtr. Consider using CodeObjectCreateExpression.'.
            this.webControl1.Size     = new System.Drawing.Size(1156, 447);
            this.webControl1.TabIndex = 3;

            webControl1.WebSession = session;

            //this.webControl1.
            //webBrowser1.ScriptErrorsSuppressed = true;
            this.TopMost       = false; //TODO
            this.ShowInTaskbar = true;
            this.Text          = MuteFm.Constants.ProgramName + " browser";
            mToolStrip.Items.Clear();
            this.SuspendLayout();
            mVolumeUpDown.Increment     = 5;
            mVolumeUpDown.DecimalPlaces = 1;
            this.Width = 950;

            InitPanelHeadersHeight = panelHeaders.Height - 31;

            //TODO
//            this.mVolumeTrackBar.Visible = false;
            // Order here matters.  Change UpdateUiForState if this gets changed (a little hacky for now)
            mToolStrip.Items.Add("", WebServer.GetBitmapFromWebServer("home.png"), new EventHandler(mHomeToolStripButton_Click));
            mToolStrip.Items.Add("", WebServer.GetBitmapFromWebServer("pin.png"), new EventHandler(mAlwaysOnTopToolStripButton_Click));
            mToolStrip.Items.Add("", WebServer.GetBitmapFromWebServer("unpin.png"), new EventHandler(mNotAlwaysOnTopToolStripButton_Click));
            //mToolStrip.Items.Add("Send To Chrome", null, new EventHandler(mAlwaysOnTopToolStripButton_Click)); // TODO: also for other browsers
            mToolStrip.Items.Add("", WebServer.GetBitmapFromWebServer("mute.png"), new EventHandler(mMuteButton_Click));
            mToolStrip.Items.Add("", WebServer.GetBitmapFromWebServer("unmute.png"), new EventHandler(mUnmuteButton_Click));
            mToolStrip.Items.Add("", WebServer.GetBitmapFromWebServer("stop.png"), new EventHandler(mStopButton_Click)); // TODO: also other operations
            //mToolStrip.Items.Add("Refresh", null, new EventHandler(mAlwaysOnTopToolStripButton_Click)); // Make this always the last button so that the next fix doesn't have to get changed
            this.ResumeLayout();
            panelToolbar.Width = mToolStrip.Left + mToolStrip.Width + 0;

            UpdateUiForState();
            webControl1.LoadingFrameComplete += new Awesomium.Core.FrameEventHandler(webControl1_LoadingFrameComplete);
            webControl1.DocumentReady        += new Awesomium.Core.UrlEventHandler(webControl1_DocumentReady);

            this.panelHeaders.Height     = InitPanelHeadersHeight; //this.panelCannotHear.Height;
            this.panelCannotHear.Visible = false;

            webControl1.AddressChanged += new Awesomium.Core.UrlEventHandler(webControl1_AddressChanged);
            this.Visible = true;
        }
Esempio n. 35
0
 //[Ignore]
 public void TestOne()
 {
     bool success = WebServer.Start(8000, 1);
 }
Esempio n. 36
0
 public static IAsyncAction StartAsync(Uri baseUri, SuperCacheConfig configuration)
 {
     webServer = new WebServer();
     return(webServer.StartAsync(baseUri, configuration));
 }
Esempio n. 37
0
 public EmbedServer(string port)
 {
     url    = $"http://localhost:{port}/";
     server = CreateWebServer(url);
 }
Esempio n. 38
0
        public WebApiService(IServiceProvider serviceProvider, IOptions <WebApiOptions> options, GameDataService gameDataService)
        {
            _gameDataService = gameDataService;
            Terminal.Settings.DisplayLoggingMessageType = LogMessageType.None;
            Terminal.OnLogMessageReceived += (_, e) =>
            {
                var logger = Log.ForContext(Constants.SourceContextPropertyName, $"WebApi-{e.Source}");
                switch (e.MessageType)
                {
                case LogMessageType.Info:
                    logger.Information(e.Exception, e.Message);
                    break;

                case LogMessageType.Debug:
                    logger.Debug(e.Exception, e.Message);
                    break;

                case LogMessageType.Trace:
                    logger.Verbose(e.Exception, e.Message);
                    break;

                case LogMessageType.Error:
                    logger.Error(e.Exception, e.Message);
                    break;

                case LogMessageType.Warning:
                    logger.Warning(e.Exception, e.Message);
                    break;

                case LogMessageType.Fatal:
                    logger.Fatal(e.Exception, e.Message);
                    break;
                }
            };

            _webServer = new WebServer(options.Value.Listener);
            _webServer.RegisterModule(new WebApiModule());

            foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())
            {
                foreach (var type in assembly.DefinedTypes)
                {
                    if (type.IsClass && !type.IsAbstract && type.IsSubclassOf(typeof(WebApiController)))
                    {
                        var parameters = new List <object>
                        {
                            null
                        };

                        var ctor = type.GetConstructors().First();
                        parameters.AddRange(ctor.GetParameters()
                                            .Skip(1)
                                            .Select(x => serviceProvider
                                                    .GetRequiredService(x.ParameterType)));

                        var arr = parameters.ToArray();
                        _webServer
                        .Module <WebApiModule>()
                        .RegisterController(type, ctx =>
                        {
                            arr[0] = ctx;
                            return(Activator.CreateInstance(type, arr));
                        });
                    }
                }
            }
        }
 protected override WebServer AdaptWebServer(WebServer webServer)
 {
     Console.WriteLine("Hello");
     webServer.Module <WebApiModule>().RegisterController <ImplictGrantAuthController>();
     return(webServer);
 }
Esempio n. 40
0
 public static void Main(string[] args)
 {
     bool success = WebServer.Start(4220, DefaultTemplate);
 }
Esempio n. 41
0
 public void Init()
 {
     WebServer = new WebServer(WebServerUrl, Logger);
     WebServer.RunAsync(app: Middleware);
 }
Esempio n. 42
0
        public static Task <OAuthCode> GetCode(
            string name, string requestUrl, [CanBeNull] string noRedirectUrl,
            [CanBeNull] string successCodeRegex = @"Success code=(\S+)", string redirectUrlKey = "redirect_uri",
            string responseError           = "error", string responseCode = "code",
            string description             = null, string title           = null,
            CancellationToken cancellation = default(CancellationToken))
        {
            Logging.Debug("Name: " + name);
            Logging.Debug("Request URL: " + requestUrl);
            Logging.Debug("Manual mode supported: " + (successCodeRegex != null));

            var tcs = new TaskCompletionSource <OAuthCode>();

            // Try to use web server and localhost to redirect
            WebServer server      = null;
            var       redirectUri = "http://localhost/" + SubUrl;

            async void DisposeLater()
            {
                await Task.Delay(2000);

                Logging.Debug("Stopping server…");
                // ReSharper disable once AccessToModifiedClosure
                server?.Dispose();
                server = null;
            }

            Logging.Debug("Prepating web-server, URL prefix: http://+:80/" + SubUrl);
            server = new WebServer("http://+:80/" + SubUrl, new Log(e => {
                tcs.TrySetException(e);
                DisposeLater();
            }), Unosquare.Labs.EmbedIO.RoutingStrategy.Wildcard);

            if (server != null)
            {
                Logging.Debug("Registering module…");
                server.RegisterModule(new WebApiModule());
                server.Module <WebApiModule>().RegisterController(() => new IndexPageController(responseError, responseCode, (e, s) => {
                    Logging.Debug($"Result: error={e}, code={s}");
                    if (e != null || s == null)
                    {
                        tcs.TrySetException(new Exception(e == null ? "Code is missing" : "Authentication went wrong: " + e));
                    }
                    else
                    {
                        tcs.TrySetResult(new OAuthCode(false, s, redirectUri));
                    }
                    DisposeLater();
                }));

                cancellation.Register(() => {
                    Logging.Debug("Cancellation token");
                    tcs.TrySetCanceled();
                    DisposeLater();
                });

                try {
                    Logging.Debug($"Launching web-server…");
                    server.RunAsync();

                    var url = requestUrl + $"&{redirectUrlKey}={Uri.EscapeDataString(redirectUri)}";
#if DEBUG
                    Logging.Debug(url);
#endif
                    WindowsHelper.ViewInBrowser(url);
                    return(tcs.Task);
                } catch (Exception e) {
                    Logging.Warning(e);
                }
            }

            DisposeLater();

            description = description ?? ToolsStrings.Uploader_EnterGoogleDriveAuthenticationCode.Replace("Google Drive", name);
            title       = title ?? ToolsStrings.Uploader_GoogleDrive.Replace("Google Drive", name);

            if (successCodeRegex == null)
            {
                throw new Exception("Failed to start a temporary web-server to get a key back");
            }

            Logging.Debug("Failed to start a temporary web-server, switching to manual way");
            return(PromptCodeFromBrowser.Show(noRedirectUrl != null ?
                                              requestUrl + $"&{redirectUrlKey}={Uri.EscapeDataString(noRedirectUrl)}" :
                                              requestUrl, new Regex(successCodeRegex, RegexOptions.Compiled),
                                              description, title, cancellation: cancellation).ContinueWith(x => new OAuthCode(true, x.Result, noRedirectUrl)));
        }
Esempio n. 43
0
        public static void Main()
        {
            try
            {
                mcp23017            = new MCP23017();     //the MCP is what allows us to talk with the RGB LCD panel. I need it in this class so I can read the button presses from the User...
                mMenu               = new Menu(mcp23017); //Configure this one first so that errors can be written to the LCD Shield
                mMenu.MenuSelection = MenuSelection.PrintLabel;

                //Setup the interrupt port for button presses from the LCD Shield.
                //Here I have the Interrupt pin from the LCD Shield (configured in the MCP23017 class) going to the Netduino Digital Pin 5
                btnShield = new InterruptPort(Pins.GPIO_PIN_D5, true, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeLow);
                // Bind the interrupt handler to the pin's interrupt event.
                btnShield.OnInterrupt += new NativeEventHandler(btnShield_OnInterrupt);

                //Configure the MUX which allows me to expand my serial ports. Here I am using digital pins 9 thru 10 to send the necessary signals to switch my MUX channels
                OutputPort DigitalPin9  = new OutputPort(Pins.GPIO_PIN_D9, false);  //Goes to S0
                OutputPort DigitalPin10 = new OutputPort(Pins.GPIO_PIN_D10, false); //Goes to S1
                OutputPort DigitalPin11 = new OutputPort(Pins.GPIO_PIN_D11, false); //Goes to S2
                OutputPort DigitalPin12 = new OutputPort(Pins.GPIO_PIN_D12, false); //Goes to S3
                Mux = new CD74HC4067(DigitalPin9, DigitalPin10, DigitalPin11, DigitalPin12);
                Mux.SetPort(MuxChannel.C0);                                         //default it to C0 which is data coming in from the Indicators Serial Port

                Settings                    = new Settings();
                Settings.Increments         = new double[] { .001, .01, .1, 1, 10, 100 };
                Settings.IncrementSelection = 3;
                Settings.RetrieveSettingsFromSDCard(WORKINGDIRECTORY, "LabelFormat.txt", "Job.txt", "Operation.txt", "ShopTrakTransactionsURL.txt",
                                                    "PieceWeight.txt", "NetWeightAdjustment.txt", "BackgroundColor.txt");

                mMenu.SetBackLightColor(Settings.BacklightColor);

                // initialize the serial port for data being input via COM1
                mIndicatorScannerSerialPort = new MySerialPort(SerialPorts.COM1, BaudRate.Baudrate9600, Parity.None, DataBits.Eight, StopBits.One);
                // initialize the serial port for data being output via COM3
                mPrinterSerialPort = new MySerialPort(SerialPorts.COM3, BaudRate.Baudrate9600, Parity.None, DataBits.Eight, StopBits.One);
                // open the serial-ports, so we can send & receive data
                mIndicatorScannerSerialPort.Open();
                mPrinterSerialPort.Open();
                // add an event-handler for handling incoming data
                mIndicatorScannerSerialPort.DataReceived += new SerialDataReceivedEventHandler(IndicatorScannerSerialPort_DataReceived);


                //Setup the Onboard button; InterruptEdgeLevelLow only fires the event the first time that the button descends
                btnBoard = new InterruptPort(Pins.ONBOARD_SW1, false, Port.ResistorMode.Disabled, Port.InterruptMode.InterruptEdgeHigh);
                // Create an event handler for the button
                btnBoard.OnInterrupt += new NativeEventHandler(btnBoard_OnInterrupt);

                // write your code here
                var webServer = new WebServer();
                webServer.AddRequestFilter(new RequestFilter());
                var fileAndDirectoryService = new FileAndDirectoryService();
                fileAndDirectoryService.SetSDCardManager(new SDCardManager(WORKINGDIRECTORY));
                webServer.SetFileAndDirectoryService(fileAndDirectoryService);
                /*Setting a default controller removes the ability to browse the files and folder of the root web directory*/
                //webServer.RouteTable.DefaultControllerName = "Scale";
                webServer.StartServer(80);//If port is not specified, then default is port 8500
                webServer.SetHostName("Cart Scale");

                //Display appropriate information to the user...
                mMenu.DisplayInformation(Settings);
            }
            catch (Exception objEx)
            {
                Debug.Print("Exception caught in Main()\r\n");
                Debug.Print(objEx.Message);
                mMenu.DisplayError(objEx);
            }

            //We are done. The thread must sleep or else the netduino turns off...
            Thread.Sleep(Timeout.Infinite);
        }
Esempio n. 44
0
        public static void Main()
        {
            var server = new WebServer(8888, new ControllerRouter(), new ResourceRouter());

            server.Run();
        }
Esempio n. 45
0
 /// <summary>
 /// Setups the specified server.
 /// </summary>
 /// <param name="server">The server.</param>
 public static void Setup(WebServer server)
 {
     server.RegisterModule(new WebSocketsModule());
     server.Module <WebSocketsModule>().RegisterWebSocketsServer <WebSocketsChatServer>();
     server.Module <WebSocketsModule>().RegisterWebSocketsServer <WebSocketsTerminalServer>();
 }
Esempio n. 46
0
 public void Dispose()
 {
     HttpClient?.Dispose();
     WebServer?.Dispose();
 }
Esempio n. 47
0
        public static void Main(string[] args)
        {
            string serverURL = Config.GetStringValue("WebServerURL");
            string htmlDir   = Config.GetPathValue("WebServerHTMLPath");

            // Reset DB?
            if (Config.GetBoolValue("DBResetOnRun"))
            {
                System.IO.File.Delete(Config.GetPathValue("DBPath"));
            }

            // Initial DB load
            // https://github.com/unosquare/litelib
            var dbContext = new Model.DataModelContext();

            dbContext.Init();
            if (Config.GetBoolValue("DBResetOnRun"))
            {
                dbContext.CreateTestPlants();
            }

            // Init the controller
            bool enableController = true;

            if (enableController)
            {
                var controller = new Controller.PlantController();
                controller.Start();
            }

            // Our web server is disposable. Note that if you don't want to use logging,
            // there are alternate constructors that allow you to skip specifying an ILog object.
            // https://github.com/unosquare/embedio
            //using (var server = new WebServer(url))
            using (var server = new WebServer(serverURL, new ConsoleLog(), RoutingStrategy.Regex))
            {
                // 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 manupulate it.
                // You could potentially implement a distributed session module using something like Redis
                server.RegisterModule(new LocalSessionModule());

                // API
                server.RegisterModule(new WebApiModule());
                server.Module <WebApiModule>().RegisterController <API.PlantController>();
                server.Module <WebApiModule>().RegisterController <API.AccountController>();
                server.Module <WebApiModule>().RegisterController <API.EditController>();

                // Here we setup serving of static files
                server.RegisterModule(new StaticFilesModule(htmlDir));
                // The static files module will cache small files in ram until it detects they have been modified.
                server.Module <StaticFilesModule>().UseRamCache      = Config.GetBoolValue("WebServerUseRamCache");
                server.Module <StaticFilesModule>().DefaultExtension = ".htm";
                // We don't need to add the line below. The default document is always index.html.
                server.Module <StaticFilesModule>().DefaultDocument = "index.htm";


                // Once we've registered our modules and configured them, we call the RunAsync() method.
                // This is a non-blocking method (it return immediately) so in this case we avoid
                // disposing of the object until a key is pressed.
                //server.Run();
                server.RunAsync();


                // Wait for any key to be pressed before disposing of our web server.
                // In a service we'd manage the lifecycle of of our web server using
                // something like a BackgroundWorker or a ManualResetEvent.
                Console.ReadKey(true);
            }
        }
Esempio n. 48
0
 public void Init()
 {
     WebServer = new WebServer(Resources.WsServerAddress.Replace("ws", "http"), Logger).WithWebSocket(typeof(TestWebSocket).Assembly);
     WebServer.RunAsync();
 }
Esempio n. 49
0
 public HeightMapRequestHandler(WebServer server, HttpRequest request, IRequestHandler handler)
     : base(server, request, handler)
 {
 }
Esempio n. 50
0
            public void ConstructorWithSinglePrefix()
            {
                var instance = new WebServer(Prefix);

                Assert.IsNotNull(instance.Listener, "It has a HttpListener");
            }
Esempio n. 51
0
        private async void Page_Loaded(object sender, RoutedEventArgs e)
        {
            InitializeContainer(new UnityContainer());

            await WebServer.InitializeWebServer();
        }
Esempio n. 52
0
 protected override void AdaptWebServer(WebServer webServer)
 {
     webServer.Module <WebApiModule>().RegisterController <TokenSwapAuthController>();
 }
Esempio n. 53
0
        /// <summary>
        /// Defines the entry point of the application.
        /// </summary>
        /// <param name="args">The arguments.</param>
        private static void Main(string[] args)
        {
            var url = "http://localhost:9696/";

            if (args.Length > 0)
            {
                url = args[0];
            }

            // Our web server is disposable. Note that if you don't want to use logging,
            // there are alternate constructors that allow you to skip specifying an ILog object.
            using (var server = new WebServer(url, Log))
            {
                // 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 manupulate it.
                server.RegisterModule(new Modules.LocalSessionModule());

                // Set the CORS Rules
                server.RegisterModule(new Modules.CorsModule(
                                          // Origins, separated by comma without last slash
                                          "http://client.cors-api.appspot.com,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
                StaticFilesSample.Setup(server);

                // 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.
                RestApiSample.Setup(server);

                // 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)
                WebSocketsSample.Setup(server);

                // Once we've registered our modules and configured them, we call the Run() method.
                // This is a non-blocking method (it return immediately) so in this case we avoid
                // disposing of the object until a key is pressed.
                //server.Run();
                server.RunAsync();

                // Fire up the browser to show the content!
#if DEBUG
                var browser = new System.Diagnostics.Process()
                {
                    StartInfo = new System.Diagnostics.ProcessStartInfo(url)
                    {
                        UseShellExecute = true
                    }
                };
                browser.Start();
#endif
                // Wait for any key to be pressed before disposing of our web server.
                // In a service we'd manage the lifecycle of of our web server using
                // something like a BackgroundWorker or a ManualResetEvent.
                Console.ReadKey(true);
            }

            // Before exiting, we shutdown the logging subsystem.
            Logger.Shutdown();
        }
Esempio n. 54
0
 public static WebServer WebSocket(this WebServer server, string path, Func <WebSocket, Task> handler, bool enableCompression = true) =>
 server.RegisterHandler(path, Serve(handler, enableCompression: enableCompression));
 protected override void AdaptWebServer(WebServer webServer)
 {
     webServer.Module <WebApiModule>().RegisterController <AuthorizationCodeAuthController>();
 }
Esempio n. 56
0
 public static void ClassCleanup()
 {
     WebServer.StopIis();
 }
Esempio n. 57
0
 public UGParts(WebServer Server)
 {
     _server = Server;
 }
Esempio n. 58
0
 public UGParts(string ServerName, string Port)
 {
     _server = new WebServer(ServerName, Port, "Le Chunming", "1qaz@WSX");
     //_server = new WebServer(ServerName, Port, "Michael", "5t6y&U*I");
 }
Esempio n. 59
0
        /// <summary>
        /// Event handler for service starting operations.
        /// </summary>
        /// <param name="sender">Event source.</param>
        /// <param name="e">Event arguments containing command line arguments passed into service at startup.</param>
        protected override void ServiceStartingHandler(object sender, EventArgs <string[]> e)
        {
            // Handle base class service starting procedures
            base.ServiceStartingHandler(sender, e);

            // Make sure openPDC specific default service settings exist
            CategorizedSettingsElementCollection systemSettings   = ConfigurationFile.Current.Settings["systemSettings"];
            CategorizedSettingsElementCollection securityProvider = ConfigurationFile.Current.Settings["securityProvider"];

            // Define set of default anonymous web resources for this site
            const string DefaultAnonymousResourceExpression = "^/@|^/Scripts/|^/Content/|^/Images/|^/fonts/|^/favicon.ico$";

            systemSettings.Add("CompanyName", "Grid Protection Alliance", "The name of the company who owns this instance of the openPDC.");
            systemSettings.Add("CompanyAcronym", "GPA", "The acronym representing the company who owns this instance of the openPDC.");
            systemSettings.Add("DiagnosticLogPath", FilePath.GetAbsolutePath(""), "Path for diagnostic logs.");
            systemSettings.Add("MaximumDiagnosticLogSize", DefaultMaximumDiagnosticLogSize, "The combined maximum size for the diagnostic logs in whole Megabytes; curtailment happens hourly. Set to zero for no limit.");
            systemSettings.Add("WebHostURL", "http://+:8180", "The web hosting URL for remote system management.");
            systemSettings.Add("WebRootPath", "wwwroot", "The root path for the hosted web server files. Location will be relative to install folder if full path is not specified.");
            systemSettings.Add("DefaultWebPage", "Index.cshtml", "The default web page for the hosted web server.");
            systemSettings.Add("DateFormat", "MM/dd/yyyy", "The default date format to use when rendering timestamps.");
            systemSettings.Add("TimeFormat", "HH:mm:ss.fff", "The default time format to use when rendering timestamps.");
            systemSettings.Add("BootstrapTheme", "Content/bootstrap.min.css", "Path to Bootstrap CSS to use for rendering styles.");
            systemSettings.Add("SubscriptionConnectionString", "server=localhost:6165; interface=0.0.0.0", "Connection string for data subscriptions to openPDC server.");
            systemSettings.Add("AuthenticationSchemes", AuthenticationOptions.DefaultAuthenticationSchemes, "Comma separated list of authentication schemes to use for clients accessing the hosted web server, e.g., Basic or NTLM.");
            systemSettings.Add("AuthFailureRedirectResourceExpression", AuthenticationOptions.DefaultAuthFailureRedirectResourceExpression, "Expression that will match paths for the resources on the web server that should redirect to the LoginPage when authentication fails.");
            systemSettings.Add("AnonymousResourceExpression", DefaultAnonymousResourceExpression, "Expression that will match paths for the resources on the web server that can be provided without checking credentials.");
            systemSettings.Add("AuthenticationToken", SessionHandler.DefaultAuthenticationToken, "Defines the token used for identifying the authentication token in cookie headers.");
            systemSettings.Add("SessionToken", SessionHandler.DefaultSessionToken, "Defines the token used for identifying the session ID in cookie headers.");
            systemSettings.Add("RequestVerificationToken", AuthenticationOptions.DefaultRequestVerificationToken, "Defines the token used for anti-forgery verification in HTTP request headers.");
            systemSettings.Add("LoginPage", AuthenticationOptions.DefaultLoginPage, "Defines the login page used for redirects on authentication failure. Expects forward slash prefix.");
            systemSettings.Add("AuthTestPage", AuthenticationOptions.DefaultAuthTestPage, "Defines the page name for the web server to test if a user is authenticated. Expects forward slash prefix.");
            systemSettings.Add("Realm", "", "Case-sensitive identifier that defines the protection space for the web based authentication and is used to indicate a scope of protection.");
            systemSettings.Add("DefaultCorsOrigins", "", "Comma-separated list of allowed origins (including http:// prefix) that define the default CORS policy. Use '*' to allow all or empty string to disable CORS.");
            systemSettings.Add("DefaultCorsHeaders", "*", "Comma-separated list of supported headers that define the default CORS policy. Use '*' to allow all or empty string to allow none.");
            systemSettings.Add("DefaultCorsMethods", "*", "Comma-separated list of supported methods that define the default CORS policy. Use '*' to allow all or empty string to allow none.");
            systemSettings.Add("DefaultCorsSupportsCredentials", true, "Boolean flag for the default CORS policy indicating whether the resource supports user credentials in the request.");

            DefaultWebPage = systemSettings["DefaultWebPage"].Value;

            Model = new AppModel();
            Model.Global.CompanyName    = systemSettings["CompanyName"].Value;
            Model.Global.CompanyAcronym = systemSettings["CompanyAcronym"].Value;
            Model.Global.NodeID         = Guid.Parse(systemSettings["NodeID"].Value);
            Model.Global.SubscriptionConnectionString = systemSettings["SubscriptionConnectionString"].Value;
            Model.Global.ApplicationName                = "openPDC";
            Model.Global.ApplicationDescription         = "openPDC System";
            Model.Global.ApplicationKeywords            = "open source, utility, software, time-series, archive";
            Model.Global.DateFormat                     = systemSettings["DateFormat"].Value;
            Model.Global.TimeFormat                     = systemSettings["TimeFormat"].Value;
            Model.Global.DateTimeFormat                 = $"{Model.Global.DateFormat} {Model.Global.TimeFormat}";
            Model.Global.PasswordRequirementsRegex      = securityProvider["PasswordRequirementsRegex"].Value;
            Model.Global.PasswordRequirementsError      = securityProvider["PasswordRequirementsError"].Value;
            Model.Global.BootstrapTheme                 = systemSettings["BootstrapTheme"].Value;
            Model.Global.WebRootPath                    = FilePath.GetAbsolutePath(systemSettings["WebRootPath"].Value);
            Model.Global.DefaultCorsOrigins             = systemSettings["DefaultCorsOrigins"].Value;
            Model.Global.DefaultCorsHeaders             = systemSettings["DefaultCorsHeaders"].Value;
            Model.Global.DefaultCorsMethods             = systemSettings["DefaultCorsMethods"].Value;
            Model.Global.DefaultCorsSupportsCredentials = systemSettings["DefaultCorsSupportsCredentials"].ValueAsBoolean(true);

            AuthenticationSchemes authenticationSchemes;

            // Parse configured authentication schemes
            if (!Enum.TryParse(systemSettings["AuthenticationSchemes"].ValueAs(AuthenticationOptions.DefaultAuthenticationSchemes.ToString()), true, out authenticationSchemes))
            {
                authenticationSchemes = AuthenticationOptions.DefaultAuthenticationSchemes;
            }

            // Initialize web startup configuration
            Startup.AuthenticationOptions.AuthenticationSchemes = authenticationSchemes;
            Startup.AuthenticationOptions.AuthFailureRedirectResourceExpression = systemSettings["AuthFailureRedirectResourceExpression"].ValueAs(AuthenticationOptions.DefaultAuthFailureRedirectResourceExpression);
            Startup.AuthenticationOptions.AnonymousResourceExpression           = systemSettings["AnonymousResourceExpression"].ValueAs(DefaultAnonymousResourceExpression);
            Startup.AuthenticationOptions.AuthenticationToken      = systemSettings["AuthenticationToken"].ValueAs(SessionHandler.DefaultAuthenticationToken);
            Startup.AuthenticationOptions.SessionToken             = systemSettings["SessionToken"].ValueAs(SessionHandler.DefaultSessionToken);
            Startup.AuthenticationOptions.RequestVerificationToken = systemSettings["RequestVerificationToken"].ValueAs(AuthenticationOptions.DefaultRequestVerificationToken);
            Startup.AuthenticationOptions.LoginPage    = systemSettings["LoginPage"].ValueAs(AuthenticationOptions.DefaultLoginPage);
            Startup.AuthenticationOptions.AuthTestPage = systemSettings["AuthTestPage"].ValueAs(AuthenticationOptions.DefaultAuthTestPage);
            Startup.AuthenticationOptions.Realm        = systemSettings["Realm"].ValueAs("");
            Startup.AuthenticationOptions.LoginHeader  = $"<h2><img src=\"/Images/{Model.Global.ApplicationName}.png\"/> {Model.Global.ApplicationName}</h2>";

            // Validate that configured authentication test page does not evaluate as an anonymous resource nor a authentication failure redirection resource
            string authTestPage = Startup.AuthenticationOptions.AuthTestPage;

            if (Startup.AuthenticationOptions.IsAnonymousResource(authTestPage))
            {
                throw new SecurityException($"The configured authentication test page \"{authTestPage}\" evaluates as an anonymous resource. Modify \"AnonymousResourceExpression\" setting so that authorization test page is not a match.");
            }

            if (Startup.AuthenticationOptions.IsAuthFailureRedirectResource(authTestPage))
            {
                throw new SecurityException($"The configured authentication test page \"{authTestPage}\" evaluates as an authentication failure redirection resource. Modify \"AuthFailureRedirectResourceExpression\" setting so that authorization test page is not a match.");
            }

            if (Startup.AuthenticationOptions.AuthenticationToken == Startup.AuthenticationOptions.SessionToken)
            {
                throw new InvalidOperationException("Authentication token must be different from session token in order to differentiate the cookie values in the HTTP headers.");
            }

            // Register a symbolic reference to global settings for use by default value expressions
            ValueExpressionParser.DefaultTypeRegistry.RegisterSymbol("Global", Program.Host.Model.Global);

            ServiceHelper.UpdatedStatus   += UpdatedStatusHandler;
            ServiceHelper.LoggedException += LoggedExceptionHandler;

            // Attach to default web server events
            WebServer webServer = WebServer.Default;

            webServer.StatusMessage      += WebServer_StatusMessage;
            webServer.ExecutionException += LoggedExceptionHandler;

            // Define types for Razor pages - self-hosted web service does not use view controllers so
            // we must define configuration types for all paged view model based Razor views here:
            webServer.PagedViewModelTypes.TryAdd("TrendMeasurements.cshtml", new Tuple <Type, Type>(typeof(ActiveMeasurement), typeof(DataHub)));
            webServer.PagedViewModelTypes.TryAdd("Devices.cshtml", new Tuple <Type, Type>(typeof(Device), typeof(DataHub)));
            webServer.PagedViewModelTypes.TryAdd("Companies.cshtml", new Tuple <Type, Type>(typeof(Company), typeof(SharedHub)));
            webServer.PagedViewModelTypes.TryAdd("Vendors.cshtml", new Tuple <Type, Type>(typeof(Vendor), typeof(SharedHub)));
            webServer.PagedViewModelTypes.TryAdd("VendorDevices.cshtml", new Tuple <Type, Type>(typeof(VendorDevice), typeof(SharedHub)));
            webServer.PagedViewModelTypes.TryAdd("Users.cshtml", new Tuple <Type, Type>(typeof(UserAccount), typeof(SecurityHub)));
            webServer.PagedViewModelTypes.TryAdd("Groups.cshtml", new Tuple <Type, Type>(typeof(SecurityGroup), typeof(SecurityHub)));

            // Define exception logger for CSV downloader
            CsvDownloadHandler.LogExceptionHandler = LogException;

            new Thread(() =>
            {
                const int RetryDelay = 1000;
                const int SleepTime  = 200;
                const int LoopCount  = RetryDelay / SleepTime;

                while (!m_serviceStopping)
                {
                    if (TryStartWebHosting(systemSettings["WebHostURL"].Value))
                    {
                        try
                        {
                            // Initiate pre-compile of base templates
                            RazorEngine <CSharpEmbeddedResource> .Default.PreCompile(LogException);
                            RazorEngine <CSharpEmbeddedResource> .Default.PreCompile(LogException, "GSF.Web.Security.Views.");
                            RazorEngine <CSharpEmbeddedResource> .Default.PreCompile(LogException, "GSF.Web.Shared.Views.");
                            RazorEngine <CSharp> .Default.PreCompile(LogException);
                        }
                        catch (Exception ex)
                        {
                            LogException(new InvalidOperationException($"Failed to initiate pre-compile of razor templates: {ex.Message}", ex));
                        }

                        break;
                    }

                    for (int i = 0; i < LoopCount && !m_serviceStopping; i++)
                    {
                        Thread.Sleep(SleepTime);
                    }
                }
            })
            {
                IsBackground = true
            }
            .Start();
        }
Esempio n. 60
0
 static void Main()
 {
     Web = new WebServer(Logs);
 }