コード例 #1
0
        RetrieveSwaggerRouteData()
        {
            var metadata = _routeCacheProvider
                           .GetCache()
                           .RetrieveMetadata <RouteOperation>()
                           .OfType <RouteOperation>();

            IDictionary <string, RouteOperation> metadict =
                new Dictionary <string, RouteOperation>();

            foreach (var e in metadata)
            {
                if (!metadict.Keys.Contains(e.Path))
                {
                    metadict.Add(e.Path, e);
                }
                else
                {
                    foreach (var method in (Dictionary <string, RouteOperationModel>)e.Operations)
                    {
                        if (!metadict[e.Path].Operations.Contains(method.Key))
                        {
                            metadict[e.Path].Operations.Add(method.Key, method.Value);
                        }
                    }
                }
            }

            return(metadict
                   .Select(r => Tuple.Create(r.Value.Path, r.Value.Operations))
                   .ToDictionary(x => x.Item1, x => x.Item2));
        }
コード例 #2
0
        public RhinoGetModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/sdk"] = _ =>
            {
                var result = new StringBuilder("<!DOCTYPE html><html><body>");
                var cache  = routeCacheProvider.GetCache();
                result.AppendLine($" <a href=\"/sdk/csharp\">C# SDK</a><BR>");
                result.AppendLine("<p>API<br>");

                int route_index = 0;
                foreach (var module in cache)
                {
                    foreach (var route in module.Value)
                    {
                        var method = route.Item2.Method;
                        var path   = route.Item2.Path;
                        if (method == "GET")
                        {
                            route_index += 1;
                            result.AppendLine($"{route_index} <a href='{path}'>{path}</a><BR>");
                        }
                    }
                }

                result.AppendLine("</p></body></html>");
                return(result.ToString());
            };

            foreach (var endpoint in GeometryEndPoint.AllEndPoints)
            {
                string key = endpoint.PathURL;
                Get[key] = _ => endpoint.Get(Context);
            }
        }
コード例 #3
0
        private void GenerateSpecification()
        {
            swaggerSpecification = new SwaggerSpecification
            {
                ApiInfo = new SwaggerApiInfo
                {
                    Title   = title,
                    Version = apiVersion,
                },
                Host     = host,
                BasePath = apiBaseUrl,
                Schemes  = schemes,
            };

            // generate documentation
            IEnumerable <SwaggerRouteMetadata> metadata = routeCacheProvider.GetCache().RetrieveMetadata <SwaggerRouteMetadata>();

            Dictionary <string, Dictionary <string, SwaggerEndpointInfo> > endpoints = new Dictionary <string, Dictionary <string, SwaggerEndpointInfo> >();

            foreach (SwaggerRouteMetadata m in metadata)
            {
                if (m == null)
                {
                    continue;
                }

                string path = m.Path;

                if (!string.IsNullOrEmpty(swaggerSpecification.BasePath) && swaggerSpecification.BasePath != "/")
                {
                    path = path.Replace(swaggerSpecification.BasePath, "");
                }

                if (!endpoints.ContainsKey(path))
                {
                    endpoints[path] = new Dictionary <string, SwaggerEndpointInfo>();
                }

                endpoints[path].Add(m.Method, m.Info);

                // add definitions
                if (swaggerSpecification.ModelDefinitions == null)
                {
                    swaggerSpecification.ModelDefinitions = new Dictionary <string, JSchema>();
                }

                foreach (string key in SchemaCache.Cache.Keys)
                {
                    if (swaggerSpecification.ModelDefinitions.ContainsKey(key))
                    {
                        continue;
                    }

                    swaggerSpecification.ModelDefinitions.Add(key, SchemaCache.Cache[key]);
                }
            }

            swaggerSpecification.PathInfos = endpoints;
        }
コード例 #4
0
 protected override IList <SwaggerRouteData> RetrieveSwaggerRouteData()
 {
     return(_routeCacheProvider
            .GetCache()
            .RetrieveMetadata <SwaggerRouteData>()
            .OfType <SwaggerRouteData>()
            .ToList()); // filter nulls
 }
コード例 #5
0
        private object GetRoutes(dynamic arg)
        {
            var cache = _routeCacheProvider.GetCache().Values.SelectMany(v => v).Select(v => v.Item2)
                        .Select(v => v.Path)
                        .ToList();

            return(Data(cache));
        }
コード例 #6
0
        public DocModule(IRouteCacheProvider cacheProvider) : base("/docs")
        {
            Get("/", _ =>
            {
                var metadata = cacheProvider.GetCache().RetrieveMetadata <CustomMetadata>().Where(w => w != null)
                               .ToList();

                return(Response.AsJson(metadata));
            });

            Get("/page", _ =>
            {
                var metaData = cacheProvider.GetCache().RetrieveMetadata <CustomMetadata>().Where(w => w != null)
                               .ToList();

                return(View["RouteInfo.html", metaData]);
            });
        }
コード例 #7
0
 public DocumentationModule(IRouteCacheProvider routeCacheProvider) : base("/documentation")
 {
     Get["/"] = parameters =>
     {
         var model = new DocumentationViewModel(routeCacheProvider.GetCache().SelectMany(p => p.Value)
                                                .SelectMany(p => p.Item2.Metadata.Raw.Select(g => (DocumentationObject)g.Value).ToList()).Where(p => p != null).ToList());
         return(Response.AsJson(model));
     };
 }
コード例 #8
0
        private HomeModel GetIndex()
        {
            var response = new HomeModel();

            // get the cached routes
            var cache = routeCache.GetCache();

            response.Routes = cache.Values.SelectMany(t => t.Select(t1 => t1.Item2));

            return(response);
        }
コード例 #9
0
        /// <summary>
        /// Returns the information about the services
        /// </summary>
        /// <param name="cacheProvider">The cache provider</param>
        /// <returns>The response</returns>
        private object ShowInfo(IRouteCacheProvider cacheProvider)
        {
            var metaData = cacheProvider.GetCache().RetrieveMetadata <CustomMetadata>().Where(w => w != null).ToList();

            var data = new
            {
                BaseData = GetBaseData(),
                Metadata = metaData
            };

            return(View["info.html", data]);
        }
コード例 #10
0
        public IndexModule(IRouteCacheProvider routeCache) : base("/api/")
        {
            this.EnableCors();
            m_routeCache = routeCache;
            Get["/"]     = parameters =>
            {
                var responseObject = new IndexModel();
                var cache          = m_routeCache.GetCache();

                responseObject.Routes = cache.Values.SelectMany(t => t.Select(t1 => t1.Item2));

                return(Response.AsJson(responseObject.Routes.Select(p => new KeyValuePair <string, string>(p.Path, p.Method))));
            };
        }
コード例 #11
0
ファイル: MainModule.cs プロジェクト: tt/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/"] = x => {
                return View.Razor("~/views/routes.cshtml", routeCacheProvider.GetCache());
            };

            // TODO - implement filtering at the RouteDictionary GetRoute level
            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/static"] = x => {
                return View.Static("~/views/static.htm");
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View.Razor("~/views/razor.cshtml", model);
            };

            Get["/ndjango"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View.Django("~/views/ndjango.django", model);
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View.Spark("~/views/spark.spark", model);
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsXml(model);
            };
        }
コード例 #12
0
        public DocMudule(IRouteCacheProvider routeCacheProvider) : base("/docs")
        {
            this._routeCacheProvider = routeCacheProvider;

            Get["/"] = _ =>
            {
                var routeDescriptionList = _routeCacheProvider
                                           .GetCache()
                                           .SelectMany(x => x.Value)
                                           .Select(x => x.Item2)
                                           .Where(x => !string.IsNullOrWhiteSpace(x.Name))
                                           .ToList();

                return(Response.AsJson(routeDescriptionList));
            };
        }
