コード例 #1
0
        public static IApplicationBuilder UseOwinAppBuilder(this IApplicationBuilder app, Action <IAppBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            return(app.UseOwin(setup => setup(next => {
                var builder = new AppBuilder();
                var lifetime = (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));

                var properties = new AppProperties(builder.Properties);
                properties.AppName = app.ApplicationServices.GetApplicationUniqueIdentifier();
                properties.OnAppDisposing = lifetime.ApplicationStopping;
                properties.DefaultApp = next;

                configuration(builder);

                return builder.Build <Func <IDictionary <string, object>, Task> >();
            })));
        }
コード例 #2
0
        public void Configuration(IAppBuilder app)
        {
            // ADD YOUR DSN BELOW:
            var flush      = SentrySdk.Init("https://[email protected]/1188141");
            var properties = new AppProperties(app.Properties);

            properties.OnAppDisposing.Register(() => flush.Dispose());

            AppDomain.CurrentDomain.FirstChanceException += (sender, args) =>
            {
                // ALL exceptions go through this callback before reaching your catch blocks!
                SentrySdk.CaptureException(args.Exception);
            };

            var config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();
            config.Services.Replace(typeof(IExceptionHandler), new SentryExceptionHandler());

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
                );

            app.UseOwinExceptionHandler();
            app.UseWebApi(config);
        }
コード例 #3
0
 public static void WriteLogClientAction(string machineName, string format, params object[] paramArray)
 {
     if (AppProperties.GetBoolProperty("IsLogClientAction"))
     {
         _logger.Trace("clt {0}|{1}", machineName, string.Format(format, paramArray));
     }
 }
コード例 #4
0
 public static AppProperties GetAppPropertiess()
 {
     try
     {
         if (!System.IO.Directory.Exists(globalVariables.m_strPropertiesFolder))
         {
             Directory.CreateDirectory(globalVariables.m_strPropertiesFolder);
         }
         var    myProperty = new AppProperties();
         string filePath   = string.Format(@"{0}\{1}.xml", globalVariables.m_strPropertiesFolder, myProperty.GetType().Name);
         if (!File.Exists(filePath))
         {
             return(myProperty);
         }
         var myFileStream = new FileStream(filePath, FileMode.Open);
         var mySerializer = new XmlSerializer(myProperty.GetType());
         myProperty = (AppProperties)mySerializer.Deserialize(myFileStream);
         myFileStream.Close();
         return(myProperty);
     }
     catch (Exception ex)
     {
         return(new AppProperties());
     }
 }
コード例 #5
0
ファイル: OwinConfiguration.cs プロジェクト: tintoy/Wakka
        public static void Configure(IAppBuilder app)
        {
            if (app == null)
                throw new ArgumentNullException("app");

            IContainer container = IocConfiguration.BuildContainer(actorSystemName: "Wakka");
            app.UseAutofacMiddleware(container);

            HttpConfiguration webApiConfiguration = new HttpConfiguration
            {
                // Only used when mapping attribute routes.
                DependencyResolver = new AutofacWebApiDependencyResolver(container)
            };
            app.UseAutofacWebApi(webApiConfiguration); // Share OWIN lifetime scope.

            webApiConfiguration.MapHttpAttributeRoutes();
            webApiConfiguration.EnsureInitialized();

            app.UseWebApi(webApiConfiguration);

            // Explicitly start the actor system when the OWIN app is started.
            ActorSystem actorSystem = container.ResolveNamed<ActorSystem>("Wakka");

            // Try to gracefully shut down the actor system when the host is shutting down.
            AppProperties appProperties = new AppProperties(app.Properties);
            appProperties.OnAppDisposing.Register(() =>
            {
                actorSystem.Shutdown();
                actorSystem.AwaitTermination(
                    timeout: TimeSpan.FromSeconds(5)
                );
            });
        }
