public void Initialize(ForumEntity forumEntity)
 {
     SubForumEntities = new ObservableCollection<ForumEntity>();
     ForumEntity = forumEntity;
     ForumTitle = forumEntity.Name;
     Refresh();
 }
        public static async Task<bool> CreateSecondaryForumLinkTile(ForumEntity forumEntity)
        {
            var tileId = forumEntity.ForumId;
            var pinned = SecondaryTile.Exists(tileId.ToString());
            if (pinned)
                return true;

            Uri square150X150Logo = new Uri("ms-appx:///Assets/Logo.png");

            var tile = new SecondaryTile(tileId.ToString())
            {
                DisplayName = forumEntity.Name,
                Arguments = JsonConvert.SerializeObject(forumEntity),
                VisualElements = { Square150x150Logo = square150X150Logo, ShowNameOnSquare150x150Logo = true},
            };
            return await tile.RequestCreateAsync();
        }
        public static async Task AddNewJumplistForum(ForumEntity forum)
        {
            if (!JumpList.IsSupported())
            {
                return;
            }

            var jumplist = await JumpList.LoadCurrentAsync();
            var itemExists = false;
            foreach (var item in jumplist.Items)
            {
                var args = JsonConvert.DeserializeObject<ToastNotificationArgs>(item.Arguments);
                if (args == null)
                {
                    continue;
                }
                if (args.openPrivateMessages || args.openBookmarks)
                {
                    continue;
                }
                if (args.openForum && args.forumId == forum.Id)
                {
                    itemExists = true;
                }
            }

            if (itemExists)
            {
                return;
            }

            var newArgs = new ToastNotificationArgs()
            {
                type = "jumplist",
                openForum = true,
                forumId = forum.Id
            };

            
            var jumpItem = JumpListItem.CreateWithArguments(JsonConvert.SerializeObject(newArgs), $"Open {forum.Name}");
            jumpItem.Logo = new Uri("ms-appx:///Assets/BadgeLogo.scale-100.png");
            jumplist.Items.Add(jumpItem);
            await jumplist.SaveAsync();
        }
Ejemplo n.º 4
0
        public async Task <List <ForumThreadEntity> > GetBookmarks(ForumEntity forumCategory)
        {
            var    forumSubcategoryList = new List <ForumEntity>();
            var    forumThreadList      = new List <ForumThreadEntity>();
            String url = forumCategory.Location;

            if (forumCategory.CurrentPage > 0)
            {
                url = forumCategory.Location + string.Format(Constants.PAGE_NUMBER, forumCategory.CurrentPage);
            }

            HtmlDocument doc       = (await _webManager.DownloadHtml(url)).Document;
            HtmlNode     forumNode = doc.DocumentNode.Descendants().FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("threadlist"));


            foreach (HtmlNode threadNode in forumNode.Descendants("tr").Where(node => node.GetAttributeValue("class", string.Empty).StartsWith("thread")))
            {
                var threadEntity = new ForumThreadEntity();
                threadEntity.Parse(threadNode);
                forumThreadList.Add(threadEntity);
            }
            return(forumThreadList);
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            _siteName = HttpUtility.HtmlEncode(ApplicationAdapter.GetSiteName());

            int forumID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ForumID"]);

            _forum = CacheManager.GetForum(forumID);
            if ((_forum != null) && _forum.HasRSSFeed)
            {
                _forumURL = "http://" + Request.Url.Host + ApplicationAdapter.GetVirtualRoot() + String.Format(@"Threads.aspx?ForumID={0}", forumID);

                // get the messages
                ForumMessagesTypedList messages = ForumGuiHelper.GetLastPostedMessagesInForum(10, forumID);
                rptRSS.DataSource = messages;
                rptRSS.DataBind();

                Response.Cache.SetExpires(DateTime.Now.AddDays(7));
                Response.Cache.SetCacheability(HttpCacheability.Public);
                Response.Cache.SetValidUntilExpires(true);
                Response.Cache.VaryByParams["ForumID"] = true;
                Response.Cache.AddValidationCallback(new HttpCacheValidateHandler(Validate), null);
            }
        }
Ejemplo n.º 6
0
 /// <summary>
 /// The methods provided in this section are simply used to allow
 /// NavigationHelper to respond to the page's navigation methods.
 /// <para>
 /// Page specific logic should be placed in event handlers for the
 /// <see cref="NavigationHelper.LoadState"/>
 /// and <see cref="NavigationHelper.SaveState"/>.
 /// The navigation parameter is available in the LoadState method
 /// in addition to page state preserved during an earlier session.
 /// </para>
 /// </summary>
 /// <param name="e">Provides data for navigation methods and event
 /// handlers that cannot cancel the navigation request.</param>
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     // TODO: Move to seperate method.
     if (_vm.ThreadListPageViewModel != null && _vm.ThreadListPageViewModel.ForumPageScrollingCollection.Any())
     {
         if (_localSettings.Values.ContainsKey(Constants.AUTO_REFRESH))
         {
             var autoRefresh = (bool)_localSettings.Values[Constants.AUTO_REFRESH];
             if (autoRefresh)
             {
                 var forum = new ForumEntity()
                 {
                     Name        = "Bookmarks",
                     IsSubforum  = false,
                     Location    = Constants.USER_CP,
                     IsBookmarks = true
                 };
                 _vm.ThreadListPageViewModel.RefreshForum(forum);
             }
         }
     }
     this.navigationHelper.OnNavigatedTo(e);
 }
Ejemplo n.º 7
0
        private async Task Update(IBackgroundTaskInstance taskInstance)
        {
            ApplicationDataContainer localSettings = ApplicationData.Current.LocalSettings;
            var forumCategory = new ForumEntity()
            {
                Name        = "Bookmarks",
                IsSubforum  = false,
                IsBookmarks = true,
                Location    = Constants.USER_CP
            };

            ObservableCollection <ForumThreadEntity> forumThreadEntities = await _threadManager.GetBookmarks(forumCategory, 1);

            CreateBookmarkLiveTiles(forumThreadEntities);

            if (localSettings.Values.ContainsKey("_threadIds") && !string.IsNullOrEmpty((string)localSettings.Values["_threadIds"]))
            {
                DeserializeXmlToList((string)localSettings.Values["_threadIds"]);
                List <ForumThreadEntity> list =
                    forumThreadEntities.Where(thread => _threadIds.Contains(thread.ThreadId)).ToList();
                CreateToastNotifications(list);
            }
        }
Ejemplo n.º 8
0
        public async Task <ActionResult> RemovePost(int?id)
        {
            if (id != null)
            {
                var db   = new ForumEntity();
                var post = await db.Posts.Where(p => p.post_id == id.Value)
                           .FirstOrDefaultAsync();

                if (post != null)
                {
                    var files = await db.PostFiles.Where(f => f.ref_id == post.post_id)
                                .ToListAsync();

                    if (files.Count != 0)
                    {
                        db.PostFiles.RemoveRange(files);
                    }

                    db.Posts.Remove(post);
                    var th = await db.Topics.Where(t => t.topic_id == post.post_topic)
                             .FirstOrDefaultAsync();

                    var len = await db.Posts.Where(m => m.post_topic == th.topic_id)
                              .CountAsync() - 1;

                    if (th.status != 3 && len == 1)
                    {
                        th.status = 1;
                    }
                    await db.SaveChangesAsync();
                }

                return(new HttpStatusCodeResult(HttpStatusCode.NotFound, "Post has been not found!"));
            }

            return(new HttpStatusCodeResult(HttpStatusCode.BadRequest, "Select post!"));
        }