コード例 #13
0
ファイル: Program.cs プロジェクト: jtyow1/resthopper.compute
        public RhinoModule(IRouteCacheProvider routeCacheProvider)
        {
            Get[""]             = _ => FixedEndpoints.HomePage(Context);
            Get["/healthcheck"] = _ => "healthy";
            Get["version"]      = _ => FixedEndpoints.GetVersion(Context);
            Get["sdk/csharp"]   = _ => FixedEndpoints.CSharpSdk(Context);
            Post["hammertime"]  = _ => FixedEndpoints.HammerTime(Context);

            Get["/sdk"] = _ =>
            {
                var result = new StringBuilder("<!DOCTYPE html><html><body>");
                var cache  = routeCacheProvider.GetCache();
                result.AppendLine($" <a href=\"/sdk/csharp\">C# SDK</a><BR>");
                result.AppendLine("<p>API<br>");

                int route_index = 0;
                foreach (var module in cache)
                {
                    foreach (var route in module.Value)
                    {
                        var method = route.Item2.Method;
                        var path   = route.Item2.Path;
                        if (method == "GET")
                        {
                            route_index += 1;
                            result.AppendLine($"{route_index} <a href='{path}'>{path}</a><BR>");
                        }
                    }
                }

                result.AppendLine("</p></body></html>");
                return(result.ToString());
            };

            foreach (string nameSpace in new List <string>()
            {
                "Rhino.Geometry", "Rhino.Geometry.Intersect"
            })
            {
                foreach (var endpoint in CreateEndpoints(typeof(Rhino.RhinoApp).Assembly, nameSpace))
                {
                    string key = endpoint.Path.ToLowerInvariant();
                    Get[key]  = _ => endpoint.Get(Context);
                    Post[key] = _ => endpoint.Post(Context);
                }
            }
        }
コード例 #14
0
ファイル: MainModule.cs プロジェクト: gatapia/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/"] = x => {
                return View["routes.cshtml", routeCacheProvider.GetCache()];
            };

            Get["/style/{file}"] = x => {
                return Response.AsCss("Content/" + (string)x.file);
            };

            Get["/scripts/{file}"] = x => {
                return Response.AsJs("Content/" + (string)x.file);
            };

            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar);
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/dotliquid"] = parameters => {
                return View["dot", new { name = "dot" }];
            };

            Get["/javascript"] = x => {
                return View["javascript.html"];
            };

            Get["/static"] = x => {
                return View["static.htm"];
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor.cshtml", model];
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor-simple.cshtml", model];
            };

            Get["/razor-dynamic"] = x =>
            {
                return View["razor.cshtml", new { FirstName = "Frank" }];
            };

            Get["/ssve"] = x =>
            {
                var model = new RatPack { FirstName = "You" };
                return View["ssve.sshtml", model];
            };

            Get["/embedded"] = x => {
                var model = new RatPack { FirstName = "Embedded" };
                return View["embedded", model];
            };

            Get["/embedded2"] = x => {
                var model = new RatPack { FirstName = "Embedded2" };
                return View["embedded.django", model];
            };

            Get["/viewmodelconvention"] = x => {
                return View[new SomeViewModel()];
            };

            Get["/ndjango"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View["ndjango.django", model];
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View["spark.spark", model];
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return View["anon.spark", model];
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsXml(model);
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (String.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return output;
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return output;
            };
        }
コード例 #15
0
ファイル: MainModule.cs プロジェクト: rodrigoi/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/"] = x =>{
                return View["routes.cshtml", routeCacheProvider.GetCache()];
            };

            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar);
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/dotliquid"] = parameters => {
                return View["dot", new { name = "dot" }];
            };

            Get["/javascript"] = x => {
                return View["javascript.html"];
            };

            Get["/static"] = x => {
                return View["static"];
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor.cshtml", model];
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor-simple.cshtml", model];
            };

            Get["/razor-dynamic"] = x =>
            {
                return View["razor.cshtml", new { FirstName = "Frank" }];
            };

            Get["/ssve"] = x =>
            {
                var model = new RatPack { FirstName = "You" };
                return View["ssve.sshtml", model];
            };

            Get["/viewmodelconvention"] = x => {
                return View[new SomeViewModel()];
            };

            Get["/ndjango"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View["ndjango.django", model];
            };

            Get["/ndjango-extends"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View["with-master.django", model];
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View["spark.spark", model];
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return View["anon.spark", model];
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsXml(model);
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (String.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return output;
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return output;
            };

            Get["/error"] = x =>
                {
                    throw new NotSupportedException("This is an exception thrown in a route.");
                };

            Get["/customErrorHandler"] = _ => HttpStatusCode.ImATeapot;

            Get["/csrf"] = x => this.View["csrf", new { Blurb = "CSRF without an expiry using the 'session' token" }];

            Post["/csrf"] = x =>
            {
                this.ValidateCsrfToken();

                return string.Format("Hello {0}!", Request.Form.Name);
            };

            Get["/csrfWithExpiry"] = x =>
                {
                    // Create a new one because we have an expiry to check
                    this.CreateNewCsrfToken();

                    return this.View["csrf", new { Blurb = "You have 20 seconds to submit the page.. TICK TOCK :-)" }];
                };

            Post["/csrfWithExpiry"] = x =>
                {
                    this.ValidateCsrfToken(TimeSpan.FromSeconds(20));

                    return string.Format("Hello {0}!", Request.Form.Name);
                };
        }
コード例 #16
0
ファイル: MainModule.cs プロジェクト: ToJans/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/"] = x => {
                return View["routes.cshtml", routeCacheProvider.GetCache()];
            };

            Get["/style/{file}"] = x => {
                return Response.AsCss("Content/" + (string)x.file);
            };

            Get["/scripts/{file}"] = x => {
                return Response.AsJs("Content/" + (string)x.file);
            };

            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar);
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/javascript"] = x => {
                return View["~/views/javascript.html"];
            };

            Get["/static"] = x => {
                return View["~/views/static.htm"];
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View["~/views/razor.cshtml", model];
            };

            Get["/embedded"] = x => {
                var model = new RatPack { FirstName = "Embedded" };
                return View["embedded", model];
            };

            Get["/embedded2"] = x => {
                var model = new RatPack { FirstName = "Embedded2" };
                return View["embedded.django", model];
            };

            Get["/viewmodelconvention"] = x => {
                return View[new SomeViewModel()];
            };

            Get["/ndjango"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View["~/views/ndjango.django", model];
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View["~/views/spark.spark", model];
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsXml(model);
            };

            Get["session"] = x =>
                {
                    var value = Session["moo"] ?? "";

                    var output = "Current session value is: " + value;

                    if (String.IsNullOrEmpty(value.ToString()))
                    {
                        Session["moo"] = "I've created a session!";
                    }

                    return output;
                };

            Get["sessionObject"] = x =>
            {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return output;
            };
        }
コード例 #17
0
ファイル: MainModule.cs プロジェクト: sequoiar/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            //Compiles but does not execute as expected under Mono 2.8
            //            Get["/"] = x => {
            //                return View.Razor("~/views/routes.cshtml", routeCacheProvider.GetCache());
            //            };

            Get["/"] = x => {
                var model = routeCacheProvider.GetCache().ToList();
                return View.Spark("~/views/routes.spark", model);
            };

            // TODO - implement filtering at the RouteDictionary GetRoute level
            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get["/redirect"] = x => {
                return Response.AsRedirect("http://www.google.com");
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/static"] = x => {
                return View.Static("~/views/static.htm");
            };

            //Compiles but does not execute as expected under Mono 2.8
            //            Get["/razor"] = x => {
            //                var model = new RatPack { FirstName = "Frank" };
            //                return View.Razor("~/views/razor.cshtml", model);
            //            };

            Get["/ndjango"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View.Django("~/views/ndjango.django", model);
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View.Spark("~/views/spark.spark", model);
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsXml(model);
            };

            //Call the following url to test
            //http://127.0.0.1:8080/access?oauth_token=11111111111111&oauth_verifier=2222222222222222
            //Dynamic cast is for Mono 2.8 only - Fixed in Mono 2.10 Preview
            Get["/access"] = x => {
                try{
                    return "Success: " + ((dynamic)Request.Query).oauth_token + "; " + ((dynamic)Request.Query).oauth_verifier;
                }
                catch {
                    return "Call as: /access?oauth_token=11111111111111&oauth_verifier=2222222222222222";
                }
            };
        }
コード例 #18
0
ファイル: SystemModule.cs プロジェクト: Gadarr/Gadarr
 private Response GetRoutes()
 {
     return(_routeCacheProvider.GetCache().Values.AsResponse());
 }
コード例 #19
0
 private object GetRoutes()
 {
     return(_routeCacheProvider.GetCache().Values);
 }
