Ejemplo n.º 1
0
        public LessModule(IRootPathProvider root)
        {
            var urlPrefix = System.Configuration.ConfigurationManager.AppSettings["app:UrlPrefix"] ?? string.Empty;

            Get[urlPrefix + "/less/desktop"] = _ =>
            {
                var manifest = System.Configuration.ConfigurationManager.AppSettings["app:LessManifest"];
                if (manifest.StartsWith("/"))
                {
                    manifest = manifest.Substring(1);
                }

                manifest = manifest.Replace("/", "\\");

                var lessFile = Path.Combine(root.GetRootPath(), manifest);

                if (!File.Exists(lessFile))
                {
                    throw new FileNotFoundException("Less manifest was not found");
                }

                var less = File.ReadAllText(lessFile);

                var config = dotless.Core.configuration.DotlessConfiguration.GetDefaultWeb();
                config.Logger = typeof(dotless.Core.Loggers.AspResponseLogger);
                config.CacheEnabled = false;
                config.MinifyOutput = true;
                var css = dotless.Core.LessWeb.Parse(less, config);

                return Response.AsText(css, "text/css");
            };
        }
Ejemplo n.º 2
0
 public CachedFeedService(IConfigSettings configSettings, IRootPathProvider rootPathProvider)
 {
     this.rootPathProvider = rootPathProvider;
     cacheMinutes = configSettings.GetAppSetting<int>("cacheminutes");
     nancyCategories = configSettings.GetAppSetting("nancycategories")
         .Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
 }
Ejemplo n.º 3
0
        /// <summary>
        /// Initializes a new instance of the <see cref="ArticleModule" />.
        /// </summary>
        /// <param name="repository">The article's repository</param>
        public ArticleModule(IApplication application, IArticleRepository articleRepository, IRootPathProvider rootPathProvider)
            : base(application)
        {
            this._ArticleRepository = articleRepository;
            this._RootPathProvider = rootPathProvider;

            // Bind the HTTP GET verb to the ListArticles method
            this.Get["/articles"] = ListArticles;

            // Bind the HTTP GET verb to the ListHomeArticles method
            this.Get["/articles/homeArticles"] = ListHomeArticles;

            // Bind the HTTP GET verb to the ListSliderArticles method
            this.Get["/articles/sliderArticles"] = ListSliderArticles;

            // Define a route for urls "/articles/{seoTitle}" which will returns the article matching the specified slug
            this.Get["/articles/{seoTitle}"] = GetArticle;

            // Define a route for urls "/article/{seoTitle}" which will returns the article matching the specified slug
            this.Get["/article/apercu/{seoTitle}"] = GetArticleBySeoTitle;

            // Define a route for urls "/article/{seoTitle}" which will returns the article matching the specified slug
            this.Get["/article/{seoTitle}"] = GetArticleBySeoTitle;

            // Define a route for urls "/articles/byId" which will returns the article matching the specified id
            this.Get["/articles/articles/byId"] = GetArticlebyId;

            // Bind the HTTP GET verb to the ListEvents method
            this.Get["/actualites/actualites"] = ListPublicArticles;
        }
Ejemplo n.º 4
0
 public DiagnosticsModuleBuilder(IRootPathProvider rootPathProvider, IModelBinderLocator modelBinderLocator, INancyEnvironment diagnosticsEnvironment, INancyEnvironment environment)
 {
     this.rootPathProvider = rootPathProvider;
     this.serializerFactory = new DiagnosticsSerializerFactory(diagnosticsEnvironment);
     this.modelBinderLocator = modelBinderLocator;
     this.environment = environment;
 }
Ejemplo n.º 5
0
 /// <summary>
 /// Initializes a new instance of the <see cref="ViewNotFoundException"/>.
 /// </summary>
 /// <param name="viewName">The name of the view that was being located.</param>
 /// <param name="availableViewEngineExtensions">List of available view extensions that can be rendered by the available view engines.</param>
 /// <param name="inspectedLocations">The locations that were inspected for the view.</param>
 /// <param name="rootPathProvider">An <see cref="IRootPathProvider"/> instance.</param>
 public ViewNotFoundException(string viewName, string[] availableViewEngineExtensions, string[] inspectedLocations, IRootPathProvider rootPathProvider)
 {
     this.rootPathProvider = rootPathProvider;
     this.ViewName = viewName;
     this.AvailableViewEngineExtensions = availableViewEngineExtensions;
     this.InspectedLocations = inspectedLocations;
 }
Ejemplo n.º 6
0
 /// <summary>
 /// Initializes a new instance of the <see cref="DefaultResponseFormatter"/> class.
 /// </summary>
 /// <param name="rootPathProvider">The <see cref="IRootPathProvider"/> that should be used by the instance.</param>
 /// <param name="context">The <see cref="NancyContext"/> that should be used by the instance.</param>
 /// <param name="serializerFactory">An <see cref="ISerializerFactory" /> instance"/>.</param>
 /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param>
 public DefaultResponseFormatter(IRootPathProvider rootPathProvider, NancyContext context, ISerializerFactory serializerFactory, INancyEnvironment environment)
 {
     this.rootPathProvider = rootPathProvider;
     this.context = context;
     this.serializerFactory = serializerFactory;
     this.environment = environment;
 }
Ejemplo n.º 7
0
        public static void Enable(IApplicationPipelines applicationPipelines, IRootPathProvider rootPathProvider, IStitchConfiguration configuration)
        {
            if (applicationPipelines == null)
            {
                throw new ArgumentNullException("applicationPipelines");
            }

            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            if (rootPathProvider == null)
            {
                throw new ArgumentNullException("rootPathProvider");
            }

            var compilerTypes =
                from type in AppDomainAssemblyTypeScanner.Types
                where typeof(ICompile).IsAssignableFrom(type)
                select type;

            var compilers = compilerTypes.Select(compiler => (ICompile) Activator.CreateInstance(compiler)).ToList();

            applicationPipelines.BeforeRequest.AddItemToStartOfPipeline(GetStitchResponse(compilers, rootPathProvider, configuration));
        }
