예제 #1
0
        public IEnumerable<PostFullModel> GetPostsByCategories(int id)
        {
            BlogContext context = new BlogContext();

            Category category = context.Categories.Find(id);

            if (category == null)
            {
                var errResponse =
                    this.Request.CreateErrorResponse(HttpStatusCode.NotFound, "Invalid category id");
                throw new HttpResponseException(errResponse);
            }

            var posts = context.Posts
                .Where(p => p.Categories.Any(c => c.Name == category.Name))
                .Select(p => new PostFullModel()
                {
                    PostId = p.PostId,
                    Title = p.Title,
                    Content = p.Content,
                    Categories = p.Categories.Select(c => new CategoryModel()
                    {
                        CategoryId = c.CategoryId,
                        Name = c.Name,
                    })
                });

            return posts;
        }
 public static void DropDatabase()
 {
     using (var blogContext = new BlogContext())
     {
         blogContext.Database.Delete();
     }
 }
예제 #3
0
 public ListViewModel(BlogContext _blogContext, int page)
 {
     currentPage = page;
     Posts = _blogContext.AllPostsByPage(page - 1, split);
     //TotalPosts = _blogContext.TotalPosts();
     //totalPages = (int)Math.Ceiling((double)TotalPosts / (double)split);
 }
예제 #4
0
 protected virtual void HandleBeginRequest(object sender, EventArgs e)
 {
     string host = HttpContext.Current.Request.Headers["HOST"];
     BlogContext context = new BlogContext();
     context.Blog = blogRepository.GetBlog();
     BlogContext.Current = context;
 }
예제 #5
0
        public void SeedBlogPostTagAndComments()
        {
            var context = new BlogContext();
            var seeder = new SeedData(context);
            var success = seeder.SeedPostTagComments();

            Assert.False(success);
        }
 public static void InitializeDatabase()
 {
     using (var blogContext = new BlogContext())
     {
         blogContext.Database.Initialize(true);
         blogContext.Database.Connection.Close();
     }
 }
예제 #7
0
        public HttpResponseMessage CreatePost([FromBody]CreatePostModel item)
        {
            BlogContext context = new BlogContext();

            Post entity = new Post()
            {
                Content = item.Content,
                Title = item.Title,
            };

            var categories = new HashSet<Category>();

            if (item.Categories != null)
            {
                foreach (string catName in item.Categories)
                {
                    Category cat = context.Categories.FirstOrDefault(c => c.Name == catName);

                    if (cat == null)
                    {
                        cat = new Category() { Name = catName, };
                    }

                    categories.Add(cat);
                }
            }
            else
            {
                Category cat = context.Categories.FirstOrDefault(c => c.Name == "Default");
                if (cat == null)
                {
                    cat = new Category() { Name = "Default" };
                }
                categories.Add(cat);
            }

            entity.Categories = categories;

            context.Posts.Add(entity);
            context.SaveChanges();

            PostFullModel model = new PostFullModel()
            {
                PostId = entity.PostId,
                Title = entity.Title,
                Content = entity.Content,
                Categories = entity.Categories.Select(c => new CategoryModel()
                {
                    CategoryId = c.CategoryId,
                    Name = c.Name,
                }),
            };

            HttpResponseMessage response = this.Request.CreateResponse(HttpStatusCode.Created, model);
            response.Headers.Location = new Uri(Url.Link("DefaultApi", new { id = model.PostId }));

            return response;
        }
예제 #8
0
 public IEnumerable<CategoryModel> GetAllCategories()
 {
     BlogContext context = new BlogContext();
     return context.Categories.Select(c => new CategoryModel()
     {
         CategoryId = c.CategoryId,
         Name = c.Name
     });
 }
