public void TestBookWithRelatedLinksWithoutIncludes() { //SETUP var options = this.NewMethodUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var book = context.Books .Single(p => p.Title == "Quantum Networking"); context.Books.Remove(book); context.SaveChanges(); //VERIFY context.Books.Count().ShouldEqual(3); context.PriceOffers.Count().ShouldEqual(0); //Quantum Networking is the only book with a priceOffer and reviews context.Set <Review>().Count().ShouldEqual(0); context.Set <BookAuthor>().Count().ShouldEqual(3); //three books left, each with a one author foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void TestDeletePriceOfferWithLogging() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { context.SeedDatabaseFourBooks(); var logIt = new LogDbContext(context); var numPromotions = context.PriceOffers.Count(); //ATTEMPT var promotion = context.PriceOffers //#A .First(); //#A context.PriceOffers.Remove(promotion); //#B context.SaveChanges(); //#C //VERIFY context.PriceOffers.Count().ShouldEqual(numPromotions - 1); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void UsingTransaction() { var options = this.SetupOptions(seedData: false); using var context = new BloggingContext(options); using var transaction = context.Database.BeginTransaction(); logIt = new LogDbContext(context); try { context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); context.SaveChanges(); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet2" }); context.SaveChanges(); transaction.Commit(); } catch (Exception e) { transaction.Rollback(); } var blogs = context.Blogs .OrderBy(b => b.Url) .ToList(); Assert.NotEmpty(blogs); }
public HomeController(AccountDbContext accountDbContext, ShardDbContext shardDbContext, LogDbContext logDbContext, PanelDbContext panelDbContext) { _accountDbContext = accountDbContext; _shardDbContext = shardDbContext; _logDbContext = logDbContext; _panelDbContext = panelDbContext; }
public void TestAverageOk() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var dtos = context.Books.Select(p => new { NumReviews = p.Reviews.Count, ReviewsAverageVotes = p.Reviews.Count == 0 ? null : (double?)p.Reviews.Average(q => q.NumStars) }).ToList(); //VERIFY dtos.Any(x => x.ReviewsAverageVotes > 0).ShouldBeTrue(); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void TestIQueryableSelectBookListDtoOk() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var dtos = context.Books.MapBookToDto().OrderByDescending(x => x.BookId).ToList(); //VERIFY //dtos.Last().BookId.ShouldNotEqual(0); //dtos.Last().Title.ShouldNotBeNull(); //dtos.Last().Price.ShouldNotEqual(0); //dtos.Last().ActualPrice.ShouldNotEqual(dtos.Last().Price); //dtos.Last().AuthorsOrdered.Length.ShouldBeInRange(1, 100); //dtos.Last().ReviewsCount.ShouldEqual(2); //dtos.Last().ReviewsAverageVotes.ShouldEqual(5); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void GetRecentRequests() { using (var db1 = new LogDbContext(dbOptions)) { db1.RequestLogs.AddRange( new RequestLog { RequestId = 1, RequestGuid = guid, DateTimeUtc = today, RequestType = "GET" }, new RequestLog { RequestId = 2, RequestGuid = guid, DateTimeUtc = today.AddHours(1), RequestType = "GET" } ); db1.ResponseLogs.AddRange( new ResponseLog { ResponseId = 1, RequestGuid = guid, DateTimeUtc = today, Status = "HTTP 200 : OK" }, new ResponseLog { ResponseId = 2, RequestGuid = guid, DateTimeUtc = today.AddHours(1), Status = "HTTP 302 : Found" } ); db1.SaveChanges(); } var results = repo.ListRequest(20); Assert.AreEqual(2, results.Count()); Assert.AreEqual("GET", results.First().RequestType); Assert.AreEqual(new DateTime(2011, 1, 1, 21, 0, 0), results.First().DateTimeUtc); }
/// <summary> /// /// </summary> /// <returns></returns> public ActionResult GetErrors() { var db = new LogDbContext(); var model = db.Log.Where(l => l.Level.Equals("ERROR") || l.Level.Equals("FATAL")).OrderByDescending(l => l.Date).Take(250).OrderBy(l => l.Date); return(View("Index", model)); }
public void GetRequestsOnlyHttpOps() { using (var db1 = new LogDbContext(dbOptions)) { db1.RequestLogs.AddRange( new RequestLog { RequestId = 1, DateTimeUtc = today, RequestType = "GET" }, new RequestLog { RequestId = 2, DateTimeUtc = today, RequestType = "POST" }, new RequestLog { RequestId = 3, DateTimeUtc = today, RequestType = "PUT" }, new RequestLog { RequestId = 4, DateTimeUtc = today, RequestType = "DELETE" }, new RequestLog { RequestId = 5, DateTimeUtc = today, RequestType = "Other" } ); db1.SaveChanges(); } int count = repo.TotalRequests(0); Assert.AreEqual(4, count); }
public void TestRawSqlOk() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var books = context.Books .IgnoreQueryFilters() //Have to add this otherwise SQL fails because the SQL becomes a sub-query .FromSql( "SELECT * FROM dbo.books AS a ORDER BY (SELECT AVG(b.NumStars) FROM dbo.Review AS b WHERE b.BookId = a.BookId) DESC") .ToList(); //VERIFY books.First().Title.ShouldEqual("Quantum Networking"); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void UnauthorizedRequestsTime() { using (var db1 = new LogDbContext(dbOptions)) { db1.RequestLogs.AddRange( new RequestLog { RequestId = 1, RequestGuid = guid, DateTimeUtc = today, RequestType = "GET" }, new RequestLog { RequestId = 2, RequestGuid = guid, DateTimeUtc = today.AddHours(1), RequestType = "GET" }, new RequestLog { RequestId = 3, RequestGuid = guid, DateTimeUtc = today.AddHours(2), RequestType = "GET" } ); db1.ResponseLogs.AddRange( new ResponseLog { ResponseId = 1, RequestGuid = guid, DateTimeUtc = today, Status = "HTTP 200 : OK" }, new ResponseLog { ResponseId = 2, RequestGuid = guid, DateTimeUtc = today.AddHours(1).AddSeconds(2), Status = "Other" }, new ResponseLog { ResponseId = 3, RequestGuid = guid, DateTimeUtc = today.AddHours(2).AddSeconds(7), Status = "HTTP 401 : Unauthorized" } ); db1.SaveChanges(); } int count = repo.UnauthorizedRequestTime(0); Assert.AreEqual(7000, count); }
public void CountFailedRequests() { using (var db1 = new LogDbContext(dbOptions)) { db1.RequestLogs.AddRange( new RequestLog { RequestId = 1, RequestGuid = guid, DateTimeUtc = today, RequestType = "GET" }, new RequestLog { RequestId = 2, RequestGuid = guid, DateTimeUtc = today.AddHours(1), RequestType = "GET" }, new RequestLog { RequestId = 3, RequestGuid = guid, DateTimeUtc = today.AddHours(2), RequestType = "GET" } ); db1.ResponseLogs.AddRange( new ResponseLog { ResponseId = 1, RequestGuid = guid, DateTimeUtc = today, Status = "HTTP 200 : OK" }, new ResponseLog { ResponseId = 2, RequestGuid = guid, DateTimeUtc = today.AddHours(1), Status = "HTTP 302 : Found" }, new ResponseLog { ResponseId = 3, RequestGuid = guid, DateTimeUtc = today.AddHours(2), Status = "Other" } ); db1.SaveChanges(); } int count = repo.FailedRequests(0); Assert.AreEqual(1, count); }
public void TestEagerLoadBookAndReviewOk() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var book = context.Books .Include(r => r.Reviews) //#A .First(); //#B /********************************************************* #A The Include() gets a collection of Reviews, which may be an empty collection #B This takes the first book * *******************************************************/ //VERIFY book.Reviews.ShouldNotBeNull(); book.AuthorsLink.ShouldBeNull(); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void TestSelectLoadBookOk() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var books = context.Books .Select(p => new //#A { //#A p.Title, //#B p.Price, //#B NumReviews //#C = p.Reviews.Count, //#C } ).ToList(); /********************************************************* #A This uses the LINQ select keyword and creates an anonymous type to hold the results #B These are simple copies of a couple of properties #C This runs a query that counts the number of reviews * *******************************************************/ //VERIFY books.First().NumReviews.ShouldEqual(0); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
protected void Application_Start() { AreaRegistration.RegisterAllAreas(); GlobalConfiguration.Configure(WebApiConfig.Register); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); log4net.Config.XmlConfigurator.Configure(); Database.SetInitializer(new CreateDatabaseIfNotExists <LogDbContext>()); var db = new LogDbContext(); if (!db.Log.Any()) { var log = new Log { Date = DateTime.Now, Level = "INIT", Logger = "INIT", Message = "Initial Entry", Thread = "xxx", }; db.Log.Add(log); db.SaveChanges(); } #if DEBUG var path = Server.MapPath("~/images"); Database.SetInitializer(new TestDataInitializer(path)); #else Database.SetInitializer(new MigrateDatabaseToLatestVersion <QuestDbContext, Migrations.Configuration>()); #endif }
/// <summary> /// /// </summary> /// <returns></returns> public FileResult GetLogs() { var start = new DateTime(2014, 2, 22); var db = new LogDbContext(); var logs = db.Log.Where(log => log.Date >= start).OrderBy(log => log.Date); var ms = new MemoryStream(); var writer = new StreamWriter(ms, Encoding.Default); writer.Write("Datum;Zeit;Level;Logger;Nachricht"); writer.Write(Environment.NewLine); foreach (var log in logs) { writer.Write(String.Format("{0};{1};{2};{3};{4}", log.Date.Date.ToShortDateString(), log.Date.TimeOfDay, log.Level, log.Logger, log.Message )); writer.Write(Environment.NewLine); } writer.Flush(); writer.Dispose(); return(File(ms.GetBuffer(), "text/csv", "Logs.csv")); }
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, LogDbContext logDbContext) { logDbContext.Database.EnsureCreated(); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } //app.UseHttpsRedirection(); app.UseAuthentication(); app.UseMiddleware <ApiLoggingMiddleware>(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), // specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("./swagger/v1/swagger.json", "V1"); c.RoutePrefix = string.Empty; }); app.UseMvc(); }
/// <summary> /// /// </summary> /// <returns></returns> public ActionResult GetMails() { var db = new LogDbContext(); var model = db.Log.Where(l => l.Logger.Equals("SendMail")).OrderByDescending(l => l.Date).Take(250).OrderBy(l => l.Date); return(View("Index", model)); }
public void TestClientServerSortOnEvaluatedPortion() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var books = context.Books .Select(p => new { p.BookId, p.Title, //… other properties left out AuthorsString = string.Join(", ", p.AuthorsLink .OrderBy(q => q.Order) .Select(q => q.Author.Name)), } ).OrderBy(p => p.AuthorsString).ToList(); //VERIFY books.Select(x => x.BookId).ShouldEqual(new [] { 3, 4, 1, 2 }); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void TestDirectSelectBookListDtoOk() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var dtos = context.Books.Select(p => new BookListDto { BookId = p.BookId, Title = p.Title, Price = p.Price, PublishedOn = p.PublishedOn, }).ToList(); //VERIFY dtos.Last().BookId.ShouldNotEqual(0); dtos.Last().Title.ShouldNotBeNull(); dtos.Last().Price.ShouldNotEqual(0); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void TestClientServerSimpleBookOk() { //SETUP var options = this.ClassUniqueDatabaseSeeded4Books(); using (var context = new EfCoreContext(options)) { var logIt = new LogDbContext(context); //ATTEMPT var us = new CultureInfo("en-US"); //#A var books = context.Books .Select(p => new { p.Title, PriceString = p.Price.ToString("C"), //#B NumReviews = p.Reviews.Count } ).ToList(); /********************************************************* #A This creates a culture for the USA, so that the ToString will use a dollar sign on the currency #B ToString("C", culture) is not a supported SQL command, so EF Core applies it to the data after the SQL query * *******************************************************/ //VERIFY books.First().PriceString.ShouldNotBeNull(); foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
public void InternalTransaction() { var options = this.SetupOptions(seedData: false); using var context = new BloggingContext(options); try { logIt = new LogDbContext(context); context.Blogs.Add(new Blog { Url = "http://blogs.msdn.com/dotnet" }); context.Blogs.Add(new Blog { Url = null }); context.SaveChanges(); } catch { //for testing purposes } var blogs = context.Blogs .OrderBy(b => b.Url) .ToList(); Assert.Empty(blogs); }
public PartialViewResult Search(string thread, string logger) { var db = new LogDbContext(); List <Log> logs = null; if (string.IsNullOrEmpty(thread) && !string.IsNullOrEmpty(logger)) { logs = db.Log.Where(l => l.Logger.Contains(logger)).ToList(); } else if (!string.IsNullOrEmpty(thread) && string.IsNullOrEmpty(logger)) { logs = db.Log.Where(l => l.Thread.Contains(logger)).ToList(); } else if (!string.IsNullOrEmpty(thread) && !string.IsNullOrEmpty(logger)) { logs = db.Log.Where(l => l.Logger.Contains(logger) && l.Thread.Contains(thread)).ToList(); } else { logs = new List <Log>(); } return(PartialView("_LogTable", logs)); }
public void UpdatePublicationDateWithLogging() { //SETUP var options = this.NewMethodUniqueDatabaseSeeded4Books(); //#A using (var context = new EfCoreContext(options)) { //REMOVE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! var logIt = new LogDbContext(context); //ATTEMPT var book = context.Books //#B .Single(p => p.Title == "Quantum Networking"); //#B book.PublishedOn = new DateTime(2058, 1, 1); //#C context.SaveChanges(); //#D //VERIFY var bookAgain = context.Books //#E .Single(p => p.Title == "Quantum Networking"); //#E bookAgain.PublishedOn //#F .ShouldEqual(new DateTime(2058, 1, 1)); //#F //REMOVE!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! foreach (var log in logIt.Logs) { _output.WriteLine(log); } } }
/// <summary> /// 查询单个对象 /// </summary> public AuditLog GetAuditLog(int id) { using (var db = new LogDbContext()) { return(db.Find <AuditLog>(id)); } }
public async System.Threading.Tasks.Task <IActionResult> IndexAsync(CancellationToken cancellationToken = default) { await LogDbContext.People.AddAsync(new Person { Id = 1, FullName = "SinjulMSBH" }, cancellationToken); await LogDbContext.People.AddAsync(new Person { Id = 2, FullName = "SinjulMSBH" }, cancellationToken); await LogDbContext.People.AddAsync(new Person { Id = 3, FullName = "JackSlater" }, cancellationToken); await LogDbContext.SaveChangesAsync(cancellationToken); var people2 = LogDbContext.People.ToListAsync(cancellationToken); await ApplicationDbContext.People.AddAsync(new Person { Id = 1, FullName = "SinjulMSBH" }, cancellationToken); await AlphaDbContext.SaveChangesAsync(cancellationToken); var people1 = ApplicationDbContext.People.ToListAsync(cancellationToken); await AlphaDbContext.People.AddAsync(new Person { Id = 1, FullName = "SinjulMSBH" }, cancellationToken); await AlphaDbContext.People.AddAsync(new Person { Id = 2, FullName = "JackSlater" }, cancellationToken); await AlphaDbContext.SaveChangesAsync(cancellationToken); var people = await AlphaDbContext.People.ToListAsync(cancellationToken); return(Ok(people)); }
public void AddingANewBlog() { var contextOptions = SetInMemoryOptions(); int numberOfBlogs = 0; var blog = new Blog() { Url = "http://blog1.com", Posts = new List <Post>() { new Post() { Content = "my first content!", Title = "this is my first post!" } } }; using (var context = new BloggingContext(contextOptions.Options)) { logIt = new LogDbContext(context); context.Blogs.Add(blog); context.SaveChanges(); numberOfBlogs = context.Blogs.Count(); } Assert.Equal(1, numberOfBlogs); }
public AuditLog GetLogBasedata(int id) { using (var dbContext = new LogDbContext()) { return(dbContext.Find <AuditLog>(id)); } }
public void InitBase() { LogDbOptions = new DbContextOptionsBuilder <LogDbContext>() .UseInMemoryDatabase(databaseName: "logDb" + Guid.NewGuid().ToString()) .Options; AppDbOptions = new DbContextOptionsBuilder <AppDbContext>() .UseInMemoryDatabase(databaseName: "appDb" + Guid.NewGuid().ToString()) .Options; //Set up DI var logDb = new LogDbContext(LogDbOptions); var appDb = new AppDbContext(AppDbOptions); TimeProvider = new Mock <ITimeProvider>(); ServiceCollection services = new ServiceCollection(); services.AddScoped(c => logDb) .AddScoped(c => appDb) .AddSingleton(c => TimeProvider.Object); serviceProvider = services.BuildServiceProvider(); var _serviceScopeFactory = new Mock <IServiceScopeFactory>(); _serviceScopeFactory .Setup(x => x.CreateScope()) .Returns(serviceProvider.CreateScope()); serviceScopeFactory = _serviceScopeFactory.Object; }
/// <summary> /// Получить последнюю запись /// </summary> /// <returns></returns> public Log GetLast() { using (var context = new LogDbContext()) { var log = context.Logs.OrderByDescending(p => p.Id).FirstOrDefault(); return(log); } }