public void ForumCategory_CanBeCreated_ReturnsID()
        {
            // arrange
            string uniqueKey = Guid.NewGuid().ToString();

            // act
            using (var context = new DasKlubDbContext())
            {
                context.ForumCategory.Add(new ForumCategory
                {
                    Description = Guid.NewGuid().ToString(),
                    Title = Guid.NewGuid().ToString(),
                    Key = uniqueKey,
                    CreatedByUserID = 0
                });

                context.SaveChanges();
            }

            // assert
            using (var context = new DasKlubDbContext())
            {
                Assert.IsNotNull(context.ForumCategory.FirstOrDefault().Key == uniqueKey);
            }
        }
Beispiel #2
0
        public ActionResult Admin()
        {
            using (var context = new DasKlubDbContext())
            {
                var allEntries = context.CalendarContestEntry.Where(x => x.Competition == currentCompetition)
                                                             .OrderByDescending(item => item.CreateDate).ToList();

                var calendarEntries = new List<CalendarEntryDisplayModel>();

                foreach (var entry in allEntries)
                {
                    calendarEntries.Add(new CalendarEntryDisplayModel()
                    {
                        EntryPhotoUrlPreview = Utilities.S3ContentPath(entry.EntryPhotoKeyPreview),
                        ProofPhotoUrlPreview = Utilities.S3ContentPath(entry.ProofPhotoKeyPreview),
                        ModelName = entry.ModelName,
                        PhotographerName = entry.PhotographerName,
                        CalendarContestEntryId = entry.CalendarContestEntryId,
                        IsApproved = entry.IsApproved,
                        Email = entry.Email

                    });
                }

                ViewBag.Entries = calendarEntries;
            }

            return View();
        }
        public void ForumPost_CanBeCreated_ReturnsID()
        {
            // arrange
            string uniqueKeyForum = Guid.NewGuid().ToString();
            string uniqueKeySubCat = Guid.NewGuid().ToString();
            string uniqueKeyPost = Guid.NewGuid().ToString();

            // act
            using (var context = new DasKlubDbContext())
            {
                context.ForumCategory.Add(new ForumCategory
                {
                    Description = Guid.NewGuid().ToString(),
                    Title = Guid.NewGuid().ToString(),
                    Key = uniqueKeyForum,
                    CreatedByUserID = 0
                });

                context.SaveChanges();
            }

            using (var context = new DasKlubDbContext())
            {
                int forumID = context.ForumCategory.FirstOrDefault(x => x.Key == uniqueKeyForum).ForumCategoryID;

                context.ForumSubCategory.Add(new ForumSubCategory
                {
                    Description = Guid.NewGuid().ToString(),
                    Title = Guid.NewGuid().ToString(),
                    Key = uniqueKeySubCat,
                    CreatedByUserID = 0,
                    ForumCategoryID = forumID
                });

                context.SaveChanges();
            }

            using (var context = new DasKlubDbContext())
            {
                int forumSubCategoryID =
                    context.ForumSubCategory.FirstOrDefault(x => x.Key == uniqueKeySubCat).ForumSubCategoryID;

                context.ForumPost.Add(new ForumPost
                {
                    Detail = uniqueKeyPost,
                    CreatedByUserID = 0,
                    ForumSubCategoryID = forumSubCategoryID
                });

                context.SaveChanges();
            }

            // assert
            using (var context = new DasKlubDbContext())
            {
                Assert.IsNotNull(context.ForumPost.FirstOrDefault().Detail == uniqueKeyPost);
            }
        }
Beispiel #4
0
        public async Task<ActionResult> Log(string userAccountId, string url)
        {
            // TODO: FIX 500 ERROR
            return new HttpStatusCodeResult(200);

            using (var context = new DasKlubDbContext())
            {
                context.UserRequest.Add(new UserRequest()
                {
                    CreatedByUserID = Convert.ToInt32(userAccountId),
                    CreateDate = DateTime.UtcNow,
                    Url = url
                });

                await context.SaveChangesAsync(); 
            }

            return new EmptyResult();
        }
Beispiel #5
0
        public ActionResult AdminEdit(int id)
        {
            using (var context = new DasKlubDbContext())
            {
                var entry = context.CalendarContestEntry.First(item => item.CalendarContestEntryId == id);

                var model = new CalendarEntryDisplayModel();

                model.IsApproved = entry.IsApproved;
                model.CalendarContestEntryId = entry.CalendarContestEntryId;
                model.ModelName = entry.ModelName;
                model.PhotographerName = entry.PhotographerName;
                model.EntryPhotoUrlPreview = Utilities.S3ContentPath(entry.EntryPhotoKeyPreview);
                model.EntryPhotoUrlRaw = Utilities.S3ContentPath(entry.EntryPhotoKeyRaw);
                model.EntryPhotoUrlThumb = Utilities.S3ContentPath(entry.EntryPhotoKeyThumb);
                model.ProofPhotoUrlPreview = Utilities.S3ContentPath(entry.ProofPhotoKeyPreview);
                model.ProofPhotoUrlRaw = Utilities.S3ContentPath(entry.ProofPhotoKeyRaw);
                model.ProofPhotoUrlThumb = Utilities.S3ContentPath(entry.ProofPhotoKeyThumb);

                return View(model);
            }
        }
Beispiel #6
0
        public ActionResult Search(string query, int pageNumber = 1)
        {
            if (string.IsNullOrWhiteSpace(query)) return View("Index");

            query = query.Trim();

            var searchModel = new SearchResultsModel();

            using (var context = new DasKlubDbContext())
            {
                List<int> posts = context.ForumPost
                                         .Where(post => post.Detail.Contains(query))
                                         .Select(post => post.ForumSubCategoryID)
                                         .ToList();

                List<int> threads = context.ForumSubCategory
                                           .Where(thread => thread.Title.Contains(query) || thread.Description.Contains(query))
                                           .Select(x => x.ForumSubCategoryID)
                                           .ToList();

                List<int> uniqueThreads = posts.Union(threads).ToList();

                searchModel.TotalThreads = uniqueThreads.Count();
                searchModel.PageNumber = pageNumber;
                searchModel.Query = query;
                searchModel.PageCount = (searchModel.TotalThreads + PageSize - 1) / PageSize;

                var pred = LinqExtensions.False<ForumSubCategory>();

                pred = pred.In("ForumSubCategoryID", uniqueThreads);

                // include both the count of replies and the total amount of threads
                searchModel.ResultsItems = context.ForumSubCategory
                                                  .Where(pred)
                                                  .OrderByDescending(x => x.CreateDate)
                                                  .Skip(PageSize * (pageNumber - 1))
                                                  .Take(PageSize)
                                                  .Select(thread => new SearchResultItem()
                                                  {
                                                      Title = thread.Title,
                                                      Description = thread.Description,
                                                      ForumCategoryId = thread.ForumCategoryID,
                                                      Key = thread.Key
                                                  }).ToList();

                foreach (var result in searchModel.ResultsItems)
                {
                    var forumCategory = context.ForumCategory.First(category => category.ForumCategoryID == result.ForumCategoryId);

                    result.ForumUrl = forumCategory.ForumURL;
                    result.ForumTitle = forumCategory.Title;

                    result.ThreadUrl = LinkHelper.ThreadUrl(forumCategory.Key, result.Key);
                }
            }

            return View(searchModel);
        }