예제 #9
0
        public void Should_be_able_to_recreate_a_database()
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
            IDbConnectionFactory connection = new SqlConnectionFactory(connectionString);
            Database.DefaultConnectionFactory = connection;
            Database.SetInitializer(new BlogDbInitializer());

            var context = new BlogContext(connectionString);
            Assert.IsTrue(context.Posts.Any());
        }
        public static void DropView()
        {
            using (var blogContext = new BlogContext())
            {
                const string command = "IF  EXISTS (SELECT * FROM sys.views WHERE object_id = OBJECT_ID(N'[dbo].[Posts_Blog]')) " +
                                       "DROP VIEW [dbo].[Posts_Blog]";

                blogContext.Database.ExecuteSqlCommand(command);
            }
        }
        public static void CreateView()
        {
            using (var blogContext = new BlogContext())
            {
                const string command = "CREATE View Posts_Blog " +
                                       "AS " +
                                       "SELECT P.Title, P.DateCreated, P.Content, B.BloggerName " +
                                       "FROM Posts p " +
                                       "INNER JOIN Blogs B ON B.Id = P.BlogId ";

                blogContext.Database.ExecuteSqlCommand(command);
            }
        }
예제 #12
0
 public AccountController(
     UserManager<ApplicationUser> userManager,
     SignInManager<ApplicationUser> signInManager,
     IEmailSender emailSender,
     ISmsSender smsSender,
     BlogContext applicationDbContext)
 {
     _userManager = userManager;
     _signInManager = signInManager;
     _emailSender = emailSender;
     _smsSender = smsSender;
     _applicationDbContext = applicationDbContext;
 }
            public void Can_save_and_query_with_implicit_services_and_OnConfiguring()
            {
                using (var context = new BlogContext())
                {
                    context.Blogs.Add(new Blog { Name = "The Waffle Cart" });
                    context.SaveChanges();
                }

                using (var context = new BlogContext())
                {
                    var blog = context.Blogs.SingleOrDefault();

                    Assert.NotEqual(0, blog.Id);
                    Assert.Equal("The Waffle Cart", blog.Name);
                }
            }
예제 #14
0
        public IEnumerable<PostFullModel> GetAll()
        {
            BlogContext context = new BlogContext();

            var postsModels = context.Posts.Select(p => new PostFullModel()
            {
                PostId = p.PostId,
                Title = p.Title,
                Content = p.Content,
                Categories = p.Categories.Select(c => new CategoryModel()
                {
                    CategoryId = c.CategoryId,
                    Name = c.Name,
                }),
            });

            return postsModels;
        }
            public void Can_save_and_query_with_implicit_services_and_explicit_config()
            {
                var options = new DbContextOptions().UseInMemoryStore();

                using (var context = new BlogContext(options))
                {
                    context.Blogs.Add(new Blog { Name = "The Waffle Cart" });
                    context.SaveChanges();
                }

                using (var context = new BlogContext(options))
                {
                    var blog = context.Blogs.SingleOrDefault();

                    Assert.NotEqual(0, blog.Id);
                    Assert.Equal("The Waffle Cart", blog.Name);
                }
            }
예제 #16
0
        public static Author AddSeed(this DbSet<Author> authors, BlogContext context, string name, string email,
            Action<Author> configItem = null)
        {
            var item = new Author
            {
                Name = name,
                Email = email
            };

            if (configItem != null)
            {
                configItem(item);
            }

            authors.AddOrUpdate(x => x.Name, item);
            context.SaveChanges();

            return authors.First(x => x.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase));
        }