Ejemplo n.º 8
0
        private static TinyIoCContainer ConfigureContainer(IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment)
        {
            var diagContainer = new TinyIoCContainer();

            diagContainer.Register<IInteractiveDiagnostics, InteractiveDiagnostics>();
            diagContainer.Register<IRequestTracing>(requestTracing);
            diagContainer.Register<IRootPathProvider>(rootPathProvider);
            diagContainer.Register<NancyInternalConfiguration>(configuration);
            diagContainer.Register<IModelBinderLocator, DefaultModelBinderLocator>();
            diagContainer.Register<IBinder, DefaultBinder>();
            diagContainer.Register<IFieldNameConverter, DefaultFieldNameConverter>();
            diagContainer.Register<BindingDefaults, BindingDefaults>();
            diagContainer.Register<INancyEnvironment>(diagnosticsEnvironment);
            diagContainer.Register<ISerializer>(new DefaultJsonSerializer(diagnosticsEnvironment));

            foreach (var diagnosticsProvider in providers)
            {
                var key = string.Concat(
                    diagnosticsProvider.GetType().FullName,
                    "_",
                    diagnosticsProvider.DiagnosticObject.GetType().FullName);

                diagContainer.Register<IDiagnosticsProvider>(diagnosticsProvider, key);
            }

            foreach (var moduleType in AppDomainAssemblyTypeScanner.TypesOf<DiagnosticModule>().ToArray())
            {
                diagContainer.Register(typeof(INancyModule), moduleType, moduleType.FullName).AsMultiInstance();
            }

            return diagContainer;
        }
Ejemplo n.º 9
0
        private static TinyIoCContainer ConfigureContainer(IModuleKeyGenerator moduleKeyGenerator, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, DiagnosticsConfiguration diagnosticsConfiguration)
        {
            var diagContainer = new TinyIoCContainer();

            diagContainer.Register<IModuleKeyGenerator>(moduleKeyGenerator);
            diagContainer.Register<IInteractiveDiagnostics, InteractiveDiagnostics>();
            diagContainer.Register<IRequestTracing>(requestTracing);
            diagContainer.Register<IRootPathProvider>(rootPathProvider);
            diagContainer.Register<NancyInternalConfiguration>(configuration);
            diagContainer.Register<IModelBinderLocator, DefaultModelBinderLocator>();
            diagContainer.Register<IBinder, DefaultBinder>();
            diagContainer.Register<IFieldNameConverter, DefaultFieldNameConverter>();
            diagContainer.Register<BindingDefaults, BindingDefaults>();
            diagContainer.Register<ISerializer, DefaultJsonSerializer>();
            diagContainer.Register<DiagnosticsConfiguration>(diagnosticsConfiguration);

            foreach (var diagnosticsProvider in providers)
            {
                diagContainer.Register<IDiagnosticsProvider>(diagnosticsProvider, diagnosticsProvider.GetType().FullName);
            }

            foreach (var moduleType in AppDomainAssemblyTypeScanner.TypesOf<DiagnosticModule>().ToArray())
            {
                diagContainer.Register(typeof(NancyModule), moduleType, moduleKeyGenerator.GetKeyForModuleType(moduleType)).AsMultiInstance();
            }

            return diagContainer;
        }
 public XmlFormatterExtensionsFixtures()
 {
     this.rootPathProvider = A.Fake<IRootPathProvider>();
     this.responseFormatter = new DefaultResponseFormatter(this.rootPathProvider);
     this.model = new Person { FirstName = "Andy", LastName = "Pike" };
     this.response = this.responseFormatter.AsXml(model);
 }
Ejemplo n.º 11
0
        public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration)
            : base("/info")
        {
            Get["/"] = _ => View["Info"];

            Get["/data"] = _ =>
            {
                dynamic data = new ExpandoObject();

                data.Nancy = new ExpandoObject();
                data.Nancy.Version = string.Format("v{0}", this.GetType().Assembly.GetName().Version.ToString());
                data.Nancy.CachesDisabled = StaticConfiguration.DisableCaches;
                data.Nancy.TracesDisabled = StaticConfiguration.DisableErrorTraces;
                data.Nancy.CaseSensitivity = StaticConfiguration.CaseSensitive ? "Sensitive" : "Insensitive";
                data.Nancy.RootPath = rootPathProvider.GetRootPath();
                data.Nancy.Hosting = this.GetHosting();
                data.Nancy.BootstrapperContainer = this.GetBootstrapperContainer();
                data.Nancy.LocatedBootstrapper = NancyBootstrapperLocator.Bootstrapper.GetType().ToString();
                data.Nancy.LoadedViewEngines = GetViewEngines();

                data.Configuration = new Dictionary<string, object>();
                foreach (var propertyInfo in configuration.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
                {
                    var value =
                        propertyInfo.GetValue(configuration, null);

                    data.Configuration[propertyInfo.Name] = (!typeof(IEnumerable).IsAssignableFrom(value.GetType())) ?
                        new[] { value.ToString() } :
                        ((IEnumerable<object>) value).Select(x => x.ToString());
                }

                return Response.AsJson((object)data);
            };
        }
Ejemplo n.º 12
0
        public InfoModel(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration)
        {
            this.rootPathProvider = rootPathProvider;

            Configuration = new Dictionary<string, IEnumerable<string>>();
            foreach (var propertyInfo in configuration.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public))
            {
                var value = propertyInfo.GetValue(configuration, null);

                Configuration[propertyInfo.Name] = (!typeof(IEnumerable).IsAssignableFrom(value.GetType())) ?
                    new[] { value.ToString() } :
                    ((IEnumerable<object>)value).Select(x => x.ToString());
            }

            var properties = SettingTypes
                .SelectMany(t => t.GetProperties(BindingFlags.Static | BindingFlags.Public))
                .Where(x => x.PropertyType == typeof(bool));

            Settings = from property in properties
                       orderby property.Name
                       let value = (bool)property.GetValue(null, null)
                       select new SettingsModel
                       {
                           Name = Regex.Replace(property.Name, "[A-Z]", " $0"),
                           Value = value
                       };
        }
Ejemplo n.º 13
0
        public DocsModule(IRootPathProvider rootPathProvider)
            : base("api-docs")
        {
            _rootPathProvider = rootPathProvider;

            Get["/"] = Index;
        }
