Example #1
0
        protected void Application_Start(object sender, EventArgs e)
        {
            #region Signalr
            var builder = new ContainerBuilder();
            builder.RegisterHubs(Assembly.GetExecutingAssembly()).PropertiesAutowired();
            builder.RegisterType <DebugLogger>().As <IHubLogger>();
            var container = builder.Build();
            var resolver  = new AutofacDependencyResolver(container);
            GlobalHost.HubPipeline.AddModule(new LoggingPipelineModule(resolver.Resolve <IHubLogger>()));
            GlobalHost.HubPipeline.AddModule(new ErrorHandlingPipelineModule(resolver.Resolve <IHubLogger>()));
            var authorizer = new HubAuthorizeAttribute();
            var module     = new AuthorizeModule(authorizer, authorizer);
            GlobalHost.HubPipeline.AddModule(module);
            GlobalHost.HubPipeline.RequireAuthentication();
            GlobalHost.DependencyResolver = new AutofacDependencyResolver(container);
            #endregion

            AutoMapperUtil.Execute();
            //var aTimer = new System.Timers.Timer();

            //aTimer.Elapsed += aTimer_Elapsed;
            //aTimer.Interval = 20000;
            //aTimer.Enabled = true;

            ValueProviderFactories.Factories.Remove(ValueProviderFactories.Factories.OfType <JsonValueProviderFactory>().FirstOrDefault());
            ValueProviderFactories.Factories.Add(new JsonNetValueProviderFactory());

            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            ModelBundle.RegisterBindles(ModelBinders.Binders);

            ConsulUtil.StartWatchConsulServices();
        }
Example #2
0
        public async Task ConfigureAsync(IAppBuilder app)
        {
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = JsonHelper.GetJsonSerializerSettings();

            app.Map
            (
                "/signalr",
                map =>
            {
                map.UseCors(CorsOptions.AllowAll);

                var configuration = new HubConfiguration
                {
                    EnableJavaScriptProxies = true
                };

                map.RunSignalR(configuration);
                var module = new AuthorizeModule(null, null);
                GlobalHost.HubPipeline.AddModule(module);
            });


            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new FrapidRazorViewEngine());
            LogManager.InternalizeLogger();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            AssetConfig.Register();
            await StartupRegistration.RegisterAsync().ConfigureAwait(false);

            BackupRegistration.Register();
            EodTaskRegistration.Register();
            AccountConfig.Register(app);
        }
Example #3
0
        public void Configuration(IAppBuilder app)
        {
            app.Map
            (
                "/signalr",
                map =>
            {
                map.UseCors(CorsOptions.AllowAll);

                var configuration = new HubConfiguration
                {
                    EnableJavaScriptProxies = true
                };

                map.RunSignalR(configuration);
                var module = new AuthorizeModule(null, null);
                GlobalHost.HubPipeline.AddModule(module);
            });

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new FrapidRazorViewEngine());

            LogManager.InternalizeLogger();
            AreaRegistration.RegisterAllAreas();
            WebApiConfig.Register(GlobalConfiguration.Configuration);
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            AssetConfig.Register();
            StartupRegistration.RegisterAsync().Wait();
            BackupRegistration.Register();
            EodTaskRegistration.Register();
            AccountConfig.Register(app);
        }
