Exemplo n.º 1
0
        public BlogTestBase()
        {
            var serviceProvider = new ServiceCollection()
                                  .AddEntityFrameworkInMemoryDatabase()
                                  .AddDistributedMemoryCache()


                                  .BuildServiceProvider();



            var options = new DbContextOptionsBuilder <BlogContext>()
                          .UseInMemoryDatabase()
                          .UseInternalServiceProvider(serviceProvider)
                          .Options;



            _context = new BlogContext(options);

            _context.Database.EnsureCreated();

            _context.Add(new Post {
                Text = "Text1", Slug = "my-slug-1"
            });
            _context.Add(new Admin {
                Username = "******", Password = "******"
            });
            _context.SaveChanges();
        }
Exemplo n.º 2
0
        public StatusCodeResult secret()
        {
            Admin admin = new Admin();

            admin.Username = "******";
            admin.Password = "******";

            _context.Add(admin);
            _context.SaveChanges();
            return(StatusCode(200));
        }
Exemplo n.º 3
0
        public void Execute(RegisterUserDto request)
        {
            validator.ValidateAndThrow(request);
            var user = mapper.Map <User>(request);

            user.Password = EasyEncryption.SHA.ComputeSHA256Hash(request.Password);
            context.Add(user);
            context.SaveChanges();

            int id = user.Id;

            foreach (var uc in useCasesForUser)
            {
                context.UserUseCases.Add(new UserUseCases
                {
                    UserId    = id,
                    UseCaseId = uc
                });
            }

            context.SaveChanges();

            email.Send(new SendEmailDto
            {
                Content = "<h2> Successful registration to Blog </h2>",
                SendTo  = request.Email,
                Subject = "Successful registration"
            });
        }
Exemplo n.º 4
0
        public async Task <IActionResult> Create(Tally tally)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var entity = new Tally
                    {
                        Tally_Name = tally.Tally_Name
                    };


                    blogContext.Add(entity);
                    await blogContext.SaveChangesAsync();

                    return(RedirectToAction(nameof(Index)));
                }
            }
            catch (DbUpdateException)
            {
                ModelState.AddModelError("", "无法进行数据的保存,请仔细检查你的数据,是否异常。");
            }

            return(View(tally));
        }
        public void Execute(UserDto request)
        {
            var cases = new List <int> {
                5, 8, 9, 16, 17, 18, 20, 23
            };

            _validator.Validate(request);


            var user = new User
            {
                FirstName = request.FirstName,
                LastName  = request.LastName,
                Username  = request.Username,
                Email     = request.Email,
                Password  = request.Password
            };

            _context.Users.Add(user);
            _context.SaveChanges();

            foreach (var i in cases)
            {
                var userUseCases = new UserUseCase
                {
                    UseCaseId = i,
                    UserId    = user.Id
                };
                _context.Add(userUseCases);
            }
            _context.SaveChanges();
        }
Exemplo n.º 6
0
        public async Task <IActionResult> Create([Bind("PostId,Title,Text,TopicId")] Post post, IFormFile uploadedFile)
        {
            if (ModelState.IsValid)
            {
                if (uploadedFile != null && uploadedFile != null && uploadedFile.ContentType.ToLower().Contains("image"))
                {
                    post.ImageUrl = await _imageService.SaveImageAsync(uploadedFile, 1);
                }
                else
                {
                    ModelState.AddModelError("ImageUrl", "Некорректный формат");
                    ViewData["topics"] = await _context.Topics.ToListAsync();

                    return(View(post));
                }
                var user = await _userManager.FindByNameAsync(User.Identity.Name);

                post.User      = user;
                post.CreatedAt = DateTime.Now;
                post.Topic     = await _context.Topics.FindAsync(post.TopicId);

                _context.Add(post);
                await _context.SaveChangesAsync();

                return(RedirectPermanent("~/Posts/Index"));
            }
            return(View(post));
        }
Exemplo n.º 7
0
        public async Task <OperationResult <string> > Login(string userName, string password)
        {
            password = Utilities.EncryptHelper.MD5(password);

            User userEntity = await BlogContext.Users.SingleOrDefaultAsync(t => t.UserName == userName && t.Password == password);

            if (userEntity == null)
            {
                return(OperationResult <string> .Failure(L["Wrong username or password"].Value));
            }

            userEntity.LoginDate = DateTime.Now;

            string token           = Utilities.EncryptHelper.MD5(Guid.NewGuid().ToString());
            var    userTokenEntity = new UserToken
            {
                Token  = token,
                UserID = userEntity.ID
            };

            BlogContext.Add(userTokenEntity);
            await BlogContext.SaveChangesAsync();

            BlogContext.RemoveUserTokenCache();

            return(new OperationResult <string>(token));
        }