Ejemplo n.º 14
0
        public RazorViewEngineFixture()
        {
            var environment = new DefaultNancyEnvironment();
            environment.Tracing(
                enabled: true,
                displayErrorTraces: true);

            this.configuration = A.Fake<IRazorConfiguration>();
            this.engine = new RazorViewEngine(this.configuration, environment);

            var cache = A.Fake<IViewCache>();
            A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Func<INancyRazorView>>>.Ignored))
                .ReturnsLazily(x =>
                {
                    var result = x.GetArgument<ViewLocationResult>(0);
                    return x.GetArgument<Func<ViewLocationResult, Func<INancyRazorView>>>(1).Invoke(result);
                });

            this.renderContext = A.Fake<IRenderContext>();
            A.CallTo(() => this.renderContext.ViewCache).Returns(cache);
            A.CallTo(() => this.renderContext.LocateView(A<string>.Ignored, A<object>.Ignored))
                .ReturnsLazily(x =>
                {
                    var viewName = x.GetArgument<string>(0);
                    return FindView(viewName);
                });

            this.rootPathProvider = A.Fake<IRootPathProvider>();
            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "TestViews"));

            this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader());

            AppDomainAssemblyTypeScanner.AddAssembliesToScan("Nancy.ViewEngines.Razor.Tests.Models.dll");
        }
 public FakeDiagnostics(
     IRootPathProvider rootPathProvider,
     IRequestTracing requestTracing,
     NancyInternalConfiguration configuration,
     IModelBinderLocator modelBinderLocator,
     IEnumerable<IResponseProcessor> responseProcessors,
     IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints,
     ICultureService cultureService,
     IRequestTraceFactory requestTraceFactory,
     IEnumerable<IRouteMetadataProvider> routeMetadataProviders,
     ITextResource textResource,
     INancyEnvironment environment,
     IRuntimeEnvironmentInformation runtimeEnvironmentInformation)
 {
     this.diagnosticProviders = (new IDiagnosticsProvider[] { new FakeDiagnosticsProvider() }).ToArray();
     this.rootPathProvider = rootPathProvider;
     this.requestTracing = requestTracing;
     this.configuration = configuration;
     this.modelBinderLocator = modelBinderLocator;
     this.responseProcessors = responseProcessors;
     this.routeSegmentConstraints = routeSegmentConstraints;
     this.cultureService = cultureService;
     this.requestTraceFactory = requestTraceFactory;
     this.routeMetadataProviders = routeMetadataProviders;
     this.textResource = textResource;
     this.environment = environment;
     this.runtimeEnvironmentInformation = runtimeEnvironmentInformation;
 }
Ejemplo n.º 16
0
 public FileSystemTemplateFinder(IFileScanner fileScanner, IRootPathProvider rootPathProvider, IFindModelFromViewCollection findModelFromViewCollection)
 {
     this.fileScanner = fileScanner;
     this.rootPathProvider = rootPathProvider;
     this.findModelFromViewCollection = findModelFromViewCollection;
     requestConfig = new CompositeAction<ScanRequest>();
 }
Ejemplo n.º 17
0
 /// <summary>
 /// Creates a new instance of the <see cref="DefaultDiagnostics"/> class.
 /// </summary>
 /// <param name="diagnosticProviders"></param>
 /// <param name="rootPathProvider"></param>
 /// <param name="requestTracing"></param>
 /// <param name="configuration"></param>
 /// <param name="modelBinderLocator"></param>
 /// <param name="responseProcessors"></param>
 /// <param name="routeSegmentConstraints"></param>
 /// <param name="cultureService"></param>
 /// <param name="requestTraceFactory"></param>
 /// <param name="routeMetadataProviders"></param>
 /// <param name="textResource"></param>
 /// <param name="environment"></param>
 /// <param name="typeCatalog"></param>
 public DefaultDiagnostics(
     IEnumerable<IDiagnosticsProvider> diagnosticProviders,
     IRootPathProvider rootPathProvider,
     IRequestTracing requestTracing,
     NancyInternalConfiguration configuration,
     IModelBinderLocator modelBinderLocator,
     IEnumerable<IResponseProcessor> responseProcessors,
     IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints,
     ICultureService cultureService,
     IRequestTraceFactory requestTraceFactory,
     IEnumerable<IRouteMetadataProvider> routeMetadataProviders,
     ITextResource textResource,
     INancyEnvironment environment,
     ITypeCatalog typeCatalog)
 {
     this.diagnosticProviders = diagnosticProviders;
     this.rootPathProvider = rootPathProvider;
     this.requestTracing = requestTracing;
     this.configuration = configuration;
     this.modelBinderLocator = modelBinderLocator;
     this.responseProcessors = responseProcessors;
     this.routeSegmentConstraints = routeSegmentConstraints;
     this.cultureService = cultureService;
     this.requestTraceFactory = requestTraceFactory;
     this.routeMetadataProviders = routeMetadataProviders;
     this.textResource = textResource;
     this.environment = environment;
     this.typeCatalog = typeCatalog;
 }
Ejemplo n.º 18
0
        public FaceModule(IRootPathProvider pathProvider)
        {
            Post["/api/face/upload", true] = async (parameters, ct) =>
            {
                var file = this.Request.Files.FirstOrDefault();

                if (file == null)
                    return HttpStatusCode.BadRequest;

                var faceService = new Pubhack4.Services.Face.FaceService();
                var faces = await faceService.GetFacesFromImage(file.Value);

                return Response.AsJson(faces);
            };

            Post["/api/face/base64", true] = async (parameters, ct) =>
            {
                string x = Context.Request.Form["image"];

                var data = System.Convert.FromBase64String(x.Split(',')[1]);

                if (data == null)
                    return HttpStatusCode.BadRequest;

                var ms = new MemoryStream(data, 0, data.Length);

                var faceService = new Pubhack4.Services.Face.FaceService();
                var faces = await faceService.GetFacesFromImage(ms);

                return Response.AsJson(faces);
            };
        }
Ejemplo n.º 19
0
        public PublicModule(IApplication application, IRootPathProvider rootPathProvider,
		                    IArticleRepository articleRepository, IPageRepository pageRepository)
            : base(application)
        {
            this._ArticleRepository = articleRepository;
            this._PageRepository = pageRepository;
            this._rootPathProvider = rootPathProvider;

            // Bind the HTTP POST verb with /robots.txt with a response filled by text
            this.Get["/robots.txt"] = GetRobotTxt;

            // Bind the HTTP POST verb with /sitemap.xml to the GetSitemap method
            this.Get["/sitemap.xml"] = GetSitemap;

            // Define a route for urls "/{seoTitle}" which will returns the article matching the specified slug
            this.Get["/{category}/{seoTitle}"] = parameters => {
                // [BUG]: /sitemap.xml n'est pas prioritaire sur /{seoTitle}
                if(parameters.seoTitle == "rss")
                    return GetRSSFeed(parameters);
                // fin de [BUG]
                return GetStaticPage(parameters);
            };

            // Define a route for urls "/{seoTitle}" which will returns the article matching the specified slug
            this.Get["/{seoTitle}"] = parameters => {
                // [BUG]: /sitemap.xml n'est pas prioritaire sur /{seoTitle}
                if(parameters.seoTitle == "sitemap")
                    return GetSitemap(parameters);
                // fin de [BUG]
                return GetStaticPage(parameters);
            };
        }