Beispiel #7
0
        public ActionResult Index()
        {
            var model = new List<ForumItemModel>();

            using (var context = new DasKlubDbContext())
            {
                var forums = context.ForumCategory.OrderBy(x => x.CreateDate).ToList();

                foreach (var forum in forums)
                {
                    var item = new ForumItemModel();

                    item.ForumTitle = forum.Title;
                    item.ForumUrl = forum.ForumURL;
                    item.PostCount = forum.PostCount;
                    item.ThreadCount = forum.ThreadCount;

                    var lastThreadInForum = context.ForumSubCategory.FirstOrDefault(x => x.ForumSubCategoryID == forum.LastActiveSubCategoryId);

                    item.ThreadUrl = lastThreadInForum.SubForumURL;

                    if (lastThreadInForum != null)
                    {
                        lastThreadInForum.ForumCategory = forum;

                        item.LastActiveDateTimeUtc = lastThreadInForum.LastActiveDateTimeUtc;

                        var pageCount = ((lastThreadInForum.PostCount) + PageSize - 1) / PageSize;

                        item.LastPostUrl = LinkHelper.ForumPostUrl(lastThreadInForum.LastActiveForumPostId, lastThreadInForum, pageCount);

                        var lastUser = new UserAccount(lastThreadInForum.LastActiveUserId);

                        item.LastUserName = lastUser.UserName;
                        item.LastUserUrl = lastUser.UrlTo;
                        item.UserCountry = lastUser.Country;
                        item.UserCountryName = lastUser.CountryName;
                    }

                    if (_mu != null)
                    {
                        int userId = Convert.ToInt32(_mu.ProviderUserKey);

                        var notification = context.ForumPostNotification.FirstOrDefault(
                                    x => x.ForumSubCategoryID == forum.LastActiveSubCategoryId &&
                                    x.UserAccountID == userId);

                        if (notification != null && !notification.IsRead)
                        {
                            item.IsSubscribedAndUnread = true;
                        }
                    }

                    model.Add(item);
                }
            }

            return View(model);
        }
Beispiel #8
0
        private ForumFeedModel LoadMostPopularThisWeek(
            IGrouping<int, ForumPost> mostPopularThisWeek,
            DasKlubDbContext context,
            UserAccount ua)
        {
            ForumSubCategory topForumThreadOfTheWeek = (mostPopularThisWeek != null) ?
                context.ForumSubCategory.FirstOrDefault(x => x.ForumSubCategoryID == mostPopularThisWeek.Key) : null;

            if (topForumThreadOfTheWeek == null) return null;

            var topFeedItem = new ForumFeedModel { ForumSubCategory = topForumThreadOfTheWeek };

            // the thread itself is a post
            //topFeedItem.PostCount = 1;

            topFeedItem.PostCount = topFeedItem.ForumSubCategory.PostCount;

            topFeedItem.ForumCategory =
                context.ForumCategory.FirstOrDefault(
                    x => x.ForumCategoryID == topFeedItem.ForumSubCategory.ForumCategoryID);
            ForumPost mostRecentPostToTopThread = context.ForumPost.OrderByDescending(x => x.CreateDate)
                .FirstOrDefault(
                    x =>
                        x.ForumSubCategoryID ==
                        topFeedItem.ForumSubCategory.ForumSubCategoryID);
            if (mostRecentPostToTopThread != null)
            {
                var lastUser = new UserAccount(mostRecentPostToTopThread.CreatedByUserID);
                topFeedItem.UserName = lastUser.UserName;
                topFeedItem.UserAccount = lastUser;
                topFeedItem.LastPosted = mostRecentPostToTopThread.CreateDate;
            }

            if (ua == null) return topFeedItem;

            ForumPostNotification isNew =
                context.ForumPostNotification.FirstOrDefault(
                    x =>
                        x.ForumSubCategoryID == topForumThreadOfTheWeek.ForumSubCategoryID &&
                        x.UserAccountID == ua.UserAccountID);

            if (isNew == null || isNew.IsRead) return topFeedItem;

            topFeedItem.IsNewPost = true;

            int forumSubPostCount =
                context.ForumPost.Count(
                    x => x.ForumSubCategoryID == topFeedItem.ForumSubCategory.ForumSubCategoryID);

            int pageCount = (forumSubPostCount + ForumController.PageSize - 1) /
                            ForumController.PageSize;

            if (mostRecentPostToTopThread != null)
            {
                topFeedItem.URLTo = LinkHelper.ForumPostUri(topFeedItem, pageCount, mostRecentPostToTopThread);
            }
            return topFeedItem;
        }
Beispiel #9
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int minWordCount = 300;
            string siteDomain = string.Format("{0}/", GeneralConfigs.SiteDomain);
            Response.Clear();
            Response.ContentType = "text/xml";

            var writer = new XmlTextWriter(Response.OutputStream, Encoding.UTF8);

            writer.WriteStartDocument();
            writer.WriteStartElement("urlset");
            writer.WriteAttributeString("xmlns", "http://www.sitemaps.org/schemas/sitemap/0.9");
            writer.WriteString(Environment.NewLine);

            // home
            writer.WriteStartElement("url");
            writer.WriteElementString("loc", siteDomain);
            writer.WriteElementString("lastmod", String.Format("{0:yyyy-MM-dd}", DateTime.UtcNow));
            writer.WriteElementString("changefreq", "daily");
            writer.WriteElementString("priority", "1.0");
            writer.WriteEndElement();
            writer.WriteString(Environment.NewLine);

            // news
            var contents = new Contents();
            contents.GetContentPageWiseReleaseAll(1, 10000);

            foreach (Content c1 in contents)
            {
                string text = c1.ContentDetail;

                if (text.Split(' ').Length < minWordCount) continue;

                writer.WriteStartElement("url");
                writer.WriteElementString("loc", string.Format("{0}news/{1}", siteDomain, c1.ContentKey.ToLower()));
                DateTime lastmod = c1.ReleaseDate;
                if (c1.Comments != null && c1.Comments.Count > 0)
                {
                    lastmod = c1.Comments[c1.Comments.Count - 1].CreateDate;
                }
                writer.WriteElementString("lastmod", String.Format("{0:yyyy-MM-dd}", lastmod));
                writer.WriteElementString("changefreq", "monthly");
                writer.WriteElementString("priority", "0.8");
                writer.WriteEndElement();
                writer.WriteString(Environment.NewLine);
            }

            using (var context = new DasKlubDbContext())
            {
                List<ForumCategory> forumCategory = context.ForumCategory
                    .OrderBy(x => x.CreateDate)
                    .ToList();

                foreach (ForumCategory category in forumCategory)
                {
                    ForumCategory category1 = category;
                    IQueryable<ForumSubCategory> subForums =
                        context.ForumSubCategory.Where(x => x.ForumCategoryID == category1.ForumCategoryID);

                    using (var context2 = new DasKlubDbContext())
                    {
                        foreach (ForumSubCategory thread in subForums)
                        {
                            string text = thread.Description;
                            IQueryable<ForumPost> allPosts =
                                context2.ForumPost.Where(x => x.ForumSubCategoryID == thread.ForumSubCategoryID);

                            var allPostText = new StringBuilder();

                            foreach (ForumPost item in allPosts)
                            {
                                allPostText.Append(item.Detail);
                            }

                            allPostText.Append(text);

                            if (allPostText.ToString().Split(' ').Length < minWordCount)
                            {
                                continue;
                            }

                            writer.WriteStartElement("url");
                            writer.WriteElementString("loc", thread.SubForumURL.ToString().ToLower());

                            ForumSubCategory thread1 = thread;
                            ForumPost lastPost = context2.ForumPost
                                .Where(post => post.ForumSubCategoryID == thread1.ForumSubCategoryID)
                                .OrderByDescending(post => post.CreateDate).FirstOrDefault();

                            writer.WriteElementString("lastmod",
                                lastPost != null
                                    ? String.Format("{0:yyyy-MM-dd}", lastPost.CreateDate)
                                    : String.Format("{0:yyyy-MM-dd}", thread.CreateDate));
                            writer.WriteElementString("changefreq", "daily");
                            writer.WriteElementString("priority", "0.8");
                            writer.WriteEndElement();
                            writer.WriteString(Environment.NewLine);

                            int totalCount =
                                context2.ForumPost.Count(x => x.ForumSubCategoryID == thread.ForumSubCategoryID);
                            int pageCount = (totalCount + ForumController.PageSize - 1)/
                                            ForumController.PageSize;

                            if (pageCount <= 1) continue;

                            for (int i = 2; i <= pageCount; i++)
                            {
                                writer.WriteStartElement("url");
                                writer.WriteElementString("loc",
                                    string.Format("{0}/{1}", thread.SubForumURL, i).ToLower());
                                writer.WriteElementString("lastmod", String.Format("{0:yyyy-MM-dd}", thread.CreateDate));
                                writer.WriteElementString("changefreq", "weekly");
                                writer.WriteElementString("priority", "0.8");
                                writer.WriteEndElement();
                                writer.WriteString(Environment.NewLine);
                            }
                        }
                    }
                }
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Flush();

            Response.End();
        }
