public void ConverterCombinationWillBeInvokedIfNeeded()
        {
            var builder = new AppBuilder();
            Func<AppFunc, DifferentType> convert1 = _ => new DifferentType();
            Func<DifferentType, AppFunc> convert2 = _ => call => { throw new NotImplementedException(); };
            builder.AddSignatureConversion(convert1);
            builder.AddSignatureConversion(convert2);

            var diff = builder.Build<DifferentType>();
        }
        public void DelegateShouldBeCalledWithParameters()
        {
            string theDefault = "default";

            var builder = new AppBuilder();
            builder.Properties["builder.DefaultApp"] = theDefault;
            builder.Use(new Func<string, int, long, string>((s, i, l) => i + l + s), 1, 2L);
            var theApp = builder.Build<string>();

            theApp.ShouldNotBeSameAs("12" + theDefault);
        }
Exemple #3
0
        public void ChainedPredicatesAsync_Success()
        {
            IAppBuilder builder = new AppBuilder();

            builder.MapWhenAsync(TruePredicateAsync, map1 =>
            {
                map1.MapWhenAsync((PredicateAsync)FalsePredicateAsync, UseNotImplemented);
                map1.MapWhenAsync((PredicateAsync)TruePredicateAsync, map2 => map2.MapWhenAsync((PredicateAsync)TruePredicateAsync, UseSuccess));
                map1.Run(NotImplemented);
            });
            var app = builder.Build <OwinMiddleware>();

            IOwinContext context = new OwinContext();

            app.Invoke(context).Wait();
            Assert.Equal(200, context.Response.StatusCode);
        }
        private static HttpClient CreateClient(int length)
        {
            var app = new AppBuilder();

            app.MaxQueryStringLength(length)
            .MaxUrlLength(length)
            .Use((context, next) =>
            {
                context.Response.StatusCode   = 200;
                context.Response.ReasonPhrase = "OK";
                return(Task.FromResult(0));
            });
            return(new HttpClient(new OwinHttpMessageHandler(app.Build()))
            {
                BaseAddress = new Uri("http://example.com")
            });
        }
        public static IApplicationBuilder UseSignalR2(this IApplicationBuilder app)
        {
            app.UseOwin(configure =>
            {
                configure(next =>
                {
                    var appBuilder = new AppBuilder();
                    appBuilder.Properties["builder.DefaultApp"] = next;

                    appBuilder.MapSignalR();

                    return(appBuilder.Build <Func <IDictionary <string, object>, Task> >());
                });
            });

            return(app);
        }
Exemple #6
0
        private Response Call(Action <IAppBuilder> pipe)
        {
            var builder = new AppBuilder();

            pipe(builder);
            var     app     = (AppFunc)builder.Build(typeof(AppFunc));
            Request request = Request.Create();

            request.Method = "GET";
            Response     response = new Response(request.Environment);
            MemoryStream buffer   = new MemoryStream();

            response.OutputStream = buffer;
            app(request.Environment).Wait();
            response.OutputStream = buffer; // Replace the buffer so it can be read.
            return(response);
        }
Exemple #7
0
        public void UseHandlerWithIOwinContext()
        {
            var builder = new AppBuilder();

            builder.Use((context, next) =>
            {
                context.Response.ReasonPhrase = "Set In Middleware";
                return(next());
            });

            AppFunc      theApp      = builder.Build();
            IOwinContext baseContext = new OwinContext();

            theApp(baseContext.Environment).Wait();
            Assert.Equal(404, baseContext.Response.StatusCode);
            Assert.Equal("Set In Middleware", baseContext.Response.ReasonPhrase);
        }
Exemple #8
0
        public Startup()
        {
            var builder = new AppBuilder();

            Configuration(builder);
            _owinAppFunc = builder.Build();
            var deployDir = System.Configuration.ConfigurationManager.AppSettings["DeployDir"];

            if (!string.IsNullOrEmpty(deployDir))
            {
                Setting.InitWebRoot(deployDir, true);
            }
            else
            {
                Setting.InitWebRoot(AppDomain.CurrentDomain.BaseDirectory);
            }
        }
Exemple #9
0
        private int Call(Action <IAppBuilder> pipe, string path)
        {
            var builder = new AppBuilder();

            pipe(builder);
            var app = builder.Build <AppFunc>();

            Request request = Request.Create();

            request.Path   = path;
            request.Method = "GET";
            Response response = new Response(request.Environment);

            response.OutputStream = new MemoryStream();
            app(request.Environment).Wait();
            return(response.StatusCode);
        }