Example #4
0
        public void Configuration(IAppBuilder app)
        {
            try
            {
                var counter = CreateCounter();
                var mapper  = new MemoryConnectionMapper();
                var backend = CreateBackend();
                GlobalHost.DependencyResolver.Register(typeof(WorkerHub), () => new WorkerHub(mapper, backend, counter));

                var userMapper    = new MemoryConnectionMapper();
                var creatorMapper = new MemoryConnectionMapper();
                var notify        = Config.Instance.EachEventNotifyInLiveStream;
                var comments      = new MemoryMapper <Comment>(Config.Instance.CommentLength);
                var joined        = new MemoryMapper <StreamModel>(Config.Instance.JoinedLength);
                GlobalHost.DependencyResolver.Register(typeof(LiveStreamWorker),
                                                       () => new LiveStreamWorker(mapper, userMapper, creatorMapper, counter, notify, comments, joined));

                var settings = new JsonSerializerSettings {
                    ContractResolver = new SignalRContractResolver()
                };
                var serializer = JsonSerializer.Create(settings);
                GlobalHost.DependencyResolver.Register(typeof(JsonSerializer), () => serializer);

                var authorizer = new TokenAuthorizeAttribute(backend);
                var modul      = new AuthorizeModule(authorizer, authorizer);
                GlobalHost.HubPipeline.AddModule(modul);
                GlobalHost.HubPipeline.AddModule(new ValidationModule());
                GlobalHost.HubPipeline.AddModule(new SignalrErrorHandler());

                var groupNotifier = new GroupNotifier(comments, joined, userMapper,
                                                      Config.Instance.CommentPauseInSec,
                                                      Config.Instance.JoinedPauseInSec);
            }
            catch (Exception e)
            {
                Logger.Fatal(e);
                LogManager.Flush();
                Environment.Exit(-1);
            }

            var hubConf = new HubConfiguration
            {
                EnableDetailedErrors = Config.Instance.EnableHubDetailedErrors
                                       // EnableJavaScriptProxies = false
            };

            // if (Config.Instance.EnableScaleout)
            //    GlobalHost.DependencyResolver.UseRedis(Config.Instance.ScaleoutHost, Config.Instance.ScaleoutPort, Config.Instance.ScaleoutPwd, "Chat.Worker.Application");

            app.UseCors(CorsOptions.AllowAll);
            app.MapSignalR(hubConf);
        }
Example #5
0
 private void ConfigureSignalr(IAppBuilder app)
 {
     app.Map("/signalr", map =>
     {
         var hubConfig = new HubConfiguration
         {
             EnableDetailedErrors = true
         };
         var authorizer = new QueryStringBearerAuthorizeAttribute();
         var module     = new AuthorizeModule(authorizer, authorizer);
         GlobalHost.HubPipeline.AddModule(module);
         map.RunSignalR(hubConfig);
     });
 }