コード例 #20
0
ファイル: MainModule.cs プロジェクト: jeremymeng/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider, INancyEnvironment environment)
        {
            Get["/"] = x => {
                return View["routes", routeCacheProvider.GetCache()];
            };

            Get["/texts"] = parameters => {
                return (string)this.Context.Text.Menu.Home;
            };

            Get["/env"] = _ =>
            {
                return "From nancy environment: " + environment.GetValue<MyConfig>().Value;
            };

            Get["/meta"] = parameters =>
            {
                return Negotiate
                    .WithModel(routeCacheProvider.GetCache().RetrieveMetadata<MyRouteMetadata>())
                    .WithView("meta");
            };

            Get["/uber-meta"] = parameters =>
            {
                return Negotiate
                    .WithModel(routeCacheProvider.GetCache().RetrieveMetadata<MyUberRouteMetadata>().OfType<MyUberRouteMetadata>())
                    .WithView("uber-meta");
            };

            Get["/text"] = x =>
            {
                var value = (string)this.Context.Text.Menu.Home;
                return string.Concat("Value of 'Home' resource key in the Menu resource file: ", value);
            };

            Get["/negotiated"] = parameters => {
                return Negotiate
                    .WithModel(new RatPack {FirstName = "Nancy "})
                    .WithMediaRangeModel("text/html", new RatPack {FirstName = "Nancy fancy pants"})
                    .WithView("negotiatedview")
                    .WithHeader("X-Custom", "SomeValue");
            };

            Get["/user/{name}"] = parameters =>
            {
                return (string)parameters.name;
            };

            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar);
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/nustache"] = parameters => {
                return View["nustache", new { name = "Nancy", value = 1000000 }];
            };

            Get["/dotliquid"] = parameters => {
                return View["dot", new { name = "dot" }];
            };

            Get["/javascript"] = x => {
                return View["javascript.html"];
            };

            Get["/static"] = x => {
                return View["static"];
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor.cshtml", model];
            };

            Get["/razor-divzero"] = x =>
            {
                var model = new { FirstName = "Frank", Number = 22 };
                return View["razor-divzero.cshtml", model];
            };

            Get["/razorError"] = x =>
            {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor-error.cshtml", model];
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor-simple.cshtml", model];
            };

            Get["/razor-dynamic"] = x =>
            {
                return View["razor.cshtml", new { FirstName = "Frank" }];
            };

            Get["/razor-cs-strong"] = x =>
            {
                return View["razor-strong.cshtml", new RatPack { FirstName = "Frank" }];
            };

            Get["/razor-vb-strong"] = x =>
            {
                return View["razor-strong.vbhtml", new RatPack { FirstName = "Frank" }];
            };

            Get["/razor2"] = _ => new Razor2();

            Get["/ssve"] = x =>
            {
                var model = new RatPack { FirstName = "You" };
                return View["ssve.sshtml", model];
            };

            Get["/viewmodelconvention"] = x => {
                return View[new SomeViewModel()];
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View["spark.spark", model];
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return View["anon.spark", model];
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return this.Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return this.Response.AsXml(model);
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (String.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return output;
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return output;
            };

            Get["/error"] = x =>
                {
                    throw new NotSupportedException("This is an exception thrown in a route.");
                };

            Get["/customErrorHandler"] = _ => HttpStatusCode.ImATeapot;

            Get["/csrf"] = x => this.View["csrf", new { Blurb = "CSRF without an expiry using the 'session' token" }];

            Post["/csrf"] = x =>
            {
                this.ValidateCsrfToken();

                return string.Format("Hello {0}!", this.Request.Form.Name);
            };

            Get["/csrfWithExpiry"] = x =>
                {
                    // Create a new one because we have an expiry to check
                    this.CreateNewCsrfToken();

                    return this.View["csrf", new { Blurb = "You have 20 seconds to submit the page.. TICK TOCK :-)" }];
                };

            Post["/csrfWithExpiry"] = x =>
                {
                    this.ValidateCsrfToken(TimeSpan.FromSeconds(20));

                    return string.Format("Hello {0}!", this.Request.Form.Name);
                };

            Get["/viewNotFound"] = _ => View["I-do-not-exist"];

            Get["/fileupload"] = x =>
            {
                return View["FileUpload", new { Posted = "Nothing" }];
            };

            Post["/fileupload"] = x =>
            {
                var file = this.Request.Files.FirstOrDefault();

                string fileDetails = "Nothing";

                if (file != null)
                {
                    fileDetails = string.Format("{3} - {0} ({1}) {2}bytes", file.Name, file.ContentType, file.Value.Length, file.Key);
                }

                return View["FileUpload", new { Posted = fileDetails }];
            };

            Get["NamedRoute", "/namedRoute"] = _ => "I am a named route!";
        }
コード例 #21
0
ファイル: MainModule.cs プロジェクト: nathanpalmer/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/"] = x => {
                return View["routes.cshtml", routeCacheProvider.GetCache()];
            };

            Get["/style/{file}"] = x => {
                return Response.AsCss("Content/" + (string)x.file);
            };

            Get["/scripts/{file}"] = x => {
                return Response.AsJs("Content/" + (string)x.file);
            };

            Get["/images/{file}"] = x =>
            {
                return Response.AsImage("Content/" + (string)x.file);
            };

            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar);
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/dotliquid"] = parameters => {
                return View["dot", new { name = "dot" }];
            };

            Get["/javascript"] = x => {
                return View["javascript.html"];
            };

            Get["/static"] = x => {
                return View["static.htm"];
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor.cshtml", model];
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack { FirstName = "Frank" };
                return View["razor-simple.cshtml", model];
            };

            Get["/razor-dynamic"] = x =>
            {
                return View["razor.cshtml", new { FirstName = "Frank" }];
            };

            Get["/ssve"] = x =>
            {
                var model = new RatPack { FirstName = "You" };
                return View["ssve.sshtml", model];
            };

            Get["/viewmodelconvention"] = x => {
                return View[new SomeViewModel()];
            };

            Get["/ndjango"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View["ndjango.django", model];
            };

            Get["/ndjango-extends"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return View["with-master.django", model];
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View["spark.spark", model];
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return View["anon.spark", model];
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsXml(model);
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (String.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return output;
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return output;
            };

            Get["/error"] = x =>
                {
                    throw new NotSupportedException("This is an exception thrown in a route.");
                };
        }
コード例 #22
0
        /// <summary>
        /// This operation generates the specification upon the openApiSpecification variable.
        /// </summary>
        private void GenerateSpecification()
        {
            openApiSpecification = new OpenApiSpecification
            {
                Info = new Info
                {
                    Title          = title,
                    Version        = apiVersion,
                    TermsOfService = termsOfService,
                    Contact        = contact,
                    License        = license,
                },
                Servers      = hosts,
                Tags         = tags,
                ExternalDocs = externalDocs
            };

            // Generate documentation
            IEnumerable <OpenApiRouteMetadata> metadata = routeCacheProvider.GetCache().RetrieveMetadata <OpenApiRouteMetadata>();

            var endpoints = new Dictionary <string, Dictionary <string, Endpoint> >();

            foreach (OpenApiRouteMetadata m in metadata)
            {
                if (m is null)
                {
                    continue;
                }

                string path = m.Path;

                //OpenApi doesnt handle these special characters on the url path construction, but Nancy allows it.
                path = Regex.Replace(path, "[?:.*]", string.Empty);

                if (!endpoints.ContainsKey(path))
                {
                    endpoints[path] = new Dictionary <string, Endpoint>();
                }

                endpoints[path].Add(m.Method, m.Info);

                // add component definitions
                if (openApiSpecification.Component is null)
                {
                    openApiSpecification.Component = new Component();

                    if (openApiSpecification.Component.ModelDefinitions is null)
                    {
                        openApiSpecification.Component.ModelDefinitions = new Dictionary <string, NJsonSchema.JsonSchema4>();
                    }
                }

                //Components added here from Cache
                foreach (string key in SchemaCache.ComponentCache.Keys)
                {
                    if (openApiSpecification.Component.ModelDefinitions.ContainsKey(key))
                    {
                        continue;
                    }

                    openApiSpecification.Component.ModelDefinitions.Add(key, SchemaCache.ComponentCache[key]);
                }

                //Security Schemes Added here from Cache
                foreach (string key in SchemaCache.SecurityCache.Keys)
                {
                    //Since we could have all unsecured components, the Security Scheme is optional.
                    if (openApiSpecification.Component.SecuritySchemes is null)
                    {
                        openApiSpecification.Component.SecuritySchemes = new Dictionary <string, SecurityScheme>();
                    }

                    if (openApiSpecification.Component.SecuritySchemes.ContainsKey(key))
                    {
                        continue;
                    }

                    openApiSpecification.Component.SecuritySchemes.Add(key, SchemaCache.SecurityCache[key]);
                }

                //Security Requirements from the list defined by endpoint.
                if (m.Info.Security is List <Model.Security> list)
                {
                    foreach (var sec in list)
                    {
                        if (openApiSpecification.Security is null)
                        {
                            openApiSpecification.Security = new List <Model.Security>();
                        }

                        if (openApiSpecification.Security.Contains(sec))
                        {
                            continue;
                        }

                        openApiSpecification.Security.Add(sec);
                    }
                }
                else
                {
                    //If no Security was defined on each operation we assign nothing for now.
                    m.Info.Security = new List <Model.Security>();
                }
            }

            openApiSpecification.PathInfos = endpoints;
        }