Beispiel #10
0
        private List<ForumSubCategory> GetForumUserPosts(
                int pageIndex, 
                int pageSize, 
                int createdByUserAccountId, 
                out int totalRecords)
        {
            DbCommand comm = DbAct.CreateCommand();
            comm.CommandText = "up_GetForumUserPosts";

            DbParameter param = comm.CreateParameter();
            param.ParameterName = "@RecordCount";
            param.Size = 1000;
            param.Direction = ParameterDirection.Output;
            comm.Parameters.Add(param);

            comm.AddParameter("PageIndex", pageIndex);
            comm.AddParameter("PageSize", pageSize);
            comm.AddParameter("createdByUserAccountId", createdByUserAccountId);

            DataSet ds = DbAct.ExecuteMultipleTableSelectCommand(comm);

            totalRecords = Convert.ToInt32(comm.Parameters["@RecordCount"].Value);

            if (ds == null || ds.Tables[0].Rows.Count <= 0) return null;

            var threads = new List<ForumSubCategory>();

            using (var context = new DasKlubDbContext())
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    var forumSubCategoryId = Convert.ToInt32(dr["ForumSubCategoryID"]);
                    var threadItem = context.ForumSubCategory.First(x => x.ForumSubCategoryID == forumSubCategoryId);
                    var forum = context.ForumCategory.First(x => x.ForumCategoryID == threadItem.ForumCategoryID);
                    threadItem.ForumCategory = forum;
                    threads.Add(threadItem);
                }
            }
            return threads;
        }
Beispiel #11
0
        public ActionResult EditForum(ForumCategory model)
        {
            if (_mu == null) return RedirectToAction("Index");

            var ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));

            if (!ua.IsAdmin) throw new UnauthorizedAccessException();

            using (var context = new DasKlubDbContext())
            {
                if (model == null) return RedirectToAction("Index");

                ForumCategory forumCategory = context.ForumCategory.First(x => x.ForumCategoryID == model.ForumCategoryID);

                forumCategory.CreatedByUserID = ua.UserAccountID;
                forumCategory.Key = FromString.UrlKey(model.Title);
                forumCategory.Title = model.Title.Trim();
                forumCategory.Description = model.Description.Trim();

                context.Entry(forumCategory).State = EntityState.Modified;
                context.SaveChanges();
            }

            return RedirectToAction("Index");
        }
Beispiel #12
0
        public ActionResult EditForum(string key)
        {
            if (_mu == null) return View();

            var ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));
            if (!ua.IsAdmin) throw new UnauthorizedAccessException();

            ForumCategory model;

            using (var context = new DasKlubDbContext())
            {
                model = context.ForumCategory.First(x => x.Key == key);
            }

            return View(model);
        }
Beispiel #13
0
        public ActionResult DeleteSubForum(int forumSubCategoryID)
        {
            using (var context = new DasKlubDbContext())
            {
                ForumSubCategory thread =
                    context.ForumSubCategory.First(x => x.ForumSubCategoryID == forumSubCategoryID);

                if (Convert.ToInt32(_mu.ProviderUserKey) != thread.CreatedByUserID && !_ua.IsAdmin)
                    return RedirectToAction("Index");

                context.ForumSubCategory.Remove(thread);

                ForumCategory forum = context.ForumCategory.First(x => x.ForumCategoryID == thread.ForumCategoryID);
                var previousThread = context.ForumSubCategory
                                        .OrderByDescending(x => x.LastActiveDateTimeUtc)
                                        .Where(x => x.ForumSubCategoryID != forumSubCategoryID &&
                                                    x.ForumCategoryID == forum.ForumCategoryID)
                                        .FirstOrDefault();

                if (previousThread != null)
                {
                    forum.LastActiveSubCategoryId = previousThread.ForumSubCategoryID;
                }
                else
                {
                    forum.LastActiveSubCategoryId = 0;
                }

                forum.PostCount -= thread.PostCount;
                forum.ThreadCount -= 1;
                context.Entry(forum).State = EntityState.Modified;

                context.SaveChanges();

                return RedirectToAction("Index");
            }
        }
Beispiel #14
0
        public ActionResult DeleteForumPost(int forumPostID)
        {
            using (var context = new DasKlubDbContext())
            {
                ForumPost forumPost = context.ForumPost.First(x => x.ForumPostID == forumPostID);

                if (Convert.ToInt32(_mu.ProviderUserKey) != forumPost.CreatedByUserID && !_ua.IsAdmin)
                    return RedirectToAction("Index");

                context.ForumPost.Remove(forumPost);

                var previousPost = context.ForumPost
                                          .OrderByDescending(x => x.CreateDate)
                                          .Where(x => x.ForumPostID != forumPostID &&
                                                      x.ForumSubCategoryID == forumPost.ForumSubCategoryID)
                                          .FirstOrDefault();

                var subForum = context.ForumSubCategory.First(x => x.ForumSubCategoryID == forumPost.ForumSubCategoryID);
                subForum.PostCount -= 1;

                if (previousPost != null)
                {
                    subForum.LastActiveDateTimeUtc = previousPost.CreateDate;
                    subForum.LastActiveForumPostId = previousPost.ForumPostID;
                    subForum.LastActiveUserId = previousPost.CreatedByUserID;
                }
                else
                {
                    subForum.LastActiveDateTimeUtc = subForum.CreateDate;
                    subForum.LastActiveForumPostId = 0;
                    subForum.LastActiveUserId = subForum.CreatedByUserID;
                }

                context.Entry(subForum).State = EntityState.Modified;

                var forum = context.ForumCategory.First(x => x.ForumCategoryID == subForum.ForumCategoryID);
                forum.PostCount -= 1;
                context.Entry(forum).State = EntityState.Modified;

                context.SaveChanges();

                return RedirectToAction("Index");
            }
        }