예제 #17
0
        public void Rule_FilterOverLeftOuterJoin_promotes_to_InnerJoin_if_using_database_null_semantics()
        {
            var expectedSql =
            @"SELECT
            [Extent1].[Id] AS [Id],
            [Extent1].[Name] AS [Name]
            FROM  [dbo].[Blogs] AS [Extent1]
            INNER JOIN  (SELECT TOP (1) [c].[Name] AS [Name]
            FROM [dbo].[BlogEntries] AS [c] ) AS [Limit1] ON [Extent1].[Name] = [Limit1].[Name]";

            using (var context = new BlogContext())
            {
                context.Configuration.UseDatabaseNullSemantics = true;

                var query = from b in context.Blogs
                            where b.Name == context.BlogEntries.FirstOrDefault().Name
                            select b;

                QueryTestHelpers.VerifyDbQuery(query, expectedSql);
            }
        }
        public static void CreateUser(string username, string password)
        {
            using (var blogContext = new BlogContext())
            {
                var command = string.Format("IF  EXISTS (SELECT * FROM sys.server_principals WHERE name = N'{0}') " +
                                            "DROP LOGIN [{0}] " +
                                            "CREATE LOGIN [{0}] WITH PASSWORD=N'{1}', DEFAULT_DATABASE=[Blog], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON " +
                                            "EXEC sys.sp_addsrvrolemember @loginame = N'{0}', @rolename = N'sysadmin' " +
                                            "EXEC sys.sp_addsrvrolemember @loginame = N'{0}', @rolename = N'securityadmin' " +
                                            "EXEC sys.sp_addsrvrolemember @loginame = N'{0}', @rolename = N'serveradmin' " +
                                            "EXEC sys.sp_addsrvrolemember @loginame = N'{0}', @rolename = N'setupadmin' " +
                                            "USE [Blog] " +
                                            "IF  EXISTS (SELECT * FROM sys.database_principals WHERE name = N'{0}') " +
                                            "DROP USER [{0}] " +
                                            "USE [Blog] " +
                                            "CREATE USER [{0}] FOR LOGIN [{0}] WITH DEFAULT_SCHEMA=[dbo] "
                                            , username, password);

                blogContext.Database.ExecuteSqlCommand(command);
            }
        }
예제 #19
0
        public void Rule_FilterOverLeftOuterJoin_does_not_promote_to_InnerJoin_if_filter_predicate_is_expanded_in_null_semantics_phase()
        {
            var expectedSql =
            @"SELECT
            [Extent1].[Id] AS [Id],
            [Extent1].[Name] AS [Name]
            FROM  [dbo].[Blogs] AS [Extent1]
            LEFT OUTER JOIN  (SELECT TOP (1) [c].[Name] AS [Name]
            FROM [dbo].[BlogEntries] AS [c] ) AS [Limit1] ON 1 = 1
            WHERE ([Extent1].[Name] = [Limit1].[Name]) OR (([Extent1].[Name] IS NULL) AND ([Limit1].[Name] IS NULL))";

            using (var context = new BlogContext())
            {
                context.Configuration.UseDatabaseNullSemantics = false;

                var query = from b in context.Blogs
                            where b.Name == context.BlogEntries.FirstOrDefault().Name
                            select b;

                QueryTestHelpers.VerifyDbQuery(query, expectedSql);
            }
        }
예제 #20
0
        static void Main(string[] args)
        {
            using (var context = new BlogContext())
            {
                Console.WriteLine("Enter a name for a new blog: ");
                var name = Console.ReadLine();

                var blog = new Blog();
                blog.Name = name;
                context.Blogs.Add(blog);
                context.SaveChanges();
                var query = from b in context.Blogs
                    orderby b.Name
                    select b;

                foreach (var item in query)
                {
                    Console.WriteLine(item.Name);
                }

            }        
        }
예제 #21
0
        public void Rule_FilterOverOuterApply_promotes_to_CrossApply_if_using_database_null_semantics()
        {
            var expectedSql =
            @"SELECT
            [Extent1].[Id] AS [Id],
            [Extent1].[Name] AS [Name]
            FROM  [dbo].[Blogs] AS [Extent1]
            CROSS APPLY  (SELECT TOP (1) [Extent2].[Name] AS [Name]
            FROM [dbo].[BlogEntries] AS [Extent2]
            WHERE [Extent2].[Name] = [Extent1].[Name] ) AS [Limit1]
            WHERE [Extent1].[Name] = [Limit1].[Name]";

            using (var context = new BlogContext())
            {
                context.Configuration.UseDatabaseNullSemantics = true;

                var query = from b in context.Blogs
                            from e in context.BlogEntries.Where(e => e.Name == b.Name).Take(1).DefaultIfEmpty()
                            where b.Name == e.Name
                            select b;

                QueryTestHelpers.VerifyDbQuery(query, expectedSql);
            }
        }
 public GetPaginatedPostByKeywordQuery(BlogContext context) : base(context)
 {
 }
