示例#1
0
 public AccountController(AlbumViewerContext ctx,
                          IServiceProvider svcProvider)
 //SignInManager<User> signInManager)
 {
     context         = ctx;
     serviceProvider = svcProvider;
 }
        public async Task <IEnumerable> Artists()
        {
            // For demonstration use a manually instantiated instance of
            // the dbContext.
            //
            // Note the need to pass in serviceProvider or *something*
            // that gives access to the Configuration so the connection
            // string from config can be found.
            //
            // This overload is what EF uses internally to create a
            // to create a configured instance of a context.
            //
            // Scoped instances of Context can be problematic in some
            // controllers - you're incurring overhead for each hit even
            // if context is isn't used in an action. If you need multiple instances
            // of contexts you may also need to manually instantiate.
            using (var ctxt = new AlbumViewerContext(serviceProvider))
            {
                var result = await ctxt.Artists
                             .OrderBy(art => art.ArtistName)
                             .Select(art => new
                {
                    art.ArtistName,
                    art.Description,
                    art.ImageUrl,
                    art.Id,
                    AlbumCount = context.Albums.Count(alb => alb.ArtistId == art.Id)
                })
                             .ToListAsync();

                return(result);
            }
        }
示例#3
0
        public AlbumApiController(AlbumViewerContext context, ArtistRepository artistRepository, ILogger <AlbumApiController> logger)
        {
            this._context = context;

            this._artistRepository = artistRepository;

            this._logger = logger;
        }
示例#4
0
        public void ImportAlbumData()
        {
            File.Delete("AlbumViewerData.sqlite");

            var Context = new AlbumViewerContext()
            {
                useSqLite        = true,
                ConnectionString = "server=.;database=AlbumViewer2;integrated security=true;MultipleActiveResultSets=true;App=AlbumViewer"
            };

            AlbumViewerDataImporter.EnsureAlbumData(Context, Path.GetFullPath("./albums.js"));
        }
示例#5
0
        public void SetUp()
        {
            _connection = new SqliteConnection("DataSource=:memory:");
            _connection.Open();

            var options = new DbContextOptionsBuilder <AlbumViewerContext>()
                          .UseSqlite(_connection)
                          .Options;

            _albumViewerContext = new AlbumViewerContext(options);

            _albumViewerContext.Database.EnsureCreated();
        }
        public AlbumViewerApiController(
            AlbumViewerContext ctx,
            IServiceProvider svcProvider,
            IArtistRepository artistRepo,
            IAlbumRepository albumRepo,
            IConfiguration config,
            ILogger <AlbumViewerApiController> logger,
            IHostingEnvironment env)
        {
            context = ctx;

            AlbumRepo = albumRepo;
        }
        public AlbumViewerApiController(
            AlbumViewerContext ctx,
            IServiceProvider svcProvider,
            ArtistRepository artistRepo,
            AlbumRepository albumRepo,
            IConfiguration config)
        {
            context         = ctx;
            serviceProvider = svcProvider;
            Configuration   = config;

            AlbumRepo  = albumRepo;
            ArtistRepo = artistRepo;
        }
示例#8
0
        public AlbumViewerApiController(
            AlbumViewerContext ctx,
            IServiceProvider svcProvider,
            ArtistRepository artistRepo,
            AlbumRepository albumRepo,
            IConfiguration config,
            ILogger <AlbumViewerApiController> logger,
            IWebHostEnvironment env)
        {
            context         = ctx;
            serviceProvider = svcProvider;
            Configuration   = config;

            AlbumRepo  = albumRepo;
            ArtistRepo = artistRepo;
            Logger     = logger;

            HostingEnv = env;
        }
示例#9
0
        public void EfCoreQueryWithSqLiteDataBug()
        {
            var Context = new AlbumViewerContext()
            {
                useSqLite = true
            };


            IQueryable <Album> albums = Context.Albums
                                        .Include(ctx => ctx.Tracks)
                                        .Include(ctx => ctx.Artist)
                                        .OrderBy(alb => alb.Artist);


            var list = albums.ToList();

            var listUninitialized = list.Where(a => a.Artist.Id == 0).ToList();

            Assert.IsTrue(list.Count > 80, $"Total number of records should be greater than 80 but is {list.Count}");
            Assert.IsTrue(listUninitialized.Count == 0,
                          $"There are {listUninitialized.Count} uninitialized Artist records");
        }