Beispiel #15
0
        public ActionResult CreateSubCategory(ForumSubCategory model)
        {
            if (_mu == null) return new EmptyResult();

            using (var context = new DasKlubDbContext())
            {
                if (model == null) return new EmptyResult();

                ForumCategory forum = context.ForumCategory.First(x => x.Key == model.Key);

                ViewBag.Forum = forum;

                if (!ModelState.IsValid)
                {
                    return View(model);
                }

                if (forum.ThreadsRequirePermission && ((_ua == null) || !_ua.IsAdmin))
                {
                    return new EmptyResult();
                }

                model.LastActiveDateTimeUtc = DateTime.UtcNow; // nulls are allowed, change when modifying
                model.LastActiveUserId = _ua.UserAccountID;
                model.ForumCategoryID = forum.ForumCategoryID;
                model.CreatedByUserID = _ua.UserAccountID;
                model.Key = FromString.UrlKey(model.Title);
                model.Title = model.Title.Trim();
                model.Description = model.Description.Trim();
                model.PostCount += 1;

                var existingThreadInForum = context.ForumSubCategory.FirstOrDefault(
                    forumSubCategory =>
                        forumSubCategory.ForumCategoryID == model.ForumCategoryID &&
                        forumSubCategory.Key             == model.Key);

                if (existingThreadInForum != null)
                {
                    // TODO: LOCALIZE
                    existingThreadInForum.ForumCategory = forum;

                    ModelState.AddModelError("Title",
                        string.Format(@"The title '{0}' is already taken, change your title.",
                        model.Title));

                    return View(model);
                }

                context.ForumSubCategory.Add(model);

                //update the forum category
                forum.PostCount += 1;
                forum.ThreadCount += 1;

                context.Entry(forum).State = EntityState.Modified;

                var notification = new ForumPostNotification
                {
                    CreatedByUserID = Convert.ToInt32(_mu.ProviderUserKey),
                    IsRead = true,
                    UserAccountID = Convert.ToInt32(_mu.ProviderUserKey),
                    ForumSubCategoryID = model.ForumSubCategoryID
                };

                context.ForumPostNotification.Add(notification);

                context.SaveChanges();

                // update to the last active
                forum.LastActiveSubCategoryId = model.ForumSubCategoryID;
                context.Entry(forum).State = EntityState.Modified;
                model.LastActiveDateTimeUtc = model.CreateDate;
                context.Entry(model);

                context.SaveChanges();

                return RedirectToAction("ForumPost", "Forum", new {subkey = model.Key, key = forum.Key});
            }
        }
Beispiel #16
0
        public ActionResult CreateForumPost(ForumPost model, int forumSubCategoryID)
        {
            using (var context = new DasKlubDbContext())
            {
                string currentLang = Utilities.GetCurrentLanguageCode();

                ForumSubCategory subForum = context.ForumSubCategory
                    .First(x => x.ForumSubCategoryID == forumSubCategoryID);

                if (!ModelState.IsValid)
                {
                    ViewBag.SubForum = subForum;

                    return View(model);
                }

                var ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));

                model.ForumSubCategoryID = forumSubCategoryID;
                model.CreatedByUserID = ua.UserAccountID;
                context.ForumPost.Add(model);

                ForumPostNotification currentUserNotification = context.ForumPostNotification
                    .FirstOrDefault(
                        x => x.ForumSubCategoryID == forumSubCategoryID && x.UserAccountID == ua.UserAccountID);

                if (currentUserNotification == null || currentUserNotification.ForumPostNotificationID == 0)
                {
                    var notification = new ForumPostNotification
                    {
                        CreatedByUserID = Convert.ToInt32(_mu.ProviderUserKey),
                        IsRead = true,
                        UserAccountID = Convert.ToInt32(_mu.ProviderUserKey),
                        ForumSubCategoryID = forumSubCategoryID
                    };

                    context.ForumPostNotification.Add(notification);
                }

                List<ForumPostNotification> allUserNotifications =
                    context.ForumPostNotification.Where(x => x.ForumSubCategoryID == forumSubCategoryID).ToList();

                subForum.ForumCategory = context.ForumCategory.First(x => x.ForumCategoryID == subForum.ForumCategoryID);

                if (context.ForumPost.FirstOrDefault(
                    x =>
                        x.ForumSubCategoryID == forumSubCategoryID && x.Detail == model.Detail &&
                        x.CreatedByUserID == ua.UserAccountID) != null) return new EmptyResult();

                Thread.CurrentThread.CurrentUICulture =
                    CultureInfo.CreateSpecificCulture(SiteEnums.SiteLanguages.EN.ToString());

                Thread.CurrentThread.CurrentCulture =
                    CultureInfo.CreateSpecificCulture(SiteEnums.SiteLanguages.EN.ToString());

                foreach (var forumPostNotification in
                        allUserNotifications.Where(
                            forumPostNotification => forumPostNotification.UserAccountID != ua.UserAccountID))
                {
                    forumPostNotification.IsRead = false;
                    forumPostNotification.UpdatedByUserID = Convert.ToInt32(_mu.ProviderUserKey);
                    context.Entry(forumPostNotification).State = EntityState.Modified;

                    var notifiedUser = new UserAccount(forumPostNotification.UserAccountID);
                    var notifiedUserDetails = new UserAccountDetail();
                    notifiedUserDetails.GetUserAccountDeailForUser(forumPostNotification.UserAccountID);

                    if (!notifiedUserDetails.EmailMessages) continue;

                    string title = ua.UserName + " => " + subForum.Title;
                    var body = new StringBuilder(100);
                    body.Append(Messages.New);
                    body.Append(": ");
                    body.Append(subForum.SubForumURL);
                    body.AppendLine();
                    body.AppendLine();
                    body.Append(model.Detail);
                    body.AppendLine();
                    body.AppendLine();
                    body.Append(Messages.Reply);
                    body.Append(": ");
                    body.AppendFormat("{0}/create", subForum.SubForumURL);

                    try
                    {
                        _mail.SendMail(AmazonCloudConfigs.SendFromEmail, notifiedUser.EMail, title, body.ToString());
                    }
                    catch (Exception ex)
                    {
                        Utilities.LogError(ex);
                    }
                }

                var forum = context.ForumCategory.First(x => x.ForumCategoryID == subForum.ForumCategoryID);

                forum.PostCount += 1;
                forum.LastActiveSubCategoryId = forumSubCategoryID;
                context.Entry(forum).State = EntityState.Modified;

                try
                {
                    context.SaveChanges();

                    subForum.PostCount += 1;
                    subForum.LastActiveDateTimeUtc = model.CreateDate;
                    subForum.LastActiveForumPostId = model.ForumPostID;
                    subForum.LastActiveUserId = model.CreatedByUserID;
                    context.Entry(subForum).State = EntityState.Modified;

                    context.SaveChanges();
                }
                catch (Exception ex)
                {
                    Utilities.LogError(ex);
                }

                Thread.CurrentThread.CurrentUICulture = CultureInfo.CreateSpecificCulture(currentLang);
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(currentLang);

                Response.Redirect(subForum.SubForumURL.ToString());

                return new EmptyResult();
            }
        }