Ejemplo n.º 9
0
        /// <summary>
        ///     Populates the page with content passed during navigation. Any saved state is also
        ///     provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="sender">
        ///     The source of the event; typically <see cref="NavigationHelper" />
        /// </param>
        /// <param name="e">
        ///     Event data that provides both the navigation parameter passed to
        ///     <see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested and
        ///     a dictionary of state preserved by this page during an earlier
        ///     session. The state will be null the first time a page is visited.
        /// </param>
        private async void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
        {
            var jsonObjectString = (string)e.NavigationParameter;

            _forumEntity = JsonConvert.DeserializeObject <ForumEntity>(jsonObjectString);
            if (_forumEntity == null)
            {
                return;
            }
            if (_vm.ForumEntity == null || _vm.ForumEntity.ForumId != _forumEntity.ForumId)
            {
                _vm.Initialize(_forumEntity);
            }

            if (_vm.ForumEntity != null && _vm.ForumEntity.IsBookmarks && _vm.ForumPageScrollingCollection.Any())
            {
                if (_localSettings.Values.ContainsKey(Constants.AUTO_REFRESH))
                {
                    var autoRefresh = (bool)_localSettings.Values[Constants.AUTO_REFRESH];
                    if (autoRefresh)
                    {
                        var forum = new ForumEntity()
                        {
                            Name        = "Bookmarks",
                            IsSubforum  = false,
                            Location    = Constants.USER_CP,
                            IsBookmarks = true
                        };
                        _vm.RefreshForum(forum);
                    }
                }
            }

            // TODO: This is stupid shit that should be removed.
            ViewStateStringFullScreen = "FullScreen" + GetViewStateString(_forumEntity.ForumId);
            ViewStateStringSnapped    = "Snapped" + GetViewStateString(_forumEntity.ForumId);
        }
Ejemplo n.º 10
0
        public async Task <IEnumerable <PostIconCategoryEntity> > GetPostIcons(ForumEntity forum)
        {
            string url = string.Format(Constants.NEW_THREAD, forum.ForumId);

            WebManager.Result result = await _webManager.GetData(url);

            HtmlDocument doc = result.Document;

            HtmlNode[] pageNodes          = doc.DocumentNode.Descendants("div").Where(node => node.GetAttributeValue("class", string.Empty).Equals("posticon")).ToArray();
            var        postIconEntityList = new List <PostIconEntity>();

            foreach (var pageNode in pageNodes)
            {
                var postIconEntity = new PostIconEntity();
                postIconEntity.Parse(pageNode);
                postIconEntityList.Add(postIconEntity);
            }
            var postIconCategoryEntity = new PostIconCategoryEntity("Post Icon", postIconEntityList);
            var postIconCategoryList   = new List <PostIconCategoryEntity> {
                postIconCategoryEntity
            };

            return(postIconCategoryList);
        }
Ejemplo n.º 11
0
 public async void Initialize(ForumEntity forumEntity)
 {
     this.ForumEntity = forumEntity;
     IsBookmarks      = forumEntity.IsBookmarks;
     ForumTitle       = forumEntity.Name;
     SubForumEntities = new ObservableCollection <ForumEntity>();
     try
     {
         if (forumEntity.IsBookmarks)
         {
             _localSettings = ApplicationData.Current.LocalSettings;
             ForumPageScrollingCollection = new PageScrollingCollection(forumEntity, 1);
         }
         else
         {
             ForumPageScrollingCollection = new PageScrollingCollection(forumEntity, 1);
             SubForumEntities             = await _forumManager.GetSubForums(forumEntity);
         }
     }
     catch (Exception ex)
     {
         AwfulDebugger.SendMessageDialogAsync("Failed to initialize threads", ex);
     }
 }
Ejemplo n.º 12
0
        public async Task <ObservableCollection <ForumEntity> > GetSubForums(ForumEntity forumCategory)
        {
            var          subforumList = new List <ForumEntity>();
            string       url          = forumCategory.Location;
            HtmlDocument doc          = (await _webManager.GetData(url)).Document;

            if (
                !doc.DocumentNode.Descendants()
                .Any(node => node.GetAttributeValue("id", string.Empty).Contains("subforums")))
            {
                return(null);
            }
            HtmlNode forumNode =
                doc.DocumentNode.Descendants()
                .FirstOrDefault(node => node.GetAttributeValue("id", string.Empty).Contains("subforums"));

            subforumList.AddRange(from subforumNode in forumNode.Descendants("tr")
                                  where subforumNode.Descendants("a").Any()
                                  select
                                  new ForumEntity
            {
                Name     = WebUtility.HtmlDecode(subforumNode.Descendants("a").FirstOrDefault().InnerText).Trim(),
                Location = Constants.BASE_URL +
                           subforumNode.Descendants("a").FirstOrDefault().GetAttributeValue("href", string.Empty),
                IsSubforum = true
            })
            ;
            var obSubforumList = new ObservableCollection <ForumEntity>();

            foreach (var forum in subforumList)
            {
                forum.SetForumId();
                obSubforumList.Add(forum);
            }
            return(obSubforumList);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Modifies the given forum with the information given
        /// </summary>
        /// <param name="forumID">ID of forum to modify</param>
        /// <param name="sectionID">ID of section to locate this forum in</param>
        /// <param name="forumName">Name of the forum</param>
        /// <param name="forumDescription">Short description of the forum.</param>
        /// <param name="hasRSSFeed">True if the forum has an RSS feed.</param>
        /// <param name="defaultSupportQueueID">The ID of the default support queue for this forum. Can be null.</param>
        /// <param name="defaultThreadListInterval">The default thread list interval.</param>
        /// <param name="orderNo">The order no for the section. Sections are sorted ascending on orderno.</param>
        /// <param name="maxAttachmentSize">Max. size of an attachment.</param>
        /// <param name="maxNoOfAttachmentsPerMessage">The max no of attachments per message.</param>
        /// <param name="newThreadWelcomeText">The new thread welcome text, as shown when a new thread is created. Can be null.</param>
        /// <param name="newThreadWelcomeTextAsHTML">The new thread welcome text as HTML, is null when newThreadWelcomeText is null or empty.</param>
        /// <returns>True if succeeded, false otherwise</returns>
        public static bool ModifyForum(int forumID, int sectionID, string forumName, string forumDescription, bool hasRSSFeed, int?defaultSupportQueueID,
                                       int defaultThreadListInterval, short orderNo, int maxAttachmentSize, short maxNoOfAttachmentsPerMessage,
                                       string newThreadWelcomeText, string newThreadWelcomeTextAsHTML)
        {
            ForumEntity forum = ForumGuiHelper.GetForum(forumID);

            if (forum == null)
            {
                // not found
                return(false);                  // doesn't exist
            }
            forum.SectionID                 = sectionID;
            forum.ForumDescription          = forumDescription;
            forum.ForumName                 = forumName;
            forum.HasRSSFeed                = hasRSSFeed;
            forum.DefaultSupportQueueID     = defaultSupportQueueID;
            forum.DefaultThreadListInterval = Convert.ToByte(defaultThreadListInterval);
            forum.OrderNo                      = orderNo;
            forum.MaxAttachmentSize            = maxAttachmentSize;
            forum.MaxNoOfAttachmentsPerMessage = maxNoOfAttachmentsPerMessage;
            forum.NewThreadWelcomeText         = newThreadWelcomeText;
            forum.NewThreadWelcomeTextAsHTML   = newThreadWelcomeTextAsHTML;
            return(forum.Save());
        }
Ejemplo n.º 14
0
 public TopicService()
 {
     db = new ForumEntity();
 }
Ejemplo n.º 15
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx");
            }

            bool userMayMoveThread = SessionAdapter.HasSystemActionRight(ActionRights.SystemWideThreadManagement);

            if (!userMayMoveThread)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("Messages.aspx?ThreadID=" + threadID, true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            if (!Page.IsPostBack)
            {
                // fill the page's content. Bind the known sections
                SectionCollection sections = CacheManager.GetAllSections();
                cbxSections.DataSource = sections;
                cbxSections.DataBind();

                lblThreadSubject.Text = HttpUtility.HtmlEncode(_thread.Subject);
                ForumEntity forum = CacheManager.GetForum(_thread.ForumID);
                if (forum == null)
                {
                    // Orphaned thread
                    Response.Redirect("default.aspx", true);
                }

                // pre-select the section the forum is currently in. Do that with an in-memory search through the known sections.
                SectionEntity toFind = new SectionEntity();
                toFind.Fields[(int)SectionFieldIndex.SectionID].ForcedCurrentValueWrite(forum.SectionID);
                toFind.IsNew = false;
                int index = sections.IndexOf(toFind);
                if (index >= 0)
                {
                    cbxSections.SelectedIndex = index;
                }
            }
        }
 private async Task<List<ForumThreadEntity>> GetBookmarkedThreadsAsync()
 {
     var bookmarkThreads = new List<ForumThreadEntity>();
     var threadManager = new ThreadManager();
     var forum = new ForumEntity()
     {
         Name = "Bookmarks",
         IsBookmarks = true,
         IsSubforum = false,
         Location = Constants.UserCp
     };
     var pageNumber = 1;
     var hasItems = false;
     while (!hasItems)
     {
         var bookmarks = await threadManager.GetBookmarksAsync(forum, pageNumber);
         bookmarkThreads.AddRange(bookmarks);
         if (!bookmarks.Any())
         {
             hasItems = true;
         }
         else
         {
             pageNumber++;
         }
     }
     return bookmarkThreads;
 }
