/// <summary>
 /// Initializes a new instance of the <see cref="Http2OwinMessageHandler"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="end"></param>
 /// <param name="transportInfo">The transport information.</param>
 /// <param name="next">The next layer delegate.</param>
 /// <param name="cancel">The cancellation token.</param>
 public Http2OwinMessageHandler(DuplexStream stream, ConnectionEnd end, TransportInformation transportInfo,
                         AppFunc next, CancellationToken cancel)
     : base(stream, end, stream.IsSecure, transportInfo, cancel)
 {
     _next = next;
     stream.OnClose += delegate { Dispose(); };
 }
Пример #2
0
        public ResttpComponent(AppFunc next, ResttpConfiguration config)
        {
            _next = next;
            Config = config;

            //TestRoutes(new HttpRouteResolver(Config.HttpRoutes));
        }
Пример #3
0
        public Error404Module(AppFunc next)
        {
            if (next == null)
                throw new ArgumentNullException("next");

            this.next = next;
        }
Пример #4
0
 public XXssMiddleware(AppFunc next, XXssProtectionOptions options)
     : base(next)
 {
     _config = options;
     var headerGenerator = new HeaderGenerator();
     _headerResult = headerGenerator.CreateXXssProtectionResult(_config);
 }
 /// <summary>
 /// Initializes a new instance of the <see cref="Http2OwinMessageHandler"/> class.
 /// </summary>
 /// <param name="stream">The stream.</param>
 /// <param name="end"></param>
 /// <param name="isSecure"></param>
 /// <param name="next">The next layer delegate.</param>
 /// <param name="cancel">The cancellation token.</param>
 public Http2OwinMessageHandler(Stream stream, ConnectionEnd end, bool isSecure,
                         AppFunc next, CancellationToken cancel)
     : base(stream, end, isSecure, cancel)
 {
     _next = next;
     _session.OnSessionDisposed += delegate { Dispose(); };
 }
 public ActionInvokerComponent(AppFunc next, MediaTypeFormatterCollection formatters, IContentNegotiator contentNegotiator, IActionParameterBinder parameterBinder)
 {
     _next = next;
     _formatters = formatters;
     _contentNegotiator = contentNegotiator;
     _actionParameterBinder = parameterBinder;
 }
 public PersistentConnectionHandler(AppFunc next, string path, Type connectionType, ConnectionConfiguration configuration)
 {
     _next = next;
     _path = path;
     _connectionType = connectionType;
     _configuration = configuration;
 }
        public CanonicalRequestPatterns(AppFunc next)
        {
            _next = next;

            _paths = new Dictionary<string, Tuple<AppFunc, string>>();
            _paths["/"] = new Tuple<AppFunc, string>(Index, null);

            var items = GetType().GetMethods()
                .Select(methodInfo => new
                {
                    MethodInfo = methodInfo,
                    Attribute = methodInfo.GetCustomAttributes(true).OfType<CanonicalRequestAttribute>().SingleOrDefault()
                })
                .Where(item => item.Attribute != null)
                .Select(item => new
                {
                    App = (AppFunc)Delegate.CreateDelegate(typeof(AppFunc), this, item.MethodInfo),
                    item.Attribute.Description,
                    item.Attribute.Path,
                });

            foreach (var item in items)
            {
                _paths.Add(item.Path, Tuple.Create(item.App, item.Description));
            }
        }
 public HtmlAppenderMiddleware(AppFunc next, HtmlAppenderMiddlewareOptions options)
 {
     if (null == next) throw new ArgumentNullException("next");
     if (null == options) throw new ArgumentNullException("options");
     _next = next;
     _options = options;
 }