Beispiel #17
0
        public ActionResult CreateForumPost(string key, string subKey)
        {
            using (var context = new DasKlubDbContext())
            {
                GetValue(key, subKey, context);
            }

            return View();
        }
Beispiel #18
0
        public ActionResult CreateForum(ForumCategory model)
        {
            if (_mu == null) return RedirectToAction("Index");

            var ua = new UserAccount(Convert.ToInt32(_mu.ProviderUserKey));

            if (!ua.IsAdmin) throw new UnauthorizedAccessException();

            using (var context = new DasKlubDbContext())
            {
                if (model == null) return RedirectToAction("Index");

                model.CreatedByUserID = ua.UserAccountID;
                model.Key = FromString.UrlKey(model.Title);
                model.Title = model.Title.Trim();
                model.Description = model.Description.Trim();

                context.ForumCategory.Add(model);

                context.SaveChanges();
            }

            return RedirectToAction("Index");
        }
Beispiel #19
0
        public ActionResult SubCategory(string key, int pageNumber = 1)
        {
            var model = new List<ThreadItemModel>();

            using (var context = new DasKlubDbContext())
            {
                context.Configuration.ProxyCreationEnabled = false;
                context.Configuration.LazyLoadingEnabled = false;

                var forum = context.ForumCategory.First(x => x.Key == key);

                forum.UserCanPostThreads = true; // force to true for now
                ViewBag.Title = forum.Title;
                ViewBag.MetaDescription = forum.Description;
                ViewBag.Forum = forum;
                ViewBag.IsAdmin = _ua != null && _ua.IsAdmin;

                var threads = context.ForumSubCategory
                    .Where(x => x.ForumCategoryID == forum.ForumCategoryID)
                    .OrderByDescending(x => x.LastActiveDateTimeUtc)
                    .Skip(SubCatPageSize * (pageNumber - 1))
                    .Take(SubCatPageSize)
                    .ToList();

                int totalCount = forum.ThreadCount - 1;
                int totalPages = (totalCount + SubCatPageSize - 1) / SubCatPageSize;

                ViewBag.PageCount = totalPages;
                ViewBag.PageNumber = pageNumber;

                foreach (var thread in threads)
                {
                    var item = new ThreadItemModel();

                    int totalCountInThread = thread.PostCount;
                    int totalPagesInThread = (totalCountInThread + SubCatPageSize - 1) / SubCatPageSize;

                    item.LastPostUrl = LinkHelper.ForumPostUrl(thread.LastActiveForumPostId, thread, totalPagesInThread);

                    item.PostCount = thread.PostCount;
                    item.LastActiveDateTimeUtc = thread.LastActiveDateTimeUtc;
                    item.ThreadTitle = thread.Title;
                    item.ThreadUrl = LinkHelper.ThreadUrl(forum.Key, thread.Key);

                    var user = new UserAccount(thread.LastActiveUserId);

                    item.LastUserName = user.UserName;
                    item.LastUserUrl = user.UrlTo;
                    item.UserCountry = user.Country;
                    item.UserCountryName = user.CountryName;

                    if (_mu != null)
                    {
                        int userID = Convert.ToInt32(_mu.ProviderUserKey);

                        var notification =
                            context.ForumPostNotification.FirstOrDefault(
                                x =>
                                    x.ForumSubCategoryID == thread.ForumSubCategoryID &&
                                    x.UserAccountID == userID);

                        if (notification != null && !notification.IsRead)
                        {
                            item.IsSubscribedAndUnread = true;
                        }
                    }

                    model.Add(item);
                }

                return View(model);
            }
        }
Beispiel #20
0
        public ActionResult EditForumPost(string key, string subKey, int forumPostID)
        {
            ForumPost model;

            using (var context = new DasKlubDbContext())
            {
                model = context.ForumPost.First(existingForumPost => existingForumPost.ForumPostID == forumPostID);

                if (_ua.UserAccountID != model.CreatedByUserID && !_ua.IsAdmin)
                {
                    throw new UnauthorizedAccessException();
                }

                ForumSubCategory subCategory = context.ForumSubCategory.First(forumSubCategory =>
                    forumSubCategory.ForumSubCategoryID == model.ForumSubCategoryID);
                ViewBag.SubForum = subCategory;
                ViewBag.Forum =
                    context.ForumCategory.First(forum => forum.ForumCategoryID == subCategory.ForumCategoryID);
            }

            return View(model);
        }
Beispiel #21
0
        private void GetValue(string key, string subKey, DasKlubDbContext context)
        {
            var forum = context.ForumCategory.First(existingForum => existingForum.Key == key);
            ViewBag.Forum = forum;

            var subForum = context.ForumSubCategory
                .First(
                    existingSubForum =>
                        existingSubForum.Key == subKey && existingSubForum.ForumCategoryID == forum.ForumCategoryID);
            ViewBag.SubForum = subForum;
        }
Beispiel #22
0
        private string GetUserMails(int userAccountId, int pageNumber = 1)
        {
            // TODO: IMPROVE PERFORMANCE BY GETTING EVERYTHING IN 1 DB CALL
            var amountPerPage = PageSize;

            using (var context = new DasKlubDbContext())
            {
                var query =
                context.DirectMessage
                       .Where(x => x.toUserAccountID == userAccountId)
                       .GroupBy(s => s.fromUserAccountID)
                       .Select(s => new UserMailModel()
                       {
                           FromUserAccountId = s.Key,
                           LastMessageDateTime = s.Max(m => m.createDate),
                           LastMessageBody = s.OrderByDescending(x => x.createDate).FirstOrDefault().message,
                           TotalUnread = s.Count(x => x.isRead == false && x.fromUserAccountID == s.Key),
                          // UserName = context.UserAccount.Where(x => x.userAccountID == s.Key).FirstOrDefault().userName
                       });

                ViewBag.RecordCount = query.Count();
                var results = query.OrderByDescending(x => x.LastMessageDateTime)
                        .Skip((pageNumber - 1) * amountPerPage)
                        .Take(amountPerPage)
                        .ToList();

                var maxStringLength = 100;

                foreach (var item in results)
                {
                    var ua = new UserAccount(item.FromUserAccountId);
                    var uad = new UserAccountDetail();
                    uad.GetUserAccountDeailForUser(item.FromUserAccountId);

                    item.ResponseToMessageUrl =
                        VirtualPathUtility.ToAbsolute("~/account/reply/") + ua.UserNameLower;
                    item.UserIcon = uad.SmallUserIcon;
                    item.LastMessageBody = FromString.Truncate(item.LastMessageBody, maxStringLength);
                }

                var sb = new StringBuilder();

                foreach (var formattedItem in results)
                {
                    sb.Append(@"<div class=""row"">");

                    sb.Append(@"<div class=""span2 user_icons"" style=""width: 120px;margin-left:0;"">");
                    sb.Append(@"<ul>");
                    sb.Append(formattedItem.UserIcon);
                    sb.Append(@"</ul>");
                    sb.Append(@"</div>");

                    sb.Append(@"<div class=""span6"">");
                    sb.AppendFormat(@"<span title=""{0}"">{1}</span>",
                        FromDate.DateToYYYY_MM_DD(formattedItem.LastMessageDateTime),
                        Utilities.TimeElapsedMessage(formattedItem.LastMessageDateTime));
                    sb.Append(@"<br />");

                    if (formattedItem.TotalUnread > 0)
                    {
                        sb.AppendFormat(@"<span class=""badge badge-warning"">{0} {1}</span>",
                                formattedItem.TotalUnread,
                                Messages.New);
                    }

                    sb.Append(@"<ul class=""nav nav-pills nav-stacked"">");

                    sb.Append(@"<li>");

                    sb.AppendFormat(@"<a href=""{0}"">{1}</a>",
                        formattedItem.ResponseToMessageUrl,
                        formattedItem.LastMessageBody);

                    sb.Append(@"</li>");
                    sb.Append(@"</ul>");
                    sb.Append(@"</div>");

                    sb.Append(@"</div>");
                    sb.Append(@"<hr />");
                }

                return sb.ToString();
            }
        }