Ejemplo n.º 17
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _deleteMessageID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["MessageID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)

            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            // Check if the current user is allowed to delete the message. If not, don't continue.
            _userMayDeleteMessages = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditDeleteOtherUsersMessages);
            if (!_userMayDeleteMessages)
            {
                // is not allowed to delete the message
                Response.Redirect("Messages.aspx?ThreadID=" + threadID, true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            // check if the message is the first message in the thread. If so, delete isn't allowed.
            if (ThreadGuiHelper.CheckIfMessageIsFirstInThread(threadID, _deleteMessageID))
            {
                // is first in thread, don't proceed. Caller has fabricated the url manually.
                Response.Redirect("default.aspx", true);
            }

            // Get the message
            MessageEntity message = MessageGuiHelper.GetMessage(_deleteMessageID);

            // User may delete current message.
            if (!Page.IsPostBack)
            {
                if (message != null)
                {
                    // message is found.
                    ForumEntity forum = CacheManager.GetForum(_thread.ForumID);
                    if (forum == null)
                    {
                        // Orphaned thread
                        Response.Redirect("default.aspx", true);
                    }
                    lblForumName_Header.Text = forum.ForumName;
                    lblMessageBody.Text      = message.MessageTextAsHTML;
                    lblPostingDate.Text      = message.PostingDate.ToString(@"dd-MMM-yyyy HH:mm:ss");
                }
                else
                {
                    btnYes.Visible = false;
                }
            }
        }
Ejemplo n.º 18
0
 /// <summary>
 /// Sets a new Forum.
 /// </summary>
 /// <param name="forum">Obj.: ForumEntity.</param>
 public async Task Create(ForumEntity forum)
 {
     _context.Add(forum);
     await _context.SaveChangesAsync();
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            _startAtMessageIndex = HnDGeneralUtils.TryConvertToInt(Request.QueryString["StartAtMessage"]);
            _quoteMessageID      = HnDGeneralUtils.TryConvertToInt(Request.QueryString["QuoteMessageID"]);

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx");
            }

            // Check if the current user is allowed to add new messages to the thread.
            bool userMayAddNewMessages = false;

            if (!_thread.IsClosed)
            {
                if (_thread.IsSticky)
                {
                    if (SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessageInSticky))
                    {
                        userMayAddNewMessages = true;
                    }
                }
                else
                {
                    if (SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessage))
                    {
                        userMayAddNewMessages = true;
                    }
                }
            }

            if (!userMayAddNewMessages)
            {
                // is not allowed to post a new message
                Response.Redirect("Messages.aspx?ThreadID=" + threadID, true);
            }

            // use BL class. We could have used Lazy loading, though for the sake of separation, we'll call into the BL class.
            ForumEntity forum = CacheManager.GetForum(_thread.ForumID);

            if (forum == null)
            {
                // orphaned thread
                Response.Redirect("default.aspx");
            }

            // check if the user can view the thread the message is in. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers))
            {
                // can't add a message, it's in a thread which isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            meMessageEditor.ShowAddAttachment = ((forum.MaxNoOfAttachmentsPerMessage > 0) &&
                                                 SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAttachment));
            meMessageEditor.ShowSubscribeToThread = !UserGuiHelper.CheckIfThreadIsAlreadySubscribed(SessionAdapter.GetUserID(), _thread.ThreadID);

            // User is able to post a new message to the current thread.
            if (!Page.IsPostBack)
            {
                // fill the page's content
                lnkThreads.Text               = HttpUtility.HtmlEncode(forum.ForumName);
                lnkThreads.NavigateUrl       += "?ForumID=" + _thread.ForumID;
                meMessageEditor.ForumName     = forum.ForumName;
                meMessageEditor.ThreadSubject = _thread.Subject;
                lblSectionName.Text           = CacheManager.GetSectionName(forum.SectionID);
                lnkMessages.NavigateUrl      += threadID;
                lnkMessages.Text              = HttpUtility.HtmlEncode(_thread.Subject);
                phLastPostingInThread.Visible = (_quoteMessageID <= 0);

                bool userMayEditMemo = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditThreadMemo);

                // get quoted message if passed in.
                if (_quoteMessageID > 0)
                {
                    // get message and insert it into the textbox including quote tags.
                    MessageEntity messageToQuote = MessageGuiHelper.GetMessage(_quoteMessageID);
                    if (messageToQuote != null)
                    {
                        // message found.
                        UserEntity quotedUser = UserGuiHelper.GetUser(messageToQuote.PostedByUserID);
                        if (quotedUser != null)
                        {
                            // user found. proceed
                            meMessageEditor.OriginalMessageText = TextParser.MakeStringQuoted(messageToQuote.MessageText, quotedUser.NickName);
                        }
                    }
                }
                else
                {
                    // no quoted message. Load the last message from the active thread and display it in the form. This
                    // message entity has the poster user entity prefetched, together with the usertitle of the user.
                    MessageEntity lastMessageInThread = ThreadGuiHelper.GetLastMessageInThreadWithUserInfo(threadID);
                    if (lastMessageInThread != null)
                    {
                        litMessageBody.Text = lastMessageInThread.MessageTextAsHTML;
                        lblPostingDate.Text = lastMessageInThread.PostingDate.ToString("dd-MMM-yyyy HH:mm:ss");
                        if (lastMessageInThread.PostedByUser != null)
                        {
                            UserEntity messagePoster = lastMessageInThread.PostedByUser;
                            if (messagePoster.UserTitle != null)
                            {
                                lblUserTitleDescription.Text = messagePoster.UserTitle.UserTitleDescription;
                            }
                            lblLocation.Text = messagePoster.Location;
                            if (messagePoster.JoinDate.HasValue)
                            {
                                lblJoinDate.Text = messagePoster.JoinDate.Value.ToString("dd-MMM-yyyy HH:mm:ss");
                            }
                            if (messagePoster.AmountOfPostings.HasValue)
                            {
                                lblAmountOfPostings.Text = messagePoster.AmountOfPostings.Value.ToString();
                            }
                            if (messagePoster.SignatureAsHTML != null)
                            {
                                litSignature.Text = messagePoster.SignatureAsHTML;
                            }
                            lblNickname.Text = messagePoster.NickName;
                        }
                    }
                }

                if ((_thread.Memo.Length > 0) && userMayEditMemo)
                {
                    // convert memo contents to HTML so it's displayed above the thread.
                    string parserLog, messageTextXml;
                    bool   errorsOccured = false;
                    string memoAsHTML    = TextParser.TransformUBBMessageStringToHTML(_thread.Memo, ApplicationAdapter.GetParserData(), out parserLog, out errorsOccured, out messageTextXml);
                    lblMemo.Text = memoAsHTML;
                }
                phMemo.Visible = userMayEditMemo;
            }
        }
