public override void Configure(INancyEnvironment environment) { if (_webHostEnvironment.IsDevelopment()) { environment.Tracing(true, true); } }
/// <summary> /// Creates a new instance of the <see cref="DefaultNancyContextFactory"/> class. /// </summary> /// <param name="cultureService">An <see cref="ICultureService"/> instance.</param> /// <param name="requestTraceFactory">An <see cref="IRequestTraceFactory"/> instance.</param> /// <param name="textResource">An <see cref="ITextResource"/> instance.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public DefaultNancyContextFactory(ICultureService cultureService, IRequestTraceFactory requestTraceFactory, ITextResource textResource, INancyEnvironment environment) { this.cultureService = cultureService; this.requestTraceFactory = requestTraceFactory; this.textResource = textResource; this.environment = environment; }
public override void Configure(INancyEnvironment environment) { environment.Tracing( enabled: true, displayErrorTraces: true ); }
/// <summary> /// Configures <see cref="GlobalizationConfiguration"/> /// </summary> /// <param name="environment">An <see cref="INancyEnvironment"/> that should be configured.</param> /// <param name="supportedCultureNames">Cultures that the application can accept</param> /// <param name="defaultCulture">Used to set a default culture for the application</param> /// <param name="dateTimeStyles">The <see cref="DateTimeStyles"/> that should be used for date parsing.</param> /// <remarks>If defaultCulture not specified the first supported culture is used</remarks> public static void Globalization(this INancyEnvironment environment, IEnumerable <string> supportedCultureNames, string defaultCulture = null, DateTimeStyles?dateTimeStyles = null) { environment.AddValue(new GlobalizationConfiguration( supportedCultureNames: supportedCultureNames, defaultCulture: defaultCulture, dateTimeStyles: dateTimeStyles)); }
/// <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> 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) { 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; }
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; }
/// <summary> /// Configures the Nancy environment /// </summary> /// <param name="environment">The <see cref="T:Nancy.Configuration.INancyEnvironment" /> instance to configure</param> public override void Configure(INancyEnvironment environment) { base.Configure(environment); environment.Tracing(true, true); environment.Diagnostics("wb"); }
public override void Configure(INancyEnvironment environment) { //Tracing and Diagnostics: //environment.Tracing(true, true); //environment.Diagnostics(true, "password"); base.Configure(environment); }
public DiagnosticsModuleBuilder(IRootPathProvider rootPathProvider, IModelBinderLocator modelBinderLocator, INancyEnvironment diagnosticsEnvironment, INancyEnvironment environment) { this.rootPathProvider = rootPathProvider; this.serializerFactory = new DiagnosticsSerializerFactory(diagnosticsEnvironment); this.modelBinderLocator = modelBinderLocator; this.environment = environment; }
/// <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; }
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; }
public override void Configure(INancyEnvironment environment) { environment.Tracing(enabled: true, displayErrorTraces: true); environment.Diagnostics( enabled: true, password: "******"); }
public DefaultResponseProcessor( IEnumerable <ISerializer> serializers, INancyEnvironment environmentInstance) { serializer = serializers.FirstOrDefault(x => x.CanSerialize("application/json")); environment = environmentInstance; }
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, ITypeCatalog typeCatalog) { 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.typeCatalog = typeCatalog; }
public override void Configure(INancyEnvironment environment) { environment.Diagnostics(true, "pass"); environment.StaticContent("/Content"); environment.Tracing(true, true); base.Configure(environment); }
/// <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; }
/// <summary> /// Initializes a new instance of the <see cref="Browser"/> class. /// </summary> /// <param name="bootstrapper">A <see cref="INancyBootstrapper"/> instance that determines the Nancy configuration that should be used by the browser.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(INancyBootstrapper bootstrapper, Action<BrowserContext> defaults = null) { bootstrapper.Initialise(); this.engine = bootstrapper.GetEngine(); this.environment = bootstrapper.GetEnvironment(); this.defaultBrowserContext = defaults ?? DefaultBrowserContext; }
public ErrorResponse(Error error, INancyEnvironment env, HttpStatusCode statusCode = HttpStatusCode.InternalServerError) : base(error, new JsonNetSerializer(new CustomJsonSerializer()), env) { // TODO: this might fail if the status code enums are not identical StatusCode = (Nancy.HttpStatusCode)Enum.Parse(typeof(Nancy.HttpStatusCode), statusCode.ToString()); }
/// <summary> /// Initializes a new instance of the <see cref="Browser"/> class. /// </summary> /// <param name="bootstrapper">A <see cref="INancyBootstrapper"/> instance that determines the Nancy configuration that should be used by the browser.</param> /// <param name="defaults">The default <see cref="BrowserContext"/> that should be used in a all requests through this browser object.</param> public Browser(INancyBootstrapper bootstrapper, Action <BrowserContext> defaults = null) { bootstrapper.Initialise(); this.engine = bootstrapper.GetEngine(); this.environment = bootstrapper.GetEnvironment(); this.defaultBrowserContext = defaults ?? DefaultBrowserContext; }
// Override with a valid password(albeit a really really bad one!) // to enable the diagnostics dashboard public override void Configure(INancyEnvironment environment) { // https://github.com/NancyFx/Nancy/issues/2632 // Nancy.Json.JsonConfiguration.Default = new // Nancy.Json.JsonConfiguration( //Nancy.Json.JsonConfiguration.Default.RetainCasing = true; //Nancy.Json.JsonSettings.RetainCasing = true; // base.Configure(environment); /* * environment.Diagnostics( * enabled: true, * password: "******", * path: "/_Nancy", * cookieName: "__custom_cookie", * slidingTimeout: 30, * cryptographyConfiguration: CryptographyConfiguration.NoEncryption); */ environment.Tracing( enabled: true, displayErrorTraces: true); }
public AlreadyKnownRouteResolver(INancyEnvironment environment, nancyrouting.Route route, INancyModule module, nancyrouting.Trie.MatchResult matchResult) { _globalizationConfiguraton = environment.GetValue <GlobalizationConfiguration>(); _route = route; _module = module; _matchResult = matchResult; }
/// <summary> /// Initializes a new instance of the <see cref="RazorViewEngine"/> class. /// </summary> /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param> public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog) { this.razorAssemblyProvider = new RazorAssemblyProvider(configuration, assemblyCatalog); this.viewRenderer = new CSharpRazorViewRenderer(this.razorAssemblyProvider); this.razorConfiguration = configuration; this.traceConfiguration = environment.GetValue <TraceConfiguration>(); this.AddDefaultNameSpaces(this.viewRenderer.Host); }
/*private byte[] favicon; * * protected override byte[] FavIcon * { * get { return favicon ?? (favicon = LoadFavIcon()); } * } * * private byte[] LoadFavIcon() * { * var ico = Assembly.GetEntryAssembly().GetManifestResourceStream($"{PROJECT}.{PROJECT}Web.res.img.{PROJECT}.ico"); * favicon = new byte[ico.Length]; * ico.Read(favicon, 0, favicon.Length); * return favicon; * }*/ public override void Configure(INancyEnvironment environment) { base.Configure(environment); #if DEBUG environment.Views(runtimeViewUpdates: true); #endif }
public override void Configure(INancyEnvironment environment) { base.Configure(environment); //TODO: для отладки, потом убрать environment.Diagnostics(true, "Qaz123"); environment.Tracing(enabled: false, displayErrorTraces: true); }
public override void Configure(INancyEnvironment environment) { base.Configure(environment); environment.AddValue("AssetServer", this.assetServer); environment.Tracing(enabled: true, displayErrorTraces: true); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultViewLocator"/> class. /// </summary> /// <param name="viewLocationProvider">An <see cref="IViewLocationProvider"/> instance.</param> /// <param name="viewEngines">An <see cref="IEnumerable{T}"/> of <see cref="IViewEngine"/> instances.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public DefaultViewLocator(IViewLocationProvider viewLocationProvider, IEnumerable<IViewEngine> viewEngines, INancyEnvironment environment) { this.viewLocationProvider = viewLocationProvider; this.viewEngines = viewEngines; this.invalidCharacters = Path.GetInvalidFileNameChars().Where(c => c != '/').ToArray(); this.viewLocationResults = new List<ViewLocationResult>(this.GetInititialViewLocations()); this.configuration = environment.GetValue<ViewConfiguration>(); }
public override void Configure(INancyEnvironment environment) { base.Configure(environment); #if DEBUG environment.Tracing(true, true); #endif }
/// <summary> /// Initializes a new instance of the <see cref="RazorViewEngine"/> class. /// </summary> /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> /// <param name="assemblyCatalog">An <see cref="IAssemblyCatalog"/> instance.</param> public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment, IAssemblyCatalog assemblyCatalog) { this.razorAssemblyProvider = new RazorAssemblyProvider(configuration, assemblyCatalog); this.viewRenderer = new CSharpRazorViewRenderer(this.razorAssemblyProvider); this.razorConfiguration = configuration; this.traceConfiguration = environment.GetValue<TraceConfiguration>(); this.AddDefaultNameSpaces(this.viewRenderer.Host); }
/// <summary> /// Configures JSON serialization. /// </summary> /// <param name="environment"><see cref="INancyEnvironment"/> that should be configured.</param> /// <param name="maxJsonLength">Max length of JSON output.</param> /// <param name="defaultEncoding">The <see cref="Encoding"/> that should be as a default.</param> /// <param name="converters">List of <see cref="JavaScriptConverter"/> that should be used.</param> /// <param name="primitiveConverters">List of <see cref="JavaScriptPrimitiveConverter"/> that should be used.</param> /// <param name="retainCasing"><see langword="true" /> if C# casing should be retained, otherwise <see langword="false" /> to use camel-casing.</param> public static void Json(this INancyEnvironment environment, int?maxJsonLength = null, Encoding defaultEncoding = null, IList <JavaScriptConverter> converters = null, IList <JavaScriptPrimitiveConverter> primitiveConverters = null, bool?retainCasing = null) { environment.AddValue(new JsonConfiguration( defaultEncoding ?? JsonConfiguration.Default.DefaultEncoding, converters ?? JsonConfiguration.Default.Converters, primitiveConverters ?? JsonConfiguration.Default.PrimitiveConverters, retainCasing ?? JsonConfiguration.Default.RetainCasing)); }
/// <summary> /// Initializes a new instance of the <see cref="NancyViewFolder"/> class, using the provided <see cref="viewEngineStartupContext"/> instance. /// </summary> /// <param name="viewEngineStartupContext">A <see cref="ViewEngineStartupContext"/> instance.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public NancyViewFolder(ViewEngineStartupContext viewEngineStartupContext, INancyEnvironment environment) { this.viewEngineStartupContext = viewEngineStartupContext; this.configuration = environment.GetValue <ViewConfiguration>(); // No need to lock here this.currentlyLocatedViews = new List <ViewLocationResult>(viewEngineStartupContext.ViewLocator.GetAllCurrentlyDiscoveredViews()); }
/// <summary> /// Configures diagnostics. /// </summary> /// <param name="environment"><see cref="INancyEnvironment"/> that should be configured.</param> /// <param name="password">Password used to secure the dashboard.</param> /// <param name="path">Relative path of the dashboard.</param> /// <param name="cookieName">Name of the cookie to store diagnostics information.</param> /// <param name="slidingTimeout">Number of minutes that expiry of the diagnostics dashboard.</param> /// <param name="cryptographyConfiguration">Cryptography config to use for securing the dashboard.</param> public static void Diagnostics(this INancyEnvironment environment, string password, string path = null, string cookieName = null, int slidingTimeout = 15, CryptographyConfiguration cryptographyConfiguration = null) { environment.AddValue(new DiagnosticsConfiguration( password, path, cookieName, slidingTimeout, cryptographyConfiguration)); }
public override void Configure(INancyEnvironment environment) { base.Configure(environment); //activate that errors are shown on webpage environment.Tracing( enabled: true, displayErrorTraces: true); }
/// <summary> /// Initializes a new instance of the <see cref="NancyViewFolder"/> class, using the provided <see cref="viewEngineStartupContext"/> instance. /// </summary> /// <param name="viewEngineStartupContext">A <see cref="ViewEngineStartupContext"/> instance.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public NancyViewFolder(ViewEngineStartupContext viewEngineStartupContext, INancyEnvironment environment) { this.viewEngineStartupContext = viewEngineStartupContext; this.configuration = environment.GetValue<ViewConfiguration>(); // No need to lock here this.currentlyLocatedViews = new List<ViewLocationResult>(viewEngineStartupContext.ViewLocator.GetAllCurrentlyDiscoveredViews()); }
public override void Configure(INancyEnvironment environment) { base.Configure(environment); if (Application.isEditor) { environment.Tracing(enabled: true, displayErrorTraces: true); environment.Diagnostics(password: "******"); } }
public override void Configure(INancyEnvironment environment) { var hostEnv = _services.BuildServiceProvider().GetService <IWebHostEnvironment>(); if (!hostEnv.IsProduction()) { environment.Tracing(false, true); } }
/// <summary> /// Initializes a new instance of the <see cref="DefaultRouteResolver"/> class, using /// the provided <paramref name="catalog"/>, <paramref name="moduleBuilder"/>, /// <paramref name="routeCache"/> and <paramref name="trie"/>. /// </summary> /// <param name="catalog">An <see cref="INancyModuleCatalog"/> instance.</param> /// <param name="moduleBuilder">An <see cref="INancyModuleBuilder"/> instance.</param> /// <param name="routeCache">An <see cref="IRouteCache"/> instance.</param> /// <param name="trie">An <see cref="IRouteResolverTrie"/> instance.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public DefaultRouteResolver(INancyModuleCatalog catalog, INancyModuleBuilder moduleBuilder, IRouteCache routeCache, IRouteResolverTrie trie, INancyEnvironment environment) { this.catalog = catalog; this.moduleBuilder = moduleBuilder; this.routeCache = routeCache; this.trie = trie; this.configuration = new Lazy<RouteConfiguration>(environment.GetValue<RouteConfiguration>); this.BuildTrie(); }
/// <summary> /// Enable JSONP support in the application /// </summary> /// <param name="pipelines">Application Pipeline to Hook into</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public static void Enable(IPipelines pipelines, INancyEnvironment environment) { var jsonpEnabled = pipelines.AfterRequest.PipelineItems.Any(ctx => ctx.Name == "JSONP"); if (!jsonpEnabled) { encoding = environment.GetValue<JsonConfiguration>().DefaultEncoding; pipelines.AfterRequest.AddItemToEndOfPipeline(JsonpItem); } }
public StaticContentConventionBuilderFixture() { var assembly = typeof(StaticContentConventionBuilderFixture).GetAssembly(); var localPath = new Uri(assembly.CodeBase).LocalPath; this.directory = new DirectoryInfo(localPath).Parent.FullName; this.environment = new DefaultNancyEnvironment(); this.environment.StaticContent(safepaths: this.directory); }
public DefaultNancyEnvironmentConfiguratorFixture() { this.environment = A.Fake<INancyEnvironment>(); this.factory = A.Fake<INancyEnvironmentFactory>(); this.defaultConfigurationProviders = A.Fake<IEnumerable<INancyDefaultConfigurationProvider>>(); A.CallTo(() => this.factory.CreateEnvironment()).Returns(this.environment); this.configurator = new DefaultNancyEnvironmentConfigurator(this.factory, this.defaultConfigurationProviders); }
/// <summary> /// Initializes a new instance of the <see cref="BrowserContext"/> class, /// with the provided <see cref="INancyEnvironment"/>. /// </summary> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public BrowserContext(INancyEnvironment environment) { this.Environment = environment; this.Values.Headers = new Dictionary<string, IEnumerable<string>>(StringComparer.OrdinalIgnoreCase); this.Values.Protocol = string.Empty; this.Values.QueryString = string.Empty; this.Values.BodyString = string.Empty; this.Values.FormValues = string.Empty; this.Values.HostName = string.Empty; }
public DefaultNancyEnvironmentConfiguratorFixture() { this.environment = A.Fake <INancyEnvironment>(); this.factory = A.Fake <INancyEnvironmentFactory>(); this.defaultConfigurationProviders = A.Fake <IEnumerable <INancyDefaultConfigurationProvider> >(); A.CallTo(() => this.factory.CreateEnvironment()).Returns(this.environment); this.configurator = new DefaultNancyEnvironmentConfigurator(this.factory, this.defaultConfigurationProviders); }
// Override with a valid password (albeit a really really bad one!) // to enable the diagnostics dashboard public override void Configure(INancyEnvironment environment) { environment.Diagnostics( password: "******", path: "/_Nancy", cookieName: "__custom_cookie", slidingTimeout: 30, cryptographyConfiguration: CryptographyConfiguration.NoEncryption); environment.MyConfig("Hello World"); }
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 override void Configure(INancyEnvironment environment) { environment.Diagnostics( enabled: true, password: "******" ); environment.Tracing( enabled: false, displayErrorTraces: true ); }
/// <summary> /// Initializes a new instance of the <see cref="RazorViewEngine"/> class. /// </summary> /// <param name="configuration">The <see cref="IRazorConfiguration"/> that should be used by the engine.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public RazorViewEngine(IRazorConfiguration configuration, INancyEnvironment environment) { this.viewRenderers = new List<IRazorViewRenderer> { new CSharpRazorViewRenderer(), new VisualBasicRazorViewRenderer() }; this.razorConfiguration = configuration; this.traceConfiguration = environment.GetValue<TraceConfiguration>(); foreach (var renderer in this.viewRenderers) { this.AddDefaultNameSpaces(renderer.Host); } }
/// <summary> /// Initializes a new instance of the <see cref="NancyEngine"/> class. /// </summary> /// <param name="dispatcher">An <see cref="IRouteResolver"/> instance that will be used to resolve a route, from the modules, that matches the incoming <see cref="Request"/>.</param> /// <param name="contextFactory">A factory for creating contexts</param> /// <param name="statusCodeHandlers">Error handlers</param> /// <param name="requestTracing">The request tracing instance.</param> /// <param name="staticContentProvider">The provider to use for serving static content</param> /// <param name="negotiator">The response negotiator.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public NancyEngine(IRequestDispatcher dispatcher, INancyContextFactory contextFactory, IEnumerable<IStatusCodeHandler> statusCodeHandlers, IRequestTracing requestTracing, IStaticContentProvider staticContentProvider, IResponseNegotiator negotiator, INancyEnvironment environment) { if (dispatcher == null) { throw new ArgumentNullException("dispatcher", "The resolver parameter cannot be null."); } if (contextFactory == null) { throw new ArgumentNullException("contextFactory"); } if (statusCodeHandlers == null) { throw new ArgumentNullException("statusCodeHandlers"); } if (requestTracing == null) { throw new ArgumentNullException("requestTracing"); } if (staticContentProvider == null) { throw new ArgumentNullException("staticContentProvider"); } if (negotiator == null) { throw new ArgumentNullException("negotiator"); } this.dispatcher = dispatcher; this.contextFactory = contextFactory; this.statusCodeHandlers = statusCodeHandlers.ToArray(); this.requestTracing = requestTracing; this.staticContentProvider = staticContentProvider; this.negotiator = negotiator; this.engineDisposedCts = new CancellationTokenSource(); this.traceConfiguration = environment.GetValue<TraceConfiguration>(); }
/// <summary> /// Initializes a new instance of the <see cref="BindingDefaults"/> class, /// with the provided <see cref="INancyEnvironment"/>. /// </summary> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public BindingDefaults(INancyEnvironment environment) { // Ordering is important - for now we will new just these up // as the binding defaults class itself is replaceable if necessary, // and none of defaults have any dependencies. this.defaultTypeConverters = new ITypeConverter[] { new CollectionConverter(), new FallbackConverter(), }; this.defaultBodyDeserializers = new IBodyDeserializer[] { new JsonBodyDeserializer(environment), new XmlBodyDeserializer() }; }
/// <summary> /// Initializes a new instance of the <see cref="DefaultStatusCodeHandler"/> type. /// </summary> /// <param name="responseNegotiator">The response negotiator.</param> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public DefaultStatusCodeHandler(IResponseNegotiator responseNegotiator, INancyEnvironment environment) { this.errorMessages = new Dictionary<HttpStatusCode, string> { { HttpStatusCode.NotFound, "The resource you have requested cannot be found." }, { HttpStatusCode.InternalServerError, "Something went horribly, horribly wrong while servicing your request." } }; this.errorPages = new Dictionary<HttpStatusCode, string> { { HttpStatusCode.NotFound, LoadResource("404.html") }, { HttpStatusCode.InternalServerError, LoadResource("500.html") } }; this.responseNegotiator = responseNegotiator; this.configuration = environment.GetValue<TraceConfiguration>(); }
public override void Configure(INancyEnvironment environment) { var config = JObject.Parse(File.ReadAllText(_configurationFile)); foreach(var element in config) { environment.AddValue<string>(element.Key, element.Value.Value<string>()); } environment.Diagnostics( enabled: true, password: config["GTDPad.DiagnosticsPassword"].Value<string>() ); environment.Tracing( enabled: false, displayErrorTraces: true ); }
public NancyEngineFixture() { this.environment = new DefaultNancyEnvironment(); this.environment.Tracing( enabled: true, displayErrorTraces: true); this.resolver = A.Fake<IRouteResolver>(); this.response = new Response(); this.route = new FakeRoute(response); this.context = new NancyContext(); this.statusCodeHandler = A.Fake<IStatusCodeHandler>(); this.requestDispatcher = A.Fake<IRequestDispatcher>(); this.negotiator = A.Fake<IResponseNegotiator>(); A.CallTo(() => this.requestDispatcher.Dispatch(A<NancyContext>._, A<CancellationToken>._)) .Returns(Task.FromResult(new Response())); A.CallTo(() => this.statusCodeHandler.HandlesStatusCode(A<HttpStatusCode>.Ignored, A<NancyContext>.Ignored)).Returns(false); contextFactory = A.Fake<INancyContextFactory>(); A.CallTo(() => contextFactory.Create(A<Request>._)).Returns(context); var resolveResult = new ResolveResult { Route = route, Parameters = DynamicDictionary.Empty, Before = null, After = null, OnError = null }; A.CallTo(() => resolver.Resolve(A<NancyContext>.Ignored)).Returns(resolveResult); var applicationPipelines = new Pipelines(); this.routeInvoker = A.Fake<IRouteInvoker>(); A.CallTo(() => this.routeInvoker.Invoke(A<Route>._, A<CancellationToken>._, A<DynamicDictionary>._, A<NancyContext>._)).ReturnsLazily(arg => { return ((Route)arg.Arguments[0]).Action.Invoke((DynamicDictionary)arg.Arguments[1], A<CancellationToken>._).Result; }); this.engine = new NancyEngine(this.requestDispatcher, this.contextFactory, new[] { this.statusCodeHandler }, A.Fake<IRequestTracing>(), new DisabledStaticContentProvider(), this.negotiator, this.environment) { RequestPipelinesFactory = ctx => applicationPipelines }; }
public ViewEngineStartupFixture() { this.views = new List<ViewLocationResult> { new ViewLocationResult("", "", "html", null), new ViewLocationResult("", "", "spark", null), }; var viewLocationProvider = A.Fake<IViewLocationProvider>(); A.CallTo(() => viewLocationProvider.GetLocatedViews(A<IEnumerable<string>>._)) .Returns(views); var viewEngine = A.Fake<IViewEngine>(); A.CallTo(() => viewEngine.Extensions).Returns(new[] { "liquid" }); this.environment = new DefaultNancyEnvironment(); this.environment.AddValue(ViewConfiguration.Default); this.viewLocator = new DefaultViewLocator(viewLocationProvider, new[] { viewEngine }, this.environment); this.viewCache = A.Fake<IViewCache>(); }
public InfoModule(IRootPathProvider rootPathProvider, NancyInternalConfiguration configuration, INancyEnvironment environment, ITypeCatalog typeCatalog) : base("/info") { this.typeCatalog = typeCatalog; Get["/"] = async (_, __) => { return View["Info"]; }; Get["/data"] = async (_, __) => { dynamic data = new ExpandoObject(); data.Nancy = new ExpandoObject(); data.Nancy.Version = string.Format("v{0}", this.GetType().Assembly.GetName().Version.ToString()); data.Nancy.TracesDisabled = !environment.GetValue<TraceConfiguration>().DisplayErrorTraces; data.Nancy.CaseSensitivity = StaticConfiguration.CaseSensitive ? "Sensitive" : "Insensitive"; data.Nancy.RootPath = rootPathProvider.GetRootPath(); data.Nancy.Hosting = GetHosting(); data.Nancy.BootstrapperContainer = 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 this.Response.AsJson((object)data); }; }
public DotLiquidViewEngineFixture() { this.environment = new DefaultNancyEnvironment(); this.environment.AddValue(ViewConfiguration.Default); this.factory = A.Fake<IFileSystemFactory>(); this.engine = new DotLiquidViewEngine(this.factory, new RubyNamingConvention()); this.engineCSharp = new DotLiquidViewEngine(this.factory, new CSharpNamingConvention()); var cache = A.Fake<IViewCache>(); A.CallTo(() => cache.GetOrAdd(A<ViewLocationResult>.Ignored, A<Func<ViewLocationResult, Template>>.Ignored)) .ReturnsLazily(x => { var result = x.GetArgument<ViewLocationResult>(0); return x.GetArgument<Func<ViewLocationResult, Template>>(1).Invoke(result); }); var context = new NancyContext(); this.renderContext = A.Fake<IRenderContext>(); A.CallTo(() => this.renderContext.ViewCache).Returns(cache); A.CallTo(() => this.renderContext.Context).Returns(context); }
public DiagnosticsModuleCatalog(IEnumerable<IDiagnosticsProvider> providers, IRootPathProvider rootPathProvider, IRequestTracing requestTracing, NancyInternalConfiguration configuration, INancyEnvironment diagnosticsEnvironment) { this.container = ConfigureContainer(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment); }
/// <summary> /// Enables the diagnostics dashboard and will intercept all requests that are passed to /// the condigured paths. /// </summary> public static void Enable(IPipelines pipelines, IEnumerable<IDiagnosticsProvider> providers, 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) { var diagnosticsConfiguration = environment.GetValue<DiagnosticsConfiguration>(); var diagnosticsEnvironment = GetDiagnosticsEnvironment(); var diagnosticsModuleCatalog = new DiagnosticsModuleCatalog(providers, rootPathProvider, requestTracing, configuration, diagnosticsEnvironment); var diagnosticsRouteCache = new RouteCache( diagnosticsModuleCatalog, new DefaultNancyContextFactory(cultureService, requestTraceFactory, textResource), new DefaultRouteSegmentExtractor(), new DefaultRouteDescriptionProvider(), cultureService, routeMetadataProviders); var diagnosticsRouteResolver = new DefaultRouteResolver( diagnosticsModuleCatalog, new DiagnosticsModuleBuilder(rootPathProvider, modelBinderLocator, diagnosticsEnvironment, environment), diagnosticsRouteCache, new RouteResolverTrie(new TrieNodeFactory(routeSegmentConstraints))); 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(Path.DirectorySeparatorChar, '.')); } return new EmbeddedFileResponse( typeof(DiagnosticsHook).Assembly, resourceNamespace, Path.GetFileName(ctx.Request.Url.Path)); } RewriteDiagnosticsUrl(diagnosticsConfiguration, ctx); return ValidateConfiguration(diagnosticsConfiguration) ? ExecuteDiagnostics(ctx, diagnosticsRouteResolver, diagnosticsConfiguration, serializer) : GetDiagnosticsHelpView(ctx); })); }
/// <summary> /// Initializes a new instance of the <see cref="DefaultRequestTraceFactory"/> class. /// </summary> /// <param name="environment">An <see cref="INancyEnvironment"/> instance.</param> public DefaultRequestTraceFactory(INancyEnvironment environment) { this.configuration = environment.GetValue<TraceConfiguration>(); }
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!"; }