Beispiel #23
0
        public ActionResult EditForumPost(ForumPost model)
        {
            using (var context = new DasKlubDbContext())
            {
                ForumPost forumPost = context.ForumPost.First(
                    currentForumPost => currentForumPost.ForumPostID == model.ForumPostID);

                if (_ua.UserAccountID != forumPost.CreatedByUserID && !_ua.IsAdmin)
                {
                    throw new UnauthorizedAccessException();
                }
                forumPost.UpdatedByUserID = _ua.UserAccountID;

                forumPost.Detail = model.Detail;

                context.Entry(forumPost).State = EntityState.Modified;
                context.SaveChanges();

                ForumSubCategory subForum = context.ForumSubCategory.First(
                    currentForumSubCategory =>
                        currentForumSubCategory.ForumSubCategoryID == model.ForumSubCategoryID);

                subForum.ForumCategory =
                    context.ForumCategory.First(forum => forum.ForumCategoryID == subForum.ForumCategoryID);

                return new RedirectResult(subForum.SubForumURL.ToString());
            }
        }
Beispiel #24
0
        public ActionResult AdminEdit(CalendarEntryDisplayModel model)
        {
            using (var context = new DasKlubDbContext())
            {
                var entry = context.CalendarContestEntry.First(item => item.CalendarContestEntryId == model.CalendarContestEntryId);

                entry.IsApproved = model.IsApproved;

                context.Entry(entry).State = EntityState.Modified;

                context.SaveChanges();

                return View(model);
            }
        }
Beispiel #25
0
            public void Execute(IJobExecutionContext context)
            {
                using (var contextDb = new DasKlubDbContext())
                {
                    var oneWeekAgo = DateTime.UtcNow.AddDays(-7);

                    const int totalTopAmount = 3;

                    var mostPopularForumPosts =
                        contextDb.ForumPost
                            .Where(x => x.CreateDate > oneWeekAgo)
                            .GroupBy(x => x.ForumSubCategoryID)
                            .OrderByDescending(y => y.Count())
                            .Take(totalTopAmount)
                            .ToList();

                    if (mostPopularForumPosts.Count == totalTopAmount)
                    {
                        var threads = new StringBuilder();

                        foreach (var item in mostPopularForumPosts)
                        {
                            ForumSubCategory forumThread =
                                contextDb.ForumSubCategory
                                    .FirstOrDefault(x => x.ForumSubCategoryID == item.Key);

                            ForumCategory forum =
                                contextDb.ForumCategory
                                    .FirstOrDefault(x => x.ForumCategoryID == forumThread.ForumCategoryID);

                            threads.Append(forumThread.Title);
                            threads.AppendLine();
                            threads.AppendFormat("{0}/forum/{1}/{2}", GeneralConfigs.SiteDomain, forum.Key,
                                forumThread.Key);
                            threads.AppendLine();
                            threads.Append("------------------------------");
                            threads.AppendLine();
                            threads.AppendLine();
                        }

                        string top3Threads = threads.ToString();

                        DateTimeFormatInfo dfi = DateTimeFormatInfo.CurrentInfo;
                        Calendar cal = dfi.Calendar;
                        int weekNumber = cal.GetWeekOfYear(DateTime.UtcNow, dfi.CalendarWeekRule, dfi.FirstDayOfWeek);

                        string title = string.Format("TOP {0} Forum Threads [Week: {1}, {2}]",
                            totalTopAmount,
                            weekNumber,
                            DateTime.UtcNow.Year);

                        var uas = new UserAccounts();
                        uas.GetAll();

                        foreach (UserAccount user in uas)
                        {
                            var uad = new UserAccountDetail();
                            uad.GetUserAccountDeailForUser(user.UserAccountID);

                            if (!uad.EmailMessages || uad.UserAccountDetailID == 0) continue;

                            string message = string.Format(
                                                "Hello {0}! {1}{1}{2}",
                                                user.UserName,
                                                Environment.NewLine,
                                                top3Threads);

                            System.Threading.Thread.Sleep(1000 / MaxEmailsPerSecond);

                            _mail.SendMail(AmazonCloudConfigs.SendFromEmail,
                                user.EMail,
                                title,
                                message);

                            Log.Info(string.Format("Sent top 3 to: {0}", user.EMail));
                        }
                    }
                    else
                    {
                        Log.Info("Not enough forum activity to mail users");
                    }
                }
            }
Beispiel #26
0
        public ActionResult EditSubCategory(string key, string subKey)
        {
            ForumSubCategory model;

            using (var context = new DasKlubDbContext())
            {
                var allForums = context.ForumCategory.ToList();
                ViewBag.AllForums = allForums.Select(i => new SelectListItem()
                {
                    Text = i.Title,
                    Value = i.ForumCategoryID.ToString()
                }); ;

                var forum = allForums.First(existingForum => existingForum.Key == key);
                ViewBag.Forum = forum;

                ForumSubCategory subForum = context.ForumSubCategory
                    .First(
                        existingSubForum =>
                            existingSubForum.Key == subKey && existingSubForum.ForumCategoryID == forum.ForumCategoryID);
                ViewBag.SubForum = subForum;

                if (_ua.UserAccountID != subForum.CreatedByUserID && !_ua.IsAdmin)
                {
                    throw new UnauthorizedAccessException();
                }

                model = subForum;
            }

            return View(model);
        }