Ejemplo n.º 20
0
        /// <summary>
        /// Overload.
        /// Collects the necessary data, generates then returns a Forum object for a Board.
        /// </summary>
        /// <param name="forum">ForumEntity object.</param>
        /// <returns>BoardEntity object: a board based on the given forum.</returns>
        private BoardListingModel BuildBoardListing(ForumEntity forum)
        {
            var board = forum.Board;

            return(BuildBoardListing(board));
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int forumID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ForumID"]);

            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx");
            }

            bool userCanCreateThreads = (SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.AddNormalThread) ||
                                         SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.AddStickyThread));

            // Controls are visible by default. Hide them when the user can't create threads on this forum
            if (!userCanCreateThreads)
            {
                lnkNewThreadBottom.Visible = false;
                lnkNewThreadTop.Visible    = false;
            }

            // fill the page's content
            ForumEntity forum = CacheManager.GetForum(forumID);

            if (forum == null)
            {
                // not found.
                Response.Redirect("default.aspx");
            }
            _forumName = forum.ForumName;

            if (!Page.IsPostBack)
            {
                cbxThreadListInterval.SelectedValue = forum.DefaultThreadListInterval.ToString();

                string forumNameEncoded = HttpUtility.HtmlEncode(_forumName);
                lblForumName.Text        = forumNameEncoded;
                lblForumName_Header.Text = HttpUtility.HtmlEncode(_forumName);
                lblForumDescription.Text = HttpUtility.HtmlEncode(forum.ForumDescription);
                lblSectionName.Text      = CacheManager.GetSectionName(forum.SectionID);

                string newThreadURL = string.Format("{0}?ForumID={1}", lnkNewThreadTop.NavigateUrl, forumID);
                lnkNewThreadTop.NavigateUrl    = newThreadURL;
                lnkNewThreadBottom.NavigateUrl = newThreadURL;
                if (forum.HasRSSFeed)
                {
                    lnkForumRSS.NavigateUrl += string.Format("?ForumID={0}", forumID);
                }
                else
                {
                    lnkForumRSS.Visible        = false;
                    litRssButtonSpacer.Visible = false;
                }
            }

            SystemDataEntity systemData = CacheManager.GetSystemData();
            int      postLimiter        = HnDGeneralUtils.TryConvertToInt(cbxThreadListInterval.SelectedValue);
            DataView threadsView        = ForumGuiHelper.GetAllThreadsInForumAsDataView(forumID, (ThreadListInterval)(byte)postLimiter,
                                                                                        systemData.MinNumberOfThreadsToFetch, systemData.MinNumberOfNonStickyVisibleThreads,
                                                                                        SessionAdapter.CanPerformForumActionRight(forumID, ActionRights.ViewNormalThreadsStartedByOthers),
                                                                                        SessionAdapter.GetUserID());

            rpThreads.DataSource = threadsView;
            rpThreads.DataBind();
            threadsView.Dispose();
        }
Ejemplo n.º 22
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            _startAtMessageIndex = HnDGeneralUtils.TryConvertToInt(Request.QueryString["StartAtMessage"]);

            if (_thread.IsClosed)
            {
                // is already closed
                Response.Redirect("default.aspx", true);
            }

            // Check access credentials
            bool userHasAccess             = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);
            bool userMayDoThreadManagement = SessionAdapter.HasSystemActionRight(ActionRights.ForumSpecificThreadManagement) ||
                                             SessionAdapter.HasSystemActionRight(ActionRights.SystemWideThreadManagement);

            if (!userHasAccess || !userMayDoThreadManagement)
            {
                // doesn't have access to this forum or may not alter the thread's properties. redirect
                Response.Redirect("default.aspx", true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            bool userMayAddNewMessages = false;

            if (!_thread.IsClosed)
            {
                if (_thread.IsSticky)
                {
                    if (SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessageInSticky))
                    {
                        userMayAddNewMessages = true;
                    }
                }
                else
                {
                    if (SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessage))
                    {
                        userMayAddNewMessages = true;
                    }
                }
            }

            if (!userMayAddNewMessages)
            {
                // is not allowed to post a new message. This forum allows the user to add a new message and close the thread at the same time.
                // deny.
                Response.Redirect("default.aspx", true);
            }

            if (!Page.IsPostBack)
            {
                // fill the page's content
                ForumEntity forum = CacheManager.GetForum(_thread.ForumID);
                if (forum == null)
                {
                    // Orphaned thread
                    Response.Redirect("default.aspx", true);
                }
                meMessageEditor.ForumName     = forum.ForumName;
                meMessageEditor.ThreadSubject = _thread.Subject;
            }
        }
Ejemplo n.º 23
0
        public void BookmarkButton_Click(object sender, RoutedEventArgs e)
        {
            var forum = new ForumEntity("Bookmarks", Constants.USER_CP, string.Empty, false);

            this.Frame.Navigate(typeof(ThreadListPage), forum);
        }
Ejemplo n.º 24
0
        /// <summary>
        ///     Invoked when the application is launched normally by the end user.  Other entry points
        ///     will be used such as when the application is launched to open a specific file.
        /// </summary>
        /// <param name="e">Details about the launch request and process.</param>
        protected override async void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            // Show graphics profiling information while debugging.
            if (Debugger.IsAttached)
            {
                // Display the current frame rate counters
                DebugSettings.EnableFrameRateCounter = true;
            }
