Ejemplo n.º 1
0
 public IList<BlogPost> GetBlogPosts(int skip, int take)
 {
     using(var db = new BlogPostContext()) {
         var query = db.BlogPost.Include("Tags").Include("Author").OrderByDescending(bp => bp.DateCreated).Skip(skip).Take(take);
         return query.ToList();
     }
 }
Ejemplo n.º 2
0
 public static void Initialize(IApplicationBuilder app)
 {
     using var serviceScope = app.ApplicationServices.GetService <IServiceScopeFactory>().CreateScope();
     context = serviceScope.ServiceProvider.GetRequiredService <BlogPostContext>();
     context.Database.Migrate();
     InitilizeDatabase();
 }
 public StudentsController(BlogPostContext context, IMapper mapper, IStudentService studentService, IStudentRepository studentRepository)
 {
     this.context           = context;
     this.mapper            = mapper;
     this.studentService    = studentService;
     this.studentRepository = studentRepository;
 }
Ejemplo n.º 4
0
        public async Task Should_AddNewStudent()
        {
            // arrange
            ActionResult <StudentResponse> result;
            var studentRequest = new CreateStudentRequest {
                Name = fixture.NewStudent.Name
            };
            Student studentResult;

            // act
            using (var dbContext = new BlogPostContext(fixture.Options))
            {
                var controller = new StudentsController(dbContext, fixture.Mapper, studentServiceMock.Object, studentRepositoryMock.Object);
                result = await controller.PostStudent(studentRequest);

                studentResult = dbContext.Students.FirstOrDefault(x => x.Name == fixture.NewStudent.Name);
            }

            var apiResult = result.Result.As <CreatedAtActionResult>();
            var students  = apiResult.Value.As <StudentResponse>();

            // assert
            apiResult.StatusCode.Should().Be(StatusCodes.Status201Created);
            students.Should().BeEquivalentTo(studentResult);
        }
Ejemplo n.º 5
0
 protected Repository(
     IUnitOfWork unitOfWork,
     BlogPostContext dbContext)
 {
     UnitOfWork = unitOfWork;
     DbContext  = dbContext;
     DbSet      = DbContext.Set <TEntity>();
 }
Ejemplo n.º 6
0
        public BlogPostsUpdate()
        {
            secrets = GetSecrets.GetSecretsDictionary();
            string connstr = GetSecrets.GetSecretConnectionString();

            bpc = GetConnectionString.GetContext(connstr);
            AWSXRayRecorder.InitializeInstance();
        }
Ejemplo n.º 7
0
 public ActionResult Index()
 {
     using (var db = new BlogPostContext())
     {
         ViewBag.AllBlogPosts = db.BlogPosts.OrderByDescending(x => x.Created).ToList();
     };
     return(View());
 }
Ejemplo n.º 8
0
        public void TestNullReturn()
        {
            BlogPostContext    ctx     = newContext();
            BlogPostCtxWrapper wrapper = new BlogPostCtxWrapper(ctx);
            BlogController     bpc     = new BlogController(wrapper);
            var obj = bpc.Get(2);

            Assert.Null(obj.Value);
        }
Ejemplo n.º 9
0
 public PostRepository(BlogPostContext context, IMemoryCache _cache)
 {
     Context = context;
     Cache   = _cache;
     if (!Context.Posts.Any())
     {
         SeedData.Initialize(Context);
     }
 }
 public void DeleteBlogPost(int id)
 {
     using (BlogPostContext context = new BlogPostContext(_connectionName, _schemaName))
     {
         Data.Model.BlogPost post = context.BlogPosts.Find(id);
         context.Entry(post).State = System.Data.EntityState.Deleted;
         context.SaveChanges();
     }
 }
Ejemplo n.º 11
0
        public BlogPostsGetAll()
        {
            secrets = GetSecrets.GetSecretsDictionary();
            string connstr = GetSecrets.GetSecretConnectionString();

            Console.WriteLine($"Connection string:: {connstr}");
            bpc = GetConnectionString.GetContext(connstr);
            AWSXRayRecorder.InitializeInstance();
        }
Ejemplo n.º 12
0
 public BlogPost GetBlogPost(string urlSlug)
 {
     using (var db = new BlogPostContext())
     {
         var query = db.BlogPost.Include("Tags").Include("Author")
             .Where(bp => bp.UrlSlug.Equals(urlSlug));
         return query.SingleOrDefault();
     }
 }