Exemple #10
0
        public void NearMatch_RedirectAddSlash(string baseUrl, string baseDir, string requestUrl)
        {
            IAppBuilder builder = new AppBuilder();

            builder.UseDirectoryBrowser(baseUrl, baseDir);
            var app = (AppFunc)builder.Build(typeof(AppFunc));

            IDictionary <string, object> env = CreateEmptyRequest(requestUrl);

            app(env).Wait();

            Assert.Equal(301, env["owin.ResponseStatusCode"]);
            var responseHeaders = (IDictionary <string, string[]>)env["owin.ResponseHeaders"];

            Assert.Equal(requestUrl + "/", responseHeaders["Location"][0]);
            Assert.Equal(0, ((Stream)env["owin.ResponseBody"]).Length);
        }
        public void ChainedPredicatesAsync_Success()
        {
            IAppBuilder builder = new AppBuilder();

            builder.MapPredicateAsync(TruePredicateAsync, subBuilder =>
            {
                subBuilder.MapPredicateAsync(FalsePredicateAsync, FuncNotImplemented);
                subBuilder.MapPredicateAsync(TruePredicateAsync, subBuilder1 => { subBuilder.MapPredicateAsync(TruePredicateAsync, Success); });
                subBuilder.Run(FuncNotImplemented);
            });
            var app = builder.Build <AppFunc>();

            IDictionary <string, object> environment = CreateEmptyRequest();

            app(environment).Wait();
            Assert.Equal(200, environment["owin.ResponseStatusCode"]);
        }
Exemple #12
0
        public static IApplicationBuilder UseAppBuilder(this IApplicationBuilder app, Action <IAppBuilder> configure)
        {
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var appBuilder = new AppBuilder();
                    appBuilder.Properties["builder.DefaultApp"] = next;

                    configure(appBuilder);

                    return(appBuilder.Build <AppFunc>());
                });
            });

            return(app);
        }
Exemple #13
0
        private static HttpClient CreateHttpClient(Func <RequestContext, int> getMaxContentLength)
        {
            var app = new AppBuilder();

            app.MaxRequestContentLength(getMaxContentLength)
            .Use(async(context, _) =>
            {
                await new StreamReader(context.Request.Body).ReadToEndAsync();
                await new StreamWriter(context.Response.Body).WriteAsync("Lorem ipsum");
                context.Response.StatusCode   = 200;
                context.Response.ReasonPhrase = "OK";
            });
            return(new HttpClient(new OwinHttpMessageHandler(app.Build()))
            {
                BaseAddress = new Uri("http://example.com")
            });
        }
        public void FoundFile_Served(string baseUrl, string baseDir, string requestUrl)
        {
            IAppBuilder builder = new AppBuilder();

            builder.UseStaticFiles(baseUrl, baseDir);
            var app = (AppFunc)builder.Build(typeof(AppFunc));

            IDictionary <string, object> env = CreateEmptyRequest(requestUrl);

            app(env).Wait();

            var responseHeaders = (IDictionary <string, string[]>)env["owin.ResponseHeaders"];

            Assert.Equal("text/xml", responseHeaders["Content-Type"][0]);
            Assert.True(responseHeaders["Content-Length"][0].Length > 0);
            Assert.Equal(responseHeaders["Content-Length"][0], ((Stream)env["owin.ResponseBody"]).Length.ToString());
        }
Exemple #15
0
        static void Main(string[] args)
        {
            var app = new AppBuilder();

            OwinServerFactory.Initialize(app.Properties);

            app.UseWindsorContainer("windsor.config");

            var container     = app.GetWindsorContainer();
            var logMiddleware = container.Resolve <ConsoleLogMiddleware>();

            app.Use(logMiddleware);

            var options = container.Resolve <StaticFileMiddlewareOptions>();

            app.UseStaticFile(options);

            var startup = new Startup();

            startup.Configuration(app);

            var          builder = new ServerBuilder();
            const string ip      = "127.0.0.1";
            const int    port    = 8888;

            builder.SetAddress(IPAddress.Parse(ip)).SetPort(port)
            .SetOwinApp(app.Build())
            .SetOwinCapabilities((IDictionary <string, object>)app.Properties[OwinKeys.ServerCapabilitiesKey]);

            using (var server = builder.Build()) {
                var serverRef = new WeakReference <INowinServer>(server);

                Task.Run(() => {
                    INowinServer nowinServer;
                    if (serverRef.TryGetTarget(out nowinServer))
                    {
                        nowinServer.Start();
                    }
                });

                var baseAddress = "http://" + ip + ":" + port + "/";
                Console.WriteLine("Nowin server listening {0}, press ENTER to exit.", baseAddress);

                Console.ReadLine();
            }
        }