#endif

            var rootFrame = Window.Current.Content as Frame;
            SettingsPane.GetForCurrentView().CommandsRequested += SettingCharmManager_CommandsRequested;
            // Do not repeat app initialization when the Window already has content,
            // just ensure that the window is active
            TileUpdateManager.CreateTileUpdaterForApplication().Clear();
            BadgeUpdateManager.CreateBadgeUpdaterForApplication().Clear();
            TileUpdateManager.CreateTileUpdaterForApplication().EnableNotificationQueue(true);
            if (rootFrame == null)
            {
                // Create a Frame to act as the navigation context and navigate to the first page
                rootFrame = new Frame();
                //Associate the frame with a SuspensionManager key
                SuspensionManager.RegisterFrame(rootFrame, "AppFrame");

                if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
                {
                    // Restore the saved session state only when appropriate
                    try
                    {
                        await SuspensionManager.RestoreAsync();
                    }
                    catch (SuspensionManagerException)
                    {
                        //Something went wrong restoring state.
                        //Assume there is no state and continue
                    }
                }

                // Place the frame in the current Window
                Window.Current.Content = rootFrame;
            }
            if (rootFrame.Content == null)
            {
                // When the navigation stack isn't restored navigate to the first page,
                // configuring the new page by passing required information as a navigation
                // parameter
                var             localStorageManager = new LocalStorageManager();
                CookieContainer cookieTest          = await localStorageManager.LoadCookie(Constants.COOKIE_FILE);

                if (cookieTest.Count <= 0)
                {
                    if (!rootFrame.Navigate(typeof(LoginPage)))
                    {
                        throw new Exception("Failed to create initial page");
                    }
                }
                else
                {
                    var localSettings = ApplicationData.Current.LocalSettings;
                    if (localSettings.Values.ContainsKey(Constants.BOOKMARK_STARTUP) && (bool)localSettings.Values[Constants.BOOKMARK_STARTUP])
                    {
                        var forum = new ForumEntity()
                        {
                            Name       = "Bookmarks",
                            IsSubforum = false,
                            Location   = Constants.USER_CP
                        };
                        string jsonObjectString = JsonConvert.SerializeObject(forum);
                        rootFrame.Navigate(typeof(ThreadListPage), jsonObjectString);
                    }
                    else
                    {
                        if (!rootFrame.Navigate(typeof(MainForumsPage)))
                        {
                            throw new Exception("Failed to create initial page");
                        }
                    }
                }
            }
            // Ensure the current window is active
            Window.Current.Activate();
        }
Ejemplo n.º 25
0
 public UserService()
 {
     db = new ForumEntity();
 }
Ejemplo n.º 26
0
        public async Task <ObservableCollection <ForumThreadEntity> > GetForumThreads(ForumEntity forumCategory, int page)
        {
            // TODO: Remove parsing logic from managers. I don't think they have a place here...
            string url = forumCategory.Location + string.Format(Constants.PAGE_NUMBER, page);

            HtmlDocument doc = (await _webManager.GetData(url)).Document;

            HtmlNode bodyNode = doc.DocumentNode.Descendants("body").First();

            int forumId = Convert.ToInt32(bodyNode.GetAttributeValue("data-forum", string.Empty));

            HtmlNode forumNode =
                doc.DocumentNode.Descendants()
                .FirstOrDefault(node => node.GetAttributeValue("class", string.Empty).Contains("threadlist"));
            var forumThreadList = new ObservableCollection <ForumThreadEntity>();

            foreach (
                HtmlNode threadNode in
                forumNode.Descendants("tr")
                .Where(node => node.GetAttributeValue("class", string.Empty).StartsWith("thread")))
            {
                var threadEntity = new ForumThreadEntity();
                threadEntity.Parse(threadNode);
                threadEntity.ForumId = forumId;
                forumThreadList.Add(threadEntity);
            }
            return(forumThreadList);
        }
Ejemplo n.º 27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            int messageID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["MessageID"]);

            _message = MessageGuiHelper.GetMessage(messageID);
            if (_message == null)
            {
                // not found
                Response.Redirect("default.aspx", true);
            }

            _sourceType = HnDGeneralUtils.TryConvertToInt(Request.QueryString["SourceType"]);
            switch (_sourceType)
            {
            case 1:
                // new message, or message view, for now no action needed
                break;

            case 2:
                // new thread, for now no action needed
                break;

            default:
                // unknown, redirect
                Response.Redirect("default.aspx", true);
                break;
            }

            // We could have used Lazy loading here, but for the sake of separation, we use the BL method.
            _thread = ThreadGuiHelper.GetThread(_message.ThreadID);
            if (_thread == null)
            {
                // not found. Orphaned message.
                Response.Redirect("default.aspx", true);
            }

            _forum = CacheManager.GetForum(_thread.ForumID);
            if (_forum == null)
            {
                // not found.
                Response.Redirect("default.aspx", true);
            }

            // check if this forum accepts attachments.
            if (_forum.MaxNoOfAttachmentsPerMessage <= 0)
            {
                // no, so no right to be here nor is the user here via a legitimate route.
                Response.Redirect("default.aspx", true);
            }

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx", true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            // Check if the current user is allowed to manage attachments of this message, and other rights.
            _userMayManageAttachments = ((_message.PostedByUserID == SessionAdapter.GetUserID()) ||
                                         SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ManageOtherUsersAttachments));
            _userCanAddAttachments = (((_message.PostedByUserID == SessionAdapter.GetUserID()) ||
                                       SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ManageOtherUsersAttachments)) &&
                                      SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAttachment));
            _userCanApproveAttachments = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ApproveAttachment);

            phAttachmentLimits.Visible = _userMayManageAttachments;

            if (!Page.IsPostBack)
            {
                // fill the page's content
                lnkThreads.Text          = HttpUtility.HtmlEncode(_forum.ForumName);
                lnkThreads.NavigateUrl  += "?ForumID=" + _thread.ForumID;
                lblSectionName.Text      = CacheManager.GetSectionName(_forum.SectionID);
                lnkMessages.NavigateUrl += _message.ThreadID;
                lnkMessages.Text         = HttpUtility.HtmlEncode(_thread.Subject);

                lblMaxFileSize.Text = String.Format("{0} KB", _forum.MaxAttachmentSize);
                lblMaxNoOfAttachmentsPerMessage.Text = _forum.MaxNoOfAttachmentsPerMessage.ToString();
                lnkMessage.Text        += messageID.ToString();
                lnkMessage.NavigateUrl += String.Format("MessageID={0}&ThreadID={1}", messageID, _thread.ThreadID);

                phAddNewAttachment.Visible = _userCanAddAttachments;

                BindAttachments();
            }
            else
            {
                object numberOfAttachments = ViewState["numberOfAttachments"];
                if (numberOfAttachments != null)
                {
                    _numberOfAttachments = (int)numberOfAttachments;
                }
            }
        }
Ejemplo n.º 28
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to default page
                Response.Redirect("default.aspx", true);
            }

            _startAtMessage = HnDGeneralUtils.TryConvertToInt(Request.QueryString["StartAtMessage"]);

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx", true);
            }

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            // Check if the current user is allowed to edit the memo
            if (!SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditThreadMemo))
            {
                // is not allowed to edit the memo
                Response.Redirect("Messages.aspx?ThreadID=" + threadID, true);
            }

            // User may edit memo, proceed
            if (!Page.IsPostBack)
            {
                // fill the page's content
                ForumEntity forum = CacheManager.GetForum(_thread.ForumID);
                if (forum == null)
                {
                    // Orphaned thread
                    Response.Redirect("default.aspx", true);
                }
                lnkThreads.Text               = HttpUtility.HtmlEncode(forum.ForumName);
                lnkThreads.NavigateUrl       += "?ForumID=" + _thread.ForumID;
                meMessageEditor.ForumName     = forum.ForumName;
                meMessageEditor.ThreadSubject = "Memo for thread: " + HttpUtility.HtmlEncode(_thread.Subject);
                lblSectionName.Text           = CacheManager.GetSectionName(forum.SectionID);
                lnkMessages.NavigateUrl      += threadID;
                lnkMessages.Text              = HttpUtility.HtmlEncode(_thread.Subject);

                string memoText = _thread.Memo;
                memoText += string.Format("{2}[b]-----------------------------------------------------------------{2}{1} [color value=\"0000AA\"]{0}[/color] wrote:[/b] ", SessionAdapter.GetUserNickName(), DateTime.Now.ToString(@"dd-MMM-yyyy HH:mm:ss"), Environment.NewLine);
                meMessageEditor.OriginalMessageText = memoText;
            }
        }