Ejemplo n.º 20
0
        public RazorViewEngineFixture()
        {
            this.configuration = A.Fake<IRazorConfiguration>();
            this.engine = new RazorViewEngine(this.configuration);

            var cache = A.Fake<IViewCache>();
            A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Func<NancyRazorViewBase>>>.Ignored))
                .ReturnsLazily(x =>
                {
                    var result = x.GetArgument<ViewLocationResult>(0);
                    return x.GetArgument<Func<ViewLocationResult, Func<NancyRazorViewBase>>>(1).Invoke(result);
                });

            this.renderContext = A.Fake<IRenderContext>();
            A.CallTo(() => this.renderContext.ViewCache).Returns(cache);
            A.CallTo(() => this.renderContext.LocateView(A<string>.Ignored, A<object>.Ignored))
                .ReturnsLazily(x =>
                {
                    var viewName = x.GetArgument<string>(0);
                    return FindView(viewName); ;
                });

            this.rootPathProvider = A.Fake<IRootPathProvider>();
            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "TestViews"));

            this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader());
        }
Ejemplo n.º 21
0
 public static void RenderExternalJavascript(Stream responseStream, IRootPathProvider rootPath)
 {
     using (var js = new FileStream(Path.Combine(rootPath.GetRootPath(), "content/external.js"), FileMode.Open))
     {
         js.CopyTo(responseStream);
     }
 }
Ejemplo n.º 22
0
 /// <summary>
 /// Creates a new instance of the <see cref="DefaultDiagnostics"/> class.
 /// </summary>
 /// <param name="diagnosticsConfiguration"></param>
 /// <param name="diagnosticProviders"></param>
 /// <param name="rootPathProvider"></param>
 /// <param name="requestTracing"></param>
 /// <param name="configuration"></param>
 /// <param name="modelBinderLocator"></param>
 /// <param name="responseProcessors"></param>
 /// <param name="routeSegmentConstraints"></param>
 /// <param name="cultureService"></param>
 /// <param name="requestTraceFactory"></param>
 public DefaultDiagnostics(
     DiagnosticsConfiguration diagnosticsConfiguration,
     IEnumerable<IDiagnosticsProvider> diagnosticProviders,
     IRootPathProvider rootPathProvider,
     IRequestTracing requestTracing,
     NancyInternalConfiguration configuration,
     IModelBinderLocator modelBinderLocator,
     IEnumerable<IResponseProcessor> responseProcessors,
     IEnumerable<IRouteSegmentConstraint> routeSegmentConstraints,
     ICultureService cultureService,
     IRequestTraceFactory requestTraceFactory,
     IEnumerable<IRouteMetadataProvider> routeMetadataProviders)
 {
     this.diagnosticsConfiguration = diagnosticsConfiguration;
     this.diagnosticProviders = diagnosticProviders;
     this.rootPathProvider = rootPathProvider;
     this.requestTracing = requestTracing;
     this.configuration = configuration;
     this.modelBinderLocator = modelBinderLocator;
     this.responseProcessors = responseProcessors;
     this.routeSegmentConstraints = routeSegmentConstraints;
     this.cultureService = cultureService;
     this.requestTraceFactory = requestTraceFactory;
     this.routeMetadataProviders = routeMetadataProviders;
 }
Ejemplo n.º 23
0
        public ConnectionManager(IRootPathProvider rootPathProvider)
        {
            this.factory = DbProviderFactories.GetFactory("System.Data.SQLite");
            this.databaseName = Path.Combine(rootPathProvider.GetRootPath(), "data.db");

            CreateDatabase();
        }
Ejemplo n.º 24
0
 public WebHost(IRootPathProvider rootPathProvider, Func<NancyContext> getContext)
 {
   this.rootPathProvider = rootPathProvider;
   this.getContext = getContext;
   this.logger = NLog.LogManager.GetCurrentClassLogger();
   logger.Debug("WebHost.ctor: constructed!");
 }
Ejemplo n.º 25
0
        public static void Enable(DiagnosticsConfiguration diagnosticsConfiguration, IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IEnumerable<ISerializer> serializers, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable<IResponseProcessor> responseProcessors, ICultureService cultureService)
        {
            var keyGenerator = new DefaultModuleKeyGenerator();
            var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(keyGenerator, providers, rootPathProvider, requestTracing, configuration, diagnosticsConfiguration);

            var diagnosticsRouteCache = new RouteCache(diagnosticsModuleCatalog, keyGenerator, new DefaultNancyContextFactory(cultureService), new DefaultRouteSegmentExtractor(), new DefaultRouteDescriptionProvider(), cultureService);

            var diagnosticsRouteResolver = new DefaultRouteResolver(
                diagnosticsModuleCatalog,
                new DefaultRoutePatternMatcher(),
                new DiagnosticsModuleBuilder(rootPathProvider, serializers, modelBinderLocator),
                diagnosticsRouteCache,
                responseProcessors);

            var serializer = new DefaultObjectSerializer();

            pipelines.BeforeRequest.AddItemToStartOfPipeline(
                new PipelineItem<Func<NancyContext, Response>>(
                    PipelineKey,
                    ctx =>
                    {
                        if (!ctx.ControlPanelEnabled)
                        {
                            return null;
                        }

                        if (!ctx.Request.Path.StartsWith(diagnosticsConfiguration.Path, StringComparison.OrdinalIgnoreCase))
                        {
                            return null;
                        }

                        ctx.Items[ItemsKey] = true;

                        var resourcePrefix =
                            string.Concat(diagnosticsConfiguration.Path, "/Resources/");

                        if (ctx.Request.Path.StartsWith(resourcePrefix, StringComparison.OrdinalIgnoreCase))
                        {
                            var resourceNamespace = "Nancy.Diagnostics.Resources";

                            var path = Path.GetDirectoryName(ctx.Request.Url.Path.Replace(resourcePrefix, string.Empty)) ?? string.Empty;
                            if (!string.IsNullOrEmpty(path))
                            {
                                resourceNamespace += string.Format(".{0}", path.Replace('\\', '.'));
                            }

                            return new EmbeddedFileResponse(
                                typeof(DiagnosticsHook).Assembly,
                                resourceNamespace,
                                Path.GetFileName(ctx.Request.Url.Path));
                        }

                        RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx);

                        return diagnosticsConfiguration.Valid
                                   ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer)
                                   : GetDiagnosticsHelpView(ctx);
                    }));
        }
 public DefaultNancyModuleBuilderFixture()
 {
     this.module = new FakeNancyModule();
     this.rootPathProvider = A.Fake<IRootPathProvider>();
     this.responseFormatter = new DefaultResponseFormatter(this.rootPathProvider);
     this.viewFactory = A.Fake<IViewFactory>();
     this.builder = new DefaultNancyModuleBuilder(this.viewFactory, this.responseFormatter);
 }