コード例 #6
0
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();

            config.MapHttpAttributeRoutes();

            app.UseCors(CorsOptions.AllowAll);

            ConfigureJsonSerialisation(config);

            app.UseWebApi(config);

            // Configure and start Autofac
            Container = ConfigureContainer(config);
            app.UseAutofacMiddleware(Container);

            app.UseAutofacWebApi(config);

            // Start Mass Transit Service bus, and register stopping of bus on app dispose
            var bus       = Container.Resolve <IBusControl>();
            var busHandle = TaskUtil.Await(() => bus.StartAsync());

            var properties = new AppProperties(app.Properties);

            if (properties.OnAppDisposing != CancellationToken.None)
            {
                properties.OnAppDisposing.Register(() => busHandle.Stop(TimeSpan.FromSeconds(30)));
            }

            config.EnsureInitialized();
        }
コード例 #7
0
        public void GetWordsForRegex()
        {
            List <string> words = new List <string>()
            {
                "spin", "span", "spit", "cats", "boot"
            };

            AppProperties props = new AppProperties()
            {
                StartWord         = "spin",
                EndWord           = "spot",
                WordList          = words,
                MismatchThreshold = 2
            };

            List <Node> nodes = _wordFilter.GetWordsForRegex("sp\\wn|spi\\w", props, new Node()
            {
                Word = "spin"
            });

            nodes.OrderBy(x => x.Word);

            Assert.IsTrue(nodes.Count == 2);
            Assert.AreEqual(nodes[0].Word, "span");
            Assert.AreEqual(nodes[1].Word, "spit");
        }
コード例 #8
0
 public MobileApplication(AppProperties appProperties)
 {
     DeviceName         = DefaultDeviceName;
     this.appProperties = appProperties;
     appiumServer       = new AppiumServer();
     appiumServer.StartServer1();
 }
コード例 #9
0
ファイル: Startup.cs プロジェクト: lathakan2103/MassTransitDI
        public void Configuration(IAppBuilder app)
        {
            HttpConfiguration config = new HttpConfiguration();
            var builder = new ContainerBuilder();

            builder.RegisterType <FooService>().As <IFooService>();
            builder.RegisterConsumers(typeof(FooConsumer).Assembly);
            builder.RegisterModule <BusModule>();

            // Register Web API controllers
            builder.RegisterApiControllers(Assembly.GetExecutingAssembly());

            // Resolve dependencies
            var container = builder.Build();

            config.DependencyResolver = new AutofacWebApiDependencyResolver(container);

            WebApiConfig.Register(config);
            SwaggerConfig.Register(config);
            app.UseCors(CorsOptions.AllowAll);

            // Register the Autofac middleware FIRST.
            app.UseAutofacMiddleware(container);
            app.UseWebApi(config);

            // Starts MassTransit Service bus, and registers stopping of bus on app dispose
            var bus        = container.Resolve <IBusControl>();
            var busHandle  = bus.StartAsync();
            var properties = new AppProperties(app.Properties);

            if (properties.OnAppDisposing != CancellationToken.None)
            {
                properties.OnAppDisposing.Register(() => busHandle.Result.StopAsync(TimeSpan.FromSeconds(30)));
            }
        }
コード例 #10
0
 // отладочные сообщения
 // стандартные действия службы
 public static void WriteLogTraceMessage(string msg)
 {
     if (AppProperties.GetBoolProperty("IsWriteTraceMessages"))
     {
         _logger.Trace(msg);
     }
 }
コード例 #11
0
 public static void WriteLogTraceMessage(string format, params object[] paramArray)
 {
     if (AppProperties.GetBoolProperty("IsWriteTraceMessages"))
     {
         _logger.Trace(format, paramArray);
     }
 }