Ejemplo n.º 29
0
        public async Task <ObservableCollection <ForumCategoryEntity> > GetForumCategoryMainPage()
        {
            var forumGroupList = new ObservableCollection <ForumCategoryEntity>();
            var result         = await _webManager.GetData(Constants.FORUM_LIST_PAGE);

            HtmlDocument doc = result.Document;

            HtmlNode forumNode =
                doc.DocumentNode.Descendants("select")
                .FirstOrDefault(node => node.GetAttributeValue("name", string.Empty).Equals("forumid"));

            if (forumNode != null)
            {
                try
                {
                    IEnumerable <HtmlNode> forumNodes = forumNode.Descendants("option");

                    foreach (HtmlNode node in forumNodes)
                    {
                        string value = node.Attributes["value"].Value;
                        int    id;
                        if (!int.TryParse(value, out id) || id <= -1)
                        {
                            continue;
                        }
                        if (node.NextSibling.InnerText.Contains("--"))
                        {
                            string forumName =
                                WebUtility.HtmlDecode(node.NextSibling.InnerText.Replace("-", string.Empty));
                            bool isSubforum       = node.NextSibling.InnerText.Count(c => c == '-') > 2;
                            var  forumSubCategory = new ForumEntity
                            {
                                Name       = forumName.Trim(),
                                Location   = string.Format(Constants.FORUM_PAGE, value),
                                IsSubforum = isSubforum
                            };
                            forumSubCategory.SetForumId();
                            forumGroupList.LastOrDefault().ForumList.Add(forumSubCategory);
                        }
                        else
                        {
                            string forumName  = WebUtility.HtmlDecode(node.NextSibling.InnerText);
                            var    forumGroup = new ForumCategoryEntity(forumName,
                                                                        string.Format(Constants.FORUM_PAGE, value));
                            forumGroupList.Add(forumGroup);
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Main Forum Parsing Error: " + ex.StackTrace);
                }
            }

#if DEBUG
            if (forumGroupList.Any())
            {
                forumGroupList[3].ForumList.Add(AddDebugForum());
            }
#endif

            return(forumGroupList);
        }
Ejemplo n.º 30
0
 /// <summary>
 ///     Populates the page with content passed during navigation. Any saved state is also
 ///     provided when recreating a page from a prior session.
 /// </summary>
 /// <param name="sender">
 ///     The source of the event; typically <see cref="NavigationHelper" />
 /// </param>
 /// <param name="e">
 ///     Event data that provides both the navigation parameter passed to
 ///     <see cref="Frame.Navigate(Type, Object)" /> when this page was initially requested and
 ///     a dictionary of state preserved by this page during an earlier
 ///     session. The state will be null the first time a page is visited.
 /// </param>
 private void navigationHelper_LoadState(object sender, LoadStateEventArgs e)
 {
     _forum = (ForumEntity)e.NavigationParameter;
 }
Ejemplo n.º 31
0
        public async Task <ActionResult> RemoveTopic(int?id)
        {
            var db    = new ForumEntity();
            var table = new Dictionary <string, dynamic>();

            if (id != null)
            {
                var email = (Request.Cookies["user"] != null) ? Request.Cookies["user"].Value : "";
                var user  = await db.Users.Where(node => node.user_email == email).FirstOrDefaultAsync();

                if (user != null)
                {
                    var item = await db.Topics.Where(node => node.topic_id == id.Value && (node.topic_by == user.Id || user.user_level))
                               .FirstOrDefaultAsync();

                    if (item != null)
                    {
                        // remove topic successfully...
                        var posts = await db.Posts.Where(node => node.post_topic == item.topic_id).ToListAsync();

                        posts.ForEach((post) =>
                        {
                            var files = db.PostFiles.Where(node => node.ref_id == post.post_id).ToList();
                            if (files.Count != 0)
                            {
                                db.PostFiles.RemoveRange(files);
                            }
                        });

                        if (posts.Count != 0)
                        {
                            db.Posts.RemoveRange(posts);
                        }
                        db.Topics.Remove(item);
                        await db.SaveChangesAsync();

                        table.Add("message", "All posts and topic itself have been removed!");
                        table.Add("success", true);
                        return(Json(table, JsonRequestBehavior.AllowGet));
                    }
                    else
                    {
                        table.Add("message", "There is not exists this topic!");
                        table.Add("success", false);
                        return(Json(table, JsonRequestBehavior.AllowGet));
                    }
                }
                else
                {
                    table.Add("message", "You are not authorized to remove data!");
                    table.Add("success", false);
                    return(Json(table, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                table.Add("message", "Must to specify the topic in order to remove him!");
                table.Add("success", false);
                return(Json(table, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 32
0
        private void Page_Load(object sender, System.EventArgs e)
        {
            // If the user doesn't have any access rights to management stuff, the user should
            // be redirected to the default of the global system.
            if (!SessionAdapter.HasSystemActionRights())
            {
                // doesn't have system rights. redirect.
                Response.Redirect("../Default.aspx", true);
            }

            // Check if the user has the right systemright
            if (!SessionAdapter.HasSystemActionRight(ActionRights.SystemManagement))
            {
                // no, redirect to admin default page, since the user HAS access to the admin menu.
                Response.Redirect("Default.aspx", true);
            }

            _forumID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ForumID"]);

            if (!Page.IsPostBack)
            {
                // read sections for the drop down list.
                SectionCollection sections = SectionGuiHelper.GetAllSections();
                cbxSections.DataSource = sections;
                cbxSections.DataBind();

                SupportQueueCollection supportQueues = CacheManager.GetAllSupportQueues();
                cbxSupportQueues.DataSource = supportQueues;
                cbxSupportQueues.DataBind();

                // Load the forum.
                ForumEntity forum = ForumGuiHelper.GetForum(_forumID);
                if (forum != null)
                {
                    // forum found
                    tbxForumDescription.Text = forum.ForumDescription;
                    tbxForumName.Value       = forum.ForumName;
                    tbxOrderNo.Text          = forum.OrderNo.ToString();

                    cbxSections.SelectedValue = forum.SectionID.ToString();

                    if (forum.DefaultSupportQueueID.HasValue)
                    {
                        cbxSupportQueues.SelectedValue = forum.DefaultSupportQueueID.Value.ToString();
                    }
                    chkHasRSSFeed.Checked = forum.HasRSSFeed;
                    cbxThreadListInterval.SelectedValue  = forum.DefaultThreadListInterval.ToString();
                    tbxMaxAttachmentSize.Text            = forum.MaxAttachmentSize.ToString();
                    tbxMaxNoOfAttachmentsPerMessage.Text = forum.MaxNoOfAttachmentsPerMessage.ToString();

                    if (forum.NewThreadWelcomeText != null)
                    {
                        tbxNewThreadWelcomeText.Text = forum.NewThreadWelcomeText;
                    }
                }
                else
                {
                    // not found
                    Response.Redirect("Default.aspx", true);
                }
            }
        }
Ejemplo n.º 33
0
        public async Task <ActionResult> AddTopic(int id, string subject, string question, HttpPostedFileBase view)
        {
            var db    = new ForumEntity();
            var email = Request.Cookies["user"] != null ? Request.Cookies["user"].Value : "";
            var user  = await db.Users.Where(node => node.user_email == email).FirstOrDefaultAsync();

            var type = await db.Categories.Where(node => node.cat_id == id).FirstOrDefaultAsync();

            bool user_exists = (user != null);
            bool cat_exists  = (type != null);

            var  table = new Dictionary <string, dynamic>();
            bool ok    = user_exists && cat_exists;

            if (ok)
            {
                var topic = new Topic
                {
                    topic_cat     = id,
                    topic_subject = subject,
                    topic_date    = DateTime.Now,
                    topic_by      = user.Id,
                    status        = 1
                };

                var QueryTopic = await db.Topics.Where(node => node.topic_subject == subject).FirstOrDefaultAsync();

                bool exists = (QueryTopic != null) ? true : false;

                if (!exists)
                {
                    db.Topics.Add(topic);
                    await db.SaveChangesAsync();

                    var top = await db.Topics.Where(t => t.topic_subject == subject).FirstOrDefaultAsync();

                    var post = new Post
                    {
                        post_content = question,
                        post_date    = DateTime.Now,
                        post_topic   = top.topic_id,
                        post_by      = user.Id
                    };

                    db.Posts.Add(post);
                    await db.SaveChangesAsync();

                    var ms = new MemoryStream();

                    if (view != null)
                    {
                        await view.InputStream.CopyToAsync(ms);

                        var item = await db.Posts.Where(p => p.post_content == question).FirstOrDefaultAsync();

                        var file = new PostFile
                        {
                            file_name    = Path.GetFileName(view.FileName),
                            file_type    = view.ContentType,
                            file_content = ms.ToArray(),
                            ref_id       = item.post_id
                        };

                        db.PostFiles.Add(file);
                        await db.SaveChangesAsync();
                    }

                    table.Add("message", "New topic has been successfully registered!");
                    table.Add("success", true);
                    return(Json(table, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    table.Add("message", "This topic already exists!");
                    table.Add("success", false);
                    return(Json(table, JsonRequestBehavior.AllowGet));
                }
            }
            else
            {
                table.Add("message", "Something went wrong!");
                table.Add("success", false);
                return(Json(table, JsonRequestBehavior.AllowGet));
            }
        }
Ejemplo n.º 34
0
        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        private void Page_Load(object sender, System.EventArgs e)
        {
            int threadID = HnDGeneralUtils.TryConvertToInt(Request.QueryString["ThreadID"]);

            _thread = ThreadGuiHelper.GetThread(threadID);
            if (_thread == null)
            {
                // not found, return to start page
                Response.Redirect("default.aspx");
            }

            // Check credentials
            bool userHasAccess = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);

            if (!userHasAccess)
            {
                // doesn't have access to this forum. redirect
                Response.Redirect("default.aspx");
            }

            _startMessageNo = HnDGeneralUtils.TryConvertToInt(Request.QueryString["StartAtMessage"]);
            bool highLightSearchResults = (HnDGeneralUtils.TryConvertToInt(Request.QueryString["HighLight"]) == 1);

            if (!_thread.IsClosed)
            {
                if (_thread.IsSticky)
                {
                    _userMayAddNewMessages = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessageInSticky);
                }
                else
                {
                    _userMayAddNewMessages = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAndEditMessage);
                }
                // set show*link class members. These have to be set despite the postback status, as they're used in the repeater. Only set
                // them to true if the thread isn't closed. They've been initialized to false already.
                _showEditMessageLink   = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditDeleteOtherUsersMessages);
                _showDeleteMessageLink = _showEditMessageLink;
                _showQuoteMessageLink  = _userMayAddNewMessages;
            }

            // show user IP addresses if the user has system admin rights, security admin rights or user admin rights.
            _showIPAddresses = (SessionAdapter.HasSystemActionRight(ActionRights.SystemManagement) ||
                                SessionAdapter.HasSystemActionRight(ActionRights.SecurityManagement) ||
                                SessionAdapter.HasSystemActionRight(ActionRights.UserManagement));
            // Get the forum entity related to the thread. Use BL class. We could have used Lazy loading, though for the sake of separation, we'll
            // call into the BL class.
            ForumEntity forum = CacheManager.GetForum(_thread.ForumID);

            if (forum == null)
            {
                // not found, orphaned thread, return to default page.
                Response.Redirect("default.aspx");
            }
            _forumAllowsAttachments = (forum.MaxNoOfAttachmentsPerMessage > 0);

            // check if the user can view this thread. If not, don't continue.
            if ((_thread.StartedByUserID != SessionAdapter.GetUserID()) &&
                !SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ViewNormalThreadsStartedByOthers) &&
                !_thread.IsSticky)
            {
                // can't view this thread, it isn't visible to the user
                Response.Redirect("default.aspx", true);
            }

            _threadStartedByCurrentUser = (_thread.StartedByUserID == SessionAdapter.GetUserID());
            _userMayAddAttachments      = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddAttachment);
            _userCanCreateThreads       = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddNormalThread) ||
                                          SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AddStickyThread);
            _userMayDoForumSpecificThreadManagement = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.ForumSpecificThreadManagement);
            _userMayDoSystemWideThreadManagement    = SessionAdapter.HasSystemActionRight(ActionRights.SystemWideThreadManagement);
            _userMayEditMemo                   = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.EditThreadMemo);
            _userMayMarkThreadAsDone           = (SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.FlagThreadAsDone) || _threadStartedByCurrentUser);
            _userMayManageSupportQueueContents = SessionAdapter.HasSystemActionRight(ActionRights.QueueContentManagement);
            _userMayDoBasicThreadOperations    = (SessionAdapter.GetUserID() > 0);

            if (!Page.IsPostBack)
            {
                plPageListBottom.HighLight = highLightSearchResults;
                plPageListTop.HighLight    = highLightSearchResults;
                litHighLightLogic.Visible  = highLightSearchResults;

                if (highLightSearchResults)
                {
                    // make highlighting of search results possible
                    string searchTerms = SessionAdapter.GetSearchTerms();
                    if (searchTerms == null)
                    {
                        searchTerms = string.Empty;
                    }
                    this.ClientScript.RegisterHiddenField("searchTerms", searchTerms.Replace("AND", "").Replace("OR", "").Replace("and", "").Replace("or", "").Replace("\"", ""));
                }
                else
                {
                    // replace hightlighting scriptblock.
                    this.ClientScript.RegisterClientScriptBlock(this.GetType(), "onLoad", "<script language=\"javascript\"  type=\"text/javascript\">function SearchHighlight() {}</script>");
                }

                if (_userMayManageSupportQueueContents)
                {
                    // fill support queue management area with data.
                    SupportQueueCollection supportQueues = CacheManager.GetAllSupportQueues();
                    cbxSupportQueues.DataSource = supportQueues;
                    cbxSupportQueues.DataBind();

                    SupportQueueEntity containingQueue = SupportQueueGuiHelper.GetQueueOfThread(_thread.ThreadID);
                    if (containingQueue != null)
                    {
                        cbxSupportQueues.SelectedValue = containingQueue.QueueID.ToString();
                        // get claim info
                        SupportQueueThreadEntity supportQueueThreadInfo = SupportQueueGuiHelper.GetSupportQueueThreadInfo(_thread.ThreadID, true);
                        if ((supportQueueThreadInfo != null) && supportQueueThreadInfo.ClaimedByUserID.HasValue)
                        {
                            // claimed by someone
                            lblClaimDate.Text             = supportQueueThreadInfo.ClaimedOn.Value.ToString("dd-MMM-yyyy HH:mm.ss", DateTimeFormatInfo.InvariantInfo);
                            lnkClaimerThread.Visible      = true;
                            lblNotClaimed.Visible         = false;
                            lnkClaimerThread.Text         = supportQueueThreadInfo.ClaimedByUser.NickName;
                            lnkClaimerThread.NavigateUrl += supportQueueThreadInfo.ClaimedByUserID.ToString();
                            btnClaim.Visible              = false;
                            btnRelease.Visible            = true;
                        }
                        else
                        {
                            // not claimed
                            lblClaimDate.Text  = string.Empty;
                            btnClaim.Visible   = true;
                            btnRelease.Visible = false;
                        }
                    }
                }
                phSupportQueueManagement.Visible = _userMayManageSupportQueueContents;

                if ((_thread.Memo.Length > 0) && _userMayEditMemo)
                {
                    // convert memo contents to HTML so it's displayed above the thread.
                    string parserLog, messageTextXml;
                    bool   errorsOccured = false;
                    string memoAsHTML    = TextParser.TransformUBBMessageStringToHTML(_thread.Memo, ApplicationAdapter.GetParserData(), out parserLog, out errorsOccured, out messageTextXml);
                    lblMemo.Text = memoAsHTML;
                }
                phMemo.Visible = _userMayEditMemo;

                bool isBookmarked = UserGuiHelper.CheckIfThreadIsAlreadyBookmarked(SessionAdapter.GetUserID(), threadID);
                bool isSubscribed = UserGuiHelper.CheckIfThreadIsAlreadySubscribed(SessionAdapter.GetUserID(), threadID);
                btnBookmarkThread.Visible   = !isBookmarked && _userMayDoBasicThreadOperations;
                btnUnbookmarkThread.Visible = isBookmarked && _userMayDoBasicThreadOperations;
                bool sendReplyNotifications = CacheManager.GetSystemData().SendReplyNotifications;
                btnSubscribeToThread.Visible     = !isSubscribed && _userMayDoBasicThreadOperations && sendReplyNotifications;
                btnUnsubscribeFromThread.Visible = isSubscribed && _userMayDoBasicThreadOperations && sendReplyNotifications;

                // fill the page's content
                lnkThreads.Text          = HttpUtility.HtmlEncode(forum.ForumName);
                lnkThreads.NavigateUrl  += "?ForumID=" + _thread.ForumID;
                lblForumName_Header.Text = forum.ForumName;
                lblSectionName.Text      = CacheManager.GetSectionName(forum.SectionID);

                // Check if the current user is allowed to add new messages to the thread.

                // these controls are not visible by default, show them if necessary
                if (_userMayDoForumSpecificThreadManagement || _userMayDoSystemWideThreadManagement)
                {
                    if (!_thread.IsClosed && _userMayAddNewMessages)
                    {
                        lnkCloseThread.Visible      = true;
                        lnkCloseThread.NavigateUrl += "?ThreadID=" + threadID + "&StartAtMessage=" + _startMessageNo;
                    }
                    lnkEditThreadProperties.Visible      = true;
                    lnkEditThreadProperties.NavigateUrl += "?ThreadID=" + threadID;
                }

                if (_userMayDoSystemWideThreadManagement)
                {
                    lnkMoveThread.Visible        = true;
                    lnkMoveThread.NavigateUrl   += "?ThreadID=" + threadID;
                    lnkDeleteThread.Visible      = true;
                    lnkDeleteThread.NavigateUrl += "?ThreadID=" + threadID;
                }

                btnThreadDone.Visible    = _thread.MarkedAsDone;
                btnThreadNotDone.Visible = !_thread.MarkedAsDone;
                btnThreadDone.Enabled    = _userMayMarkThreadAsDone;
                btnThreadNotDone.Enabled = _userMayMarkThreadAsDone;

                if (_userMayEditMemo)
                {
                    lnkEditMemo.Visible      = true;
                    lnkEditMemo.NavigateUrl += "?ThreadID=" + threadID + "&StartAtMessage=" + _startMessageNo;
                }

                // These controls are visible by default. Hide them when the user can't create threads on this forum
                if (_userCanCreateThreads)
                {
                    lnkNewThreadBottom.NavigateUrl += "?ForumID=" + _thread.ForumID + "&StartAtMessage=" + _startMessageNo;
                    lnkNewThreadTop.NavigateUrl    += "?ForumID=" + _thread.ForumID + "&StartAtMessage=" + _startMessageNo;
                }
                else
                {
                    lnkNewThreadBottom.Visible = false;
                    lnkNewThreadTop.Visible    = false;
                }

                if (_userMayAddNewMessages)
                {
                    lnkNewMessageBottom.NavigateUrl += "?ThreadID=" + threadID + "&StartAtMessage=" + _startMessageNo;
                    lnkNewMessageTop.NavigateUrl    += "?ThreadID=" + threadID + "&StartAtMessage=" + _startMessageNo;
                }
                else
                {
                    lnkNewMessageBottom.Visible = false;
                    lnkNewMessageTop.Visible    = false;
                }
                lblSeparatorTop.Visible    = (_userMayAddNewMessages && _userCanCreateThreads);
                lblSeparatorBottom.Visible = (_userMayAddNewMessages && _userCanCreateThreads);

                // The amount of postings in this thread are in the dataview row, which should contain just 1 row.
                int maxAmountMessagesPerPage = SessionAdapter.GetUserDefaultNumberOfMessagesPerPage();
                int amountOfMessages         = ThreadGuiHelper.GetTotalNumberOfMessagesInThread(threadID);
                int amountOfPages            = ((amountOfMessages - 1) / maxAmountMessagesPerPage) + 1;
                int currentPageNo            = (_startMessageNo / maxAmountMessagesPerPage) + 1;
                lblCurrentPage.Text = currentPageNo.ToString();
                lblTotalPages.Text  = amountOfPages.ToString();

                lnkPrintThread.NavigateUrl += "?ThreadID=" + threadID;

                plPageListBottom.AmountMessages = amountOfMessages;
                plPageListBottom.StartMessageNo = _startMessageNo;
                plPageListBottom.ThreadID       = threadID;
                plPageListTop.AmountMessages    = amountOfMessages;
                plPageListTop.StartMessageNo    = _startMessageNo;
                plPageListTop.ThreadID          = threadID;

                // Get messages and bind it to the repeater control. Use the startmessage to get only the message visible on the current page.
                MessagesInThreadTypedList messages = ThreadGuiHelper.GetAllMessagesInThreadAsTypedList(threadID, currentPageNo, maxAmountMessagesPerPage);
                rptMessages.DataSource = messages;
                rptMessages.DataBind();
            }
        }