Beispiel #27
0
        private void GetForumThreads(DateTime oneWeekAgo, UserAccount ua)
        {
            var threads = new List<ForumSubCategory>();
            using (var context = new DasKlubDbContext())
            {
                IGrouping<int, ForumPost> mostPopularForumPosts =
                    context.ForumPost
                        .Where(x => x.CreateDate > oneWeekAgo)
                        .GroupBy(x => x.ForumSubCategoryID)
                        .OrderByDescending(y => y.Count())
                        .Take(1)
                        .ToList()
                        .FirstOrDefault();

                ForumFeedModel mostPopularThread = LoadMostPopularThisWeek(mostPopularForumPosts, context, ua);
                if (mostPopularThread != null)
                {
                    var topThread = new ForumHomePageItem();

                    topThread.RowTitle = "Top This Week:";
                    topThread.ForumTitle = mostPopularThread.ForumCategory.Title;
                    topThread.ForumUrl = mostPopularThread.ForumCategory.ForumURL;

                    if (_mu != null)
                    {
                        int userID = Convert.ToInt32(_mu.ProviderUserKey);

                        var notification =
                        context.ForumPostNotification.FirstOrDefault(
                            x =>
                                x.ForumSubCategoryID == mostPopularThread.ForumSubCategory.ForumSubCategoryID &&
                                x.UserAccountID == userID);

                        if (notification != null && !notification.IsRead)
                        {
                            topThread.IsSubscribedAndUnread = true;
                        }
                    }

                    topThread.LastActiveDateTimeUtc = mostPopularThread.LastPosted;
                    topThread.LastUserName = mostPopularThread.UserAccount.UserName;
                    topThread.LastUserUrl = mostPopularThread.UserAccount.UrlTo;
                    topThread.PostCount = mostPopularThread.PostCount;

                    int totalCountInThread = mostPopularThread.PostCount - 1;
                    int totalPagesInThread = (totalCountInThread + ForumController.SubCatPageSize - 1) / ForumController.SubCatPageSize;

                    topThread.LastPostUrl = LinkHelper.ForumPostUrl(
                            mostPopularThread.ForumSubCategory.LastActiveForumPostId,
                            mostPopularThread.ForumSubCategory,
                            totalPagesInThread);

                    topThread.ThreadTitle = mostPopularThread.ForumSubCategory.Title;
                    topThread.ThreadUrl = mostPopularThread.ForumSubCategory.SubForumURL;
                    topThread.UserCountry = mostPopularThread.UserAccount.Country;
                    topThread.UserCountryName = mostPopularThread.UserAccount.CountryName;

                    ViewBag.TopThreadOfTheWeek = topThread;

                    threads = context.ForumSubCategory
                                     .OrderByDescending(x => x.LastActiveDateTimeUtc)
                                     .Where(x => x.ForumSubCategoryID != mostPopularThread.ForumSubCategory.ForumSubCategoryID)
                                     .Take(ForumThreadsToDisplay).ToList();
                }
                else
                {
                    threads = context.ForumSubCategory
                                     .OrderByDescending(x => x.LastActiveDateTimeUtc)
                                     .Take(ForumThreadsToDisplay).ToList();
                }
            }

            var forumItems = new List<ForumHomePageItem>();

            foreach (var thread in threads)
            {
                using (var context = new DasKlubDbContext())
                {
                    var forumItem = new ForumHomePageItem();

                    var forum = context.ForumCategory.First(x => x.ForumCategoryID == thread.ForumCategoryID);

                    forumItem.ForumUrl = forum.ForumURL;
                    forumItem.ForumTitle = forum.Title;
                    forumItem.LastActiveDateTimeUtc = thread.LastActiveDateTimeUtc;
                    forumItem.ThreadTitle = thread.Title;
                    forumItem.PostCount = thread.PostCount;
                    thread.ForumCategory = forum;
                    forumItem.ThreadUrl = thread.SubForumURL;

                    int totalCountInThread = thread.PostCount - 1;
                    int totalPagesInThread = (totalCountInThread + ForumController.SubCatPageSize - 1) / ForumController.SubCatPageSize;

                    forumItem.LastPostUrl = LinkHelper.ForumPostUrl(thread.LastActiveForumPostId, thread, totalPagesInThread);

                    if (_mu != null)
                    {
                        int userID = Convert.ToInt32(_mu.ProviderUserKey);

                        var notification =
                            context.ForumPostNotification.FirstOrDefault(
                                x =>
                                    x.ForumSubCategoryID == thread.ForumSubCategoryID &&
                                    x.UserAccountID == userID);

                        if (notification != null && !notification.IsRead)
                        {
                            forumItem.IsSubscribedAndUnread = true;
                        }
                    }

                    var user = new UserAccount(thread.LastActiveUserId);

                    forumItem.LastUserName = user.UserName;
                    forumItem.LastUserUrl = user.UrlTo;
                    forumItem.UserCountry = user.Country;
                    forumItem.UserCountryName = user.CountryName;

                    forumItems.Add(forumItem);
                }
            }

            ViewBag.ForumFeed = forumItems;

            var usersToGet = 7;

            using (var context = new DasKlubDbContext())
            {
                List<int> mostPostsInForum =
                (from b in context.ForumPost
                 where b.CreateDate < DateTime.UtcNow && b.CreateDate > oneWeekAgo
                 group b by b.CreatedByUserID
                    into grp
                 orderby grp.Count() descending
                 select grp.Key).Take(usersToGet).ToList();

                UserAccounts topForumUsers = LoadTopForumUsers(mostPostsInForum);

                if (topForumUsers.Count == usersToGet)
                {
                    ViewBag.TopForumUsersOfTheMonth = topForumUsers;
                }
            }
        }
Beispiel #28
0
        public ActionResult EditSubCategory(ForumSubCategory model)
        {
            using (var context = new DasKlubDbContext())
            {
                ForumSubCategory currentThread = context.ForumSubCategory.First(
                    currentForumSubCategory =>
                        currentForumSubCategory.ForumSubCategoryID == model.ForumSubCategoryID);

                if (_ua.UserAccountID != currentThread.CreatedByUserID && !_ua.IsAdmin)
                {
                    throw new UnauthorizedAccessException();
                }

                currentThread.UpdatedByUserID = _ua.UserAccountID;

                if (currentThread.ForumCategoryID != model.ForumCategoryID)
                {
                    // update switched category
                    var originalForum = context.ForumCategory.First(x => x.ForumCategoryID == currentThread.ForumCategoryID);
                    var newForum = context.ForumCategory.First(x => x.ForumCategoryID == model.ForumCategoryID);

                    originalForum.PostCount -= currentThread.PostCount;
                    originalForum.ThreadCount -= 1;

                    newForum.PostCount += currentThread.PostCount;
                    newForum.ThreadCount += 1;

                    var newForumLastThread = context.ForumSubCategory.First(x => x.ForumSubCategoryID == newForum.LastActiveSubCategoryId);

                    if (newForumLastThread.LastActiveDateTimeUtc < currentThread.LastActiveDateTimeUtc)
                    {
                        newForumLastThread.LastActiveDateTimeUtc = currentThread.LastActiveDateTimeUtc;
                        newForumLastThread.LastActiveForumPostId = currentThread.LastActiveForumPostId;
                        newForumLastThread.LastActiveUserId = currentThread.LastActiveUserId;
                    }

                    var originalForumLastThread = context.ForumSubCategory
                        .OrderByDescending(x => x.LastActiveDateTimeUtc)
                        .First(x => x.ForumSubCategoryID != currentThread.ForumSubCategoryID);

                    if (originalForumLastThread.LastActiveDateTimeUtc < currentThread.LastActiveDateTimeUtc)
                    {
                        currentThread.LastActiveDateTimeUtc = originalForumLastThread.LastActiveDateTimeUtc;
                        currentThread.LastActiveForumPostId = originalForumLastThread.LastActiveForumPostId;
                        currentThread.LastActiveUserId = originalForumLastThread.LastActiveUserId;
                    }

                    currentThread.ForumCategoryID = model.ForumCategoryID;
                }

                currentThread.Title = model.Title;
                currentThread.Description = model.Description;

                context.Entry(currentThread).State = EntityState.Modified;
                context.SaveChanges();

                model.Key = currentThread.Key;
                model.ForumCategory =
                    context.ForumCategory.First(forum => forum.ForumCategoryID == currentThread.ForumCategoryID);
            }

            return new RedirectResult(model.SubForumURL.ToString());
        }
