示例#1
0
        public async Task <bool> ApprooveNews(int newsId, string link)
        {
            var news = await context.News
                       .Include(n => n.Owner)
                       .Include(n => n.Owner.User)
                       .FirstOrDefaultAsync(n => n.Id == newsId);

            if (news != null)
            {
                if (!news.isAproove)
                {
                    news.isAproove = true;
                    news.PublishOn = DateTime.Now;
                    var isModifyed = news.isModifyed;
                    news.isModifyed = false;
                    context.News.Update(news);

                    await SetNotificationAsync(news, link, isModifyed);

                    await context.SaveChangesAsync();

                    return(true);
                }
            }
            return(false);
        }
示例#2
0
        public async Task Add([FromBody] Topic topic)
        {
            topic.Host = Host;
            await db.Topics.AddAsync(topic);

            await db.SaveChangesAsync();
        }
示例#3
0
        public async Task <IActionResult> Create([Bind("Id,TimeStamp,Text")] NewsItem newsItem)
        {
            if (ModelState.IsValid)
            {
                _context.Add(newsItem);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(newsItem));
        }
示例#4
0
        public async Task <bool> CreateComment(CommentCreateModel model, string userName, string link, int?commentId)
        {
            var userProfile = await context
                              .Profiles
                              .Include(u => u.User)
                              .FirstOrDefaultAsync(p => p.User.UserName == userName);

            var news = await context
                       .News
                       .FirstOrDefaultAsync(n => n.Id == model.NewsId);

            if (news != null)
            {
                await statisticNewsService.SetState(model.NewsId, userName, "view", string.Empty);

                var now = DateTime.Now;
                await context.Comments.AddAsync(new Data.dbModels.Comment
                {
                    News        = news,
                    DateComment = now,
                    Text        = model.TextComment,
                    Owner       = userProfile,
                    UserNameTo  = model.UsernameAddresTo,
                    CommentIdTo = model.CommentIdTo
                });

                if (!string.IsNullOrEmpty(model.UsernameAddresTo))
                {
                    var profileFrom  = userProfile.Id;
                    var userFromName = userProfile.User.UserName;

                    var userToId = (await context
                                    .Users
                                    .FirstOrDefaultAsync(u => u.UserName == model.UsernameAddresTo))
                                   ?.Id;

                    var profileTo = await context.Profiles.FirstOrDefaultAsync(p => p.UserId == userToId);

                    if (profileTo != null)
                    {
                        await SetNotificationAsync(profileTo, profileFrom, link, userFromName, commentId);
                    }
                }

                await context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
示例#5
0
        public async Task <IActionResult> AddNews(NewsModel newsModel)
        {
            News news = new News();

            news.Image = await newsModel.Image.GetBytes();

            news.Title       = newsModel.Title;
            news.SubTitle    = newsModel.SubTitle;
            news.Description = newsModel.Description;
            await _newsDbContext.News.AddAsync(news);

            await _newsDbContext.SaveChangesAsync();

            return(Redirect("/admin/"));
        }
示例#6
0
        public async Task <IActionResult> AddNews([FromBody] Models.News news)
        {
            _context.News.Add(news);
            await _context.SaveChangesAsync();

            await _hubContext.Clients.All.SendAsync("AddNews", news);

            var json = @"{
              'notification': {
                'title': 'News',
                'body': 'New news arrived...',
                'sound': 'default',
                'click_action': 'FCM_PLUGIN_ACTIVITY',
                'icon': 'fcm_push_icon',
              },
              'data': {
                'newsId': 'adrenokortikotropik hormon',
              },
              'to': '/topics/all',
              'priority': 'high',
              'restricted_package_name': '',
            }";

            JObject requestBody = JObject.Parse(json);

            requestBody["data"]["newsId"]        = news.Id;
            requestBody["notification"]["title"] = news.Title;

            var length = 30;

            if (news.Text.Length < length)
            {
                length = news.Text.Length;
            }
            requestBody["notification"]["body"] = news.Text.Substring(0, length).Insert(length, "...");

            var client = _clientFactory.CreateClient();

            client.DefaultRequestHeaders.TryAddWithoutValidation("Content-Type", "application/json");
            client.DefaultRequestHeaders.TryAddWithoutValidation("Authorization",
                                                                 "key=AAAAwUeco1c:APA91bFY4m-vuOPPCzcqb4upPh2Y8BTNSd7bc04enZ9vONOed9YJjytF5pha1FhgQw_JZb2aq4LKy06s2vtkcfePg_SvcX_noB0MILNFLhJQzuogAYNHHnbUm9x1l1JBs_dO_si53_IE");

            var response = await client.PostAsJsonAsync("https://fcm.googleapis.com/fcm/send", requestBody);

            var result = await response.Content.ReadAsStringAsync();

            return(Ok(result));
        }
示例#7
0
        public async Task InvokeAsync(HttpContext httpcontext, NewsDbContext context)
        {
            var authHeader = httpcontext
                             .Request
                             .Headers
                             .ContainsKey("Authorization");

            if (authHeader)
            {
                var username = httpcontext
                               .User
                               .GetUserName();

                var user = await context
                           .Users
                           .FirstOrDefaultAsync(u => u.UserName == username);

                var profile = await context
                              .Profiles
                              .FirstOrDefaultAsync(p => p.UserId == user.Id && !p.isBaned);

                if (profile != null)
                {
                    profile.LastActiveOn = DateTime.Now;
                    context.Profiles.Update(profile);
                    await context.SaveChangesAsync();
                }
            }
            await next.Invoke(httpcontext);
        }
        public async Task <IHttpActionResult> Post(CreateAuthorViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var ctx = new NewsDbContext())
            {
                var author = new Author()
                {
                    Name = model.Name
                };

                ctx.Authors.Add(author);
                await ctx.SaveChangesAsync();

                var data = new AuthorViewModel()
                {
                    Id   = author.Id,
                    Name = author.Name
                };

                return(Created(new Uri(Request.RequestUri + "api/authors" + data.Id), data));
            }
        }