コード例 #23
0
        /// <summary>
        /// This operation generates the specification upon the openApiSpecification variable.
        /// </summary>
        private void GenerateSpecification()
        {
            openApiSpecification = new OpenApiSpecification
            {
                Info = new Info
                {
                    Title          = title,
                    Version        = apiVersion,
                    TermsOfService = termsOfService,
                    Contact        = contact,
                    License        = license,
                },
                Servers      = hosts,
                Tags         = tags,
                ExternalDocs = externalDocs
            };

            // Generate documentation
            IEnumerable <OpenApiRouteMetadata> metadata = routeCacheProvider.GetCache().RetrieveMetadata <OpenApiRouteMetadata>();

            var endpoints = new Dictionary <string, Dictionary <string, Endpoint> >();

            foreach (OpenApiRouteMetadata m in metadata)
            {
                if (m == null)
                {
                    continue;
                }

                string path = m.Path;

                //OpenApi doesnt handle these special characters on the url path construction, but Nancy allows it.
                path = Regex.Replace(path, "[?:.*]", string.Empty);

                if (!endpoints.ContainsKey(path))
                {
                    endpoints[path] = new Dictionary <string, Endpoint>();
                }

                endpoints[path].Add(m.Method, m.Info);

                // add definitions
                if (openApiSpecification.Component == null)
                {
                    openApiSpecification.Component = new Component();
                }

                if (openApiSpecification.Component.ModelDefinitions == null)
                {
                    openApiSpecification.Component.ModelDefinitions = new Dictionary <string, JObject>();
                }

                foreach (string key in SchemaCache.Cache.Keys)
                {
                    if (!openApiSpecification.Component.ModelDefinitions.ContainsKey(key))
                    {
                        var model = SchemaCache.Cache[key].DeepClone() as JObject;
                        openApiSpecification.Component.ModelDefinitions.Add(key, model);
                        AddSchemaDefinitionsToModels(openApiSpecification, model);
                    }
                }
            }

            openApiSpecification.PathInfos = endpoints;
        }