示例#10
0
        public void SetUp()
        {
            _connection = new SqliteConnection("DataSource=:memory:");
            _connection.Open();

            var options = new DbContextOptionsBuilder <AlbumViewerContext>()
                          .UseSqlite(_connection)
                          .Options;

            _albumViewerContext = new AlbumViewerContext(options);

            _albumViewerContext.Database.EnsureCreated();

            _serviceProvider    = Substitute.For <IServiceProvider>();
            _artistRepository   = Substitute.For <IArtistRepository>();
            _albumRepository    = Substitute.For <IAlbumRepository>();
            _configuration      = Substitute.For <IConfiguration>();
            _logger             = Substitute.For <ILogger <AlbumViewerApiController> >();
            _hostingEnvironment = Substitute.For <IHostingEnvironment>();

            _sut = new AlbumViewerApiController(_albumViewerContext, _serviceProvider, _artistRepository,
                                                _albumRepository, _configuration, _logger, _hostingEnvironment);
        }
 public AlbumViewerMvcController(AlbumViewerContext ctx, IServiceProvider svcProvider)
 {
     context         = ctx;
     serviceProvider = svcProvider;
     //this.environment = environment;
 }
 public AlbumViewerApiController(AlbumViewerContext ctx, IServiceProvider svcProvider)
 {
     context         = ctx;
     serviceProvider = svcProvider;
 }
示例#13
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IWebHostEnvironment env,
                              ILoggerFactory loggerFactory,
                              AlbumViewerContext albumContext,
                              IConfiguration configuration)
        {
            //// Serilog config -  add logfile output
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.RollingFile(pathFormat: "logs\\log-{Date}.log")
                         .CreateLogger();

            loggerFactory
            .AddSerilog();


            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }
            else
            {
                app.UseExceptionHandler(errorApp =>

                                        // Application level exception handler here - this is just a place holder
                                        errorApp.Run(async(context) =>
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>\r\n");
                    await context.Response.WriteAsync(
                        "We're sorry, we encountered an un-expected issue with your application.<br>\r\n");

                    // Capture the exception
                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        // This error would not normally be exposed to the client
                        await
                        context.Response.WriteAsync("<br>Error: " +
                                                    HtmlEncoder.Default.Encode(error.Error.Message) +
                                                    "<br>\r\n");
                    }
                    await context.Response.WriteAsync("<br><a href=\"/\">Home</a><br>\r\n");
                    await context.Response.WriteAsync("</body></html>\r\n");
                    await context.Response.WriteAsync(new string(' ', 512));                                     // Padding for IE
                }));
            }

            //app.UseHttpsRedirection();

            Console.WriteLine("\r\nPlatform: " + System.Runtime.InteropServices.RuntimeInformation.OSDescription);
            string useSqLite = Configuration["Data:useSqLite"];

            Console.WriteLine(useSqLite == "true" ? "SqLite" : "Sql Server");

            app.UseRouting();

            app.UseCors("CorsPolicy");


            app.UseAuthentication();
            app.UseAuthorization();

            //app.UseDatabaseErrorPage();
            app.UseStatusCodePages();

            app.UseDefaultFiles(); // so index.html is not required
            app.UseStaticFiles();


            // Handle Lets Encrypt Route (before MVC processing!)
            // alternately use an MVC Route (in ConfigurationController)
            //app.UseRouter(r =>
            //{
            //    r.MapGet(".well-known/acme-challenge/{id}", async (request, response, routeData) =>
            //    {
            //        var id = routeData.Values["id"] as string;
            //        var file = Path.Combine(env.WebRootPath, ".well-known","acme-challenge", id);
            //        await response.SendFileAsync(file);
            //    });
            //});

            //// put last so header configs like CORS or Cookies etc can fire
            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
                // .RequireCors("CorsPolicy"); // doesn't seem to work - .UseCors("CorsPolicy") still required
            });

            // catch-all handler for HTML5 client routes - serve index.html
            app.Run(async context =>
            {
                // Make sure Angular output was created in wwwroot
                // Running Angular in dev mode nukes output folder!
                // so it could be missing.
                if (env.WebRootPath == null)
                {
                    throw new InvalidOperationException("wwwroot folder doesn't exist. Please recompile your Angular Project before accessing index.html. API calls will work fine.");
                }

                context.Response.ContentType = "text/html";
                await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
            });

            // Initialize Database if it doesn't exist
            AlbumViewerDataImporter.EnsureAlbumData(albumContext,
                                                    Path.Combine(env.ContentRootPath, "albums.js"));
        }