コード例 #12
0
        public HttpServer(IKernel kernel, Action <IOwinConfiguration> configuration, string url)
        {
            if (kernel == null)
            {
                throw new ArgumentNullException(nameof(kernel));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }
            AssertUrl(url);

            _console = kernel.Resolve <IConsoleWriter>();

            Output($"Starting HttpServer listening on URL: {url}");

            // TODO: Make it possible to add multiple URL's to listen on
            _httpServer = WebApp.Start(new StartOptions(url), builder =>
            {
                var properties = new AppProperties(builder.Properties)
                {
                    TraceOutput    = kernel.Resolve <TextWriter>(),
                    OnAppDisposing = kernel.Resolve <IShutdown>().Token
                };

                builder.Configure(properties, kernel, configuration);
            });
        }
コード例 #13
0
        public void Configuration(IAppBuilder app)
        {
            var properties = new AppProperties(app.Properties);
            var services   = new ServiceCollection();
            var path       = HostingEnvironment.MapPath("~/Scripts/es6");

            services.AddNodeServices(opts =>
            {
                opts.LaunchWithDebugging      = true;
                opts.ProjectPath              = path;
                opts.ApplicationStoppingToken = properties.OnAppDisposing;
                opts.NodeInstanceOutputLogger = new NodeLogger();
                opts.WatchFileExtensions      = new string[0];
            });

            var builder = new ContainerBuilder();

            builder.Populate(services);

            var container = builder.Build();

            var nodeServices = container.Resolve <INodeServices>();
            var foo          = nodeServices.InvokeAsync <string>(properties.OnAppDisposing, "webpack-server-entry.js", "--mode", "development", "--watch");

            foo.ContinueWith(t =>
            {
            });
        }
コード例 #14
0
        public void Configuration(IAppBuilder app)
        {
            // Any connection or hub wire up and configuration should go here
            app.MapSignalR();

            AreaRegistration.RegisterAllAreas();

            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            //RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);

            // Configure Web API for self-host.
            HttpConfiguration config = new HttpConfiguration();

            //  Enable attribute based routing
            config.MapHttpAttributeRoutes();

            app.UseWebApi(config);

            var properties          = new AppProperties(app.Properties);
            CancellationToken token = properties.OnAppDisposing;

            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    Utilities.ThreadTracker thTrckr = Utilities.ThreadTracker.GetInstance();
                    thTrckr.IsAppStopped            = true;
                });
            }
        }
コード例 #15
0
 // подробные действия о чтении заказов из БД
 public static void WriteLogOrderDetails(string msg)
 {
     if (AppProperties.GetBoolProperty("IsWriteTraceMessages") && AppProperties.GetBoolProperty("TraceOrdersDetails"))
     {
         _logger.Trace("svcDtl|" + msg);
     }
 }
コード例 #16
0
        public void Configuration(IAppBuilder app)
        {
            app.UseCors(CorsOptions.AllowAll);

            // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=316888

            HttpConfiguration config = new HttpConfiguration();

            config.EnableCors();

            OAuthAuthorizationServerOptions options = new OAuthAuthorizationServerOptions
            {
                AllowInsecureHttp         = true,
                TokenEndpointPath         = new PathString("/api/token"),
                AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
                Provider = new AuthorizationServerProvider()
            };

            app.UseOAuthAuthorizationServer(options);
            app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());

            WebApiConfig.Register(config);

            //closing db connection
            var properties          = new AppProperties(app.Properties);
            CancellationToken token = properties.OnAppDisposing;

            token.Register(() => {
                DBConnection.closeConn();
            });
        }
コード例 #17
0
        public static OrderStatusEnum GetStatusAllDishes(IEnumerable <OrderDish> dishes)
        {
            if ((dishes == null) || (dishes.Count() == 0))
            {
                return(OrderStatusEnum.None);
            }

            int           statId = -1, curStat;
            HashSet <int> unUsedDeps = (HashSet <int>)AppProperties.GetProperty("UnusedDepartments");

            foreach (OrderDish dish in dishes)
            {
                if ((unUsedDeps != null) && (unUsedDeps.Contains(dish.DepartmentId)))
                {
                }
                else
                {
                    curStat = dish.DishStatusId;
                    if (statId == -1)
                    {
                        statId = curStat;
                    }
                    else if (statId != dish.DishStatusId)
                    {
                        return(OrderStatusEnum.None);
                    }
                }
            }

            return((OrderStatusEnum)statId);
        }