コード例 #24
0
        public CoreRequestRouter(IRouteCacheProvider routeCacheProvider)
        {
            // Section: /conversations
            #region POST /conversations
            Post[UriPrefix + "/conversations"] = _p =>
            {
                using (Trace.Cic.scope("POST /conversations"))
                {
                    try
                    {
                        UpdateCount("post /conversations");

                        var request = this.Bind <CreateConversationRequest>();

                        #region Validation

                        // Check Queue
                        if (string.IsNullOrEmpty(request.QueueName))
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: queueName"
                                   }
                        }
                        ;
                        if (request.QueueType == CicQueueType.None)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: queueType"
                                   }
                        }
                        ;

                        // Check media type parameters
                        if (request.MediaTypeParameters == null)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: mediaTypeParameters"
                                   }
                        }
                        ;

                        // Check type to block requests for new chat (unable to support at this time due to icelib constraints)
                        if (request.MediaTypeParameters is ChatInteractionMediaTypeParameters)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "MediaType of Chat is not supported for new conversation requests"
                                   }
                        }
                        ;

                        // Prevent null collections
                        if (request.MediaTypeParameters.AdditionalAttributes == null)
                        {
                            request.MediaTypeParameters.AdditionalAttributes = new List <KeyValuePair <string, string> >();
                        }

                        #endregion

                        // Create conversation
                        var conversation = CoreService.Instance.CreateConversation(request);
                        return(conversation ?? (dynamic) new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to create conversation"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in POST /conversations: " + ex.Message, EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region POST /conversations/attach
            Post[UriPrefix + "/conversations/attach"] = _p =>
            {
                using (Trace.Cic.scope("POST /conversations/attach"))
                {
                    try
                    {
                        UpdateCount("post /conversations/attach");

                        var request = this.Bind <AttachConversationRequest>();

                        #region Validation

                        // Check interaction ID
                        if (request.InteractionId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: interactionId"
                                   }
                        }
                        ;

                        // Prevent null collections
                        if (request.AdditionalAttributes == null)
                        {
                            request.AdditionalAttributes = new List <KeyValuePair <string, string> >();
                        }

                        #endregion

                        // Create conversation
                        var conversation = CoreService.Instance.AttachConversation(request);
                        return(conversation ?? (dynamic) new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to create conversation"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in POST /conversations: " + ex.Message, EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region GET /conversations
            Get[UriPrefix + "/conversations"] = _p =>
            {
                using (Trace.Cic.scope("GET /conversations"))
                {
                    try
                    {
                        UpdateCount("get /conversations");

                        return(ConversationManager.ConversationList);
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in GET /conversations: " + ex.Message, EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            #region GET /conversations/{conversationId}
            Get[UriPrefix + "/conversations/{conversationId}"] = _p =>
            {
                using (Trace.Cic.scope("GET /conversations/{conversationId}"))
                {
                    try
                    {
                        UpdateCount("get /conversations/{conversationId}");

                        // Validate input
                        if (((Guid)_p.conversationId) == Guid.Empty)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: conversationId"
                                   }
                        }
                        ;

                        // Return room
                        var conversation = ConversationManager.GetConversation((Guid)_p.conversationId);
                        return(conversation ??
                               (dynamic) new Response
                        {
                            StatusCode = HttpStatusCode.Gone,
                            ReasonPhrase = "Conversation not found"
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /conversations/{conversationId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in GET /conversations/{conversationId}: " + ex.Message, EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region DELETE /conversations/{conversationId}
            Delete[UriPrefix + "/conversations/{conversationId}"] = _p =>
            {
                using (Trace.Cic.scope("DELETE /conversations/{conversationId}"))
                {
                    try
                    {
                        UpdateCount("delete /conversations/{conversationId}");

                        // Validate input
                        if (((Guid)_p.conversationId) == Guid.Empty)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: conversationId"
                                   }
                        }
                        ;

                        // Cleanup
                        return(CoreService.Instance.CleanupConversation((Guid)_p.conversationId)
                            ? new Response
                        {
                            StatusCode = HttpStatusCode.NoContent,
                            ReasonPhrase = "Conversation deleted"
                        }
                            : new Response
                        {
                            StatusCode = HttpStatusCode.Gone,
                            ReasonPhrase = "Unable to delete conversation"
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in DELETE /conversations/{conversationId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in DELETE /conversations/{conversationId}: " + ex.Message, EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            // Section: /coreservice
            #region POST /coreservice/initialize
            Post[UriPrefix + "/coreservice/initialize"] = _p =>
            {
                using (Trace.Cic.scope("POST /coreservice/initialize"))
                {
                    try
                    {
                        UpdateCount("post /coreservice/initialize");

                        var x = CoreService.Instance;

                        return(new Response
                        {
                            StatusCode = HttpStatusCode.NoContent,
                            ReasonPhrase = "Initialized"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Exception in POST /coreservice/initialize: " + ex.Message, EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region GET /coreservice/info
            Get[UriPrefix + "/coreservice/info"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /coreservice/info"))
                {
                    try
                    {
                        UpdateCount("get /coreservice/info");

                        var info = new CicInfo
                        {
                            ConversationCount = ConversationManager.ConversationList.Count,
                            IsConnectedToCic  = CoreService.Instance.IsConnected,
                            CicServer         = CoreService.Instance.CicServer,
                            CicUser           = CoreService.Instance.CicUser,
                            Uptime            = DateTime.Now.Subtract(_initializedDateTime),
                            SessionManager    = CoreService.Instance.SessionManager,
                            ConnectionMessage = CoreService.Instance.ConnectionMessage,
                            RequestCounts     = _requestCounter
                        };

                        return(info);
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /coreservice/info: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region GET /coreservice/info/routes
            Get[UriPrefix + "/coreservice/info/routes"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /coreservice/info/routes"))
                {
                    try
                    {
                        UpdateCount("get /coreservice/info/routes");

                        // Get cache of defined routes
                        var routes          = routeCacheProvider.GetCache();
                        var serviceInfoList = new List <ServiceInfo>();

                        // Process routes
                        foreach (var route in routes)
                        {
                            // We only want info for this service
                            if (!(route.Key == GetType()))
                            {
                                continue;
                            }

                            // Create ServiceInfo for the service
                            var serviceInfo = new ServiceInfo
                            {
                                ServiceName = route.Key.FullName,
                                Routes      = new List <RouteInfo>()
                            };

                            // Add the collection of routes
                            serviceInfo.Routes.AddRange(route.Value.Select(mapping => new RouteInfo
                            {
                                Method = mapping.Item2.Method,
                                Path   = mapping.Item2.Path
                            }));

                            // Add the ServiceInfo item to the list
                            serviceInfoList.Add(serviceInfo);
                        }
                        return(serviceInfoList);
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /coreservice/info/routes: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            // Section: /queues
            #region GET /queues/stats?queues[]={queue}
            Get[UriPrefix + "/queues/stats"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /queues/stats?queues[]={queue}"))
                {
                    try
                    {
                        UpdateCount("get /queues/stats?queues[]={queue}");

                        var request = this.Bind <GetQueueInfoRequest>();

                        var result = CoreService.Instance.GetQueueInfo(request);
                        return(result ??
                               (dynamic) new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to get queue info"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /queues/stats?queues[]={queue}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
        }
コード例 #25
0
ファイル: Program.cs プロジェクト: tt-acm/compute.rhino3d
        public RhinoModule(IRouteCacheProvider routeCacheProvider)
        {
            Get[""]              = _ => FixedEndpoints.HomePage(Context);
            Get["/healthcheck"]  = _ => "healthy";
            Get["version"]       = _ => FixedEndpoints.GetVersion(Context);
            Get["servertime"]    = _ => FixedEndpoints.ServerTime(Context);
            Get["sdk/csharp"]    = _ => FixedEndpoints.CSharpSdk(Context);
            Post["hammertime"]   = _ => FixedEndpoints.HammerTime(Context);
            Post["/grasshopper"] = _ => ResthopperEndpoints.Grasshopper(Context);
            Post["/io"]          = _ => ResthopperEndpoints.GetIoNames(Context);

            Get["/sdk"] = _ =>
            {
                var result = new StringBuilder("<!DOCTYPE html><html><body>");
                var cache  = routeCacheProvider.GetCache();
                result.AppendLine($" <a href=\"/sdk/csharp\">C# SDK</a><BR>");
                result.AppendLine("<p>API<br>");

                int route_index = 0;
                foreach (var module in cache)
                {
                    foreach (var route in module.Value)
                    {
                        var method = route.Item2.Method;
                        var path   = route.Item2.Path;
                        if (method == "GET")
                        {
                            route_index += 1;
                            result.AppendLine($"{route_index} <a href='{path}'>{path}</a><BR>");
                        }
                    }
                }

                result.AppendLine("</p></body></html>");
                return(result.ToString());
            };

            foreach (string nameSpace in new List <string>()
            {
                "Rhino.Geometry", "Rhino.Geometry.Intersect"
            })
            {
                foreach (var endpoint in CreateEndpoints(typeof(Rhino.RhinoApp).Assembly, nameSpace))
                {
                    string key = endpoint.Path.ToLowerInvariant();
                    Get[key]  = _ => endpoint.Get(Context);
                    Post[key] = _ =>
                    {
                        var r = endpoint.Post(Context);
                        r.ContentType = "application/json";
                        return(r);
                    };
                }
            }

            // Load GH at startup so it can get initialized on the main thread
            var pluginObject = Rhino.RhinoApp.GetPlugInObject("Grasshopper");
            var runheadless  = pluginObject?.GetType().GetMethod("RunHeadless");

            if (runheadless != null)
            {
                runheadless.Invoke(pluginObject, null);
            }

            //var script = Rhino.Runtime.PythonScript.Create();
            //if( script != null )
            //{
            //    foreach( var endpoint in GeometryEndPoint.Create(typeof(Python)) )
            //    {
            //        string key = endpoint.Path.ToLowerInvariant();
            //        Get[key] = _ => endpoint.Get(Context);
            //        Post[key] = _ => endpoint.Post(Context);
            //    }
            //}
        }
コード例 #26
0
ファイル: MainModule.cs プロジェクト: wh20160213/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider, INancyEnvironment environment)
        {
            Get["/"] = x => {
                return(View["routes", routeCacheProvider.GetCache()]);
            };

            Get["/texts"] = parameters => {
                return((string)this.Context.Text.Menu.Home);
            };

            Get["/env"] = _ =>
            {
                return("From nancy environment: " + environment.GetValue <MyConfig>().Value);
            };

            Get["/meta"] = parameters =>
            {
                return(Negotiate
                       .WithModel(routeCacheProvider.GetCache().RetrieveMetadata <MyRouteMetadata>())
                       .WithView("meta"));
            };

            Get["/uber-meta"] = parameters =>
            {
                return(Negotiate
                       .WithModel(routeCacheProvider.GetCache().RetrieveMetadata <MyUberRouteMetadata>().OfType <MyUberRouteMetadata>())
                       .WithView("uber-meta"));
            };

            Get["/text"] = x =>
            {
                var value = (string)this.Context.Text.Menu.Home;
                return(string.Concat("Value of 'Home' resource key in the Menu resource file: ", value));
            };

            Get["/negotiated"] = parameters => {
                return(Negotiate
                       .WithModel(new RatPack {
                    FirstName = "Nancy "
                })
                       .WithMediaRangeModel("text/html", new RatPack {
                    FirstName = "Nancy fancy pants"
                })
                       .WithView("negotiatedview")
                       .WithHeader("X-Custom", "SomeValue"));
            };

            Get["/user/{name}"] = parameters =>
            {
                return((string)parameters.name);
            };

            Get["/filtered", r => true] = x => {
                return("This is a route with a filter that always returns true.");
            };

            Get["/filtered", r => false] = x => {
                return("This is also a route, but filtered out so should never be hit.");
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return(string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar));
            };

            Get["/test"] = x => {
                return("Test");
            };

            Get["/nustache"] = parameters => {
                return(View["nustache", new { name = "Nancy", value = 1000000 }]);
            };

            Get["/dotliquid"] = parameters => {
                return(View["dot", new { name = "dot" }]);
            };

            Get["/javascript"] = x => {
                return(View["javascript.html"]);
            };

            Get["/static"] = x => {
                return(View["static"]);
            };

            Get["/razor"] = x => {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor.cshtml", model]);
            };

            Get["/razor-divzero"] = x =>
            {
                var model = new { FirstName = "Frank", Number = 22 };
                return(View["razor-divzero.cshtml", model]);
            };

            Get["/razorError"] = x =>
            {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor-error.cshtml", model]);
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor-simple.cshtml", model]);
            };

            Get["/razor-dynamic"] = x =>
            {
                return(View["razor.cshtml", new { FirstName = "Frank" }]);
            };

            Get["/razor-cs-strong"] = x =>
            {
                return(View["razor-strong.cshtml", new RatPack {
                                FirstName = "Frank"
                            }]);
            };

            Get["/razor-vb-strong"] = x =>
            {
                return(View["razor-strong.vbhtml", new RatPack {
                                FirstName = "Frank"
                            }]);
            };

            Get["/razor2"] = _ => new Razor2();

            Get["/ssve"] = x =>
            {
                var model = new RatPack {
                    FirstName = "You"
                };
                return(View["ssve.sshtml", model]);
            };

            Get["/viewmodelconvention"] = x => {
                return(View[new SomeViewModel()]);
            };

            Get["/spark"] = x => {
                var model = new RatPack {
                    FirstName = "Bright"
                };
                return(View["spark.spark", model]);
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return(View["anon.spark", model]);
            };

            Get["/json"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(this.Response.AsJson(model));
            };

            Get["/xml"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(this.Response.AsXml(model));
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (string.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return(output);
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return(output);
            };

            Get["/error"] = x =>
            {
                throw new NotSupportedException("This is an exception thrown in a route.");
            };

            Get["/customErrorHandler"] = _ => HttpStatusCode.ImATeapot;

            Get["/csrf"] = x => this.View["csrf", new { Blurb = "CSRF without an expiry using the 'session' token" }];

            Post["/csrf"] = x =>
            {
                this.ValidateCsrfToken();

                return(string.Format("Hello {0}!", this.Request.Form.Name));
            };

            Get["/csrfWithExpiry"] = x =>
            {
                // Create a new one because we have an expiry to check
                this.CreateNewCsrfToken();

                return(this.View["csrf", new { Blurb = "You have 20 seconds to submit the page.. TICK TOCK :-)" }]);
            };

            Post["/csrfWithExpiry"] = x =>
            {
                this.ValidateCsrfToken(TimeSpan.FromSeconds(20));

                return(string.Format("Hello {0}!", this.Request.Form.Name));
            };

            Get["/viewNotFound"] = _ => View["I-do-not-exist"];

            Get["/fileupload"] = x =>
            {
                return(View["FileUpload", new { Posted = "Nothing" }]);
            };

            Post["/fileupload"] = x =>
            {
                var file = this.Request.Files.FirstOrDefault();

                string fileDetails = "Nothing";

                if (file != null)
                {
                    fileDetails = string.Format("{3} - {0} ({1}) {2}bytes", file.Name, file.ContentType, file.Value.Length, file.Key);
                }

                return(View["FileUpload", new { Posted = fileDetails }]);
            };

            Get["NamedRoute", "/namedRoute"] = _ => "I am a named route!";
        }
コード例 #27
0
        public VidyoRequestRouter(IRouteCacheProvider routeCacheProvider)
        {
            // Section: /rooms
            #region POST /rooms
            Post[UriPrefix + "/rooms"] = _p =>
            {
                using (Trace.Vidyo.scope("POST /rooms"))
                {
                    try
                    {
                        UpdateCount("post /rooms");

                        var room = Vidyo.AddRoom();
                        return(room ?? (dynamic) new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to create room"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in POST /rooms: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region GET /rooms
            Get[UriPrefix + "/rooms"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /rooms"))
                {
                    try
                    {
                        UpdateCount("get /rooms");

                        var rooms = Vidyo.GetRooms();
                        return(rooms ?? (dynamic) new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to get rooms"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /rooms: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            #region GET /rooms/{roomId}
            Get[UriPrefix + "/rooms/{roomId}"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /rooms/{roomId}"))
                {
                    try
                    {
                        UpdateCount("get /rooms/{roomId}");

                        // Validate input
                        if (_p.roomId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: roomId"
                                   }
                        }
                        ;

                        var room = Vidyo.GetRoom(_p.roomId);
                        return(room ?? new Response
                        {
                            StatusCode = HttpStatusCode.Gone,
                            ReasonPhrase = "Room not found"
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /rooms/{roomId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /rooms/{roomId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region DELETE /rooms/{roomId}
            Delete[UriPrefix + "/rooms/{roomId}"] = _p =>
            {
                using (Trace.Vidyo.scope("DELETE /rooms/{roomId}"))
                {
                    try
                    {
                        UpdateCount("delete /rooms/{roomId}");

                        // Validate input
                        if (_p.roomId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: roomId"
                                   }
                        }
                        ;

                        return(Vidyo.DeleteRoom(_p.roomId)
                            ? new Response
                        {
                            StatusCode = HttpStatusCode.NoContent,
                            ReasonPhrase = "Room deleted"
                        }
                            : new Response
                        {
                            StatusCode = HttpStatusCode.Gone,
                            ReasonPhrase = "Unable to delete room"
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in DELETE /rooms/{roomId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in DELETE /rooms/{roomId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            #region GET /rooms/{roomId}/participants
            Get[UriPrefix + "/rooms/{roomId}/participants"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /rooms/{roomId}/participants"))
                {
                    try
                    {
                        UpdateCount("get /rooms/{roomId}/participants");

                        // Validate input
                        if (_p.roomId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: roomId"
                                   }
                        }
                        ;

                        var participants = Vidyo.GetParticipants(_p.roomId);
                        return(participants ?? new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Unable to retrieve participants"
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /rooms/{roomId}/participants: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /rooms/{roomId}/participants: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
            #region DELETE /rooms/{roomId}/participants/{participantId}
            Delete[UriPrefix + "/rooms/{roomId}/participants/{participantId}"] = _p =>
            {
                using (Trace.Vidyo.scope("DELETE /rooms/{roomId}/participants/{participantId}"))
                {
                    try
                    {
                        UpdateCount("delete /rooms/{roomId}/participants/{participantId}");

                        // Validate input
                        if (_p.roomId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: roomId"
                                   }
                        }
                        ;
                        if (_p.participantId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: participantId"
                                   }
                        }
                        ;

                        return(Vidyo.KickParticipant(_p.roomId, _p.participantId)
                            ? new Response
                        {
                            StatusCode = HttpStatusCode.NoContent,
                            ReasonPhrase = "Participant kicked"
                        }
                            : new Response
                        {
                            StatusCode = HttpStatusCode.Gone,
                            ReasonPhrase = "Unable to kick participant"
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in DELETE /rooms/{roomId}/participants/{participantId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in DELETE /rooms/{roomId}/participants/{participantId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            #region GET /rooms/{roomId}/participantCount
            Get[UriPrefix + "/rooms/{roomId}/participantCount"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /rooms/{roomId}/participantCount"))
                {
                    try
                    {
                        UpdateCount("get /rooms/{roomId}/participantCount");

                        // Validate input
                        if (_p.roomId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: roomId"
                                   }
                        }
                        ;

                        var participants = Vidyo.GetParticipants(_p.roomId);
                        return(participants == null
                            ? (dynamic) new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Unable to retrieve participants"
                        }
                            : new ParticipantCount {
                            Count = participants.Count
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /rooms/{roomId}/participantCount: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /rooms/{roomId}/participantCount: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            #region PATCH /rooms/{roomId}/actions/{participantId}
            Patch[UriPrefix + "/rooms/{roomId}/actions/{participantId}"] = _p =>
            {
                using (Trace.Vidyo.scope("PATCH /rooms/{roomId}/actions/{participantId}"))
                {
                    try
                    {
                        UpdateCount("patch /rooms/{roomId}/actions/{participantId}");

                        var request = this.Bind <RoomActionRequest>();

                        // Validate input
                        if (_p.roomId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: roomId"
                                   }
                        }
                        ;
                        if (_p.participantId <= 0)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: participantId"
                                   }
                        }
                        ;
                        if (request.Action == RoomAction.None)
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: action"
                                   }
                        }
                        ;
                        if (string.IsNullOrEmpty(request.Data))
                        {
                            return new Response
                                   {
                                       StatusCode   = HttpStatusCode.BadRequest,
                                       ReasonPhrase = "Value cannot be empty: data"
                                   }
                        }
                        ;

                        return(Vidyo.PerformAction(_p.roomId, _p.participantId, request.Action, request.Data)
                            ? new Response
                        {
                            StatusCode = HttpStatusCode.NoContent,
                            ReasonPhrase = "Action performed"
                        }
                            : new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = "Failed to perform action"
                        });
                    }
                    catch (FormatException ex)
                    {
                        Trace.WriteEventError(ex, "Error in PATCH /rooms/{roomId}/actions/{participantId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.BadRequest,
                            ReasonPhrase = "Invalid data format"
                        });
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in PATCH /rooms/{roomId}/actions/{participantId}: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion

            // Section: /vidyoservice
            #region GET /vidyoservice/info
            Get[UriPrefix + "/vidyoservice/info"] = _p =>
            {
                try
                {
                    UpdateCount("get /vidyoservice/info");

                    var info = new VidyoInfo
                    {
                        RequestCounts = _requestCounter
                    };

                    return(info);
                }
                catch (Exception ex)
                {
                    Trace.WriteEventError(ex, "Error in GET /vidyoservice/info: " + ex.Message,
                                          EventId.GenericError);
                    return(new Response
                    {
                        StatusCode = HttpStatusCode.InternalServerError,
                        ReasonPhrase = ex.Message
                    });
                }
            };
            #endregion
            #region GET /vidyoservice/info/routes
            Get[UriPrefix + "/vidyoservice/info/routes"] = _p =>
            {
                using (Trace.Vidyo.scope("GET /vidyoservice/info/routes"))
                {
                    try
                    {
                        UpdateCount("get /vidyoservice/info/routes");

                        // Get cache of defined routes
                        var routes          = routeCacheProvider.GetCache();
                        var serviceInfoList = new List <ServiceInfo>();

                        // Process routes
                        foreach (var route in routes)
                        {
                            // We only want info for this service
                            if (!(route.Key == GetType()))
                            {
                                continue;
                            }

                            // Create ServiceInfo for the service
                            var serviceInfo = new ServiceInfo
                            {
                                ServiceName = route.Key.FullName,
                                Routes      = new List <RouteInfo>()
                            };

                            // Add the collection of routes
                            serviceInfo.Routes.AddRange(route.Value.Select(mapping => new RouteInfo
                            {
                                Method = mapping.Item2.Method,
                                Path   = mapping.Item2.Path
                            }));

                            // Add the ServiceInfo item to the list
                            serviceInfoList.Add(serviceInfo);
                        }
                        return(serviceInfoList);
                    }
                    catch (Exception ex)
                    {
                        Trace.WriteEventError(ex, "Error in GET /vidyoservice/info/routes: " + ex.Message,
                                              EventId.GenericError);
                        return(new Response
                        {
                            StatusCode = HttpStatusCode.InternalServerError,
                            ReasonPhrase = ex.Message
                        });
                    }
                }
            };
            #endregion
        }
コード例 #28
0
        public Swagger2Module(IRouteCacheProvider routeCacheProvider, NancyContext sss)
        {
            Get["SwaggerDocumentation", "/swagger/docs/v1"] = _ =>
            {
                M2.Swagger openAPI = new M2.Swagger();

                openAPI.swagger  = "2.0";
                openAPI.host     = "www.ejemplo.com"; //TODO
                openAPI.basePath = "/api/falta";      //TODO
                openAPI.schemes  = new List <string>()
                {
                    "http", "https"
                };
                openAPI.tags  = new List <M2.Tag>();
                openAPI.paths = new Dictionary <string, M2.PathItem>();
                openAPI.info  = new M2.Info()
                {
                    version = "1.0.0", contact = new M2.Contact()
                    {
                        name = "Un contacto"
                    }, title = "Esta es la API interesante"
                };                                                                                                                                             //TODO

                Dictionary <string, object> cachedDefs = new Dictionary <string, object>();
                string definitionsNamingFormat         = "#/definitions/{0}";

                foreach (var module in routeCacheProvider.GetCache())
                {
                    bool shouldProcessThisModule = true;
                    foreach (CustomAttributeData attribute in module.Key.GetCustomAttributesData())
                    {
                        if (attribute.ToString().IndexOf("SwaggerApiAttribute") > -1)
                        {
                            shouldProcessThisModule = false; // don't process this, because they are Nancy Swagger API modules
                            break;
                        }
                    }

                    if (!shouldProcessThisModule)
                    {
                        continue;
                    }

                    openAPI.tags.Add(new M2.Tag()
                    {
                        name = module.Key.Name
                    });

                    foreach (var route in module.Value)
                    {
                        M2.PathItem path = new M2.PathItem();
                        if (openAPI.paths.ContainsKey(route.Item2.Path))
                        {
                            path = openAPI.paths[route.Item2.Path];
                        }

                        M2.Operation operation = new M2.Operation();

                        operation.tags = new List <string>()
                        {
                            module.Key.Name
                        };
                        operation.operationId = !string.IsNullOrEmpty(route.Item2.Name) ? route.Item2.Name : null;

                        if (route.Item2.Metadata.Has <SwaggerRouteData>())
                        {
                            SwaggerRouteData metadata = route.Item2.Metadata.Retrieve <SwaggerRouteData>();

                            operation.summary     = metadata.OperationSummary;
                            operation.description = metadata.OperationNotes;

                            operation.parameters = new List <M2.ParameterOrReference>();
                            foreach (var parameter in metadata.OperationParameters)
                            {
                                M2.ParameterOrReference parameterInfo = new M2.ParameterOrReference()
                                {
                                    name        = parameter.Name,
                                    _in         = parameter.ParamType.ToString(),
                                    description = parameter.Description,
                                    required    = parameter.Required
                                };

                                operation.parameters.Add(parameterInfo);

                                if (parameter.ParamType == ParameterType.Body && parameter.ParameterModel != null)
                                {
                                    string defName = string.Format(definitionsNamingFormat, parameter.ParameterModel.Name);
                                    if (!cachedDefs.ContainsKey(defName))
                                    {
                                        cachedDefs[defName] = parameter.ParameterModel;
                                    }

                                    parameterInfo.schema = new M2.Schema()
                                    {
                                        _ref = string.Format(definitionsNamingFormat, parameter.ParameterModel.Name)
                                    };
                                }
                                else
                                {
                                    parameterInfo.type     = parameter.ParameterModel.Name;
                                    parameterInfo._default = parameter.DefaultValue != null?parameter.DefaultValue.ToString() : null;
                                }
                            }

                            operation.produces = new List <string>();
                            foreach (var produce in metadata.OperationProduces)
                            {
                                operation.produces.Add(produce);
                            }

                            operation.responses = new Dictionary <string, M2.Response>();
                            foreach (var response in metadata.OperationResponseMessages)
                            {
                                operation.responses[response.Code.ToString()] = new M2.Response()
                                {
                                    description = response.Message
                                };
                            }
                        }
                        else // default
                        {
                            operation.parameters = new List <M2.ParameterOrReference>();
                            operation.produces   = new List <string>()
                            {
                                "application/json"
                            };
                            operation.responses        = new Dictionary <string, M2.Response>();
                            operation.responses["200"] = new M2.Response()
                            {
                                description = "Success return"
                            };
                        }

                        string method = route.Item2.Method.ToLower();
                        if (method == "get")
                        {
                            path.get = operation;
                        }
                        else if (method == "put")
                        {
                            path.put = operation;
                        }
                        else if (method == "post")
                        {
                            path.post = operation;
                        }
                        else if (method == "delete")
                        {
                            path.delete = operation;
                        }
                        else if (method == "options")
                        {
                            path.options = operation;
                        }
                        else if (method == "head")
                        {
                            path.head = operation;
                        }
                        else if (method == "patch")
                        {
                            path.patch = operation;
                        }

                        openAPI.paths[route.Item2.Path] = path;
                    }
                }

                if (cachedDefs.Count > 0)
                {
                    openAPI.definitions = new Dictionary <string, M2.Schema>();
                    foreach (KeyValuePair <string, object> definition in cachedDefs)
                    {
                        string      definitionName = definition.Key;
                        System.Type def            = (System.Type)definition.Value;

                        M2.Schema model = new M2.Schema();
                        openAPI.definitions[definitionName] = model;

                        model.xml = new M2.Xml()
                        {
                            name = def.Name
                        };

                        Dictionary <string, bool> requiredProperties = new Dictionary <string, bool>();

                        // TODO: tomar los Atributos de esta clase 'def'
                        model.properties = new Dictionary <string, M2.Schema>();
                        foreach (PropertyInfo property in def.GetProperties())
                        {
                            M2.Schema propInfo = new M2.Schema();
                            propInfo.xml = new M2.Xml()
                            {
                                name = property.Name
                            };
                            propInfo.type = property.PropertyType.Name;
                            model.properties[property.Name] = propInfo;

                            foreach (object attribute in property.GetCustomAttributes(true))
                            {
                                if (attribute.ToString().IndexOf("RequiredAttribute") > -1) // hackie way :(
                                {
                                    requiredProperties[property.Name] = true;
                                }
                            }
                        }

                        if (requiredProperties.Count > 0)
                        {
                            model.required = new List <string>();
                            foreach (KeyValuePair <string, bool> reqProp in requiredProperties)
                            {
                                model.required.Add(reqProp.Key);
                            }
                        }
                    }
                }

                return(JsonConvert.SerializeObject(openAPI,
                                                   Newtonsoft.Json.Formatting.None,
                                                   new JsonSerializerSettings
                {
                    NullValueHandling = NullValueHandling.Ignore
                }));
            };
        }
コード例 #29
0
ファイル: MainModule.cs プロジェクト: avlasova/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/"] = x => {
                return View.Razor("~/views/routes.cshtml", routeCacheProvider.GetCache());
            };

            Get["/style/{file}"] = x => {
                return Response.AsCss("~/Content/" + (string)x.file);
            };

            Get["/scripts/{file}"] = x => {
                return Response.AsJs("~/Content/" + (string)x.file);
            };

            // TODO - implement filtering at the RouteDictionary GetRoute level
            Get["/filtered", r => true] = x => {
                return "This is a route with a filter that always returns true.";
            };

            Get["/filtered", r => false] = x => {
                return "This is also a route, but filtered out so should never be hit.";
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar);
            };

            Get["/test"] = x => {
                return "Test";
            };

            Get["/javascript"] = x => {
                return View.Static("~/views/javascript.html");
            };

            Get["/static"] = x => {
                return View.Static("~/views/static.htm");
            };

            Get["/razor"] = x => {
                var model = new RatPack { FirstName = "Frank" };
                return View.Razor("~/views/razor.cshtml", model);
            };

            Get["/ndjango"] = x => {
                var model = new RatPack { FirstName = "Michael" };
                return SmartView("~/views/ndjango.django", model);
            };

            Get["/spark"] = x => {
                var model = new RatPack { FirstName = "Bright" };
                return View.Spark("~/views/spark.spark", model);
            };

            Get["/json"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsJson(model);
            };

            Get["/xml"] = x => {
                var model = new RatPack { FirstName = "Andy" };
                return Response.AsXml(model);
            };
        }
コード例 #30
0
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            //Compiles but does not execute as expected under Mono 2.8
//            Get["/"] = x => {
//                return View.Razor("~/views/routes.cshtml", routeCacheProvider.GetCache());
//            };

            Get["/"] = x => {
                var model = routeCacheProvider.GetCache().ToList();
                return(View.Spark("~/views/routes.spark", model));
            };

            // TODO - implement filtering at the RouteDictionary GetRoute level
            Get["/filtered", r => true] = x => {
                return("This is a route with a filter that always returns true.");
            };

            Get["/filtered", r => false] = x => {
                return("This is also a route, but filtered out so should never be hit.");
            };

            Get["/redirect"] = x => {
                return(Response.AsRedirect("http://www.google.com"));
            };

            Get["/test"] = x => {
                return("Test");
            };

            Get["/static"] = x => {
                return(View.Static("~/views/static.htm"));
            };

            //Compiles but does not execute as expected under Mono 2.8
//            Get["/razor"] = x => {
//                var model = new RatPack { FirstName = "Frank" };
//                return View.Razor("~/views/razor.cshtml", model);
//            };

            Get["/ndjango"] = x => {
                var model = new RatPack {
                    FirstName = "Michael"
                };
                return(View.Django("~/views/ndjango.django", model));
            };

            Get["/spark"] = x => {
                var model = new RatPack {
                    FirstName = "Bright"
                };
                return(View.Spark("~/views/spark.spark", model));
            };

            Get["/json"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(Response.AsJson(model));
            };

            Get["/xml"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(Response.AsXml(model));
            };

            //Call the following url to test
            //http://127.0.0.1:8080/access?oauth_token=11111111111111&oauth_verifier=2222222222222222
            //Dynamic cast is for Mono 2.8 only - Fixed in Mono 2.10 Preview
            Get["/access"] = x => {
                try{
                    return("Success: " + ((dynamic)Request.Query).oauth_token + "; " + ((dynamic)Request.Query).oauth_verifier);
                }
                catch {
                    return("Call as: /access?oauth_token=11111111111111&oauth_verifier=2222222222222222");
                }
            };
        }
コード例 #31
0
ファイル: MainModule.cs プロジェクト: uffekhansen/Nancy
        public MainModule(IRouteCacheProvider routeCacheProvider)
        {
            Get["/"] = x => {
                return(View["routes", routeCacheProvider.GetCache()]);
            };

            Get["/filtered", r => true] = x => {
                return("This is a route with a filter that always returns true.");
            };

            Get["/filtered", r => false] = x => {
                return("This is also a route, but filtered out so should never be hit.");
            };

            Get[@"/(?<foo>\d{2,4})/{bar}"] = x => {
                return(string.Format("foo: {0}<br/>bar: {1}", x.foo, x.bar));
            };

            Get["/test"] = x => {
                return("Test");
            };

            Get["/nustache"] = parameters => {
                return(View["nustache", new { name = "Nancy", value = 1000000 }]);
            };

            Get["/dotliquid"] = parameters => {
                return(View["dot", new { name = "dot" }]);
            };

            Get["/javascript"] = x => {
                return(View["javascript.html"]);
            };

            Get["/static"] = x => {
                return(View["static"]);
            };

            Get["/razor"] = x => {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor.cshtml", model]);
            };

            Get["/razor-simple"] = x =>
            {
                var model = new RatPack {
                    FirstName = "Frank"
                };
                return(View["razor-simple.cshtml", model]);
            };

            Get["/razor-dynamic"] = x =>
            {
                return(View["razor.cshtml", new { FirstName = "Frank" }]);
            };

            Get["/razor-cs-strong"] = x =>
            {
                return(View["razor-strong.cshtml", new RatPack {
                                FirstName = "Frank"
                            }]);
            };

            Get["/razor-vb-strong"] = x =>
            {
                return(View["razor-strong.vbhtml", new RatPack {
                                FirstName = "Frank"
                            }]);
            };

            Get["/ssve"] = x =>
            {
                var model = new RatPack {
                    FirstName = "You"
                };
                return(View["ssve.sshtml", model]);
            };

            Get["/viewmodelconvention"] = x => {
                return(View[new SomeViewModel()]);
            };

            Get["/ndjango"] = x => {
                var model = new RatPack {
                    FirstName = "Michael"
                };
                return(View["ndjango.django", model]);
            };

            Get["/ndjango-extends"] = x => {
                var model = new RatPack {
                    FirstName = "Michael"
                };
                return(View["with-master.django", model]);
            };

            Get["/spark"] = x => {
                var model = new RatPack {
                    FirstName = "Bright"
                };
                return(View["spark.spark", model]);
            };

            Get["/spark-anon"] = x =>
            {
                var model = new { FirstName = "Anonymous" };
                return(View["anon.spark", model]);
            };

            Get["/json"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(Response.AsJson(model));
            };

            Get["/xml"] = x => {
                var model = new RatPack {
                    FirstName = "Andy"
                };
                return(Response.AsXml(model));
            };

            Get["/session"] = x => {
                var value = Session["moo"] ?? "";

                var output = "Current session value is: " + value;

                if (String.IsNullOrEmpty(value.ToString()))
                {
                    Session["moo"] = "I've created a session!";
                }

                return(output);
            };

            Get["/sessionObject"] = x => {
                var value = Session["baa"] ?? "null";

                var output = "Current session value is: " + value;

                if (value.ToString() == "null")
                {
                    Session["baa"] = new Payload(27, true, "some random string value");
                }

                return(output);
            };

            Get["/error"] = x =>
            {
                throw new NotSupportedException("This is an exception thrown in a route.");
            };

            Get["/customErrorHandler"] = _ => HttpStatusCode.ImATeapot;

            Get["/csrf"] = x => this.View["csrf", new { Blurb = "CSRF without an expiry using the 'session' token" }];

            Post["/csrf"] = x =>
            {
                this.ValidateCsrfToken();

                return(string.Format("Hello {0}!", Request.Form.Name));
            };

            Get["/csrfWithExpiry"] = x =>
            {
                // Create a new one because we have an expiry to check
                this.CreateNewCsrfToken();

                return(this.View["csrf", new { Blurb = "You have 20 seconds to submit the page.. TICK TOCK :-)" }]);
            };

            Post["/csrfWithExpiry"] = x =>
            {
                this.ValidateCsrfToken(TimeSpan.FromSeconds(20));

                return(string.Format("Hello {0}!", Request.Form.Name));
            };
        }
コード例 #32
0
ファイル: MainModule.cs プロジェクト: martindevans/WebDesktop
        private dynamic ListRoutes(dynamic parameters)
        {
            var cache = _routeCacheProvider.GetCache();

            return(View["routes.cshtml", cache]);
        }
コード例 #33
0
        public void Should_Return_Instance_Supplied_By_Func()
        {
            var result = _Provider.GetCache();

            result.ShouldBeSameAs(_RouteCache);
        }