示例#14
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              AlbumViewerContext albumContext)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                loggerFactory.AddConsole(Configuration.GetSection("Logging"));
                loggerFactory.AddDebug();
            }
            else
            {
                app.UseExceptionHandler(errorApp =>

                                        // Application level exception handler here - this is just a place holder
                                        errorApp.Run(async(context) =>
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>\r\n");
                    await
                    context.Response.WriteAsync(
                        "We're sorry, we encountered an un-expected issue with your application.<br>\r\n");

                    // Capture the exception
                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        // This error would not normally be exposed to the client
                        await
                        context.Response.WriteAsync("<br>Error: " +
                                                    HtmlEncoder.Default.Encode(error.Error.Message) +
                                                    "<br>\r\n");
                    }
                    await context.Response.WriteAsync("<br><a href=\"/\">Home</a><br>\r\n");
                    await context.Response.WriteAsync("</body></html>\r\n");
                    await context.Response.WriteAsync(new string(' ', 512));         // Padding for IE
                }));


                //loggerFactory.AddConsole(Configuration.GetSection("Logging"));

                //app.UseExceptionHandler("/");
                //app.UseExceptionHandler("/Home/Error");
            }

            //app.UseCors("CorsPolicy");

            // Enable Cookie Auth with automatic user policy
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = false,
                LoginPath             = "/api/login"
            });


            app.UseDatabaseErrorPage();
            app.UseStatusCodePages();

            app.UseDefaultFiles(); // so index.html is not required
            app.UseStaticFiles();

            // put last so header configs like CORS or Cookies etc can fire
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });



            AlbumViewerDataImporter.EnsureAlbumData(albumContext,
                                                    Path.Combine(env.WebRootPath, "App_Data/albums.js"));
        }
示例#15
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              AlbumViewerContext albumContext,
                              IConfiguration configuration)
        {
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.RollingFile(pathFormat: "logs\\log-{Date}.log")
                         .CreateLogger();

            if (env.IsDevelopment())
            {
                loggerFactory.WithFilter(new FilterLoggerSettings
                {
                    { "Trace", LogLevel.Trace },
                    { "Default", LogLevel.Trace },
                    { "Microsoft", LogLevel.Warning },   // very verbose
                    { "System", LogLevel.Warning }
                })
                .AddConsole()
                .AddSerilog();

                app.UseDeveloperExceptionPage();
            }
            else
            {
                loggerFactory.WithFilter(new FilterLoggerSettings
                {
                    { "Trace", LogLevel.Trace },
                    { "Default", LogLevel.Trace },
                    { "Microsoft", LogLevel.Warning },   // very verbose
                    { "System", LogLevel.Warning }
                })
                .AddSerilog();

                app.UseExceptionHandler(errorApp =>

                                        // Application level exception handler here - this is just a place holder
                                        errorApp.Run(async(context) =>
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>\r\n");
                    await
                    context.Response.WriteAsync(
                        "We're sorry, we encountered an un-expected issue with your application.<br>\r\n");

                    // Capture the exception
                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        // This error would not normally be exposed to the client
                        await
                        context.Response.WriteAsync("<br>Error: " +
                                                    HtmlEncoder.Default.Encode(error.Error.Message) +
                                                    "<br>\r\n");
                    }
                    await context.Response.WriteAsync("<br><a href=\"/\">Home</a><br>\r\n");
                    await context.Response.WriteAsync("</body></html>\r\n");
                    await context.Response.WriteAsync(new string(' ', 512));         // Padding for IE
                }));


                //loggerFactory.AddConsole();
                //app.UseExceptionHandler("/");
                //app.UseExceptionHandler("/Home/Error");
            }

            // enable this to log ASP.NET messages into the log
            // not very useful except for troubleshooting
            //loggerFactory.WithFilter(new FilterLoggerSettings
            //        {
            //            {"Trace",LogLevel.Information },
            //            {"Default", LogLevel.Information},
            //            {"Microsoft", LogLevel.Warning}, // very verbose
            //            {"System", LogLevel.Warning}
            //        })
            //        .AddConsole()
            //        .AddSerilog();
            // loggerFactory.AddSerilog(new LoggerConfiguration()
            //    .WriteTo.RollingFile(pathFormat: "asp-logs\\log-{Date}.log")
            //    .CreateLogger();

            //app.UseCors("CorsPolicy");

            // Enable Cookie Auth with automatic user policy
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = false,
                LoginPath             = "/api/login"
            });

            app.UseDatabaseErrorPage();
            app.UseStatusCodePages();

            app.UseDefaultFiles(); // so index.html is not required
            app.UseStaticFiles();

            // put last so header configs like CORS or Cookies etc can fire
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });



            AlbumViewerDataImporter.EnsureAlbumData(albumContext,
                                                    Path.Combine(env.ContentRootPath, "albums.js"));
        }