Ejemplo n.º 13
0
        public void TestSimpleReturn()
        {
            BlogPostContext    ctx     = newContext();
            BlogPostCtxWrapper wrapper = new BlogPostCtxWrapper(ctx);
            BlogController     bpc     = new BlogController(wrapper);
            var obj = bpc.Get(1);

            Assert.Equal("Help", obj.Value.Title);
            Assert.Equal(1, obj.Value.Version);
        }
Ejemplo n.º 14
0
 public ActionResult Create(BlogPost blogPost)
 {
     using (var db = new BlogPostContext())
     {
         blogPost.Created = DateTime.Now;
         db.BlogPosts.Add(blogPost);
         db.SaveChanges();
     }
     return(RedirectToAction("Index"));
 }
Ejemplo n.º 15
0
 public IList<BlogPost> GetBlogPostsByTag(string tagUrlSlug, int skip, int take)
 {
     using (var db = new BlogPostContext())
     {
         var query = db.BlogPost.Include("Tags").Include("Author")
             .Where(bp => bp.Tags.Any(t => t.UrlSlug == tagUrlSlug))
             .OrderByDescending(bp => bp.DateCreated).Skip(skip).Take(take);
         return query.ToList();
     }
 }
 public void UpdateBlogPost(Domain.Model.BlogPost post)
 {
     using (BlogPostContext context = new BlogPostContext(_connectionName, _schemaName))
     {
         context.Entry(new Data.Model.BlogPost {
             Id = post.Id, Post = post.Post, Title = post.Title
         }).State = System.Data.EntityState.Modified;
         context.SaveChanges();
     }
 }
Ejemplo n.º 17
0
        private void SetupDatabase()
        {
            Options = new DbContextOptionsBuilder <BlogPostContext>()
                      .UseInMemoryDatabase(databaseName: "StudentContextOptions")
                      .Options;

            using var dbContext = new BlogPostContext(Options);
            var itCourse = new Course
            {
                Name = "IT Programming"
            };

            var math = new Course
            {
                Name = "Math"
            };

            var student1 = new Student
            {
                Name    = "John Doe",
                Courses = new List <StudentCourse>
                {
                    new StudentCourse {
                        Course = itCourse
                    },
                    new StudentCourse {
                        Course = math
                    }
                }
            };

            var student2 = new Student
            {
                Name    = "Martin B",
                Courses = new List <StudentCourse>
                {
                    new StudentCourse {
                        Course = itCourse
                    },
                    new StudentCourse {
                        Course = math
                    }
                }
            };

            dbContext.Add(student1);
            dbContext.Add(student2);

            dbContext.SaveChanges();

            allStudents = new List <Student> {
                student1, student2
            };
            ExpectedStudents = Mapper.Map <IEnumerable <StudentResponse> >(allStudents);
        }
        public IEnumerable <Domain.Model.BlogPost> GetAllBlogPosts()
        {
            using (BlogPostContext context = new BlogPostContext(_connectionName, _schemaName))
            {
                IList <Data.Model.BlogPost> blogposts = context.BlogPosts.ToList <Data.Model.BlogPost>();
                var posts = from post in blogposts
                            select post.ToDomainBlogPost();

                return(posts.ToList <Domain.Model.BlogPost>());
            }
        }
 public Domain.Model.BlogPost ReadBlogPost(int id)
 {
     using (BlogPostContext context = new BlogPostContext(_connectionName, _schemaName))
     {
         var post = context.BlogPosts.Find(id);
         if (post != null)
         {
             return(post.ToDomainBlogPost());
         }
         return(null);
     }
 }
        public BlogPostsController(BlogPostContext context)
        {
            _context = context;

            if (_context.BlogPostItems.Count() == 0)
            {
                _context.BlogPostItems.Add(new BlogPostItem {
                    Title = "Item1"
                });
                _context.SaveChanges();
            }
        }