示例#9
0
        private async Task SetState(
            CProfile user,
            CNews news,
            string state,
            string link)
        {
            var isLike = await context
                         .StatisticNews
                         .FirstOrDefaultAsync(sn => sn.Like == user && sn.News == news);

            var isDislike = await context
                            .StatisticNews
                            .FirstOrDefaultAsync(sn => sn.Dislike == user && sn.News == news);

            var isViews = await context
                          .StatisticNews
                          .FirstOrDefaultAsync(sn => sn.ViewBy == user && sn.News == news);

            if (state == "like")
            {
                await SetLike(isLike, isDislike, isViews, user, news, link);
            }
            else if (state == "dislike")
            {
                await SetDislike(isDislike, isLike, isViews, user, news);
            }
            else if (state == "view")
            {
                await SetView(isViews, user, news);
            }
            await context.SaveChangesAsync();
        }
示例#10
0
        public async Task <string> UploadProfileImage(string username, IFormFile image)
        {
            var dirPath = Path.Combine(env.WebRootPath, "img");

            Directory.CreateDirectory(dirPath);
            var guid     = System.Guid.NewGuid();
            var getType  = image.ContentType;
            var imgType  = getType.Replace("image/", ".");
            var filePath = Path.Combine(dirPath, guid.ToString() + imgType);

            using (FileStream stream = new FileStream(filePath, FileMode.Create))
            {
                await image.CopyToAsync(stream);
            }

            var user = await context
                       .Users
                       .FirstOrDefaultAsync(u => u.UserName == username);

            var modPath = filePath.Replace(Path.Combine(env.WebRootPath), "");

            user.Photo = modPath;
            context.Users.Update(user);

            await context.SaveChangesAsync();

            return(modPath);
        }