예제 #23
0
        private void refresh()
        {
            bContext = new BlogContext();
            bContext.BlogsList.Load();
            bContext.PostsList.Load();
            bContext.CommentsList.Load();

            this.blogsList.DataSource = (from blog in bContext.BlogsList
                                         select blog.Name).ToList();

            blogs = bContext.BlogsList.Include(b => b.Posts);
            posts = bContext.PostsList;
            comments = bContext.CommentsList.Select(c => c);
        }
예제 #24
0
 public StatisticsService(BlogContext blogContext)
 {
     this.BlogContext = blogContext;
 }
예제 #25
0
 public ArticleService(BlogContext context, IMapper mapper, SiteSettingService settingService)
 {
     _context        = context;
     _mapper         = mapper;
     _settingService = settingService;
 }
 public CommentsController(IConfiguration configuration, BlogContext context, ICommentRepository repository)
 {
     _context       = context;
     _repository    = repository;
     _configuration = configuration;
 }
예제 #27
0
 public GetPostByIdQuery(BlogContext context) : base(context)
 {
 }
예제 #28
0
 public BlogController(ILogger <BlogController> logger, BlogContext context)
 {
     _logger  = logger;
     _context = context;
 }
예제 #29
0
 public PostService(BlogContext blogContext)
 {
     _blogContext = blogContext;
 }
 public GetCommentsByPostQuery(BlogContext context) : base(context)
 {
 }
예제 #31
0
 public ContactController(BlogContext db, MessageModel model)
 {
     _db    = db;
     _model = model;
 }
예제 #32
0
 public UnitOfWork(DbContextOptions <BlogContext> connectionString)
 {
     db = new BlogContext(connectionString);
 }
예제 #33
0
 public EfGetOneCategoryQuery(BlogContext context, IMapper mapper)
 {
     this.context = context;
     this.mapper  = mapper;
 }
예제 #34
0
 public ArticleRepository(BlogContext context)
 {
     this.context = context;
 }
            public void Can_save_and_query_with_explicit_services_and_OnConfiguring()
            {
                var services = new ServiceCollection();
                services.AddEntityFramework().AddInMemoryStore();
                var serviceProvider = services.BuildServiceProvider();

                using (var context = new BlogContext(serviceProvider))
                {
                    context.Blogs.Add(new Blog { Name = "The Waffle Cart" });
                    context.SaveChanges();
                }

                using (var context = new BlogContext(serviceProvider))
                {
                    var blog = context.Blogs.SingleOrDefault();

                    Assert.NotEqual(0, blog.Id);
                    Assert.Equal("The Waffle Cart", blog.Name);
                }
            }
예제 #36
0
 public ReviewRepository(BlogContext context)
 {
     this.context = context;
 }
 public DeletePostCommand(BlogContext context) : base(context)
 {
 }
 public ValuesController(BlogContext context, IMapper mapper)
 {
     _context = context;
     _mapper  = mapper;
 }
예제 #39
0
 public EFGenericRepository(BlogContext context)
 {
     _context = context;
 }
 public EfCreateCommentCommand(BlogContext context, CreateCommentValidator validator, IMapper mapper)
 {
     _context   = context;
     _validator = validator;
     _mapper    = mapper;
 }
 public PostsController(ILogger <PostsController> logger, BlogContext blogContext)
 {
     _logger      = logger;
     _blogContext = blogContext;
 }
예제 #42
0
 public AddModel(BlogContext context)
 {
     _context = context;
 }