Ejemplo n.º 27
0
 public RawFileRequestRewriter(BundleCollection bundles, IRootPathProvider rootPathProvider, IFileContentHasher fileContentHasher, CassetteSettings settings)
 {
   this.bundles = bundles;
   this.rootPathProvider = rootPathProvider;
   this.logger = NLog.LogManager.GetCurrentClassLogger();
   this.fileContentHasher = fileContentHasher;
   this.settings = settings;
 }
Ejemplo n.º 28
0
        public HomeModule(IRootPathProvider pathProvider)
        {
            this.Get("/", _ => this.GetSwaggerUrl());

            this.Get("/Ping", _ => HttpStatusCode.OK, null, "Ping");

            this.Get("/Version", _ => TerminologyVersion.SemanticVersion.ToString());
        }
Ejemplo n.º 29
0
 public DiagnosticsModuleBuilder(IRootPathProvider rootPathProvider, IModelBinderLocator modelBinderLocator)
 {
     this.rootPathProvider = rootPathProvider;
     this.serializers      = new[] { new DefaultJsonSerializer {
                                         RetainCasing = false
                                     } };
     this.modelBinderLocator = modelBinderLocator;
 }
Ejemplo n.º 30
0
        /// <summary>
        /// <para>
        /// Enable SassAndCoffee support in the application.
        /// </para>
        /// <para>
        /// SassAndCoffee supports on the fly compilation and caching of CoffeeScript and Sass,
        /// along with concatenation and minification.
        /// </para>
        /// </summary>
        /// <param name="pipelines">Application pipelines to hook into</param>
        /// <param name="cache">Cache provider to use</param>
        /// <param name="rootPathProvider">Root path provider</param>
        public static void Enable(IApplicationPipelines pipelines, ICompiledCache cache, IRootPathProvider rootPathProvider)
        {
            var host = new NancyCompilerHost(rootPathProvider);

            var compiler = new ContentCompiler(host, cache);

            pipelines.BeforeRequest.AddItemToStartOfPipeline(GetPipelineHook(compiler));
        }
        public DefaultResponseFormatterFactoryFixture()
        {
            this.rootPathProvider = A.Fake<IRootPathProvider>();
            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns("RootPath");

            this.serializers = new[] { A.Fake<ISerializer>() };
            this.factory = new DefaultResponseFormatterFactory(this.rootPathProvider, this.serializers);
        }
Ejemplo n.º 32
0
 public DefaultNancyModuleBuilderFixture()
 {
     this.module             = new FakeNancyModule();
     this.rootPathProvider   = A.Fake <IRootPathProvider>();
     this.responseFormatter  = new DefaultResponseFormatter(this.rootPathProvider);
     this.viewFactory        = A.Fake <IViewFactory>();
     this.modelBinderLocator = A.Fake <IModelBinderLocator>();
     this.builder            = new DefaultNancyModuleBuilder(this.viewFactory, this.responseFormatter, this.modelBinderLocator);
 }
        public DefaultResponseFormatterFactoryFixture()
        {
            this.rootPathProvider = A.Fake<IRootPathProvider>();
            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns("RootPath");

            this.serializerFactory = A.Fake<ISerializerFactory>();
            A.CallTo(() => this.serializerFactory.GetSerializer(A<MediaRange>._));
            this.factory = new DefaultResponseFormatterFactory(this.rootPathProvider, this.serializerFactory);
        }
 public XmlFormatterExtensionsFixtures()
 {
     this.rootPathProvider  = A.Fake <IRootPathProvider>();
     this.responseFormatter = new DefaultResponseFormatter(this.rootPathProvider);
     this.model             = new Person {
         FirstName = "Andy", LastName = "Pike"
     };
     this.response = this.responseFormatter.AsXml(model);
 }
Ejemplo n.º 35
0
        public IndexModule(IRootPathProvider pathProvider)//:base("product")
        {
            var uploadDirectory = Path.Combine(pathProvider.GetRootPath(), "Content", "uploads");

            //Before += ctx => {
            //    int i = 1;
            //    return "22";//null 不做处理
            //};
            Get["/"]       = _ => View["index2"];
            Get["/up2"]    = _ => View["indexup"];
            Post["/logic"] = _ =>
            {
                var t = Request.Files;
                foreach (var file in Request.Files)
                {
                    var filename = Path.Combine(uploadDirectory, file.Name);
                    using (FileStream fileStream = new FileStream(filename, FileMode.Create))
                    {
                        file.Value.CopyTo(fileStream);
                    }
                }
                return("22");
            };
            Get["/aa.jpg"] = _ =>
            {
                // return Response.AsFile("Content/uploads/b.jpg");
                return(Response.AsFile("Content/uploads/aa.jpg"));
            };
            Get["/down/{name}"] = _ =>
            {
                string fileName   = _.name;
                var    relatePath = @"Content\uploads\" + fileName;
                return(Response.AsFile(relatePath));
            };
            Get["/one"]    = _ => View["one"];
            Get["/two"]    = _ => View["two"];
            Post["/three"] = _ => {
                Student stu  = this.Bind();
                Student stu2 = new Student();
                return(Response.AsJson(stu));
            };
            Get["/pic"] = _ =>
            {
                return("");
            };
            Get["/four"] = _ => View["four"];
            // Get["/"] = parameters => "Hello World";
            Post["/login", (ctx) => ctx.Request.Form.remember] = _ =>
            {
                return("true");
            };
            Post["/login", (ctx) => !ctx.Request.Form.remember] = _ =>
            {
                return("Handling code when remember is false!");
            };
            Get["/intConstraint/{value:int}"] = _ => "Value " + _.value + " is an integer.";//路由约束
        }
Ejemplo n.º 36
0
 public ApplicationModule(IRootPathProvider pathProvider)
 {
     Get["/"]          =
         Get[@"/(.*)"] = x =>
     {
         var file = pathProvider.GetRootPath();
         file = Path.Combine(file, "index.html");
         return(Response.AsText(File.ReadAllText(file), "text/html"));
     };
 }
Ejemplo n.º 37
0
        public AdminModule(ICommandInvokerFactory commandInvokerFactory, MongoDatabase database, IViewProjectionFactory viewProjectionFactory, IRootPathProvider rootPath) : base(database, viewProjectionFactory)
        {
            _commandInvokerFactory = commandInvokerFactory;
            _rootPath = rootPath;

            Get["/admin"] = _ => Index();
            Get["/admin/changepassword"]  = _ => ChangePassword();
            Post["/admin/changepassword"] = _ => ChangePassword(this.Bind <ChangePasswordCommand>());
            Post["/admin/uploadFile"]     = _ => UploadFile(Request.Files.First());
        }