コード例 #18
0
ファイル: CommonStartup.cs プロジェクト: ziphrax/zipkin4net
        public void Configuration(IAppBuilder appBuilder)
        {
            //Setup tracing
            TraceManager.SamplingRate = 1.0f;
            var logger     = new ConsoleLogger();
            var httpSender = new HttpZipkinSender("http://localhost:9411", "application/json");
            var tracer     = new ZipkinTracer(httpSender, new JSONSpanSerializer());

            TraceManager.RegisterTracer(tracer);
            TraceManager.Start(logger);
            //

            //Stop TraceManager on app dispose
            var properties = new AppProperties(appBuilder.Properties);
            var token      = properties.OnAppDisposing;

            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    TraceManager.Stop();
                });
            }
            //

            // Setup Owin Middleware
            appBuilder.UseZipkinTracer(System.Configuration.ConfigurationManager.AppSettings["applicationName"]);
            //

            appBuilder.Run(RunHandler);
        }
コード例 #19
0
        public void Configuration(IAppBuilder app)
        {
#if BREAK_ON_STARTUP
            var debugTimeout = DateTime.UtcNow.AddSeconds(30);
            while (!System.Diagnostics.Debugger.IsAttached && DateTime.UtcNow < debugTimeout)
            {
                System.Threading.Thread.Sleep(50);
            }
            System.Diagnostics.Debugger.Break();
#endif
            try
            {
                var iocContainer = ConfigureUnity();
                _configurationFileSource = ConfigureUrchinClient(iocContainer);
                ConfigureMiddleware(app, iocContainer);

                var properties = new AppProperties(app.Properties);
                var token      = properties.OnAppDisposing;
                token.Register(() =>
                {
                    _configurationFileSource.Dispose();
                    iocContainer.Dispose();
                });
            }
            catch (Exception ex)
            {
                ConfigureFailedMiddleware(app, ex);
            }
        }
コード例 #20
0
ファイル: ModelDicts.cs プロジェクト: AlCher2018/KDS
        public static bool UpdateModelDictsFromDB(out string errMsg)
        {
            errMsg = "";
            // список статусов -> в словарь
            List <OrderStatusModel> list1 = DBOrderHelper.GetOrderStatusesList();

            if (list1 == null)
            {
                errMsg = DBOrderHelper.ErrorMessage;
                return(false);
            }
            list1.ForEach(item => _statuses.Add(item.Id, item));

            // список отделов -> в словарь
            // а также обновить словарь кол-ва блюд по цехам
            Dictionary <int, decimal> depQty = (Dictionary <int, decimal>)AppProperties.GetProperty("dishesQty");

            depQty.Clear();
            List <DepartmentModel> list2 = DBOrderHelper.GetDepartmentsList();

            if (list2 == null)
            {
                errMsg = DBOrderHelper.ErrorMessage;
                return(false);
            }
            list2.ForEach(item =>
            {
                _departments.Add(item.Id, item);
                depQty.Add(item.Id, 0m);
            });

            return(true);
        }
コード例 #21
0
        public void ProcessNodes_EndWordNotFoundFound_EventNotFired()
        {
            bool completeEventRaised = false;;

            _nodeProcessor.OnComplete += (o, e) => { completeEventRaised = true; };

            List <Node> nodes = new List <Node>();

            nodes.Add(new Node()
            {
                Word = "test"
            });
            nodes.Add(new Node()
            {
                Word = "cast"
            });

            AppProperties props = new AppProperties();

            props.StartWord = "rats";
            props.EndWord   = "cats";
            props.WordList  = new List <string>()
            {
                "test", "cats", "rats", "spin"
            };

            bool result = _nodeProcessor.ProcessNodes(nodes, props);

            Assert.IsFalse(result);
            Assert.IsFalse(completeEventRaised);
        }