Exemple #16
0
        public async Task ScriptFileCanBeExecutedByName()
        {
            var factory = new RoslynAppLoaderFactory();
            Func <string, Action <IAppBuilder> > loader = factory.Create(_ => null);
            Action <IAppBuilder> startup = loader.Invoke("Simple.csx");
            var builder = new AppBuilder();

            startup.Invoke(builder);
            var app = (AppFunc)builder.Build(typeof(AppFunc));

            OwinRequest req = OwinRequest.Create();
            await app.Invoke(req.Dictionary);

            var res = new OwinResponse(req);

            res.StatusCode.ShouldBe(24601);
        }
        private void ConfigurePipeline(AppFunc next, string fullPath)
        {
            Console.WriteLine("Configuring pipeline...");
            try
            {
                string index = string.Format(
                    "<HTML><HEAD><TITLE>Dynamic Middleware</TITLE></HEAD><BODY><p>Edit {0} and refresh to see below links change.</p>",
                    fullPath);
                var allLines = File.ReadAllLines(fullPath);

                var app = new AppBuilder();
                foreach (var line in allLines)
                {
                    var paths = line.Split(';');
                    app.UseDirectoryBrowser(new DirectoryBrowserOptions
                    {
                        RequestPath = new PathString(paths[0]),
                        FileSystem  = new PhysicalFileSystem(paths[1])
                    });
                    index += string.Format("<a href='{0}'>{0}</a><br>", paths[0]);
                    Console.WriteLine("Directory {0} on {1}", paths[1], paths[0]);
                }
                app.Use(async(ctx, next2) =>
                {
                    if (ctx.Request.Path.Value == "/")
                    {
                        await ctx.Response.WriteAsync(index);
                    }
                    await next2();
                });
                app.Run(ctx => next(ctx.Environment));
                _dynamicAppFunc = app.Build();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex);
                _dynamicAppFunc = async env =>
                {
                    var context = new OwinContext(env);
                    context.Response.StatusCode   = 500;
                    context.Response.ReasonPhrase = "Internal server error";
                    await context.Response.WriteAsync(ex.Message);
                };
            }
        }
Exemple #18
0
        public static MidFunc UseStreamStore(IStreamStore streamStore)
        {
            var streams         = new StreamResource(streamStore);
            var streamMessages  = new StreamMessageResource(streamStore);
            var streamsMetadata = new StreamMetadataResource(streamStore);

            var builder = new AppBuilder()
                          .MapWhen(IsStream, ConfigureOptions(streams))
                          .MapWhen(IsStreamMessage, ConfigureOptions(streamMessages))
                          .MapWhen(IsStreamMetadata, ConfigureOptions(streamsMetadata));

            return(next =>
            {
                builder.Run(context => next(context.Environment));

                return builder.Build();
            });
        }
        public static void UseSignalR(this IApplicationBuilder app)
        {
#if USE_SIGNALR
            app.UseOwin(pipeline =>
            {
                pipeline(next =>
                {
                    var appBuilder = new AppBuilder();

                    appBuilder.Properties["builder.DefaultApp"] = next;

                    appBuilder.MapSignalR();

                    return(appBuilder.Build());
                });
            });
#endif
        }
Exemple #20
0
        public static void Main(string[] args)
        {
            var app     = new AppBuilder();
            var startup = new Startup();

            startup.Configuration(app);
            var appFunc = app.Build();

            using (var server = ServerBuilder.
                                New()
                                .SetEndPoint(new System.Net.IPEndPoint(IPAddress.Loopback, 1926))
                                .SetOwinApp(appFunc)
                                .Build())
            {
                Console.WriteLine("Running...");
                Console.ReadKey();
            }
        }