Ejemplo n.º 38
0
        public RequestModel(NancyContext context, IRootPathProvider rootPathProvider, IRouteResolver routeResolver)
        {
            this.context          = context;
            this.rootPathProvider = rootPathProvider;
            this.routeResolution  = routeResolver.Resolve(context);

            Cookies     = this.context.Request.Headers.Cookie.Select(x => new CookieModel(x)).ToArray();
            QueryString = ((DynamicDictionary)this.context.Request.Query).Serialize();
            Parameters  = this.routeResolution.Parameters.Serialize();
        }
 public ImageFileManager(
     IImageFileProcessor imageFileProcessor,
     IRootPathProvider rootPathProvider,
     IImageFolderConfigAccessor folderConfigAccessor)
 {
     _imageFileProcessor = imageFileProcessor;
     _rootPathProvider   = rootPathProvider;
     _imageFolders       = folderConfigAccessor.GetFolderConfigs();
     _rootPath           = _rootPathProvider.GetRootPath();
 }
Ejemplo n.º 40
0
 public DiagnosticsStartup(DiagnosticsConfiguration diagnosticsConfiguration, IEnumerable <IDiagnosticsProvider> diagnosticProviders, IRootPathProvider rootPathProvider, IEnumerable <ISerializer> serializers, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator)
 {
     this.diagnosticsConfiguration = diagnosticsConfiguration;
     this.diagnosticProviders      = diagnosticProviders;
     this.rootPathProvider         = rootPathProvider;
     this.serializers        = serializers;
     this.requestTracing     = requestTracing;
     this.configuration      = configuration;
     this.modelBinderLocator = modelBinderLocator;
 }
Ejemplo n.º 41
0
        /// <summary>
        /// Initializes a new instance of the <see cref="DefaultViewFactory"/> class.
        /// </summary>
        /// <param name="viewResolver">An <see cref="IViewResolver"/> instance that should be used to resolve the location of a view.</param>
        /// <param name="viewEngines">An <see cref="IEnumerable{T}"/> instance containing the <see cref="IViewEngine"/> instances that should be able to be used to render a view</param>
        /// <param name="renderContextFactory">A <see cref="IRenderContextFactory"/> instance that should be used to create an <see cref="IRenderContext"/> when a view is rendered.</param>
        /// <param name="conventions">An <see cref="ViewLocationConventions"/> instance that should be used to resolve all possible view locations </param>
        /// <param name="rootPathProvider">An <see cref="IRootPathProvider"/> instance.</param>
        public DefaultViewFactory(IViewResolver viewResolver, IEnumerable <IViewEngine> viewEngines, IRenderContextFactory renderContextFactory, ViewLocationConventions conventions, IRootPathProvider rootPathProvider)
        {
            this.viewResolver         = viewResolver;
            this.viewEngines          = viewEngines;
            this.renderContextFactory = renderContextFactory;
            this.conventions          = conventions;
            this.rootPathProvider     = rootPathProvider;

            this.viewEngineExtensions = this.viewEngines.SelectMany(ive => ive.Extensions).ToArray();
        }
 /// <summary>
 /// Creates a new bootstrapper with store and system access goverened by the specified providers.
 /// </summary>
 /// <param name="brightstarService">The connection to the BrightstarDB stores</param>
 /// <param name="storePermissionsProvider">The store permissions provider to be used by the service</param>
 /// <param name="systemPermissionsProvider">The system permissions provider to be used by the service</param>
 /// <param name="rootPath">The path to the directory containing the service Views and assets folder</param>
 public BrightstarBootstrapper(IBrightstarService brightstarService,
                               AbstractStorePermissionsProvider storePermissionsProvider,
                               AbstractSystemPermissionsProvider systemPermissionsProvider,
                               string rootPath = null)
 {
     _brightstarService         = brightstarService;
     _storePermissionsProvider  = storePermissionsProvider;
     _systemPermissionsProvider = systemPermissionsProvider;
     _rootPathProvider          = (rootPath == null ? new DefaultRootPathProvider() : new FixedRootPathProvider(rootPath) as IRootPathProvider);
     //_rootPathProvider = new FixedRootPathProvider(rootPath);
 }
        public MarkdownViewEngineFixture()
        {
            this.renderContext = A.Fake <IRenderContext>();
            this.viewEngine    = new MarkDownViewEngine(new SuperSimpleViewEngine(Enumerable.Empty <ISuperSimpleViewEngineMatcher>()));

            this.rootPathProvider = A.Fake <IRootPathProvider>();

            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns(Path.Combine(Environment.CurrentDirectory, "Markdown"));

            this.fileSystemViewLocationProvider = new FileSystemViewLocationProvider(this.rootPathProvider, new DefaultFileSystemReader());
        }
        public Home(IRootPathProvider pathProvider)
        {
            Get["/"] = (page) => View["index.html"];

            Get["/sysinfo"] = (x) =>
            {
                var loadedReaders = Program.DataReadersManager.DataReaders.Select((r) => r.GetType().ToString());

                return(Response.AsJson(loadedReaders));
            };
        }
Ejemplo n.º 45
0
        public HomeModule(IDbConnection db, ILog log, IRootPathProvider pathProvider)
        {
            Get["/"] = parameters => {
                base.Page.Title = "首页";
                //log.Error("首页Error");
                //log.Debug("首页debug");
                return(View["Index", base.Model]);
            };

            Get["/about"] = parameters => {
                base.Page.Title = "关于我们";

                return(View["About", base.Model]);
            };

            Get["/faq"] = parameters => {
                base.Page.Title = "使用说明";

                return(View["Faq", base.Model]);
            };

            Get["/wiki"] = parameters => {
                base.Page.Title = "知识教育";

                return(View["Wiki", base.Model]);
            };

            Get["/help"] = parameters => {
                base.Page.Title = "帮助中心";

                return(View["About", base.Model]);
            };

            Get["/hubs.js"] = _ => {
                //string str = @"var data_info = [
                //    [116.417854, 39.921988, '地址:北京市东城区王府井大街88号乐天银泰百货八层'],
                //    [116.406605, 39.921585, '地址:北京市东城区东华门大街'],
                //    [116.412222, 39.912345, '地址:北京市东城区正义路甲5号'],
                //    [118.038, 25.472, '地址:福建省xx市有限公司'],
                //    [94.29, 35.747, '地址:福建省xx市有限公司']
                //];";
                string str       = "var data_info = [";
                var    suppliers = db.Select <SupplierModel>("SELECT Lng,Lat,Fname FROM t_supplier WHERE State='0' and (Lng <> 0 or Lng <> 0)");
                suppliers.ForEach(i => {
                    str = str + $@"[{i.Lng},{i.Lat},'{i.Fname}'],";
                });
                str = str.TrimEnd(',') + "];";
                return(Response.AsText(str));
            };

            //Get["/MP_verify_TDETj8nUoOHLCnHe.txt"] = parameters => {
            //    return Response.AsText(System.IO.File.ReadAllText(pathProvider.GetRootPath() + "MP_verify_TDETj8nUoOHLCnHe.txt"));
            //};
        }
        public CassetteStartup(IRootPathProvider rootPathProvider)
        {
            this.rootPathProvider = rootPathProvider;

            // This will trigger creation of the Cassette infrastructure at the time of the first request.
            // The virtual directory is not known until that point, and the virtual directory is required for creation.
            this.getApplication = InitializeApplication;
            CassetteApplicationContainer.SetApplicationAccessor(() => getApplication());

            routeGenerator = new CassetteRouteGenerator(rootPathProvider.GetRootPath(), GetCurrentContext);
        }
        private static dynamic BuildFileDownloadResponse(IRootPathProvider pathProvider, string fileName)
        {
            var           mimeType = MimeTypes.GetMimeType(fileName);
            var           path     = Path.Combine(pathProvider.GetRootPath(), fileName);
            Func <Stream> file     = () => new FileStream(path, FileMode.Open);

            var response = new StreamResponse(file, mimeType);
            var fileInfo = new FileInfo(path);

            return(response.AsAttachment(fileInfo.Name));
        }