Ejemplo n.º 21
0
        public IList<BlogPost> GetBlogPostsByMonth(int month, int year)
        {
            DateTime beginDate = new DateTime(year, month, 1);
            DateTime endDate = beginDate.AddMonths(1).AddMilliseconds(-1);

            using (var db = new BlogPostContext())
            {
                var query = db.BlogPost.Include("Tags").Include("Author")
                    .Where(bp => bp.DateCreated >= beginDate && bp.DateCreated <= endDate)
                    .OrderBy(bp => bp.DateCreated);
                return query.ToList();
            }
        }
Ejemplo n.º 22
0
        public BlogController(BlogPostContext context)
        {
            _context = context;

            if (_context.BlogPostItems.Count() == 0)
            {
                // Create a new BlogPost if collection is empty,
                _context.BlogPostItems.Add(new BlogPost {
                    Title = "Wellcome to SimpleBlog Engine", Content = " This is a very basic blog engine with  x feature and y feature   It has a simple web editor to edit multi-line blog entries. If you  have bug reports and suggestion please email to  [email protected] "
                });
                _context.SaveChanges();
            }
        }
Ejemplo n.º 23
0
        public async Task Should_CalculateWeighterAverage()
        {
            // arrange
            var expected = GetExpectedWeighterAverage();

            using var dbContext = new BlogPostContext(fixture.Options);
            sut = new StudentService(dbContext);

            // act
            var result = await sut.GetWeightedAverageForCourseAsync(courseId : 1, studentId : 1);

            // assert
            result.Should().Be(expected);
        }
Ejemplo n.º 24
0
        public void Should_ThrowException_When_CourseNotExist()
        {
            // arrange
            const int studentId           = 1;
            const int notExistingCourseId = 666;

            using var dbContext = new BlogPostContext(fixture.Options);
            sut = new StudentService(dbContext);

            // act
            Func <Task> act = async() => await sut.GetWeightedAverageForCourseAsync(notExistingCourseId, studentId);

            // assert
            act.Should().Throw <ArgumentException>();
        }
Ejemplo n.º 25
0
        private static void InsertTestData(BlogPostContext context)
        {
            if (context.Authors.Any())
            {
                return;
            }

            context.Authors.Add(new Author
            {
                Id   = Guid.NewGuid(),
                Name = "Daan"
            });

            context.SaveChanges();
        }
Ejemplo n.º 26
0
        public IList<TagCount> GetTagCounts()
        {
            using (var db = new BlogPostContext())
            {
                var query = db.BlogPost
                    .SelectMany(p => p.Tags)
                    .GroupBy(t => new { TagName = t.Name, UrlSlug = t.UrlSlug })
                    .Select(t => new TagCount
                    {
                        TagName = t.Key.TagName,
                        UrlSlug = t.Key.UrlSlug,
                        Total = t.Count()
                    })
                    .OrderBy(t => t.TagName);

                return query.ToList();
            }
        }
Ejemplo n.º 27
0
        public async Task Should_ReturnMissingGrades_ForEveryStudent()
        {
            // arrange
            using var dbContext = new BlogPostContext(fixture.Options);
            sut = new StudentService(dbContext);

            // act
            var result = await sut.GetMissingCoursesForStudentsAsync();

            // assert
            result.Should().HaveCount(fixture.ExpectedMissingGrades.Count());
            result.Should().BeEquivalentTo(fixture.ExpectedMissingGrades,
                                           options => options
                                           .IgnoringCyclicReferences()
                                           .Excluding(x => x.Assessment)
                                           .Excluding(x => x.Course)
                                           .Excluding(x => x.Student)
                                           );
        }
Ejemplo n.º 28
0
        public async Task Should_ReturnSingleStudent_WithCourses()
        {
            // arrange
            const int firstElement = 0;
            ActionResult <StudentResponse> result;
            var expected = fixture.ExpectedStudents.ElementAt(firstElement);

            // act
            using (var dbContext = new BlogPostContext(fixture.Options))
            {
                var controller = new StudentsController(dbContext, fixture.Mapper, studentServiceMock.Object, studentRepositoryMock.Object);
                result = await controller.GetStudent(ControllerFixture.StudentId);
            }

            var okResult = result.Result.As <OkObjectResult>();
            var students = okResult.Value.As <StudentResponse>();

            // assert
            okResult.StatusCode.Should().Be(StatusCodes.Status200OK);
            students.Should().BeEquivalentTo(expected);
        }