Пример #10
0
 public CarcarahOAuth(AppFunc next, OAuthOptions options)
 {
     this.next = next;
     this.options = options;
     AuthCodeStorage = new AuthorizationCodeStorage();
     RefreshTokenStorage = new RefreshTokenStorage();
 }
 public LightNodeServerMiddleware(AppFunc next, LightNodeOptions options, Assembly[] hostAssemblies)
 {
     this.next = next;
     this.useOtherMiddleware = options.UseOtherMiddleware;
     this.engine = new LightNodeServer(options);
     this.engine.RegisterHandler(hostAssemblies);
 }
        public Http2SocketServer(Func<IDictionary<string, object>, Task> next, IDictionary<string, object> properties)
        {
            _next = next;
            _socket = new Socket(SocketType.Stream, ProtocolType.Tcp); // Dual mode

            IList<IDictionary<string, object>> addresses = 
                (IList<IDictionary<string, object>>)properties[OwinConstants.CommonKeys.Addresses];

            IDictionary<string, object> address = addresses.First();
            _enableSsl = !string.Equals((address.Get<string>("scheme") ?? "http"), "http", StringComparison.OrdinalIgnoreCase);

            _port = Int32.Parse(address.Get<string>("port") ?? (_enableSsl ? "443" : "80"), CultureInfo.InvariantCulture);

            string host = address.Get<string>("host");
            if (string.IsNullOrWhiteSpace(host) || !host.Equals("*") || !host.Equals("+"))
            {
                _socket.Bind(new IPEndPoint(IPAddress.IPv6Any, _port));
            }
            else
            {
                _socket.Bind(new IPEndPoint(Dns.GetHostAddresses(host)[0], _port));
            }

            Listen();
        }
Пример #13
0
        public static IDisposable Create(AppFunc app, IDictionary<string, object> properties)
        {
            if (app == null)
            {
                throw new ArgumentNullException("app");
            }
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }

            // Retrieve the instances created in Initialize
            OwinHttpListener wrapper = properties.Get<OwinHttpListener>(typeof(OwinHttpListener).FullName)
                ?? new OwinHttpListener();
            System.Net.HttpListener listener = properties.Get<System.Net.HttpListener>(typeof(System.Net.HttpListener).FullName)
                ?? new System.Net.HttpListener();

            AddressList addresses = properties.Get<AddressList>(Constants.HostAddressesKey)
                ?? new List<IDictionary<string, object>>();

            CapabilitiesDictionary capabilities =
                properties.Get<CapabilitiesDictionary>(Constants.ServerCapabilitiesKey)
                    ?? new Dictionary<string, object>();

            var loggerFactory = properties.Get<LoggerFactoryFunc>(Constants.ServerLoggerFactoryKey);

            wrapper.Start(listener, app, addresses, capabilities, loggerFactory);
            return wrapper;
        }
Пример #14
0
		public static AppFunc Enable(AppFunc next, Func<IDictionary<string, object>, bool> requiresAuth, string realm, Func<string, UserPassword?> authenticator)
		{
			return env =>
			{
				if (!requiresAuth(env))
				{
					return next(env);
				}

				var requestHeaders = (IDictionary<string, string[]>)env[OwinConstants.RequestHeaders];

				var header = OwinHelpers.GetHeader(requestHeaders, "Authorization");

				var parsedHeader = ParseDigestHeader(header);

				if (parsedHeader == null)
				{
					return Unauthorized(env, realm);
				}

				string user = parsedHeader["username"];
				var pwd = authenticator(user);

				// TODO: check for increment of "nc" header value

				if (!pwd.HasValue || !IsValidResponse(pwd.Value.GetHA1(user, realm), (string)env[OwinConstants.RequestMethod], parsedHeader))
				{
					return Unauthorized(env, realm);
				}

				env["gate.RemoteUser"] = user;
				return next(env);
			};
		}