예제 #43
0
        public void SetUp()
        {
            MockContext = MockRepository.GenerateMock<BlogContext>();
            SetPosts = MockRepository.GenerateMock<IDbSet<Post>, IQueryable>();
            SetCategories = MockRepository.GenerateMock<IDbSet<Category>, IQueryable>();
            SetTags = MockRepository.GenerateMock<IDbSet<Tag>, IQueryable>();
            #region Sample Posts and Mock Set Up
            Posts = new List<Post>
            {
                new Post
                {
                    //Category = Categories.Single(p => p.Id == 1),
                    Description = "Hello World Welcomes you!",
                    Id = 1,
                    Meta = "helloworld",
                    Modified = new DateTime(2015, 6, 3),
                    PostedOn = new DateTime(2015, 6, 1),
                    Published = true,
                    ShortDescription = "Hello World is awesome",
                    //Tags = this.Tags.ToList(),
                    Title = "Hello World is a great starting place",
                    UrlSlug = "helloworldpost"

                },
                new Post
                {
                    //Category = Categories.Single(p => p.Id == 2),
                    Description = "GMU Welcomes you!",
                    Id = 2,
                    Meta = "gmu",
                    Modified = new DateTime(2015, 6, 3),
                    PostedOn = new DateTime(2015, 6, 1),
                    Published = true,
                    ShortDescription = "GMU is awesome",
                    //Tags = this.Tags.Where(t => t.Id == 2).ToList(),
                    Title = "GMUis a great starting place",
                    UrlSlug = "gmupost"

                },
                 new Post
                {
                   // Category = Categories.Single(p => p.Id == 3),
                    Description = "Entity Framework is great!",
                    Id = 3,
                    Meta = "ef",
                    Modified = new DateTime(2015, 6, 3),
                    PostedOn = new DateTime(2015, 6, 1),
                    Published = true,
                    ShortDescription = "Entity Framework is awesome",
                    //Tags = this.Tags.Where(t => t.Id == 1 || t.Id == 3).ToList(),
                    Title = "Entity Framework is a great starting place",
                    UrlSlug = "efpost"

                }

            }.AsQueryable();

            #endregion

            #region Sample Categories and Mock Set Up
            Categories = new List<Category>
            {
                new Category
                {
                    Description = "Humor",
                    Id = 1,
                    Name = "Humor",
                    //Posts = this.Posts.ToList(),
                    UrlSlug = "humor"
                },
                   new Category
                {
                    Description = "Programming",
                    Id = 2,
                    Name = "Programming",
                    //Posts = this.Posts.ToList(),
                    UrlSlug = "programming"
                },
                   new Category
                {
                    Description = "School",
                    Id = 3,
                    Name = "School",
                    //Posts = this.Posts.ToList(),
                    UrlSlug = "school"
                }
            }.AsQueryable();

            #endregion

            #region Sample Tags and Mock Set Up
            Tags = new List<Tag>
            {
                new Tag
                {
                    Description = "Hello World",
                    Id = 1,
                    Name = "Hello World",
                    //Posts = this.Posts.ToList(),
                    UrlSlug = "helloworld"
                },
                 new Tag
                {
                    Description = "MVC",
                    Id = 2,
                    Name = "MVC",
                   // Posts = this.Posts.ToList(),
                    UrlSlug = "MVC"
                },
                 new Tag
                {
                    Description = "Hello World",
                    Id = 3,
                    Name = "Hello World",
                    //Posts = this.Posts.ToList(),
                    UrlSlug = "helloworld"
                },

            }.AsQueryable();

            #endregion

            #region Setting relationships
            // setting relations for posts
            Random rnd = new Random();
            foreach (var post in Posts)
            {
                //assigns random tags to posts
                post.Tags = this.Tags.Where(p => p.Id == rnd.Next(1, 4)).ToList();
                //assigns random category to post
                post.Category = this.Categories.Single(p => p.Id == 1);
            }

            //setting relations for tags
            foreach (var tag in Tags)
            {
                //assigns random tags to posts
                tag.Posts = this.Posts.Where(p => p.Id == rnd.Next(1, 4)).ToList();
            }

            foreach (var category in Categories)
            {
                category.Posts = this.Posts.Where(p => p.Id == rnd.Next(1, 4)).ToList();
            }
            #endregion

            SetPosts.Stub(m => m.Provider).Return(Posts.Provider);
            SetPosts.Stub(m => m.Expression).Return(Posts.Expression);
            SetPosts.Stub(m => m.ElementType).Return(Posts.ElementType);
            SetPosts.Stub(m => m.GetEnumerator()).Return(Posts.GetEnumerator());
            MockContext.Stub(x => x.Posts).PropertyBehavior();

            MockContext.Posts = SetPosts;

            SetCategories.Stub(m => m.Provider).Return(Categories.Provider);
            SetCategories.Stub(m => m.Expression).Return(Categories.Expression);
            SetCategories.Stub(m => m.ElementType).Return(Categories.ElementType);
            SetCategories.Stub(m => m.GetEnumerator()).Return(Categories.GetEnumerator());
            MockContext.Stub(x => x.Categories).PropertyBehavior();

            MockContext.Categories = SetCategories;

            SetTags.Stub(m => m.Provider).Return(Tags.Provider);
            SetTags.Stub(m => m.Expression).Return(Tags.Expression);
            SetTags.Stub(m => m.ElementType).Return(Tags.ElementType);
            SetTags.Stub(m => m.GetEnumerator()).Return(Tags.GetEnumerator());
            MockContext.Stub(x => x.Tags).PropertyBehavior();

            MockContext.Tags = SetTags;
        }