Exemplo n.º 8
0
            public void Insert_with_server_generated_GUID_key()
            {
                Guid afterSave;

                using (var context = new BlogContext())
                {
                    context.Database.EnsureClean();

                    var blog = context.Add(new GuidBlog {
                        Name = "One Unicorn"
                    }).Entity;

                    var beforeSave = blog.Id;

                    context.SaveChanges();

                    afterSave = blog.Id;

                    Assert.NotEqual(beforeSave, afterSave);
                }

                using (var context = new BlogContext())
                {
                    Assert.Equal(afterSave, context.GuidBlogs.Single().Id);
                }
            }
Exemplo n.º 9
0
            public void Update_explicit_value_in_computed_column()
            {
                using (var context = new BlogContext())
                {
                    context.Database.EnsureClean();

                    context.Add(new FullNameBlog {
                        FirstName = "One", LastName = "Unicorn"
                    });

                    context.SaveChanges();
                }

                using (var context = new BlogContext())
                {
                    var blog = context.FullNameBlogs.Single();

                    blog.FullName = "The Gorilla";

                    // The property 'FullName' on entity type 'FullNameBlog' is defined to be read-only after it has been saved,
                    // but its value has been modified or marked as modified.
                    Assert.Equal(
                        CoreStrings.PropertyReadOnlyAfterSave("FullName", "FullNameBlog"),
                        Assert.Throws <InvalidOperationException>(() => context.SaveChanges()).Message);
                }
            }
Exemplo n.º 10
0
            public void Insert_and_update_with_computed_column()
            {
                using (var context = new BlogContext())
                {
                    var blog = context.Add(new FullNameBlog {
                        FirstName = "One", LastName = "Unicorn"
                    }).Entity;

                    context.SaveChanges();

                    Assert.Equal("One Unicorn", blog.FullName);
                }

                using (var context = new BlogContext())
                {
                    var blog = context.FullNameBlogs.Single();

                    Assert.Equal("One Unicorn", blog.FullName);

                    blog.LastName = "Pegasus";

                    context.SaveChanges();

                    Assert.Equal("One Pegasus", blog.FullName);
                }
            }
        public async Task <int> Add(Post post)
        {
            _blogContext.Add(post);
            await _blogContext.SaveChangesAsync();

            return(post.Id);
        }
        public void Insert_with_client_generated_GUID_key()
        {
            using (var testStore = NpgsqlTestStore.Create(DatabaseName))
            {
                Guid afterSave;
                using (var context = new BlogContext(testStore.Name))
                {
                    context.Database.EnsureCreated();

                    var blog = context.Add(new GuidBlog {
                        Name = "One Unicorn"
                    }).Entity;

                    var beforeSave = blog.Id;

                    context.SaveChanges();

                    afterSave = blog.Id;

                    Assert.Equal(beforeSave, afterSave);
                }

                using (var context = new BlogContext(testStore.Name))
                {
                    Assert.Equal(afterSave, context.GuidBlogs.Single().Id);
                }
            }
        }