Пример #15
0
        // Consumers should use IoC or the Default UseRazor extension method to initialize this.
        public RazorApplication(
            AppFunc nextApp,
            IFileSystem fileSystem,
            string virtualRoot,
            IRouter router,
            ICompilationManager compiler,
            IPageActivator activator,
            IPageExecutor executor,
            ITraceFactory tracer)
            : this(nextApp)
        {
            Requires.NotNull(fileSystem, "fileSystem");
            Requires.NotNullOrEmpty(virtualRoot, "virtualRoot");
            Requires.NotNull(router, "router");
            Requires.NotNull(compiler, "compiler");
            Requires.NotNull(activator, "activator");
            Requires.NotNull(executor, "executor");
            Requires.NotNull(tracer, "tracer");

            FileSystem = fileSystem;
            VirtualRoot = virtualRoot;
            Router = router;
            CompilationManager = compiler;
            Executor = executor;
            Activator = activator;
            Tracer = tracer;

            ITrace global = Tracer.ForApplication();
            global.WriteLine("Started at '{0}'", VirtualRoot);
        }
Пример #16
0
 public XfoMiddleware(AppFunc next, XFrameOptions options)
     : base(next)
 {
     _config = options;
     var headerGenerator = new HeaderGenerator();
     _headerResult = headerGenerator.CreateXfoResult(_config);
 }
 public XDownloadOptionsMiddleware(AppFunc next)
     : base(next)
 {
     _config = new SimpleBooleanConfiguration { Enabled = true };
     var headerGenerator = new HeaderGenerator();
     _headerResult = headerGenerator.CreateXDownloadOptionsResult(_config);
 }
 public OwinFriendlyExceptionsMiddleware(AppFunc next, ITransformsCollection transformsCollection,
     OwinFriendlyExceptionsParameters parameters)
 {
     _next = next;
     _transformsCollection = transformsCollection;
     _parameters = parameters;
 }
Пример #19
0
        public Static(AppFunc app, string root = null, IEnumerable<string> urls = null)
        {
            this.app = app;

            if (root == null)
            {
                root = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "public");
            }

            if (!Directory.Exists(root))
            {
                throw new DirectoryNotFoundException(string.Format("Invalid root directory: {0}", root));
            }

            if (urls == null)
            {
                var rootDirectory = new DirectoryInfo(root);
                var files = rootDirectory.GetFiles("*").Select(fi => "/" + fi.Name);
                var directories = rootDirectory.GetDirectories().Select(di => "/" + di.Name);
                urls = files.Concat(directories);
            }

            this.urls = urls;

            fileServer = new FileServer(root);
        }
Пример #20
0
        public MapPathMiddleware(AppFunc next, AppFunc branch, string pathMatch)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }
            if (branch == null)
            {
                throw new ArgumentNullException("branch");
            }
            if (pathMatch == null)
            {
                throw new ArgumentNullException("pathMatch");
            }
            // Must at least start with a "/foo" to be considered a branch. Otherwise it's a catch-all.
            if (!pathMatch.StartsWith("/", StringComparison.Ordinal) || pathMatch.Length == 1)
            {
                throw new ArgumentException("Path must start with a \"/\" followed by one or more characters.", "pathMatch");
            }

            // Only match on "/" boundaries, but permit the trailing "/" to be absent.
            if (pathMatch.EndsWith("/", StringComparison.Ordinal))
            {
                pathMatch = pathMatch.Substring(0, pathMatch.Length - 1);
            }

            _next = next;
            _branch = branch;
            _pathMatch = pathMatch;
        }
Пример #21
0
 public RouteBody(AppFunc next, string[] httpMethods, string paramKey, Func<Stream, object> converter)
 {
     this.next = next;
     this.routeParamName = paramKey;
     this.methods = httpMethods;
     this.converter = converter;
 }
Пример #22
0
        public Html5Middleware(AppFunc next, HTML5ServerOptions options)
        {
            _next = next;
            _options = options;

            _innerMiddleware = new StaticFileMiddleware(next, options.FileServerOptions.StaticFileOptions);
        }
 void IPipelineComponent.Connect(AppFunc next) {
     _next = next;
     if (_match == Match.First) {
         foreach (var option in _options) {
             option.Handler.Connect(_next);
         }
     }
 }