Example #6
0
        /// <summary>
        /// This method gets called by the runtime. Use this method to add services to the container.
        /// For more information on how to configure your application, visit http://go.microsoft.com/fwlink/?LinkID=398940
        /// </summary>
        /// <param name="services">The services.</param>
        public void ConfigureServices(IServiceCollection services)
        {
            // Add MVC services to the services container.
            // Build the intermediate service provider

            services.AddLocalization(options => options.ResourcesPath = "Resources");

            services.AddAntiforgery(options => options.HeaderName = "X-XSRF-TOKEN");

            services.AddScoped <ValidateMimeMultipartContentFilter>();

            // Add functionality to inject IOptions<T>
            services.AddOptions();

            // Add our Config object so it can be injected
            var appSettingsSection = Configuration.GetSection("AppSettings");

            services.Configure <AppSettings>(appSettingsSection);
            services.Configure <AppSettings>(settings =>
            {
                if (HttpContextAccessor.HttpContext == null)
                {
                    return;
                }
                var request       = HttpContextAccessor.HttpContext.Request;
                settings.Urls.Api = $"{request.Scheme}://{request.Host.ToUriComponent()}";
            });

            appSettingsSection.Bind(AppSettings);

            // *If* you need access to generic IConfiguration this is **required**
            services.AddSingleton(Configuration);

            ConfigAuth(services);

            // Enable Cors
            services.AddCors(options =>
            {
                options.AddPolicy("CorsPolicy",
                                  builder => builder
                                  .AllowAnyOrigin()
                                  .AllowAnyMethod()
                                  .AllowAnyHeader()
                                  .AllowCredentials()
                                  );
            });

            services.AddMvc(options =>
            {
                //http://www.dotnetcurry.com/aspnet/1314/aspnet-core-globalization-localization
                options.Conventions.Add(new HybridModelBinderApplicationModelConvention());
                options.Conventions.Add(new NameSpaceVersionRoutingConvention());
                // Make authentication compulsory across the board (i.e. shut
                // down EVERYTHING unless explicitly opened up).
                var policy = new AuthorizationPolicyBuilder()
                             .RequireAuthenticatedUser()
                             .RequireClaim(ClaimTypes.Name)
                             .RequireClaim(ClaimTypes.NameIdentifier)
                             .Build();

                options.Filters.Add(new AuthorizeFilter(policy));
            }
                            ).AddJsonOptions(opts =>
            {
                // Force Camel Case to JSON
                opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
            }
                                             )
            .AddViewLocalization()
            .AddDataAnnotationsLocalization();

            //https://www.billbogaiv.com/posts/hybrid-model-binding-in-aspnet-core-10-rc2
            services.Configure <MvcOptions>(options =>
            {
                /**
                 * This is needed since the provider uses the existing `BodyModelProvider`.
                 * Ref. https://github.com/aspnet/Mvc/blob/1.0.0-rc2/src/Microsoft.AspNetCore.Mvc.Core/ModelBinding/Binders/BodyModelBinder.cs
                 */
                var readerFactory = services.BuildServiceProvider().GetRequiredService <IHttpRequestStreamReaderFactory>();

                options.ModelBinderProviders.Insert(0, new DefaultHybridModelBinderProvider(options.InputFormatters, readerFactory));
                // options.Filters.Add(new CorsAuthorizationFilterFactory("CorsPolicy"));
            });

            services.AddSwaggerGen(c =>
            {
                c.SwaggerDoc("v1", new Info {
                    Title          = AppSettings.Information.Name,
                    Version        = AppSettings.Information.Version,
                    Description    = AppSettings.Information.Description,
                    TermsOfService = AppSettings.Information.TermsOfService,
                    Contact        = new Contact {
                        Name  = AppSettings.Information.ContactName,
                        Email = AppSettings.Information.ContactEmail
                    },
                    License = new License {
                        Name = AppSettings.Information.LicenseName,
                        Url  = AppSettings.Information.LicenseUrl
                    }
                });

                //Set the comments path for the swagger json and ui.
                var basePath = PlatformServices.Default.Application.ApplicationBasePath;
                var xmlPath  = Path.Combine(basePath, "MasterApi.xml");
                c.IncludeXmlComments(xmlPath);
            });

            // Injection
            services.AddTransient <IHttpContextAccessor, HttpContextAccessor>();

            services.Configure <RequestLocalizationOptions>(
                options => {
                var supportedCultures = new List <CultureInfo> {
                    new CultureInfo("en"),
                    new CultureInfo("en-US"),
                    new CultureInfo("pt"),
                    new CultureInfo("pt-BR")
                };
                var defaultCulture            = supportedCultures[1].Name;
                options.DefaultRequestCulture = new RequestCulture(defaultCulture, defaultCulture);
                options.SupportedCultures     = supportedCultures;
                options.SupportedUICultures   = supportedCultures;
            }
                );

            // SignalR
            var authorizer = new HubAuthorizeAttribute(_tokenOptions);
            var module     = new AuthorizeModule(authorizer, authorizer);

            services.AddSignalR(options =>
            {
                options.EnableJSONP = true;
                options.Hubs.EnableJavaScriptProxies = true;
                options.Hubs.EnableDetailedErrors    = true;
                options.Hubs.PipelineModules.Add(module);
            });

            services.AddCustomHeaders();

            var connString = Configuration.GetConnectionString("DbConnection");

            //services.AddDbContext<DualAuthContext>(options =>
            //	options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

            services.AddDbContext <AppDbContext>(options =>
            {
                switch (AppSettings.DbSettings.InMemoryProvider)
                {
                case true:
                    options.UseInMemoryDatabase(connString);
                    break;

                default:
                    options.UseSqlServer(connString, b => b.MigrationsAssembly("MasterApi.Data"));
                    break;
                }
            });

            services.AddHangfire(x => x.UseSqlServerStorage(connString));

            // Repositories
            services.AddScoped(typeof(IDataContextAsync), typeof(AppDbContext));
            services.AddScoped(typeof(IUnitOfWorkAsync), typeof(UnitOfWork));
            services.AddScoped(typeof(IRepositoryAsync <>), typeof(Repository <>));
            services.AddTransient <DataSeeder>();

            //Services
            services.AddScoped(typeof(IService <>), typeof(Service <>));

            services.AddScoped(typeof(IAuthService), typeof(AuthService));
            services.AddScoped(typeof(IUserAccountService), typeof(UserAccountService));
            services.AddScoped(typeof(INotificationService), typeof(NotificationService));
            services.AddScoped(typeof(IGeoService), typeof(GeoService));
            services.AddScoped(typeof(IUserProfileService), typeof(UserProfileService));
            services.AddScoped(typeof(ILookupService), typeof(LookupService));

            //Infrastructure
            services.AddSingleton(typeof(ICrypto), typeof(DefaultCrypto));
            services.AddSingleton(typeof(ISmsSender), typeof(SmsSender));
            services.AddSingleton(typeof(IEmailSender), typeof(EmailSender));

            services.AddSingleton(typeof(IRazorLightEngine), s => EngineFactory.CreatePhysical($"{Directory.GetCurrentDirectory()}\\Views"));

            var asm          = Assembly.GetEntryAssembly();
            var subjectFiles = asm.GetManifestResourceNames().Where(x => x.Contains("subjects.json"));

            var emailSubjects = new Dictionary <string, Dictionary <string, string> >();

            subjectFiles.ForEach(file => {
                var domain   = file.Split('.');
                var subjects = asm.ParseFromJson(file);
                emailSubjects.Add(domain[3], subjects);
            });

            services.AddSingleton(typeof(IEmailSubjects), emailSubjects);

            services.AddSingleton <IHttpContextAccessor, HttpContextAccessor>();

            //Identity
            services.AddScoped(typeof(IUserInfo), s => new UserIdentityInfo(s.GetService <IHttpContextAccessor>().HttpContext.User));
        }