コード例 #22
0
        public static IAppBuilder UseSimpleInjectorResolver(this IAppBuilder app, ScopedLifestyle lifestyle, Func <Container, Container> serviceRegistration)
        {
            if (app.GetSimpleInjectorResolver() == null)
            {
                //set the owin resolution context
                app.Properties[OWINResolutionContext] = new SimpleInjectorOwinResolutionContext(lifestyle, serviceRegistration);

                //shutdown delegate
                var token = new AppProperties(app.Properties).OnAppDisposing;
                if (token != CancellationToken.None)
                {
                    token.Register(() => app.GetSimpleInjectorResolver().Dispose());
                }

                app.Use(async(cxt, next) =>
                {
                    using (app.GetSimpleInjectorResolver().NewResolutionScope())
                    {
                        await next();
                    }
                });
            }

            return(app);
        }
コード例 #23
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            //initialize the ClusterHelper
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List <Uri>
                {
                    new Uri("http://localhost:8091/")
                }
            });

            //Register a callback that will dispose of the ClusterHelper on app shutdown
            var properties = new AppProperties(app.Properties);
            var token      = properties.OnAppDisposing;

            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    ClusterHelper.Close();
                });
            }
        }
コード例 #24
0
ファイル: Startup.cs プロジェクト: okusnadi/ModernShopping
        public static void UseIdentityServerBearerTokenAuthentication(this IApplicationBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var builder           = new Microsoft.Owin.Builder.AppBuilder();
                    var loggerFactory     = app.ApplicationServices.GetService <Microsoft.Framework.Logging.ILoggerFactory>();
                    var lifetime          = app.ApplicationServices.GetService <IApplicationLifetime>();
                    var owinLoggerFactory = new OwinLoggerFactory(loggerFactory);
                    var provider          = app.ApplicationServices.GetService(typeof(Microsoft.AspNet.DataProtection.IDataProtectionProvider)) as Microsoft.AspNet.DataProtection.IDataProtectionProvider;

                    var properties            = new AppProperties(builder.Properties);
                    properties.OnAppDisposing = lifetime.ApplicationStopping;
                    properties.DefaultApp     = next;

                    builder.SetLoggerFactory(owinLoggerFactory);
                    builder.Properties["security.DataProtectionProvider"] = new DataProtectionProviderDelegate(purposes =>
                    {
                        var dataProtection = provider.CreateProtector(string.Join(",", purposes));
                        return(new DataProtectionTuple(dataProtection.Protect, dataProtection.Unprotect));
                    });

                    builder.UseIdentityServerBearerTokenAuthentication(options);
                    return(builder.Build(typeof(Func <IDictionary <string, object>, Task>)) as Func <IDictionary <string, object>, Task>);
                });
            });
        }
コード例 #25
0
 // сообщения о действиях клиента
 public static void WriteLogClientAction(string machineName, string msg)
 {
     if (AppProperties.GetBoolProperty("IsLogClientAction"))
     {
         _logger.Trace(string.Format("clt {0}|{1}", machineName, msg));
     }
 }
コード例 #26
0
        public void Configuration(IAppBuilder app)
        {
            // These next two lines configure IocModules package to use Ninject as the IOC container
            var packageLocator = new PackageLocator().ProbeBinFolderAssemblies();
            var ninject        = new StandardKernel(new Ioc.Modules.Ninject.Module(packageLocator));

            // Use this Ninject container as the Prius factory
            Package.PriusFactory.Ninject = ninject;

            // Tell urchin to get its configuration from the config.json file in this project. Note that if
            // you edit this file whilst the site is running the changes will be applied without
            // restarting the site.
            var configFile = new FileInfo(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "config.json");
            var configurationFileSource = ninject.Get <FileSource>().Initialize(configFile, TimeSpan.FromSeconds(5));

            // Use the Owin Framework to build the OWIN pipeline
            BuildPipeline(app, ninject);

            // Register an OWIN app disposing handler that frees resources
            var properties = new AppProperties(app.Properties);
            var token      = properties.OnAppDisposing;

            token.Register(() =>
            {
                configurationFileSource.Dispose();
                ninject.Dispose();
            });
        }