示例#16
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app,
                              IHostingEnvironment env,
                              ILoggerFactory loggerFactory,
                              AlbumViewerContext albumContext,
                              IConfiguration configuration)
        {
            // Serilog config
            Log.Logger = new LoggerConfiguration()
                         .WriteTo.RollingFile(pathFormat: "logs\\log-{Date}.log")
                         .CreateLogger();

            if (env.IsDevelopment())
            {
                //loggerFactory.WithFilter(new FilterLoggerSettings
                //	{
                //		{"Trace", LogLevel.Trace},
                //		{"Default", LogLevel.Trace},
                //		{"Microsoft", LogLevel.Warning}, // very verbose
                //                    {"System", LogLevel.Warning}
                //	})

                loggerFactory
                .AddDebug()
                .AddConsole()
                .AddSerilog();

                app.UseDeveloperExceptionPage();
            }
            else
            {
                loggerFactory
                //.WithFilter(new FilterLoggerSettings
                //{
                //	{"Trace", LogLevel.Trace},
                //	{"Default", LogLevel.Trace},
                //	{"Microsoft", LogLevel.Warning}, // very verbose
                //                   {"System", LogLevel.Warning}
                //})
                .AddSerilog();

                app.UseExceptionHandler(errorApp =>

                                        // Application level exception handler here - this is just a place holder
                                        errorApp.Run(async(context) =>
                {
                    context.Response.StatusCode  = 500;
                    context.Response.ContentType = "text/html";
                    await context.Response.WriteAsync("<html><body>\r\n");
                    await context.Response.WriteAsync(
                        "We're sorry, we encountered an un-expected issue with your application.<br>\r\n");

                    // Capture the exception
                    var error = context.Features.Get <IExceptionHandlerFeature>();
                    if (error != null)
                    {
                        // This error would not normally be exposed to the client
                        await
                        context.Response.WriteAsync("<br>Error: " +
                                                    HtmlEncoder.Default.Encode(error.Error.Message) +
                                                    "<br>\r\n");
                    }
                    await context.Response.WriteAsync("<br><a href=\"/\">Home</a><br>\r\n");
                    await context.Response.WriteAsync("</body></html>\r\n");
                    await context.Response.WriteAsync(new string(' ', 512));                                     // Padding for IE
                }));

                //app.UseExceptionHandler("/");
                //app.UseExceptionHandler("/Home/Error");
            }

            Console.WriteLine("\r\nPlatform: " + System.Runtime.InteropServices.RuntimeInformation.OSDescription);
            string useSqLite = Configuration["Data:useSqLite"];

            Console.WriteLine(useSqLite == "true" ? "SqLite" : "Sql Server");

            app.UseAuthentication();

            app.UseDatabaseErrorPage();
            app.UseStatusCodePages();

            app.UseDefaultFiles(); // so index.html is not required
            app.UseStaticFiles();

            // put last so header configs like CORS or Cookies etc can fire
            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            // catch-all handler for HTML5 client routes - serve index.html
            app.Run(async context =>
            {
                context.Response.ContentType = "text/html";
                await context.Response.SendFileAsync(Path.Combine(env.WebRootPath, "index.html"));
            });

            AlbumViewerDataImporter.EnsureAlbumData(albumContext,
                                                    Path.Combine(env.ContentRootPath, "albums.js"));
        }
示例#17
0
 public AlbumViewerApiController(AlbumViewerContext context)
 {
     Context = context;
 }
示例#18
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory, AlbumViewerContext albumContext)
        {
            loggerFactory.AddConsole(Configuration.GetSection("Logging"));
            loggerFactory.AddDebug();

            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseBrowserLink();
            }
            else
            {
                app.UseExceptionHandler("/Home/Error");
            }

            // Enable Cookie Auth with automatic user policy
            app.UseCookieAuthentication(new CookieAuthenticationOptions()
            {
                AutomaticAuthenticate = true,
                AutomaticChallenge    = true,
                LoginPath             = "/api/login"
            });

            app.UseDatabaseErrorPage();

            app.UseStaticFiles();

            app.UseMvc(routes =>
            {
                routes.MapRoute(
                    name: "default",
                    template: "{controller=Home}/{action=Index}/{id?}");
            });


            bool result = AlbumViewerDataImporter.EnsureAlbumData(albumContext,
                                                                  Path.Combine(env.WebRootPath, "data//albums.js"));
        }