示例#11
0
        public async Task <IActionResult> Add(News news)
        {
            if (ModelState.IsValid)
            {
                News new_news = new News();
                new_news.SubCategoryId = news.SubCategoryId;
                new_news.ShortDesc     = news.ShortDesc;
                new_news.Text          = news.Text;
                new_news.CreatedDate   = DateTime.Now;

                db.News.Add(new_news);

                foreach (var photo in news.PhotoNames)
                {
                    NewsPhoto newsPhoto = new NewsPhoto();
                    newsPhoto.News  = new_news;
                    newsPhoto.Photo = photo;
                    db.NewsPhotos.Add(newsPhoto);
                }

                await db.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View());
        }
        public async Task ActionGetAllShouldReturnStatusCodeOkAndAllNewsItems()
        {
            //Arrange
            const string Test = "Test";

            var dbOptions = new DbContextOptionsBuilder <NewsDbContext>()
                            .UseInMemoryDatabase("NewsDb")
                            .Options;

            var db             = new NewsDbContext(dbOptions);
            var newsService    = new NewsService(db);
            var userController = new NewsController(newsService);

            var news = new News
            {
                Id          = 1,
                Title       = Test,
                Content     = "Test content",
                PublishDate = DateTime.UtcNow
            };

            await db.News.AddAsync(news);

            await db.SaveChangesAsync();

            //Act
            var result = await userController.GetAll();

            //Assert
            result
            .Should()
            .BeOfType <OkObjectResult>()
            .Which.Value.As <NewsFullDetailsServiceModel>();
        }
        /// <summary>
        /// Method for adding news
        /// </summary>
        /// <param name="news">The news object that is to be added</param>
        /// <returns>The added news if success else null</returns>
        public async Task <News> AddNews(News news)
        {
            try
            {
                await context.NewsList.AddAsync(news);

                if (await context.SaveChangesAsync() > 0)
                {
                    return(news);
                }
                return(null);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
示例#14
0
        public async Task <bool> AddSection(AddSectionNameModel model)
        {
            var SectionName = await context
                              .SectionsNames
                              .FirstOrDefaultAsync(sn => sn.SectionName == model.SectionName);

            if (SectionName == null)
            {
                await context
                .SectionsNames
                .AddAsync(new SectionsName { SectionName = model.SectionName });

                await context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }
示例#15
0
        public async Task <bool> CommitAsync()
        {
            if (await dbContext.SaveChangesAsync() > 0)
            {
                return(true);
            }

            return(false);
        }
示例#16
0
        public async Task Viewed(string username, int notificationId)
        {
            var profile = await context
                          .Profiles
                          .Include(p => p.User)
                          .FirstOrDefaultAsync(u => u.User.UserName == username);

            var notification = await context
                               .Notifications
                               .FirstOrDefaultAsync(n => n.Id == notificationId && n.Profile == profile);

            if (notification == null)
            {
                return;
            }

            notification.isViewed = true;
            context.Notifications.Update(notification);
            await context.SaveChangesAsync();
        }
示例#17
0
        public async Task <bool> CreateNews(CreateNewsModel model, string userName)
        {
            var titleExist = await context
                             .News
                             .FirstOrDefaultAsync(n => n.Title == model.Title);

            if (titleExist == null)
            {
                var profile = await context
                              .Profiles
                              .FirstOrDefaultAsync(p => p.User.UserName == userName);

                var section = await context
                              .SectionsNames
                              .FirstOrDefaultAsync(s => s.SectionName == model.SectionName);

                var now = DateTime.Now;

                if (section != null)
                {
                    var createNews = await context
                                     .News
                                     .AddAsync(new CNews
                    {
                        SectionsName = section,
                        Title        = model.Title,
                        Text         = model.Text,
                        Owner        = profile,
                        PublishOn    = now
                    });

                    await context.SaveChangesAsync();

                    return(true);
                }
            }
            return(false);
        }
示例#18
0
        public async Task Region_ShouldBeAdded()
        {
            var region = new Region {
                Name = "Belarus"
            };

            await using var context = new NewsDbContext();

            var regionEntry = await context.Region.AddAsync(region);

            await context.SaveChangesAsync();

            Assert.True(regionEntry.Entity.Id > 0);
        }
示例#19
0
        public async Task SymbolType_ShouldBeDeleted()
        {
            await using var context = new NewsDbContext();

            var toDelete = context.SymbolType.SingleOrDefault(st => st.Name == "tmp");

            if (toDelete == null)
            {
                return;
            }

            context.SymbolType.Remove(toDelete);
            await context.SaveChangesAsync();
        }
示例#20
0
        public async Task SymbolType_ShouldBeAdded()
        {
            var type = new SymbolType {
                Name = "tmp"
            };

            await using var context = new NewsDbContext();

            var symbolType = await context.SymbolType.AddAsync(type);

            await context.SaveChangesAsync();

            Assert.True(symbolType.Entity.Id > 0);
        }
示例#21
0
        public async Task Industry_ShouldCreateRecords(string name)
        {
            var type = new Industry {
                Name = name
            };

            await using var context = new NewsDbContext();

            var industry = await context.Industry.AddAsync(type);

            await context.SaveChangesAsync();

            Assert.True(industry.Entity.Id > 0);

            context.Industry.Remove(industry.Entity);
        }
        public async Task <IHttpActionResult> Delete(int id)
        {
            using (var ctx = new NewsDbContext())
            {
                var author = await ctx.Authors.FirstOrDefaultAsync(o => o.Id == id);

                if (author == null)
                {
                    return(NotFound());
                }

                ctx.Authors.Remove(author);
                await ctx.SaveChangesAsync();

                return(StatusCode(HttpStatusCode.NoContent));
            }
        }
示例#23
0
        public async Task <ActionResult> Register(RegisterModel model)
        {
            var user = await userManager.FindByNameAsync(model.UserName);

            if (user == null)
            {
                var mail = await userManager.FindByEmailAsync(model.Email);

                if (mail == null)
                {
                    var createUser = new User
                    {
                        UserName = model.UserName,
                        Email    = model.Email,
                        Photo    = Path.Combine(env.WebRootPath, "img", "userdefault.png")
                    };

                    await userManager.CreateAsync(createUser, model.Password);

                    await userManager.AddToRoleAsync(createUser, "user");

                    await context.Profiles.AddAsync(new CProfile
                    {
                        User       = createUser,
                        RegisterOn = DateTime.Now
                    });

                    await context.SaveChangesAsync();

                    var path = Path.Combine(env.WebRootPath, createUser.UserName);
                    Directory.CreateDirectory(path);

                    return(Ok());
                }
                else
                {
                    ModelState.AddModelError("mail", "Пользователь с таким E-mail уже существует");
                }
            }
            else
            {
                ModelState.AddModelError("username", "Пользователь с таким именем уже существует");
            }
            return(BadRequest(ModelState));
        }
示例#24
0
        private async Task SetState(CProfile user, CComment comment, string state)
        {
            var isLike = await context
                         .StatisticComments
                         .FirstOrDefaultAsync(sc => sc.Like == user && sc.Comment == comment);

            var isDislike = await context
                            .StatisticComments
                            .FirstOrDefaultAsync(sc => sc.Dislike == user && sc.Comment == comment);

            if (state == "like")
            {
                await SetLike(isLike, isDislike, user, comment);
            }
            else if (state == "dislike")
            {
                await SetDislike(isDislike, isLike, user, comment);
            }

            await context.SaveChangesAsync();
        }
        public async Task <IHttpActionResult> Put(EditAuthorViewModel model)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            using (var ctx = new NewsDbContext())
            {
                var author = new Author()
                {
                    Id   = model.Id.Value,
                    Name = model.Name
                };

                ctx.Authors.Attach(author);
                ctx.Entry(author).State = EntityState.Modified;
                await ctx.SaveChangesAsync();

                return(StatusCode(HttpStatusCode.NoContent));
            }
        }
        public async Task <ActionResult> AddSection(AddSectionNameModel model)
        {
            if (ModelState.IsValid)
            {
                var SectionName = context.SectionsNames.FirstOrDefault(sn => sn.SectionName == model.SectionName);
                if (SectionName == null)
                {
                    await context
                    .SectionsNames
                    .AddAsync(new SectionsName { SectionName = model.SectionName });

                    await context.SaveChangesAsync();

                    return(Ok());
                }
                else
                {
                    ModelState.AddModelError("error", "Секция с таким именем уже существует");
                }
            }

            return(BadRequest(ModelState));
        }
示例#27
0
 public async Task <int> SaveChangesAsync()
 {
     return(await _context.SaveChangesAsync());
 }
示例#28
0
 public async Task <bool> SaveAllAsync(News news)
 {
     _context.News.Add(news);
     return(await _context.SaveChangesAsync() > 0);
 }
示例#29
0
        public async Task <bool> SubState(int SubTo, string username, string state, string link)
        {
            var user = await context
                       .Users
                       .FirstOrDefaultAsync(user => user.UserName == username);

            var ownerProfile = await context
                               .Profiles
                               .Include(p => p.User)
                               .FirstOrDefaultAsync(p => p.UserId == user.Id);

            var subProfileTo = await context
                               .Profiles
                               .Include(p => p.User)
                               .FirstOrDefaultAsync(p => p.Id == SubTo);

            var isExist = await context
                          .Subscriptions
                          .FirstOrDefaultAsync(s => s.ProfileIdSub == ownerProfile.Id && s.Profile == subProfileTo);

            if (!string.IsNullOrEmpty(state) && state == "sub")
            {
                if (ownerProfile == subProfileTo)
                {
                    return(true);
                }

                if (subProfileTo != null && isExist == null)
                {
                    await context
                    .Subscriptions
                    .AddAsync(new Subscriptions
                    {
                        Profile      = subProfileTo,
                        ProfileIdSub = ownerProfile.Id
                    });

                    await SetNotification(subProfileTo, ownerProfile, link);

                    await context.SaveChangesAsync();

                    return(true);
                }
            }
            if (!string.IsNullOrEmpty(state) && state == "unsub")
            {
                if (ownerProfile == subProfileTo)
                {
                    return(true);
                }

                if (isExist == null)
                {
                    return(false);
                }

                context.Subscriptions.Remove(isExist);

                await context.SaveChangesAsync();

                return(true);
            }
            return(false);
        }