Ejemplo n.º 29
0
        // This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
        public void Configure(IApplicationBuilder app, IHostingEnvironment env, BlogPostContext context, IApiVersionDescriptionProvider apiVersionDescProvider)
        {
            if (!env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();

                context.Database.EnsureCreated();
                if (!context.BlogPosts.Any())
                {
                    var posts = new List <BlogPost>();
                    for (int i = 1; i < 6; i++)
                    {
                        posts.Add(createBlogPost("title" + i, "desc" + i));
                    }
                    context.BlogPosts.AddRange(posts);
                    context.SaveChanges();
                }
            }
            else
            {
                app.UseExceptionHandler("/api/v1/Error");
                app.UseHsts();
            }

            app.UseCors("MyPolicy");

            app.UseHttpsRedirection();
            app.UseMvc();

            _logger.LogInformation("Adding Swagger UI");
            app.UseSwagger();
            app.UseSwaggerUI(c =>
            {
                foreach (var description in apiVersionDescProvider.ApiVersionDescriptions)
                {
                    c.SwaggerEndpoint($"/swagger/{description.GroupName}/swagger.json", description.GroupName.ToUpperInvariant());
                }
                c.RoutePrefix = string.Empty; // serve the Swagger UI at the app's root
            });
        }
Ejemplo n.º 30
0
        public async Task Should_RemoveExistingStudent()
        {
            // arrange
            const int     studentId = 2;
            IActionResult result;
            Student       studentResult;

            // act
            using (var dbContext = new BlogPostContext(fixture.Options))
            {
                var controller = new StudentsController(dbContext, fixture.Mapper, studentServiceMock.Object, studentRepositoryMock.Object);
                result = await controller.DeleteStudent(studentId);

                studentResult = dbContext.Students.FirstOrDefault(x => x.Id == studentId);
            }

            // assert
            var noContentResult = result.As <NoContentResult>();

            noContentResult.StatusCode.Should().Be(StatusCodes.Status204NoContent);
            studentResult.Should().BeNull();
        }
Ejemplo n.º 31
0
        public IList<ArchiveItem> GetArchiveDetails()
        {
            using (var db = new BlogPostContext())
            {
                var query = db.BlogPost
                    .GroupBy(p => new
                    {
                        Month = p.DateCreated.Month,
                        Year = p.DateCreated.Year
                    })
                    .Select(a => new ArchiveItem
                    {
                        Month = a.Key.Month,
                        Year = a.Key.Year,
                        TotalPosts = a.Count()
                    })
                    .OrderByDescending(a => a.Year)
                    .ThenByDescending(a => a.Month);

                return query.ToList();
            }
        }
Ejemplo n.º 32
0
        public async Task Should_UpdateExistingStudent()
        {
            // arrange
            IActionResult result;
            var           studentRequest = new UpdateStudentRequest {
                Name = fixture.UpdatedStudent.Name, Id = ControllerFixture.StudentId
            };
            Student studentResult;

            // act
            using (var dbContext = new BlogPostContext(fixture.Options))
            {
                var controller = new StudentsController(dbContext, fixture.Mapper, studentServiceMock.Object, studentRepositoryMock.Object);
                result = await controller.PutStudent(ControllerFixture.StudentId, studentRequest);

                studentResult = dbContext.Students.First(x => x.Id == ControllerFixture.StudentId);
            }

            //assert
            var noContentResult = result.As <NoContentResult>();

            noContentResult.StatusCode.Should().Be(StatusCodes.Status204NoContent);
            studentResult.Name.Should().Be(studentRequest.Name);
        }
Ejemplo n.º 33
0
 public Blogs1Controller(BlogPostContext context)
 {
     _context = context;
 }
Ejemplo n.º 34
0
 public string GetTagNameFromSlug(string urlSlug)
 {
     using (var db = new BlogPostContext())
     {
         string tagName = db.Tags.Where(t => t.UrlSlug.Equals(urlSlug)).Select(t => t.Name).SingleOrDefault();
         return tagName;
     }
 }
 public StudentsController(BlogPostContext context)
 {
     this.context = context;
 }
 public StudentRepository(BlogPostContext context)
 {
     this.context = context;
 }
Ejemplo n.º 37
0
 public ImageRepository(
     IUnitOfWork unitOfWork,
     BlogPostContext dbContext)
     : base(unitOfWork, dbContext)
 {
 }