예제 #44
0
 public CategoryViewModel(BlogContext _blogContext)
 {
     this.Categories = _blogContext.AllCategories();
 }
예제 #45
0
 public UserRepo(BlogContext context, UserManager <BlogUser> userManager)
 {
     _context     = context;
     _userManager = userManager;
 }
예제 #46
0
 public ImageRepository(BlogContext context) : base(context)
 {
 }
예제 #47
0
 public PostRepository()
 {
     string connection = ConfigurationManager.ConnectionStrings["ApplicationServices"].ConnectionString;
     _context = new BlogContext(connection);
 }
예제 #48
0
        public void Rule_FilterOverOuterApply_does_not_promote_to_CrossApply_if_filter_predicate_is_expanded_in_null_semantics_phase()
        {
            var expectedSql =
            @"SELECT
            [Extent1].[Id] AS [Id],
            [Extent1].[Name] AS [Name]
            FROM  [dbo].[Blogs] AS [Extent1]
            OUTER APPLY  (SELECT TOP (1) [Extent2].[Name] AS [Name]
            FROM [dbo].[BlogEntries] AS [Extent2]
            WHERE ([Extent2].[Name] = [Extent1].[Name]) OR (([Extent2].[Name] IS NULL) AND ([Extent1].[Name] IS NULL)) ) AS [Limit1]
            WHERE ([Extent1].[Name] = [Limit1].[Name]) OR (([Extent1].[Name] IS NULL) AND ([Limit1].[Name] IS NULL))";

            using (var context = new BlogContext())
            {
                context.Configuration.UseDatabaseNullSemantics = false;

                var query = from b in context.Blogs
                    from e in context.BlogEntries.Where(e => e.Name == b.Name).Take(1).DefaultIfEmpty()
                    where b.Name == e.Name
                    select b;

                QueryTestHelpers.VerifyDbQuery(query, expectedSql);
            }
        }
 public void Throws_on_attempt_to_use_context_with_no_store()
 {
     Assert.Equal(
         GetString("FormatNoDataStoreConfigured"),
         // TODO: Should not be AggregateException
         Assert.Throws<AggregateException>(() =>
             {
                 using (var context = new BlogContext())
                 {
                     context.Blogs.Add(new Blog { Name = "The Waffle Cart" });
                     context.SaveChanges();
                 }
             }).InnerException.Message);
 }
예제 #50
0
 public TagRepository(BlogContext context) : base(context)
 {
     // This ensures our base constructor gets run.
 }