コード例 #27
0
        public virtual void Configuration(IAppBuilder app)
        {
            var properties         = new AppProperties(app.Properties);
            var configuration      = new HttpConfiguration();
            var httpServer         = new HttpServer(configuration);
            var assembliesResolver = configuration.Services.GetAssembliesResolver();
            var appSettingsPath    = Combine(GetDirectoryName(AppDomain.CurrentDomain.SetupInformation.ConfigurationFile), "appsettings.config");
            var dependencyResolver = new CompositionDependencyResolver(assembliesResolver, appSettingsPath, ApplyWebApiConventions);
            var observers          = new IObserver <IMessageDescriptor> [0];

            if (app.Properties.TryGetValue("bus.Observers", out object value))
            {
                observers = (IObserver <IMessageDescriptor>[])value;
            }

            configuration.MessageHandlers.Add(new LogicalHttpRequestMessage());
            configuration.Filters.Add(new SimpleAuthentiationFilter());
            configuration.DependencyResolver = dependencyResolver;
            configuration.AddApiVersioning();
            configuration.ConfigureOData(httpServer);
            app.UseWebApi(httpServer);
            bus = dependencyResolver.GetRequiredService <MessageBus>();
            properties.OnAppDisposing.Register(ShutDownBus);
            bus.Start(observers);
        }
コード例 #28
0
        public static void Configure(this IAppBuilder app, AppProperties properties, IKernel kernel, Action <IOwinConfiguration> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }
            if (kernel == null)
            {
                throw new ArgumentNullException(nameof(kernel));
            }
            if (configuration == null)
            {
                throw new ArgumentNullException(nameof(configuration));
            }

            HttpConfiguration httpConfiguration = new HttpConfiguration();

            configuration(new OwinConfiguration(app, properties, httpConfiguration, kernel));

            ConfigureJson(httpConfiguration);
            ConfigureServices(kernel, httpConfiguration);

            MapRoutes(httpConfiguration);

            app.UseWebApi(httpConfiguration);
        }
コード例 #29
0
        private static void setGlobalValueFromCfg <T>(string cfgElementName, T defaultValue, string globVarName = null)
        {
            string sCfgValue = CfgFileHelper.GetAppSetting(cfgElementName);

            AppProperties.SetProperty(((globVarName == null) ? cfgElementName : globVarName),
                                      (string.IsNullOrEmpty(sCfgValue) ? defaultValue : getValueFromString(ref sCfgValue, typeof(T))));
        }
コード例 #30
0
        public static void UseIdentityServerBearerTokenAuthentication(this IApplicationBuilder app, IdentityServerBearerTokenAuthenticationOptions options)
        {
            app.UseOwin(addToPipeline =>
            {
                addToPipeline(next =>
                {
                    var builder = new Microsoft.Owin.Builder.AppBuilder();
                    var loggerFactory = app.ApplicationServices.GetService<Microsoft.Extensions.Logging.ILoggerFactory>();
                    var lifetime = app.ApplicationServices.GetService<IApplicationLifetime>();
                    var owinLoggerFactory = new OwinLoggerFactory(loggerFactory);
                    var provider = app.ApplicationServices.GetService(typeof(Microsoft.AspNet.DataProtection.IDataProtectionProvider)) as Microsoft.AspNet.DataProtection.IDataProtectionProvider;

                    var properties = new AppProperties(builder.Properties);
                    properties.OnAppDisposing = lifetime.ApplicationStopping;
                    properties.DefaultApp = next;

                    builder.SetLoggerFactory(owinLoggerFactory);
                    builder.Properties["security.DataProtectionProvider"] = new DataProtectionProviderDelegate(purposes =>
                    {
                        var dataProtection = provider.CreateProtector(string.Join(",", purposes));
                        return new DataProtectionTuple(dataProtection.Protect, dataProtection.Unprotect);
                    });

                    builder.UseIdentityServerBearerTokenAuthentication(options);
                    return builder.Build(typeof(Func<IDictionary<string, object>, Task>)) as Func<IDictionary<string, object>, Task>;
                });
            });
        }