Пример #24
0
        public AutoTuneMiddleware(AppFunc next, OwinHttpListener server)
        {
            _next = next;
            _server = server;
            _server.SetRequestProcessingLimits((int)_currentMaxAccepts, _currentMaxRequests);

            _timer = new Timer(TimerFired, null, TimeSpan.FromSeconds(0), TimeSpan.FromSeconds(0.1));
        }
Пример #25
0
        public HstsMiddleware(AppFunc next, HstsOptions options)
            : base(next)
        {
            _config = options;

            var headerGenerator = new HeaderGenerator();
            _headerResult = headerGenerator.CreateHstsResult(_config);
        }
Пример #26
0
        public XRobotsTagMiddleware(AppFunc next, XRobotsTagOptions options)
            : base(next)
        {
            _config = options.Config;

            var headerGenerator = new HeaderGenerator();
            _headerResult = headerGenerator.CreateXRobotsTagResult(_config);
        }
Пример #27
0
        /// <summary>
        ///     Creates a new Liara Engine for applications.
        /// </summary>
        /// <param name="next" />
        /// <param name="configuration"></param>
        public LiaraMiddleware(AppFunc next, LiaraConfiguration configuration = null)
        {
            if (configuration == null)
                configuration = new LiaraConfiguration();

            engine = new LiaraEngine(configuration);
            this.next = next;
        }
Пример #28
0
        public HpkpMiddleware(AppFunc next, HpkpOptions options, bool reportOnly)
            : base(next)
        {
            _config = options.Config;

            var headerGenerator = new HeaderGenerator();
            _headerResult = headerGenerator.CreateHpkpResult(_config, reportOnly);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="next"></param>
        public ImpersonationMiddleware(AppFunc next)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }

            _next = next;
        }
Пример #30
0
        public static AppFunc Create(AppFunc defaultApp, IDictionary<string, AppFunc> map)
        {
            if (defaultApp == null)
                throw new ArgumentNullException("defaultApp");

            var mapper = new UrlMapper(defaultApp);
            mapper.Remap(map);
            return mapper.Call;
        }
        public void Configuration(IAppBuilder app)
        {
            AppFunc middleware = (IDictionary <string, object> env) =>
            {
                var    response = (Stream)env["owin.ResponseBody"];
                byte[] bytes    = Encoding.UTF8.GetBytes("Hello World");
                return(response.WriteAsync(bytes, 0, bytes.Length));
            };

            app.Use(middleware);
        }
Пример #32
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc FilterRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                if (AllowAccess(environment))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #33
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc AppFuncBuilder(AppFunc next)
        {
            return(async(IDictionary <string, object> environment) => {
                _Minifier = Factory.Resolve <IMinifier>();
                _Config = Factory.ResolveSingleton <IJavascriptManipulatorConfiguration>();

                ManipulateResponseStream(environment);

                await next(environment);
            });
        }
Пример #34
0
        public static AppFunc ToAppFunc(FubuRuntime runtime, OwinSettings settings = null)
        {
            settings = settings ?? runtime.Get <OwinSettings>();
            var     host    = new FubuOwinHost(runtime.Routes);
            AppFunc inner   = host.Invoke;
            AppFunc appFunc = settings.BuildAppFunc(inner, runtime.Get <IServiceFactory>());

            var diagnostics = runtime.Get <DiagnosticsSettings>();

            return(diagnostics.WrapAppFunc(runtime, appFunc));
        }
Пример #35
0
        public async Task Start(AppFunc chain, IDictionary <string, object> settings, string environment, string[] arguments)
        {
            settings.Log("Starting processmanagers for environment: {0}", LogLevel.Debug, environment);

            running = true;

            foreach (var processManager in _processManagers)
            {
                await SubscribeProcessManager(chain, processManager, settings).ConfigureAwait(false);
            }
        }