예제 #51
0
        /// <summary>
        /// Try to install the blog
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public async Task <OperationResult> TryInstallAsync(InstallModel model)
        {
            await _lock.WaitAsync();

            try
            {
                if (!RequestLocalizationOptions.Value.SupportedCultures.Any(t => t.Name.Equals(model.Language)))
                {
                    return(OperationResult.Failure(InstallLocalizer["Not supported language"]));
                }

                if (!NeedToInstall())
                {
                    return(OperationResult.Failure(InstallLocalizer["Blog has been already installed"]));
                }
                else
                {
                    using var transaction = BlogContext.Database.BeginTransaction();

                    //1. Add admin user
                    var result = await AddAdminUserAsync(model);

                    if (!result.Success)
                    {
                        return(result);
                    }

                    //2. Setup default settings
                    result = await AddSettingsAsync(model);

                    if (!result.Success)
                    {
                        return(result);
                    }

                    //3. Setup widgets
                    result = await AddWidgetsAsync(model);

                    if (!result.Success)
                    {
                        return(result);
                    }

                    await BlogContext.SaveChangesAsync();

                    //Clear settings cache
                    SettingService settingService = ServiceProvider.GetService <SettingService>();
                    settingService.RemoveCache();

                    //Clear widgets cache
                    WidgetService widgetService = ServiceProvider.GetService <WidgetService>();
                    widgetService.RemoveCache();

                    //4. Add topic
                    result = await AddSampleTopicAsync(model);

                    if (!result.Success)
                    {
                        return(result);
                    }

                    _cacheOfNeedToInstall = false;

                    await transaction.CommitAsync();

                    return(new OperationResult());
                }
            }
            finally
            {
                _lock.Release();
            }
        }
예제 #52
0
 public BlogController(BlogContext blogContext)
 {
     _blogContext = blogContext;
 }
예제 #53
0
 public CategoryService(BlogContext blogContext, IMemoryCache cache)
 {
     BlogContext = blogContext;
     Cache       = cache;
 }
예제 #54
0
        public async Task <OperationResult <TopicModel> > Edit(EditTopicModel model)
        {
            var entity = await BlogContext.Topics.SingleOrDefaultAsync(t => t.Id == model.Id);

            if (entity == null)
            {
                return(OperationResult <TopicModel> .Failure(L["The article does not exists"].Value));
            }

            using (var tran = await BlogContext.Database.BeginTransactionAsync())
            {
                List <CategoryTopic> deletedCategoryTopicList = await BlogContext.CategoryTopics.Where(t => t.TopicId == model.Id).ToListAsync();

                BlogContext.RemoveRange(deletedCategoryTopicList);
                List <TagTopic> deletedTagTopicList = await BlogContext.TagTopics.Where(t => t.TopicId == model.Id).ToListAsync();

                BlogContext.RemoveRange(deletedTagTopicList);

                await BlogContext.SaveChangesAsync();

                model.CategoryList = (model.CategoryList ?? new int[0]).Distinct().ToArray();
                model.TagList      = (model.TagList ?? new string[0]).Distinct().ToArray();

                List <Category> categoryEntityList = await BlogContext.Categories.Where(t => model.CategoryList.Contains(t.Id)).ToListAsync();

                List <Tag> tagEntityList = await BlogContext.Tags.Where(t => model.TagList.Contains(t.Keyword)).ToListAsync();

                model.Alias = await this.GenerateAlias(model.Id, model.Alias, model.Title);

                model.Summary = this.GenerateSummary(model.Summary, model.Content);

                foreach (var tag in model.TagList)
                {
                    if (!tagEntityList.Any(t => t.Keyword == tag))
                    {
                        var tagEntity = new Tag
                        {
                            Keyword = tag
                        };
                        BlogContext.Tags.Add(tagEntity);
                        tagEntityList.Add(tagEntity);
                    }
                }

                entity.Title        = model.Title;
                entity.Content      = model.Content;
                entity.Status       = model.Status;
                entity.Alias        = model.Alias;
                entity.Summary      = model.Summary;
                entity.EditDate     = model.Date ?? DateTime.Now;
                entity.AllowComment = model.AllowComment;

                List <CategoryTopic> categoryTopicList = categoryEntityList.Select(t => new CategoryTopic
                {
                    Category = t,
                    Topic    = entity
                }).ToList();
                BlogContext.CategoryTopics.AddRange(categoryTopicList);

                List <TagTopic> tagTopicList = tagEntityList.Select(t => new TagTopic
                {
                    Tag   = t,
                    Topic = entity
                }).ToList();
                BlogContext.TagTopics.AddRange(tagTopicList);

                await BlogContext.SaveChangesAsync();

                tran.Commit();
            }

            BlogContext.RemoveCategoryCache();
            BlogContext.RemoveTagCache();

            var topicModel = (await this.Transform(entity)).First();

            return(new OperationResult <TopicModel>(topicModel));
        }
            public void Throws_on_attempt_to_use_store_with_no_store_services()
            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddEntityFramework();
                var serviceProvider = serviceCollection.BuildServiceProvider();

                Assert.Equal(
                    GetString("FormatNoDataStoreService"),
                    // TODO: Should not be AggregateException
                    Assert.Throws<AggregateException>(() =>
                        {
                            using (var context = new BlogContext(serviceProvider))
                            {
                                context.Blogs.Add(new Blog { Name = "The Waffle Cart" });
                                context.SaveChanges();
                            }
                        }).InnerException.Message);
            }