Exemple #21
0
        public void SetUp()
        {
            Builder = new RequestBuilder();

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            var appBuilder = new AppBuilder();

            AddCompressionMiddleware(appBuilder);
            appBuilder.UseWebApi(config);

            HttpClient = new HttpClient(new OwinHttpMessageHandler(appBuilder.Build()))
            {
                BaseAddress = new Uri("http://localhost")
            };
        }
        public void PostDirectory_PassesThrough(string baseUrl, string baseDir, string requestUrl)
        {
            IAppBuilder builder = new AppBuilder();

            builder.UseDefaultFiles(new DefaultFilesOptions()
            {
                RequestPath = new PathString(baseUrl),
                FileSystem  = new PhysicalFileSystem(baseDir)
            });
            var app = (OwinMiddleware)builder.Build(typeof(OwinMiddleware));

            IOwinContext context = CreateEmptyRequest(requestUrl);

            context.Request.Method = "POST";
            app.Invoke(context).Wait();

            Assert.Equal(404, context.Response.StatusCode); // Passed through
        }
Exemple #23
0
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
        {
            loggerFactory.AddNLog();
            env.ConfigureNLog("nlog.config");
            app.UseOwin().UseNancy(x => x.Bootstrapper = new Bootstrapper(Configuration));
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var appBuilder = new AppBuilder();
                    appBuilder.Properties["builder.DefaultApp"] = next;
                    appBuilder.UseCors(CorsOptions.AllowAll);
                    appBuilder.MapSignalR();

                    return(appBuilder.Build());
                });
            });
        }
        public void FoundDirectoryWithDefaultFile_PathModified(string baseUrl, string baseDir, string requestUrl)
        {
            IAppBuilder builder = new AppBuilder();

            builder.UseDefaultFiles(new DefaultFilesOptions()
            {
                RequestPath = new PathString(baseUrl),
                FileSystem  = new PhysicalFileSystem(baseDir)
            });
            var app = (OwinMiddleware)builder.Build(typeof(OwinMiddleware));

            IOwinContext context = CreateEmptyRequest(requestUrl);

            app.Invoke(context).Wait();

            Assert.Equal(404, context.Response.StatusCode);                        // Passed through
            Assert.Equal(requestUrl + "default.html", context.Request.Path.Value); // Should be modified
        }
Exemple #25
0
        /// <summary>
        /// 适配器构造函数
        /// </summary>
        public Adapter()
        {
            //实例化一个应用程序生成器
            var builder = new AppBuilder();

            // 为生成器添加一些参数
            // 因某些OWIN框架需要从该参数中得到一些初始化环境信息
            // 这些信息可以包括 如“owin版本”“服务器功”能等等
            var properties = builder.Properties;

            properties["owin.Version"] = "1.0";  // 只能是1.0

            var disposeSource = new CancellationTokenSource();

            properties["server.OnDispose"] = disposeSource.Token;

            Func <Task>           svrInitCallback = null;
            Action <Func <Task> > init            = (callback) => { svrInitCallback = callback; };

            properties["server.OnInit"] = init;

            var capabilities = properties.ContainsKey("server.Capabilities") ? properties["server.Capabilities"] as IDictionary <string, object> : new Dictionary <string, object>();

            properties["server.Capabilities"] = capabilities;
            capabilities["server.Name"]       = "TinyFox";

            //实例化用户的启动类,并调用配置方法
            //如果用户启动类在其它的dll中,就需要通过反射找出这个类
            var startup = new Startup();

            startup.Configuration(builder);

            //构建OWIN应用并获取该应用的代理(委托)方法
            _owinApp = builder.Build();

            //要求应用程序域退出时,向本类发出通知
            AppDomain.CurrentDomain.DomainUnload += ((o, e) => { disposeSource.Cancel(); });

            //回调应用层初始化函数
            if (svrInitCallback != null)
            {
                svrInitCallback().Wait();
            }
        }
        public void Test_SignalrMiddlewarePipeline()
        {
            IAppBuilder builder = new AppBuilder();

            builder.Use <SignalrInterceptorMiddleware>("/signalr");
            var  pipelineObj = builder.Build();
            bool passed;

            try
            {
                pipelineObj.Invoke(GetEnvironmentData());
                passed = true;
            }
            catch
            {
                passed = false;
            }
            Assert.IsTrue(passed);
        }
Exemple #27
0
        // TODO: text/*, q rankings, etc.
        public void KnownAcceptContentType_Served(string[] acceptHeader, string expectedContentType)
        {
            IAppBuilder builder = new AppBuilder();

            builder.UseDirectoryBrowser(string.Empty, string.Empty);
            var app = (AppFunc)builder.Build(typeof(AppFunc));

            IDictionary <string, object> env = CreateEmptyRequest("/");

            SetAcceptHeader(env, acceptHeader);
            app(env).Wait();

            Assert.False(env.ContainsKey("owin.ResponseStatusCode"));
            var responseHeaders = (IDictionary <string, string[]>)env["owin.ResponseHeaders"];

            Assert.Equal(expectedContentType, responseHeaders["Content-Type"][0]);
            Assert.True(responseHeaders["Content-Length"][0].Length > 0);
            Assert.Equal(responseHeaders["Content-Length"][0], ((Stream)env["owin.ResponseBody"]).Length.ToString());
        }