Пример #36
0
 public TestableEdgeApplication(AppFunc next, string virtualRoot)
     : base(next)
 {
     VirtualRoot        = virtualRoot;
     FileSystem         = TestFileSystem = new TestFileSystem(@"C:\Test");
     Router             = new DefaultRouter(TestFileSystem);
     CompilationManager = (MockCompilationManager = new Mock <ICompilationManager>()).Object;
     Activator          = (MockActivator = new Mock <IPageActivator>()).Object;
     Executor           = (MockExecutor = new Mock <IPageExecutor>()).Object;
     Tracer             = NullTraceFactory.Instance;
 }
Пример #37
0
        /// <summary>
        /// Starts the listener and request processing threads.
        /// </summary>
        internal void Start(System.Net.HttpListener listener, AppFunc appFunc, IList <IDictionary <string, object> > addresses,
                            IDictionary <string, object> capabilities, LoggerFactoryFunc loggerFactory)
        {
            Contract.Assert(_appFunc == null); // Start should only be called once
            Contract.Assert(listener != null);
            Contract.Assert(appFunc != null);
            Contract.Assert(addresses != null);

            _listener = listener;
            _appFunc  = appFunc;
            _logger   = LogHelper.CreateLogger(loggerFactory, typeof(OwinHttpListener));

            _basePaths = new List <string>();

            foreach (var address in addresses)
            {
                // build url from parts
                string scheme = address.Get <string>("scheme") ?? Uri.UriSchemeHttp;
                string host   = address.Get <string>("host") ?? "localhost";
                string port   = address.Get <string>("port") ?? "5000";
                string path   = address.Get <string>("path") ?? string.Empty;

                // if port is present, add delimiter to value before concatenation
                if (!string.IsNullOrWhiteSpace(port))
                {
                    port = ":" + port;
                }

                // Assume http(s)://+:9090/BasePath/, including the first path slash.  May be empty. Must end with a slash.
                if (!path.EndsWith("/", StringComparison.Ordinal))
                {
                    // Http.Sys requires that the URL end in a slash
                    path += "/";
                }
                _basePaths.Add(path);

                // add a server for each url
                string url = scheme + "://" + host + port + path;
                _listener.Prefixes.Add(url);
            }

            _capabilities = capabilities;

            if (!_listener.IsListening)
            {
                _listener.Start();
            }

            SetRequestQueueLimit();

            _disconnectHandler = new DisconnectHandler(_listener, _logger);

            OffloadStartNextRequest();
        }
Пример #38
0
 void IPipelineComponent.Connect(AppFunc next)
 {
     _next = next;
     if (_match == Match.First)
     {
         foreach (var option in _options)
         {
             option.Handler.Connect(_next);
         }
     }
 }
Пример #39
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                if (AddCorsHeaders(environment))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #40
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc AppFuncBuilder(AppFunc next)
        {
            return(async(IDictionary <string, object> environment) => {
                InitialiseConfiguration();

                if (!ServeBundle(environment))
                {
                    await next(environment);
                }
            });
        }
Пример #41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="OwinExceptionHandlerMiddleware"/> class.
        /// </summary>
        /// <param name="next">
        /// The next.
        /// </param>
        /// <param name="exceptionConfiguration">
        /// The exception configuration.
        /// </param>
        /// <exception cref="ArgumentNullException">
        /// </exception>
        public OwinExceptionHandlerMiddleware(AppFunc next, IExceptionConfiguration exceptionConfiguration)
        {
            if (next == null)
            {
                throw new ArgumentNullException("next");
            }

            this._next = next;

            this._exceptionConfiguration = exceptionConfiguration;
        }