Ejemplo n.º 48
0
        public DefaultResponseFormatterFactoryFixture()
        {
            this.rootPathProvider = A.Fake <IRootPathProvider>();
            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns("RootPath");

            this.serializerFactory = A.Fake <ISerializerFactory>();

            this.environment = A.Fake <INancyEnvironment>();

            this.factory = new DefaultResponseFormatterFactory(this.rootPathProvider, this.serializerFactory, this.environment);
        }
 public FakeDiagnostics(DiagnosticsConfiguration diagnosticsConfiguration, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable <IResponseProcessor> responseProcessors, ICultureService cultureService)
 {
     this.diagnosticsConfiguration = diagnosticsConfiguration;
     this.diagnosticProviders      = (new IDiagnosticsProvider[] { new FakeDiagnosticsProvider() }).ToArray();
     this.rootPathProvider         = rootPathProvider;
     this.requestTracing           = requestTracing;
     this.configuration            = configuration;
     this.modelBinderLocator       = modelBinderLocator;
     this.responseProcessors       = responseProcessors;
     this.cultureService           = cultureService;
 }
Ejemplo n.º 50
0
 public DefaultDiagnostics(DiagnosticsConfiguration diagnosticsConfiguration, IEnumerable <IDiagnosticsProvider> diagnosticProviders, IRootPathProvider rootPathProvider, IEnumerable <ISerializer> serializers, IRequestTracing requestTracing, NancyInternalConfiguration configuration, IModelBinderLocator modelBinderLocator, IEnumerable <IResponseProcessor> responseProcessors)
 {
     this.diagnosticsConfiguration = diagnosticsConfiguration;
     this.diagnosticProviders      = diagnosticProviders;
     this.rootPathProvider         = rootPathProvider;
     this.serializers        = serializers;
     this.requestTracing     = requestTracing;
     this.configuration      = configuration;
     this.modelBinderLocator = modelBinderLocator;
     this.responseProcessors = responseProcessors;
 }
Ejemplo n.º 51
0
        public NotifyHook(IRootPathProvider rootPathProvider)
        {
            Post["/notify"] = x =>
            {
                var  rootPath = rootPathProvider.GetRootPath();
                bool skipEmail;
                bool.TryParse(Request.Query["skipEmail"], out skipEmail);

                PushData pushData = JsonConvert.DeserializeObject <PushData>(Request.Form["payload"]);

                var oldestCommit             = pushData.Commits.OrderBy(c => c.Timestamp).First();
                var oldestCommitMsgFirstLine = oldestCommit.Message.Split('\n')[0];

                var subject = string.Format("[{0}/{1}, {2}] ({3}) {4}",
                                            pushData.Repository.Owner.Name,
                                            pushData.Repository.Name,
                                            pushData.Branch,
                                            oldestCommit.Author.Username,
                                            oldestCommitMsgFirstLine);

                var template = File.ReadAllText(Path.Combine(rootPath, @"Views", @"Notify.cshtml"));
                var body     = Razor.Parse(template, pushData);

                if (skipEmail)
                {
                    return(body);
                }

                var from     = ConfigurationManager.AppSettings["EmailsFrom"];
                var fromName = ConfigurationManager.AppSettings["EmailsFromName"];

                var mailMessage = new MailMessage
                {
                    From       = new MailAddress(from, (string.IsNullOrEmpty(fromName) ? from : fromName)),
                    Subject    = subject,
                    Body       = body,
                    IsBodyHtml = true
                };

                var replyTo     = ConfigurationManager.AppSettings["EmailsReplyTo"];
                var replyToName = ConfigurationManager.AppSettings["EmailsReplyToName"];
                if (!string.IsNullOrEmpty(replyTo))
                {
                    mailMessage.ReplyToList.Add(new MailAddress(replyTo, (string.IsNullOrEmpty(replyToName) ? replyTo : replyToName)));
                }

                mailMessage.Headers.Add("gh-repo", pushData.Repository.Name);
                mailMessage.To.Add(ConfigurationManager.AppSettings["EmailsTo"]);
                new SmtpClient().Send(mailMessage);

                return("email sent");
            };
        }
Ejemplo n.º 52
0
        public XmlFormatterExtensionsFixtures()
        {
            this.rootPathProvider = A.Fake <IRootPathProvider>();

            this.responseFormatter =
                new DefaultResponseFormatter(this.rootPathProvider, new NancyContext(), new ISerializer[] { new DefaultXmlSerializer() });

            this.model = new Person {
                FirstName = "Andy", LastName = "Pike"
            };
            this.response = this.responseFormatter.AsXml(model);
        }
Ejemplo n.º 53
0
 public LogoutModule(IRootPathProvider pathProvider)
 {
     Get["/logout"] = _ =>
     {
         //delete cookie, http only with encrypted username and add it to the current response
         var mc = new NancyCookie("flex", "", true);
         mc.Expires = DateTime.Now.Subtract(new TimeSpan(100000)); //deletes the cookie
         var res = Response.AsRedirect("/");
         res.WithCookie(mc);
         return(res);
     };
 }