コード例 #31
0
        /// <summary>
        /// Adds a new OpenID Connect server instance in the OWIN pipeline.
        /// </summary>
        /// <param name="app">The web application builder.</param>
        /// <param name="configuration">
        /// A delegate allowing to modify the options
        /// controlling the behavior of the OpenID Connect server.
        /// </param>
        /// <returns>The application builder.</returns>
        public static IAppBuilder UseOpenIdConnectServer(
            [NotNull] this IAppBuilder app,
            [NotNull] Action <OpenIdConnectServerOptions> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            var options = new OpenIdConnectServerOptions();

            // By default, enable AllowInsecureHttp in development environments.
            var environment = new AppProperties(app.Properties).Get <string>("host.AppMode");

            options.AllowInsecureHttp = string.Equals(environment, "Development", StringComparison.OrdinalIgnoreCase);

            configuration(options);

            return(app.UseOpenIdConnectServer(options));
        }
コード例 #32
0
        public static IApplicationBuilder UseOwinAppBuilder(this IApplicationBuilder app, Action<IAppBuilder> configuration)
        {
            if (app == null)
            {
                throw new ArgumentNullException(nameof(app));
            }

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

            return app.UseOwin(setup => setup(next => {
                var builder = new AppBuilder();
                var lifetime = (IApplicationLifetime)app.ApplicationServices.GetService(typeof(IApplicationLifetime));
                
                var properties = new AppProperties(builder.Properties);
                properties.AppName = Guid.NewGuid().ToString();
                properties.OnAppDisposing = lifetime.ApplicationStopping;
                properties.DefaultApp = next;

                configuration(builder);

                return builder.Build<Func<IDictionary<string, object>, Task>>();
            }));
        }
コード例 #33
0
 public static void WriteLogOrderDetails(string format, params object[] paramArray)
 {
     if (AppProperties.GetBoolProperty("IsWriteTraceMessages") && AppProperties.GetBoolProperty("TraceOrdersDetails"))
     {
         string msg = string.Format(format, paramArray);
         _logger.Trace("svcDtl|" + msg);
     }
 }
コード例 #34
0
 /// <summary>
 /// Captures synchronous and asynchronous exceptions from the pipeline and generates HTML error responses.
 /// Full error details are only displayed by default if 'host.AppMode' is set to 'development' in the IAppBuilder.Properties.
 /// </summary>
 /// <param name="builder"></param>
 /// <param name="options"></param>
 /// <returns></returns>
 public static IAppBuilder UseErrorPage(this IAppBuilder builder, ErrorPageOptions options)
 {
     if (builder == null)
     {
         throw new ArgumentNullException("builder");
     }
     string appMode = new AppProperties(builder.Properties).Get<string>(Constants.HostAppMode);
     bool isDevMode = string.Equals(Constants.DevMode, appMode, StringComparison.Ordinal);
     return builder.Use<ErrorPageMiddleware>(options, isDevMode);
 }