Пример #42
0
        /// <summary>
        /// Called by <see cref="Microsoft.Owin.Hosting.ServerFactory.ServerFactoryAdapter"/>
        /// which starts the server
        /// </summary>
        /// <param name="app"></param>
        /// <param name="properties"></param>
        /// <returns></returns>
        public IDisposable Create(AppFunc app, IDictionary <string, object> properties)
        {
            var loggerFactory = properties.Get <LoggerFactoryFunc>(Constants.ServerLoggerFactoryKey);
            var logger        = new OwinLogger(loggerFactory, GetType());

            var listener = new HttpListener(logger);

            listener.OnContext = ctx => ProcessRequest(ctx, app, logger);
            listener.Prefixes.Add(_url);
            listener.Start();
            return(new Disposable(listener));
        }
Пример #43
0
        public async Task <IActionResult> PutPasswordToken([FromBody] dynamic tokenPassword)
        {
            try
            {
                string passwordString = tokenPassword.password;
                string tokenString    = tokenPassword.token;

                Token token = await AppDbContext.Tokens
                              .Include(t => t.User)
                              .ThenInclude(u => u.Role)
                              .SingleOrDefaultAsync(t => t.Value.Equals(tokenString))
                              .ConfigureAwait(false);


                if (token == null)
                {
                    /// Add the error below to the error list and return bad request
                    AppFunc.Error(ref ErrorsList, _localizer["Token Not Found."].Value);
                    return(StatusCode(417, ErrorsList));
                }

                if (token.ExpiaryDateTime < DateTime.UtcNow)
                {
                    /// Add the error below to the error list and return bad request
                    AppFunc.Error(ref ErrorsList, _localizer["Token Expired."].Value);
                    return(StatusCode(417, ErrorsList));
                }

                token.User.PasswordHash = passwordString;

                User result = await UpdatePassword(token.User).ConfigureAwait(false);

                if (result == null)
                {
                    return(StatusCode(412, ErrorsList));
                }

                result.Role = token.User.Role;
                token.User  = null;
                AppDbContext.Entry(token).State = EntityState.Deleted;
                await AppDbContext.SaveChangesAsync().ConfigureAwait(false);

                await _SignInManager.SignInAsync(result, false).ConfigureAwait(false);

                return(Ok(result));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }
        public void HostAppFunc()
        {
            AppFunc testCode = env => {
                OwinContext.Get(env)
                .TraceOutput.Write("App");
                return(TaskHelper.Completed());
            };
            var host = new TestHostAndServer(testCode);

            host.ProcessGet("/");
            host.TraceOutputValue.ShouldEqual("App");
        }
Пример #45
0
        public static AppFunc Create(AppFunc defaultApp, IDictionary <string, AppFunc> map)
        {
            if (defaultApp == null)
            {
                throw new ArgumentNullException("defaultApp");
            }

            var mapper = new UrlMapper(defaultApp);

            mapper.Remap(map);
            return(mapper.Call);
        }
Пример #46
0
        internal void Start(AppFunc next, IList <IDictionary <string, object> > addresses)
        {
            // Start a server that listens on the given address(es).

            // Listen for incoming requests.

            // Dispatch them into the OWIN pipeline by calling next.

            // Clean up the request when the AppFunc Task completes.

            // Shut down when Dispose is called.
        }
Пример #47
0
        /// <summary>
        /// Creates new isntaces of the Http11ProtocolOwinAdapter class
        /// </summary>
        /// <param name="client">The client connection.</param>
        /// <param name="protocol">Security protocol which is used for connection.</param>
        /// <param name="next">The next component in the OWIN pipeline.</param>
        public Http11ProtocolOwinAdapter(Stream client, SslProtocols protocol, AppFunc next)
        {
            // args checking
            if (client == null)
            {
                throw new ArgumentNullException("client");
            }

            _client   = client;
            _protocol = protocol;
            _next     = next;
        }
Пример #48
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                var context = PipelineContext.GetOrCreate(environment);
                if (!ServeFromFileSystem(environment))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #49
0
 public KonamiCodeMiddleware(AppFunc next, KonamiCodeMiddlewareOptions options) :
     base(next, new HtmlAppenderMiddlewareOptions {
     Head = String.Format("<script type='text/javascript' src='{0}/konami.js'></script>", options.AssetsPath),
     Body = String.Format("<script>var easter_egg = new Konami(function() {{ {0} }});</script>", options.Action)
 })
 {
     if (null == options)
     {
         throw new ArgumentNullException("options");
     }
     _options = options;
 }
Пример #50
0
        private AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                var context = PipelineContext.GetOrCreate(environment);
                if (!ProcessRequest(context))
                {
                    await next.Invoke(environment);
                }
            };

            return(appFunc);
        }