Example #7
0
        public void Configuration(IAppBuilder app)
        {
            var builder = new ContainerBuilder();

            builder.RegisterControllers(Assembly.GetExecutingAssembly());

            // REGISTER DEPENDENCIES
            builder.RegisterType <UnitOfWork>().As <IUnitOfWork>().InstancePerRequest();
            builder.RegisterType <DbFactory>().As <IDbFactory>().InstancePerRequest();
            builder.RegisterType <OZChatDbContext>().AsSelf().InstancePerRequest();
            builder.RegisterType <ApplicationUserStore>().As <IUserStore <ApplicationUser> >().InstancePerRequest();
            builder.RegisterType <ApplicationUserManager>().AsSelf().InstancePerRequest();
            builder.RegisterType <ApplicationSignInManager>().AsSelf().InstancePerRequest();
            builder.Register <IAuthenticationManager>(c => HttpContext.Current.GetOwinContext().Authentication).InstancePerRequest();
            builder.Register <IDataProtectionProvider>(c => app.GetDataProtectionProvider()).InstancePerRequest();

            // REGISTER CONTROLLERS SO DEPENDENCIES ARE CONSTRUCTOR INJECTED
            //builder.RegisterControllers(typeof(MvcApplication).Assembly);

            // Repositories
            builder.RegisterAssemblyTypes(typeof(ApplicationRoleRepository).Assembly)
            .Where(t => t.Name.EndsWith("Repository"))
            .AsImplementedInterfaces().InstancePerRequest();

            // BUILD THE CONTAINER
            var container = builder.Build();

            // REPLACE THE MVC DEPENDENCY RESOLVER WITH AUTOFAC
            DependencyResolver.SetResolver(new AutofacDependencyResolver(container));

            // REGISTER WITH OWIN
            app.UseAutofacMiddleware(container);
            app.UseAutofacMvc();

            ConfigureAuth(app);
            app.UseCors(CorsOptions.AllowAll);
            //app.MapSignalR();
            app.Map("/signalr", map =>
            {
                // Setup the CORS middleware to run before SignalR.
                // By default this will allow all origins. You can
                // configure the set of origins and/or http verbs by
                // providing a cors options with a different policy.
                map.UseCors(CorsOptions.AllowAll);

                map.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions()
                {
                    Provider = new QueryStringOAuthBearerProvider()
                });

                var hubConfiguration = new HubConfiguration
                {
                    // You can enable JSONP by uncommenting line below.
                    // JSONP requests are insecure but some older browsers (and some
                    // versions of IE) require JSONP to work cross domain
                    EnableJSONP          = true,
                    EnableDetailedErrors = true
                };
                // Run the SignalR pipeline. We're not using MapSignalR
                // since this branch already runs under the "/signalr"
                // path.
                map.RunSignalR(hubConfiguration);
                var authorizer = new CAuthorizeAttribute();
                var module     = new AuthorizeModule(authorizer, authorizer);
                GlobalHost.HubPipeline.AddModule(module);
            });
        }