Ejemplo n.º 54
0
        public HomeModule(ILocator locator, IRootPathProvider rootPathProvider)
            : base(Constants.BlogBasePath)
        {
            _locator          = locator;
            _rootPathProvider = rootPathProvider;

            Get["/"]               = parameters => RenderIndex(parameters);
            Get["/404"]            = parameters => Render404(parameters);
            Get["/about"]          = parameters => RenderAbout(parameters);
            Get["/{year}/{month}"] = parameters => RenderPosts(parameters);
            Get["/tag/{tagId}"]    = parameters => RenderPostsByTag(parameters);
            Get["/{post_url}"]     = parameters => RenderPost(parameters);
        }
Ejemplo n.º 55
0
        /// <summary>
        /// Initializes a new instance of the <see cref="SparkViewEngine"/> class.
        /// </summary>
        public SparkViewEngine(IRootPathProvider rootPathProvider)
        {
            this.settings = (ISparkSettings)ConfigurationManager.GetSection("spark") ?? new SparkSettings();

            this.engine =
                new global::Spark.SparkViewEngine(this.settings)
            {
                DefaultPageBaseType = typeof(NancySparkView).FullName,
                BindingProvider     = new NancyBindingProvider(rootPathProvider),
            };

            this.descriptorBuilder = new DefaultDescriptorBuilder(this.engine);
        }
Ejemplo n.º 56
0
        public ServerModule(SkyrimInterop skyrimInterop, IRootPathProvider pathy)
        {
            this.weaponImages = Directory.GetFiles(pathy.GetRootPath() + "/static/weapons");
            this.weaponMap    = JsonConvert.DeserializeObject <IDictionary <string, string> >(File.ReadAllText(pathy.GetRootPath() + "/weapon_map.json"));

            this.skyrimInterop = skyrimInterop;
            Get("/api/ping", _ => DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString());
            Get("/api/favorites", GetFavorites);
            Post("/api/command", PostCommand);
            Get("/", _ => Response.AsFile("static/index.html"));
            Get("/weapons/{filename}.png", GetImage);
            Get("/{filename}", _ => Response.AsFile("static/" + (string)_.filename));
        }
Ejemplo n.º 57
0
        public AdminModule(ICommandInvokerFactory commandInvokerFactory, IViewProjectionFactory viewProjectionFactory, IRootPathProvider rootPath)
            : base(viewProjectionFactory)
        {
            _commandInvokerFactory = commandInvokerFactory;
            _rootPath = rootPath;

            Get["/mz-admin"] = _ => Index();
            Get["/mz-admin/change-password"]  = _ => ChangePassword();
            Post["/mz-admin/change-password"] = _ => ChangePassword(this.Bind <ChangePasswordCommand>());

            Get["/mz-admin/change-profile"]  = _ => ChangeProfile();
            Post["/mz-admin/change-profile"] = _ => ChangeProfile(this.Bind <ChangeProfileCommand>());
        }
Ejemplo n.º 58
0
        public HomeModule(IRootPathProvider path)
        {
            this.RequiresAuthentication();
            Get["/"] = r =>
            {
                var os   = System.Environment.OSVersion;
                var p    = path.GetRootPath();
                var user = Context.CurrentUser.UserName;
                return("Hello Nancy<br/> System:" + os.VersionString + "<br/>" + p + "<br/>" + user);
            };

            Get["/blog/{name}"] = r => {
                return("blog name " + r.name);
            };

            Get["/mvc/{controller}/{action}/{id}"] = r => {
                StringBuilder mvc = new StringBuilder();
                mvc.AppendLine("controller :" + r.controller + "<br/>");
                mvc.AppendLine("action :" + r.action + "<br/>");
                mvc.AppendLine("id :" + r.id + "<br/>");
                return(mvc.ToString());
            };

            Get["/json"] = r =>
            {
                JavaScriptSerializer js = new JavaScriptSerializer();
                return(js.Serialize(new { status = 200, message = "this json" }));
            };

            Post["/file"] = r =>
            {
                var uploadDirectory = Path.Combine(path.GetRootPath(), "uploads");

                if (!Directory.Exists(uploadDirectory))
                {
                    Directory.CreateDirectory(uploadDirectory);
                }

                foreach (var file in Request.Files)
                {
                    var filename = Path.Combine(uploadDirectory, file.Name);
                    using (FileStream fileStream = new FileStream(filename, FileMode.Create))
                    {
                        file.Value.CopyTo(fileStream);
                    }
                }
                return(HttpStatusCode.OK);
            };
        }
Ejemplo n.º 59
0
        public ImageModule(IRootPathProvider rootPathProvider, ICommandParser commandParser, IBlobStore store, IImageGenerator imageGenerator)
        {
            Post["/image/"] = _ =>
            {
                Command c = null;

                if (!commandParser.TryParse(Request.Form.text.HasValue ? (string)Request.Form.text : string.Empty, out c))
                {
                    // Invalid input. Early return.
                    return(Response.AsJson(UnknownResponse));
                }

                if (string.Compare(c.Preamble, Command.HelpConstant, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    // Help request. Early return.
                    return(Response.AsJson(HelpResponse));
                }

                var imageId = string.Format("{0}-{1}-{2}.jpg",
                                            c.Preamble,
                                            Nancy.Helpers.HttpUtility.UrlEncode(c.TopLine ?? string.Empty),
                                            Nancy.Helpers.HttpUtility.UrlEncode(c.BottomLine ?? string.Empty));

                if (!store.Exists(imageId))
                {
                    var img = imageGenerator.GenerateImage(c.Preamble, c.TopLine, c.BottomLine);

                    if (img != null)
                    {
                        using (var ms = new MemoryStream())
                        {
                            img.Save(ms, ImageFormat.Jpeg);
                            ms.Seek(0, SeekOrigin.Begin);

                            store.Store(imageId, ms);
                        }
                    }
                    else
                    {
                        // We failed to generate an image; send unknown response
                        return(Response.AsJson(new Models.UnknownResponse()));
                    }
                }

                return(Response.AsJson(
                           new Models.ImageResponse(store.GetUri(imageId).ToString(),
                                                    string.Format("{0} {1}", c.TopLine, c.BottomLine))));
            };
        }
Ejemplo n.º 60
0
        public DefaultViewFactoryFixture()
        {
            this.rootPathProvider = A.Fake <IRootPathProvider>();
            A.CallTo(() => this.rootPathProvider.GetRootPath()).Returns("The root path");

            this.resolver             = A.Fake <IViewResolver>();
            this.renderContextFactory = A.Fake <IRenderContextFactory>();
            this.conventions          = new ViewLocationConventions(Enumerable.Empty <Func <string, object, ViewLocationContext, string> >());

            this.viewLocationContext =
                new ViewLocationContext
            {
                Context = new NancyContext()
            };
        }