Beispiel #29
0
        private void ForumThreads(int createdByUserId, ProfileModel model)
        {
            const int forumThreadsToDisplay = 5;

            using (var context = new DasKlubDbContext())
            {
                List<ForumSubCategory> mostRecentThreads =
                    (from thread in context.ForumSubCategory
                     where thread.CreatedByUserID == createdByUserId
                        orderby thread.CreateDate descending
                     select thread)
                        .Take(forumThreadsToDisplay)
                        .ToList();

                DbCommand command = DbAct.CreateCommand();
                command.CommandText = string.Format(@"
                    SELECT TOP {0} [ForumSubCategoryID], [CreateDate]
                    FROM
                    (
                        SELECT [ForumSubCategoryID]
                              ,[CreateDate]
                              ,ROW_NUMBER() OVER (PARTITION BY [ForumSubCategoryID]
                        ORDER BY [CreateDate] DESC) AS Seq
                        FROM  [ForumPosts]
                        WHERE createdByUserId = {1}
                    ) PartitionedTable
                    WHERE PartitionedTable.Seq = 1
                    ORDER BY [CreateDate] DESC ", forumThreadsToDisplay, createdByUserId);
                command.CommandType = CommandType.Text;
                DataTable mostRecentPostsToThreads = DbAct.ExecuteSelectCommand(command);
                var mostRecentPostsToThreadsList = new List<ForumSubCategory>();

                foreach (DataRow item in mostRecentPostsToThreads.Rows)
                {
                    mostRecentPostsToThreadsList.Add
                        (
                            new ForumSubCategory
                            {
                                CreateDate = Convert.ToDateTime(item["CreateDate"]),
                                ForumSubCategoryID = Convert.ToInt32(item["ForumSubCategoryID"])
                            }
                        );
                }

                var finalThreadList = mostRecentThreads.ToDictionary(
                                            thread => thread.ForumSubCategoryID,
                                            thread => thread.CreateDate);

                foreach (var thread in mostRecentPostsToThreadsList)
                {
                    if (finalThreadList.ContainsKey(thread.ForumSubCategoryID))
                        finalThreadList[thread.ForumSubCategoryID] = thread.CreateDate;
                    // updates to more recent date, last post
                    else
                        finalThreadList.Add(thread.ForumSubCategoryID, thread.CreateDate);
                }

                var recentThreadIds =
                    finalThreadList.OrderByDescending(x => x.Value)
                        .Select(x => x.Key)
                        .Take(forumThreadsToDisplay)
                        .ToList();

                model.ForumPostUrls = new List<ForumSubCategory>();

                foreach (var threadId in recentThreadIds)
                {
                    var thread =
                        context.ForumSubCategory.First(x => x.ForumSubCategoryID == threadId);
                    var forum =
                        context.ForumCategory.First(x => x.ForumCategoryID == thread.ForumCategoryID);
                    thread.ForumCategory = forum;
                    model.ForumPostUrls.Add(thread);
                }
            }
        }
Beispiel #30
0
        public ActionResult ForumPost(string key, string subKey, int pageNumber = 1)
        {
            using (var context = new DasKlubDbContext())
            {
                ViewBag.UserID = (_mu == null) ? 0 : Convert.ToInt32(_mu.ProviderUserKey);

                context.Configuration.ProxyCreationEnabled = false;
                context.Configuration.LazyLoadingEnabled = false;

                ForumCategory forum = context.ForumCategory.FirstOrDefault(forumPost => forumPost.Key == key);

                if (forum == null || forum.ForumCategoryID == 0)
                    return RedirectPermanent("~/forum"); // it's gone

                ViewBag.Forum = forum;
                ViewBag.MetaDescription = forum.Description;

                var subForum = context.ForumSubCategory.FirstOrDefault(forumPost =>
                    forumPost.Key == subKey &&
                    forumPost.ForumCategoryID == forum.ForumCategoryID);

                if (subForum == null || subForum.ForumSubCategoryID == 0)
                    return RedirectPermanent("~/forum"); // it's gone

                // TODO: USE LINQ or store the counts in the user profiles
                var comm = DbAct.CreateCommand();
                comm.CommandText = string.Format(@"
                    select temp.CreatedByUserID, count(*) as 'count'
                    from (
                        select CreatedByUserID, ForumSubCategoryID
                        from ForumSubCategories with (nolock)
                        union all
                        select CreatedByUserID, ForumSubCategoryID
                        from ForumPosts with (nolock)
                    ) as temp
                    where CreatedByUserID in
                        (select CreatedByUserID
                        from ForumPosts with (nolock)
                        where ForumSubCategoryID = {0})
                    group by CreatedByUserID
                    order by CreatedByUserID ",
                    subForum.ForumSubCategoryID);

                comm.CommandType = CommandType.Text;

                var userPostCounts = DbAct.ExecuteSelectCommand(comm);

                Dictionary<int, int> userPostCountList = userPostCounts.Rows
                    .Cast<DataRow>()
                    .ToDictionary(
                        row => Convert.ToInt32(row["CreatedByUserID"]),
                        row => Convert.ToInt32(row["count"]));

                ViewBag.UserPostCounts = userPostCountList;

                subForum.UserAccount = new UserAccount(subForum.CreatedByUserID);

                ViewBag.SubForum = subForum;

                List<ForumPost> forumPostDisplay = context.ForumPost
                    .Where(x => x.ForumSubCategoryID == subForum.ForumSubCategoryID)
                    .OrderBy(x => x.CreateDate)
                    .Skip(PageSize*(pageNumber - 1))
                    .Take(PageSize).ToList();

                if (_mu != null)
                {
                    var userId = Convert.ToInt32(_mu.ProviderUserKey);
                    var ua = new UserAccount(userId);
                    ViewBag.IsAdmin = ua.IsAdmin;

                    var forumPostNotification =
                        context.ForumPostNotification.FirstOrDefault(
                            x =>
                                x.ForumSubCategoryID == subForum.ForumSubCategoryID &&
                                x.UserAccountID == userId);

                    if (forumPostNotification != null)
                    {
                        forumPostNotification.IsRead = true;
                        context.Entry(forumPostNotification).State = EntityState.Modified;
                        context.SaveChanges();
                    }
                }

                int totalCount = subForum.PostCount - 1;

                ViewBag.PageCount = (totalCount + PageSize )/PageSize;
                ViewBag.PageNumber = pageNumber;
                ViewBag.PageTitle = subForum.Title;
                ViewBag.Title = pageNumber == 1
                    ? string.Format("{0}", subForum.Title)
                    : string.Format("{0} | page {1}", subForum.Title, pageNumber);

                foreach (ForumPost post in forumPostDisplay)
                {
                    post.UserAccount = new UserAccount(post.CreatedByUserID);
                }

                ViewBag.MetaDescription = FromString.GetFixedLengthString(subForum.Description, 160);

                return View(forumPostDisplay);
            }
        }