コード例 #35
0
ファイル: Startup.cs プロジェクト: movia/rps_webapp
        public void Configuration(IAppBuilder app)
        {
            var log = LogManager.GetLogger<Startup>();
            log.Info("Application is starting using OWIN.");

            log.Info("Injecting SignalR Middleware.");
            var hubConfiguration = new HubConfiguration();
            hubConfiguration.EnableDetailedErrors = true;
            app.MapSignalR(hubConfiguration);

            var httpConfiguration = new HttpConfiguration();

            httpConfiguration.Formatters.Clear();
            httpConfiguration.Formatters.Add(new JsonMediaTypeFormatter());

            httpConfiguration.Formatters.JsonFormatter.SerializerSettings =
                new JsonSerializerSettings
                {
                    ContractResolver = new CamelCasePropertyNamesContractResolver()
                };

            httpConfiguration.MapHttpAttributeRoutes();

            httpConfiguration.Routes.MapHttpRoute(
                name: "WsiProxy",
                routeTemplate: "wsi/{*path}",
                handler: HttpClientFactory.CreatePipeline(
                    innerHandler: new HttpClientHandler(), // will never get here if proxy is doing its job
                    handlers: new DelegatingHandler[] { new WsiProxyHandler() }
                  ),
                defaults: new { path = RouteParameter.Optional },
                constraints: null
            );

            log.Info("Injecting WebApi Middleware.");
            app.UseWebApi(httpConfiguration);

            var properties = new AppProperties(app.Properties);
            CancellationToken token = properties.OnAppDisposing;

            log.Info("Starting Background Services.");

            var rpsAdapter = new RpsAdapter() { CancellationToken = token };
            DataProviderManager.Instance.PositionAdapters.Add(rpsAdapter);
            DataProviderManager.Instance.Startup(token);

            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    log.Info("Application is stopping.");
                });
            }
        }
コード例 #36
0
 private void ConfigureShutdown(IAppBuilder app)
 {
     var properties = new AppProperties(app.Properties);
     CancellationToken token = properties.OnAppDisposing;
     if (token != CancellationToken.None)
     {
         token.Register(() =>
         {
             IUnityContainer container = UnityConfig.GetConfiguredContainer();
             container.Dispose();
             Dispose();
         });
     }
 }
コード例 #37
0
        /// <summary>
        /// Provides a Katana/ASP.NET Core bridge allowing to register middleware designed for OWIN/Katana.
        /// </summary>
        /// <param name="app">The ASP.NET Core application builder.</param>
        /// <param name="configuration">
        /// The delegate allowing to configure the OWIN/Katana
        /// pipeline before adding it in the ASP.NET Core application.
        /// </param>
        /// <returns>The ASP.NET Core application builder.</returns>
        public static IApplicationBuilder UseKatana(
            [NotNull] this IApplicationBuilder app,
            [NotNull] Action<IAppBuilder> configuration) {
            return app.UseOwin(setup => setup(next => {
                var builder = new AppBuilder();
                var lifetime = app.ApplicationServices.GetService<IApplicationLifetime>();

                var properties = new AppProperties(builder.Properties);
                properties.AppName = app.ApplicationServices.GetService<IHostingEnvironment>()?.ContentRootPath;
                properties.OnAppDisposing = lifetime?.ApplicationStopping ?? CancellationToken.None;
                properties.DefaultApp = next;

                configuration(builder);

                return builder.Build<Func<IDictionary<string, object>, Task>>();
            }));
        }
コード例 #38
0
        public void Configuration(IAppBuilder app)
        {
            ConfigureAuth(app);

            //initialize the ClusterHelper
            ClusterHelper.Initialize(new ClientConfiguration
            {
                Servers = new List<Uri>
                {
                    new Uri("http://localhost:8091/")
                }
            });

            //Register a callback that will dispose of the ClusterHelper on app shutdown
            var properties = new AppProperties(app.Properties);
            var token = properties.OnAppDisposing;
            if (token != CancellationToken.None)
            {
                token.Register(() =>
                {
                    ClusterHelper.Close();
                });
            }
        }
コード例 #39
0
        private IContainer CreateKernel(IAppBuilder app)
        {
            var settings = new IntegrationSettings
            {
                PathToXmiFiles = "App_Data/Xmi",
                EstablishDataEnvironment = true
            };

            var kernel = new ContainerBuilder();
            var container = kernel.UseDatenMeisterDotNet(settings);

            // Defines the shutdown
            var properties = new AppProperties(app.Properties);
            var token = properties.OnAppDisposing;
            token.Register(() =>
            {
                _lifetimeScope.UnuseDatenMeister();
            });

            return container;
        }