Пример #51
0
        public async Task StartAsync(AppFunc app)
        {
            _hostedServices = Services.GetService <IEnumerable <IServerService> >();

            foreach (var hostedService in _hostedServices)
            {
                var serverOptions = options.Servers.Find(o => o.Name == hostedService.Name);

                // Fire IHostedService.Start
                await hostedService.StartAsync(BossGroup, WorkerGroup, serverOptions, app).ConfigureAwait(false);
            }
        }
Пример #52
0
        private static AppFunc InterfaceMiddleware(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> dic) =>
            {
                IOwinContext context = new OwinContext(dic);
                await context.Response.WriteAsync("usando a IOwinContext <br>");

                await next.Invoke(dic);
            };

            return(appFunc);
        }
Пример #53
0
        public static IDisposable Create(AppFunc app, IDictionary <string, object> properties)
        {
            bool useHandshake   = ConfigurationManager.AppSettings["handshakeOptions"] != "no-handshake";
            bool usePriorities  = ConfigurationManager.AppSettings["prioritiesOptions"] != "no-priorities";
            bool useFlowControl = ConfigurationManager.AppSettings["flowcontrolOptions"] != "no-flowcontrol";

            properties.Add("use-handshake", useHandshake);
            properties.Add("use-priorities", usePriorities);
            properties.Add("use-flowControl", useFlowControl);

            return(new HttpSocketServer(app, properties));
        }
Пример #54
0
        public static async Task Main(string[] args)
        {
            AppFunc appFunc = null;

            //Only setup our AspNet Core host if within the Browser Process
            //Not needed for the sub processes (render, gpu, etc)
            //TODO: Move this somewhere internal to Chromely that
            //doesn't require the extra check and supports async
            if (!args.Any(x => x.StartsWith("--type")))
            {
                var tcs = new TaskCompletionSource <AppFunc>();

                var builder = new WebHostBuilder();

                builder.ConfigureServices(services =>
                {
                    var server = new OwinServer();
                    server.UseOwin(appFunc =>
                    {
                        tcs.SetResult(appFunc);
                    });

                    services.AddSingleton <IServer>(server);
                });

                _host = builder
                        .UseStartup <Startup>()
                        .UseContentRoot(Directory.GetCurrentDirectory())
                        .Build();

                _ = _host.RunAsync();

                appFunc = await tcs.Task;
            }

            var config = DefaultConfiguration.CreateForRuntimePlatform();

            config.WindowOptions.Title = "Title Window";
            config.StartUrl            = "https://chromely.test";
            //config.StartUrl = "chrome://version";

            var app = new OwinChromelyBasicApp(appFunc);

            AppBuilder
            .Create()
            .UseConfig <DefaultConfiguration>(config)
            .UseApp <OwinChromelyBasicApp>(app)
            .Build()
            .Run(args);

            await _host.StopAsync();
        }