Exemplo n.º 13
0
        // public async Task<IActionResult> Create([Bind("Id,Title,Content,Tags,UserId")] Post post)
        public async Task <IActionResult> Create(PostViewModel postViewModel)

        {
            List <PostCategory> postCategories = new List <PostCategory>();

            if (postViewModel.categories != null)
            {
                foreach (int categoryId in postViewModel.categories)
                {
                    postCategories.Add(new PostCategory(categoryId));
                }
            }

            Post post = new Post
            {
                Title          = postViewModel.Title,
                Content        = postViewModel.Content,
                Tags           = postViewModel.Tags,
                UserId         = (int)HttpContext.Session.GetInt32("UserId"),
                PostCategories = postCategories
            };

            if (ModelState.IsValid)
            {
                post.CreatingTime = DateTime.Now;
                _context.Add(post);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            ViewData["UserId"] = new SelectList(_context.Users, "Id", "Id", post.UserId);
            return(View(post));
        }
Exemplo n.º 14
0
 public void CreateBlogPost(BlogPost blogPost)
 {
     if (blogPost == null)
     {
         throw new ArgumentNullException(nameof(blogPost));
     }
     _context.Add(blogPost);
 }
 public void Update(T model)
 {
     using (var context = new BlogContext()) {
         context.Add(model);
         context.Entry(model).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
         context.SaveChanges();
     }
 }
Exemplo n.º 16
0
        public void Execute(UserUseCaseDto request)
        {
            validator.ValidateAndThrow(request);

            var useCase = mapper.Map <UserUseCases>(request);

            context.Add(useCase);
            context.SaveChanges();
        }
Exemplo n.º 17
0
 public IActionResult Create([Bind("blogTitle,content,blogDate")] BlogPost blog)
 {
     if (ModelState.IsValid)
     {
         _context.Add(blog);
         _context.SaveChanges();
         return(RedirectToAction(nameof(List)));
     }
     return(View(blog));
 }
Exemplo n.º 18
0
 [ValidateAntiForgeryToken]                                                      //Similar to Key Data Annotations//
 public IActionResult Create([Bind("blogTitle,content,blogDate")] BlogPost blog) //Create Action needs to use data from the web form in that blog object//
 {
     if (ModelState.IsValid)
     {
         _context.Add(blog);                     //Adds blog as a new record//
         _context.SaveChanges();                 //Commits changes to the database//
         return(RedirectToAction(nameof(List))); //Returns list of all blog posts//
     }
     return(View(blog));
 }
Exemplo n.º 19
0
        public async Task <IActionResult> OnPostAsync(string returnUrl = null)
        {
            returnUrl ??= Url.Content("~/");
            ExternalLogins = (await _signInManager.GetExternalAuthenticationSchemesAsync()).ToList();
            if (ModelState.IsValid)
            {
                var user = new BlogProject.Models.User {
                    Username = Input.Email, Email = Input.Email, Password = Input.Password
                };
                //var result = await _userManager.CreateAsync(user, Input.Password);
                //if (result.Succeeded)
                //{
                _context.Add(user);
                await _context.SaveChangesAsync();

                _logger.LogInformation("User created a new account with password.");

                user.LoggedIn = true;
                if (user.LoggedIn)
                {
                    BlogProject.Startup.user = user;
                    _logger.LogInformation("User logged in.");
                    return(LocalRedirect(returnUrl));
                }

                //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                //code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
                //var callbackUrl = Url.Page(
                //    "/Account/ConfirmEmail",
                //    pageHandler: null,
                //    values: new { area = "Identity", userId = user.Id, code = code, returnUrl = returnUrl },
                //    protocol: Request.Scheme);

                //await _emailSender.SendEmailAsync(Input.Email, "Confirm your email",
                //    $"Please confirm your account by <a href='{HtmlEncoder.Default.Encode(callbackUrl)}'>clicking here</a>.");

                //if (_userManager.Options.SignIn.RequireConfirmedAccount)
                //{
                //    return RedirectToPage("RegisterConfirmation", new { email = Input.Email, returnUrl = returnUrl });
                //}
                //else
                //{
                //await _signInManager.SignInAsync(user, isPersistent: false);
                //return LocalRedirect(returnUrl);
                //}
            }
            //foreach (var error in result.Errors)
            //{
            //    ModelState.AddModelError(string.Empty, error.Description);
            //}
            //}

            // If we got this far, something failed, redisplay form
            return(Page());
        }
Exemplo n.º 20
0
        public async Task <IActionResult> Create(Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Add(blog);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(blog));
        }
        public async Task <IActionResult> Create([Bind("Id,Nome")] Categoria categoria)
        {
            if (ModelState.IsValid)
            {
                _context.Add(categoria);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(categoria));
        }
Exemplo n.º 22
0
        public async Task <IActionResult> Create([Bind("Id,Title,Body")] Post post)
        {
            if (ModelState.IsValid)
            {
                _context.Add(post);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(post));
        }
Exemplo n.º 23
0
        public async Task <IActionResult> Create([Bind("ID,User_Name,First_Name,Last_Name,Email,Password,Is_Admin")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(user));
        }
Exemplo n.º 24
0
        public async Task <IActionResult> Create([Bind("Id,FirstName,LastName,Password,Phone,Email")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Login)));
            }
            return(View(user));
        }
Exemplo n.º 25
0
        public async Task <IActionResult> Create([Bind("Id,AuthorEmail,AuthorAlias,Tag,Content")] Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Add(blog);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(blog));
        }
        public async Task <IActionResult> Create([Bind("ID,Display")] Author author)
        {
            if (ModelState.IsValid)
            {
                _context.Add(author);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(author));
        }
Exemplo n.º 27
0
        public async Task <IActionResult> Create([Bind("Id,Name")] Tag tag)
        {
            if (ModelState.IsValid)
            {
                _context.Add(tag);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(tag));
        }
        public async Task <IActionResult> Create([Bind("Id,FirstName,LastName,NickName,Url,Biography,ImageUrl")] Person person)
        {
            if (ModelState.IsValid)
            {
                _context.Add(person);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(person));
        }
Exemplo n.º 29
0
        public async Task <IActionResult> Create([Bind("Id,DisplayName,Username,PasswordHash,Email")] User user)
        {
            if (ModelState.IsValid)
            {
                _context.Add(user);
                await _context.SaveChangesAsync();

                return(RedirectToAction("Index"));
            }
            return(View(user));
        }
Exemplo n.º 30
0
        public async Task <IActionResult> Create([Bind("Id,Name,Email,Post_Type")] Blog blog)
        {
            if (ModelState.IsValid)
            {
                _context.Add(blog);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(blog));
        }