Exemple #28
0
        public void SendAsync_ReturnsAllowAOrigin(string requestOrigin, string policyOrigin, string expectedOrigin)
        {
            IAppBuilder builder = new AppBuilder();
            var         policy  = new CorsPolicy();

            if (policyOrigin == "*")
            {
                policy.AllowAnyOrigin = true;
            }
            else
            {
                foreach (var o in policyOrigin.Split(','))
                {
                    policy.Origins.Add(o.Trim());
                }
            }

            builder.UseCors(new CorsOptions
            {
                PolicyProvider = new CorsPolicyProvider
                {
                    PolicyResolver = context => Task.FromResult(policy)
                }
            });

            builder.Use((context, next) => Task.FromResult <object>(null));

            var app = (AppFunc)builder.Build(typeof(AppFunc));

            IOwinRequest request = CreateRequest("http://localhost/sample");

            if ("header_not_set" != requestOrigin)
            {
                request.Headers.Set(CorsConstants.Origin, requestOrigin);
            }
            app(request.Environment).Wait();

            var    response = new OwinResponse(request.Environment);
            string origin   = response.Headers.Get("Access-Control-Allow-Origin");

            Assert.Equal(200, response.StatusCode);
            Assert.Equal(expectedOrigin, origin);
        }
Exemple #29
0
        // http://stackoverflow.com/a/30742029/2001966
        public static void UseOwinBuilder(this IApplicationBuilder app, Action <IAppBuilder> owinConfiguration)
        {
            app.UseOwin(
                addToPipeline =>
            {
                addToPipeline(
                    next =>
                {
                    AppBuilder builder = new AppBuilder();
                    owinConfiguration(builder);
                    builder.Run(ctx => next(ctx.Environment));

                    // ReSharper disable once SuggestVarOrType_Elsewhere
                    var appFunc = (Func <IDictionary <string, object>, Task>)builder.Build(typeof(Func <IDictionary <string, object>, Task>));

                    return(appFunc);
                });
            });
        }
        public static IApplicationBuilder UseAppBuilder(
            this IApplicationBuilder app,
            Action<IAppBuilder> configure)
        {
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var appBuilder = new AppBuilder();
                    appBuilder.Properties["builder.DefaultApp"] = next;

                    configure(appBuilder);

                    return appBuilder.Build<Func<IDictionary<string, object>, Task>>();
                });
            });

            return app;
        }
Exemple #31
0
        private static void Main(string[] args)
        {
            if (!IsRanWithoutHelpParameter(args))
            {
                return;
            }

            try
            {
                var app = AppBuilder.Build(args);
                app.Run();
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }

            Console.ReadKey();
        }
        public void Test_DashboaardMiddleware()
        {
            IAppBuilder builder = new AppBuilder();

            builder.Use <SignalrDashboardMiddleware>("/dashboard");
            var  pipelineObj = builder.Build();
            bool passed;

            try
            {
                pipelineObj.Invoke(GetEnvironmentData());
                passed = true;
            }
            catch
            {
                passed = false;
            }
            Assert.IsTrue(passed);
        }
Exemple #33
0
        static void Main(string[] args)
        {
            var builder = new AppBuilder();
            var app = builder.Build(Startup.Configuration);

            var server = new ServerFactory().Create(app, 8081);

            ThreadPool.QueueUserWorkItem(_ =>
                {
                    while (true)
                    {
                        Thread.Sleep(1000);

                        var sc = new ScreenCapture();

                        var image = sc.CaptureScreen();

                        using (var ms = new MemoryStream())
                        {
                            image.Save(ms, ImageFormat.Png);

                            var s = Convert.ToBase64String(ms.ToArray());

                            var connection = new FileConnectionManager<ScreenSharing>(
                                Startup.DependencyResolver.Resolve<IMessageBus>(),
                                Startup.DependencyResolver.Resolve<IJsonSerializer>(),
                                Startup.DependencyResolver.Resolve<ITraceManager>()
                                );

                            connection.SendFile("image/png", s);
                        }

                        Console.WriteLine("Data sent");
                    }
                });

            Console.WriteLine("Running on localhost:8081");

            Console.ReadKey();
        }