Пример #55
0
        // [Authorize(AppConst.AccessPolicies.Secret)]  /// Done
        public async Task <IActionResult> Post([FromBody] Role newRole)
        {
            try
            {
                int langId = AppFunc.GetLanguageId();
                /// if model validation failed
                if (!TryValidateModel(newRole))
                {
                    AppFunc.ExtractErrors(ModelState, ref ErrorsList);
                    /// return Unprocessable Entity with all the errors
                    return(UnprocessableEntity(ErrorsList));
                }



                /// check the database to see if a role with the same name exists
                if (await AppDbContext.Roles.Include(r => r.RoleTranslates).Select(p => new Role
                {
                    Name = p.RoleTranslates.FirstOrDefault(e => e.LangId == langId).Name,
                    AccessClaim = p.AccessClaim,
                    Id = p.Id
                }).AnyAsync(d => d.Name.Equals(newRole.Name) && d.AccessClaim.Equals(newRole.AccessClaim)).ConfigureAwait(false))
                {
                    /// extract the errors and return bad request containing the errors
                    AppFunc.Error(ref ErrorsList, _localizer["Role already exists."].Value);
                    return(StatusCode(412, ErrorsList));
                }
                foreach (string lang in AppConst.SupportLanguages)
                {
                    newRole.RoleTranslates.Add(new RoleTranslate()
                    {
                        LangId = AppFunc.GetLanguageId(lang), Name = newRole.Name
                    });
                }
                /// else role object is made without any errors
                /// Add the new role to the EF context
                await AppDbContext.Roles.AddAsync(newRole).ConfigureAwait(false);

                /// save the changes to the data base
                await AppDbContext.SaveChangesAsync().ConfigureAwait(false);

                /// return 201 created status with the new object
                /// and success message
                return(Created(_localizer["Success"].Value, newRole));
            }
            catch (Exception) // DbUpdateException, DbUpdateConcurrencyException
            {
                /// Add the error below to the error list and return bad request
                AppFunc.Error(ref ErrorsList, AppConst.CommonErrors.ServerError);
                return(StatusCode(417, ErrorsList));
            }
        }
 public CornifyMiddleware(AppFunc next, CornifyMiddlewareOptions options) :
     base(next, new HtmlAppenderMiddlewareOptions {
     Head         = String.Format("<script type='text/javascript' src='{0}/cornify.js'></script>", options.AssetsPath),
     Body         = "<script>(function() { setInterval(function(){ cornify_add(); }, " + options.AddDelayInMilliseconds + "); })();</script>",
     AppendToBody = options.Autostart
 })
 {
     if (null == options)
     {
         throw new ArgumentNullException("options");
     }
     _options = options;
 }
 public HtmlAppenderMiddleware(AppFunc next, HtmlAppenderMiddlewareOptions options)
 {
     if (null == next)
     {
         throw new ArgumentNullException("next");
     }
     if (null == options)
     {
         throw new ArgumentNullException("options");
     }
     _next    = next;
     _options = options;
 }
Пример #58
0
        public StompPipeline(Stack <MidFunc> builder)
        {
            AppFunc currentMiddleware = (IDictionary <string, object> environment)
                                        => Task.CompletedTask;

            //Here we pop the stack and pass the previous middleware.
            while (builder.Count > 0)
            {
                currentMiddleware = builder.Pop().Invoke(currentMiddleware);
            }

            Application = currentMiddleware;
        }
Пример #59
0
        /// <summary>
        /// See interface docs.
        /// </summary>
        /// <param name="next"></param>
        /// <returns></returns>
        public AppFunc HandleRequest(AppFunc next)
        {
            AppFunc appFunc = async(IDictionary <string, object> environment) => {
                InitialiseConfiguration();

                if (!ServeBundle(environment))
                {
                    await next(environment);
                }
            };

            return(appFunc);
        }
Пример #60
0
 /// <summary>
 /// Initializes a new instance of the <see cref="MapWhenMiddleware"/> class
 /// </summary>
 /// <param name="next">The normal application pipeline</param>
 /// <param name="options"></param>
 public MapWhenMiddleware(AppFunc next, MapWhenOptions options)
 {
     if (next == null)
     {
         throw new ArgumentNullException("next");
     }
     if (options == null)
     {
         throw new ArgumentNullException("options");
     }
     _next    = next;
     _options = options;
 }