예제 #56
0
        /// <summary>
        /// 得到按月份的文章统计结果
        /// </summary>
        /// <returns></returns>
        public async Task <List <MonthStatisticsModel> > QueryMonthStatistics()
        {
            var list = BlogContext.QueryMonthStatisticsFromCache();

            return(await Task.FromResult(list));
        }
                public MyBlogController(BlogContext context)
                {
                    Assert.NotNull(context);

                    _context = context;
                }
예제 #58
0
        public async Task <OperationResult <TopicModel> > Add(AddTopicModel model)
        {
            model.CategoryList = (model.CategoryList ?? new int[0]).Distinct().ToArray();
            model.TagList      = (model.TagList ?? new string[0]).Distinct().ToArray();

            List <Category> categoryEntityList = await BlogContext.Categories.Where(t => model.CategoryList.Contains(t.Id)).ToListAsync();

            List <Tag> tagEntityList = await BlogContext.Tags.Where(t => model.TagList.Contains(t.Keyword)).ToListAsync();

            model.Alias = await this.GenerateAlias(null, model.Alias, model.Title);

            model.Summary = this.GenerateSummary(model.Summary, model.Content);

            foreach (var tag in model.TagList)
            {
                if (!tagEntityList.Any(t => t.Keyword == tag))
                {
                    var tagEntity = new Tag
                    {
                        Keyword = tag
                    };
                    BlogContext.Tags.Add(tagEntity);
                    tagEntityList.Add(tagEntity);
                }
            }

            var topic = new Topic
            {
                Alias        = model.Alias,
                AllowComment = model.AllowComment,
                Content      = model.Content,
                CreateDate   = DateTime.Now,
                CreateUserId = this.ClientManager.CurrentUser.Id,
                EditDate     = model.Date ?? DateTime.Now,
                EditUserId   = 1,
                Status       = model.Status,
                Summary      = model.Summary,
                Title        = model.Title
            };

            BlogContext.Topics.Add(topic);

            List <CategoryTopic> categoryTopicList = categoryEntityList.Select(t => new CategoryTopic
            {
                Category = t,
                Topic    = topic
            }).ToList();

            BlogContext.CategoryTopics.AddRange(categoryTopicList);

            List <TagTopic> tagTopicList = tagEntityList.Select(t => new TagTopic
            {
                Tag   = t,
                Topic = topic
            }).ToList();

            BlogContext.TagTopics.AddRange(tagTopicList);

            await BlogContext.SaveChangesAsync();

            BlogContext.RemoveCategoryCache();
            BlogContext.RemoveTagCache();

            var topicModel = (await this.Transform(topic)).First();

            return(new OperationResult <TopicModel>(topicModel));
        }
예제 #59
0
 public BlogController(BlogContext context)
 {
     _context = context;
 }
예제 #60
0
 public UserService(BlogContext context, IPasswordManager passwordManager)
 {
     _context         = context;
     _passwordManager = passwordManager;
 }