Exemple #34
0
        //private static IDisposable StartupWorkingTitleApp()
        //{
        //    var server = new Server((req, resp) =>
        //                                {
        //                                    resp.Write("Hello, again, world");
        //                                    resp.End();
        //                                });
        //    server.Listen(8081, null);
        //    return server;
        //}
        private static IDisposable StartupNancyApp()
        {
            var builder = new AppBuilder();
            var app = builder.Build(Configuration);
            var server = new ServerFactory(new StdoutTrace()).Create(app, 8080);

            Console.WriteLine("Running on localhost:8080");
            return server;
        }
        public Task TheDefaultDefaultShouldBe404()
        {
            var builder = new AppBuilder();
            var app = builder.Build();

            var request = OwinRequest.Create();
            var response = new OwinResponse(request);
            return app(request.Dictionary).Then(() => response.StatusCode.ShouldBe(404));
        }
        public void OwinMiddlewareConvertsToAppFunc()
        {
            var builder = new AppBuilder();
            builder.Use(new Func<object, OwinMiddleware>(ignored => { return new OwinMiddlwareApp(); }));

            var theApp = builder.Build<AppFunc>();
            IOwinContext baseContext = new OwinContext();
            theApp.Invoke(baseContext.Environment).Wait();
            Assert.Equal(200, baseContext.Response.StatusCode);
            Assert.Equal("Set In Middleware", baseContext.Response.ReasonPhrase);
        }
        public Task TheDefaultDefaultShouldBe404()
        {
            var builder = new AppBuilder();
            var app = builder.Build();

            var helper = new OwinHelper();
            return app(helper.Env).Then(() => helper.ResponseStatusCode.ShouldBe(404));
        }
        public void TheDefaultDefaultShouldBe404()
        {
            var builder = new AppBuilder();
            var app = builder.Build<OwinMiddleware>();

            var context = new OwinContext();
            app.Invoke(context).Wait();
            context.Response.StatusCode.ShouldBe(404);
        }
        public void UseAppWithIOwinContext()
        {
            var builder = new AppBuilder();
            builder.Run(context =>
            {
                context.Response.StatusCode = 201;
                return Task.FromResult<object>(null);
            });

            AppFunc theApp = builder.Build();
            IOwinContext baseContext = new OwinContext();
            theApp(baseContext.Environment).Wait();
            Assert.Equal(201, baseContext.Response.StatusCode);
        }
        public void AppFuncConvertsToOwinMiddleware()
        {
            var builder = new AppBuilder();
            builder.Use(new Func<object, AppFunc>(ignored =>
            {
                return environment =>
                {
                    environment["owin.ResponseReasonPhrase"] = "Set In Middleware";
                    return Task.FromResult<object>(null);
                };
            }));

            var theApp = builder.Build<OwinMiddleware>();
            IOwinContext baseContext = new OwinContext();
            theApp.Invoke(baseContext).Wait();
            Assert.Equal(200, baseContext.Response.StatusCode);
            Assert.Equal("Set In Middleware", baseContext.Response.ReasonPhrase);
        }
        public void UseHandlerWithIOwinContext()
        {
            var builder = new AppBuilder();
            builder.Use((context, next) =>
            {
                context.Response.ReasonPhrase = "Set In Middleware";
                return next();
            });

            AppFunc theApp = builder.Build();
            IOwinContext baseContext = new OwinContext();
            theApp(baseContext.Environment).Wait();
            Assert.Equal(404, baseContext.Response.StatusCode);
            Assert.Equal("Set In Middleware", baseContext.Response.ReasonPhrase);
        }
 public void NoConversionAvailableThrowsArgumentException()
 {
     var builder = new AppBuilder();
     Assert.Throws<ArgumentException>(() => builder.Build<DifferentType>());
 }
 public void DelegatesWithIdenticalParametersShouldConvertAutomatically()
 {
     var builder = new AppBuilder();
     builder.Properties["builder.DefaultApp"] = new Func<string, string>(call => call);
     builder.UseFunc<AppOne>(next => call => next(call) + "1");
     builder.UseFunc<AppTwo>(next => call => next(call) + "2");
     builder.UseFunc<Func<string, string>>(next => call => next(call) + "3");
     var app = builder.Build<AppTwo>();
     app("0").ShouldBe("0321");
 }