コード例 #1
0
        public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
        {
            _threadEntity = CurrentThreadEntity;
            _threadEntity.ControlIndex += 1;
            _dataBuilder.Init(_tagList);
            _datastring = _dataBuilder.HandleData(CurrentPageClass);
            if (!_xsltLoaded || _threadEntity.WebSetting.DebugMode)
            {
                _xsltstring = HandleXSLT();
            }
            HTMLContainer _temp = new HTMLContainer(ContentContainer.Encoding);

            _xsltstring = _dataBuilder.InsertParameter(_xsltstring);
            if (!string.IsNullOrEmpty(_xsltParameter))
            {
                _xsltstring = InsertParameter(_xsltstring, CurrentPageClass);
            }
            _temp.Write(HandleHTML(_datastring, _xsltstring));

            if (_enableScript && _temp.Length > 0)
            {
                Control.ControlAnalyze _controls = new ControlAnalyze(CurrentThreadEntity, this.Map, true);
                _controls.SetContent(_temp.ToArray());
                _controls.Analyze();
                _temp.Clear();
                _controls.Handle(CurrentPageClass, _temp);
            }
            ContentContainer.Write(_temp);
            _threadEntity.ControlIndex -= 1;
        }
コード例 #2
0
ファイル: ThreadGuiHelper.cs プロジェクト: priaonehaha/HnD
        /// <summary>
        /// Constructs a TypedList with all the messages in the thread given. Poster info is included, so the
        /// returned dataview is bindable at once to the message list repeater.
        /// </summary>
        /// <param name="threadID">ID of Thread which messages should be returned</param>
        /// <param name="pageNo">The page no.</param>
        /// <param name="pageSize">Size of the page.</param>
        /// <returns>TypedList with all messages in the thread for the page specified</returns>
        public static MessagesInThreadTypedList GetAllMessagesInThreadAsTypedList(int threadID, int pageNo, int pageSize)
        {
            // we'll use a typedlist, MessagesInThread to pull the necessary data from the db. The typedlist contains fields from
            // message, user and usertitle.
            MessagesInThreadTypedList messages = new MessagesInThreadTypedList();

            //create the filter with the threadID passed to the method.
            PredicateExpression filter = new PredicateExpression(MessageFields.ThreadID == threadID);

            // Sort Messages on posting date, ascending, so the first post is located on top.
            SortExpression sorter = new SortExpression(MessageFields.PostingDate.Ascending());

            // fetch the data into the typedlist. Pass in the paging information as well, to perform server-side paging.
            messages.Fill(0, sorter, true, filter, null, null, pageNo, pageSize);

            // update thread entity directly inside the DB with a non-transactional update statement so the # of views is increased by one.
            ThreadEntity updater = new ThreadEntity();

            // set the NumberOfViews field to an expression which increases it by 1
            updater.Fields[(int)ThreadFieldIndex.NumberOfViews].ExpressionToApply = (ThreadFields.NumberOfViews + 1);
            updater.IsNew = false;

            // update the entity directly, and filter on the PK
            ThreadCollection threads = new ThreadCollection();

            threads.UpdateMulti(updater, (ThreadFields.ThreadID == threadID));

            // return the constructed typedlist
            return(messages);
        }
コード例 #3
0
ファイル: DataControl.cs プロジェクト: BrookHuang/XYFrame
        public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
        {
            _threadEntity = CurrentThreadEntity;
            _threadEntity.ControlIndex += 1;
            _dataBuilder.Init(_tagList);
            _datastring = _dataBuilder.HandleData(CurrentPageClass);

            HTMLContainer _temp = new HTMLContainer(ContentContainer.Encoding);

            if (!_xsltLoaded || _threadEntity.WebSetting.DebugMode) {
                _xsltCache = HandleXSLT();
            }
            _xsltString = _xsltCache;
            _xsltString = _dataBuilder.InsertParameter(_xsltString);
            if (!string.IsNullOrEmpty(_xsltParameter)) {
                _xsltString = InsertParameter(_xsltString, CurrentPageClass);
            }
            _temp.Write(HandleHTML(_datastring, _xsltString));

            if (_enableScript && _temp.Length > 0) {
                Control.ControlAnalyze _controls = new ControlAnalyze(CurrentThreadEntity, this.Map, true);
                _controls.SetContent(_temp.ToArray());
                _controls.Analyze();
                _temp.Clear();
                _controls.Handle(CurrentPageClass, _temp);
            }
            ContentContainer.Write(_temp);
            _threadEntity.ControlIndex -= 1;
        }
コード例 #4
0
 public void Handle(ThreadEntity CurrentThreadEntity, Page.Page CurrentPageClass)
 {
     _threadEntity = CurrentThreadEntity;
     _threadEntity.ControlIndex += 1;
     Xy.WebSetting.WebSettingItem _tempWebConfig = null;
     if (_webConfig != null) {
         _tempWebConfig = _threadEntity.WebSetting;
         _threadEntity.WebSetting = _webConfig;
     }
     InitSourceHtml();
     //if (_enableScript) {
     //    ControlCollection cc = new Control.ControlAnalyze(ref _innerHtml, _threadEntity).ControlCollection;
     //    cc.Handle(ref _innerHtml, ref _threadEntity);
     //}
     if (_enableScript) {
         ControlCollection cc;
         if (_threadEntity.WebSetting.DebugMode) {
             cc = new Control.ControlAnalyze(_innerHtml, _threadEntity).ControlCollection;
         } else {
             cc = _cacheItem._controlCollection;
         }
         cc.Handle(_innerHtml, _threadEntity, CurrentPageClass);
     }
     if (_webConfig != null) {
         _threadEntity.WebSetting = _tempWebConfig;
     }
     _threadEntity.ControlIndex -= 1;
 }
コード例 #5
0
        public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
        {
            _threadEntity = CurrentThreadEntity;
            _threadEntity.ControlIndex += 1;

            _index = Xy.Tools.Control.Tag.TransferValue("PageIndex", _index, CurrentPageClass);
            _size  = Xy.Tools.Control.Tag.TransferValue("PageSize", _size, CurrentPageClass);
            _max   = Xy.Tools.Control.Tag.TransferValue("PageMax", _max, CurrentPageClass);
            _count = Xy.Tools.Control.Tag.TransferValue("PageCount", _count, CurrentPageClass);

            if (_innerData == null || (!string.IsNullOrEmpty(_xsltstring) && _threadEntity.WebSetting.DebugMode))
            {
                if (!string.IsNullOrEmpty(_xsltstring))
                {
                    using (System.IO.FileStream fs = new System.IO.FileStream(_threadEntity.WebSetting.XsltDir + _xsltstring, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(fs)) {
                            _innerData.Write(sr.ReadToEnd());
                            sr.Close();
                        }
                        fs.Close();
                    }
                }
            }
            HandleData();
            System.Xml.XPath.XPathDocument xpathDoc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader(_datastring));

            System.Xml.Xsl.XslCompiledTransform xsl = HandleXSLT();

            ContentContainer.Write(Xy.Tools.IO.XML.TransfromXmlStringToHtml(xsl, xpathDoc));
            _threadEntity.ControlIndex -= 1;
        }
コード例 #6
0
        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 access credentials
            bool userHasAccess             = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, ActionRights.AccessForum);
            bool userMayDoThreadManagement = SessionAdapter.CanPerformForumActionRight(_thread.ForumID, 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");
            }

            if (!Page.IsPostBack)
            {
                chkIsClosed.Checked = _thread.IsClosed;
                chkIsSticky.Checked = _thread.IsSticky;
                tbxSubject.Value    = _thread.Subject;
            }
        }
コード例 #7
0
        public static List <ThreadEntity> GetAllThreadNewsOtherId(int pageIndex, int pageSize, int threadId, int imgWidth)
        {
            string key = String.Format("GetAllThreadNewsOtherId-{0}-{1}-{2}-{3}", pageIndex, pageSize, threadId, imgWidth);
            var    obj = (List <ThreadEntity>)HttpContext.Current.Cache[key];

            if (obj == null)
            {
                obj = new List <ThreadEntity>();
                DataTable da;
                using (MainDB db = new MainDB())
                {
                    da = db.StoredProcedures.GetAllThreadNewsOtherId(pageIndex, pageSize, threadId);
                }
                int          iCount = da != null ? da.Rows.Count : 0;
                DataRow      row;
                ThreadEntity thr;
                for (int i = 0; i < iCount; i++)
                {
                    row          = da.Rows[i];
                    thr          = new ThreadEntity();
                    thr.Title    = Utils.GetObj <String>(row["Title"]);
                    thr.ThreadId = Utils.GetObj <Int32>(row["Thread_Id"]);
                    thr.Url      = String.Format("/event/{0}-e{1}.html", Utils.UnicodeToKoDauAndGach(Utils.GetObj <String>(row["Title"])), thr.ThreadId);
                    thr.Image    = Utils.GetThumbNail(thr.Title, thr.Url, Utils.GetObj <String>(row["Thread_logo"]), imgWidth);
                    obj.Add(thr);
                }
                Utils.SaveToCacheDependency(TableName.DATABASE_NAME, TableName.THREAD, key, obj);
                return(obj);
            }
            return(obj);
        }
コード例 #8
0
        public int PostMessageEntity([FromRoute] int threadID, [FromBody] MessageEntity messageEntity)
        {
            if (!ModelState.IsValid)
            {
                return(-1);
            }

            ThreadEntity te = _context.Threads.Where(t => t.ID == threadID).First();

            if (te.UserAID != messageEntity.AuthorID || te.UserBID != messageEntity.AuthorID)
            {
                return(-2);
            }

            messageEntity.ThreadID = threadID;
            MessageEntity me = _context.Messages.Add(messageEntity).Entity;

            _context.SaveChanges();
            messageEntity.ID = me.ID;

            te.LastMessageID = messageEntity.ID;
            _context.Update(te);
            _context.SaveChanges();

            return(messageEntity.ID);
        }
コード例 #9
0
 public void Handle(ThreadEntity CurrentThreadEntity, Page.Page CurrentPageClass)
 {
     _threadEntity = CurrentThreadEntity;
     _threadEntity.ControlIndex += 1;
     Xy.WebSetting.WebSettingItem _tempWebConfig = null;
     if (_webConfig != null)
     {
         _tempWebConfig           = _threadEntity.WebSetting;
         _threadEntity.WebSetting = _webConfig;
     }
     InitSourceHtml();
     //if (_enableScript) {
     //    ControlCollection cc = new Control.ControlAnalyze(ref _innerHtml, _threadEntity).ControlCollection;
     //    cc.Handle(ref _innerHtml, ref _threadEntity);
     //}
     if (_enableScript)
     {
         ControlCollection cc;
         if (_threadEntity.WebSetting.DebugMode)
         {
             cc = new Control.ControlAnalyze(_innerHtml, _threadEntity).ControlCollection;
         }
         else
         {
             cc = _cacheItem._controlCollection;
         }
         cc.Handle(_innerHtml, _threadEntity, CurrentPageClass);
     }
     if (_webConfig != null)
     {
         _threadEntity.WebSetting = _tempWebConfig;
     }
     _threadEntity.ControlIndex -= 1;
 }
コード例 #10
0
        public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
        {
            _threadEntity = CurrentThreadEntity;
            _threadEntity.ControlIndex += 1;

            _index = Xy.Tools.Control.Tag.TransferValue("PageIndex", _index, CurrentPageClass);
            _size = Xy.Tools.Control.Tag.TransferValue("PageSize", _size, CurrentPageClass);
            _max = Xy.Tools.Control.Tag.TransferValue("PageMax", _max, CurrentPageClass);
            _count = Xy.Tools.Control.Tag.TransferValue("PageCount", _count, CurrentPageClass);

            if (_innerData == null || (!string.IsNullOrEmpty(_xsltstring) && _threadEntity.WebSetting.DebugMode)) {
                if (!string.IsNullOrEmpty(_xsltstring)) {
                    using (System.IO.FileStream fs = new System.IO.FileStream(_threadEntity.WebSetting.XsltDir + _xsltstring, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) {
                        using (System.IO.StreamReader sr = new System.IO.StreamReader(fs)) {
                            _innerData.Write(sr.ReadToEnd());
                            sr.Close();
                        }
                        fs.Close();
                    }
                }
            }
            HandleData();
            System.Xml.XPath.XPathDocument xpathDoc = new System.Xml.XPath.XPathDocument(new System.IO.StringReader(_datastring));

            System.Xml.Xsl.XslCompiledTransform xsl = HandleXSLT();

            ContentContainer.Write(Xy.Tools.IO.XML.TransfromXmlStringToHtml(xsl, xpathDoc));
            _threadEntity.ControlIndex -= 1;
        }
コード例 #11
0
 private void delegate_Data(string name, ThreadEntity currentThreadEntity, Page.PageAbstract currentPageClass, HTMLContainer contentContainer)
 {
     Page.PageDataItem pdi = currentPageClass.PageData[name];
     if (pdi != null)
     {
         contentContainer.Write(pdi.GetDataString());
     }
 }
コード例 #12
0
ファイル: EntityFactories.cs プロジェクト: priaonehaha/HnD
        /// <summary>Creates a new, empty ThreadEntity object.</summary>
        /// <returns>A new, empty ThreadEntity object.</returns>
        public override IEntity Create()
        {
            IEntity toReturn = new ThreadEntity();

            // __LLBLGENPRO_USER_CODE_REGION_START CreateNewThread
            // __LLBLGENPRO_USER_CODE_REGION_END
            return(toReturn);
        }
コード例 #13
0
        private void delegate_Group(string name, ThreadEntity currentThreadEntity, Page.PageAbstract currentPageClass, HTMLContainer contentContainer)
        {
            string temp = currentPageClass.Request.GroupString[name];

            if (!string.IsNullOrEmpty(temp))
            {
                contentContainer.Write(temp);
            }
        }
コード例 #14
0
        private void delegate_Translate(string name, ThreadEntity currentThreadEntity, Page.PageAbstract currentPageClass, HTMLContainer contentContainer)
        {
            string temp = _webConfig.Translate[name];

            if (!string.IsNullOrEmpty(temp))
            {
                contentContainer.Write(temp);
            }
        }
コード例 #15
0
        private void delegate_Session(string name, ThreadEntity currentThreadEntity, Page.PageAbstract currentPageClass, HTMLContainer contentContainer)
        {
            string temp = Convert.ToString(currentPageClass.Session[name]);

            if (!string.IsNullOrEmpty(temp))
            {
                contentContainer.Write(temp);
            }
        }
コード例 #16
0
ファイル: PageAnalyze.cs プロジェクト: BrookHuang/XYFrame
 public static Control.ControlAnalyze GetInstance(ThreadEntity currentTheadEntity, Page.PageAbstract currentPageClass, string map, bool useInnerMark = false)
 {
     if (currentPageClass.WebSetting.DebugMode) return new Control.ControlAnalyze(currentTheadEntity, map, useInnerMark);
     string _key = string.Concat(currentPageClass.WebSetting.Name, currentTheadEntity.URLItem.PageClassName, map);
     if (!_controlCenter.ContainsKey(_key)) {
         _controlCenter.Add(_key, new Control.ControlAnalyze(currentTheadEntity, map, useInnerMark));
     }
     return _controlCenter[_key];
 }
コード例 #17
0
        public async Task IfTheThreadToUpdate_DoesntExist_ReturnNull()
        {
            var thread = new ThreadEntity {
                Id = 3, Title = "Thread5"
            };

            var result = await _threadRepository.Update(thread);

            Assert.Null(result);
        }
コード例 #18
0
        protected void submitNewThread_Click(object sender, EventArgs e)
        {
            var secId    = int.Parse(Request.QueryString["secId"]);
            var schoolId = int.Parse(Request.Cookies["SmacCookie"]["SchoolId"]);
            var userId   = Request.Cookies["SmacCookie"]["UserId"];

            ThreadEntity.CreatePost(userId, this.threadTitle.Text, secId, this.threadInput.Text, null);

            Response.Redirect("/Threads.aspx?secId=" + secId.ToString());
        }
コード例 #19
0
        private ForumListingModel GetForumListingForThread(ThreadEntity thread)
        {
            var forum = thread.Forum;

            return(new ForumListingModel
            {
                Id = forum.Id,
                Title = forum.Title,
            });
        }
コード例 #20
0
ファイル: ThreadManager.cs プロジェクト: alexsiilvaa/credible
        private async Task LogMessage(ThreadEntity thread, MessageResponseModel message, DateTime?readAt)
        {
            var log = _mapper.Map <LogEntity>(thread);

            log               = _mapper.Map(message, log, options => options.Items[MappingConstants.RecipientUserId] = thread.Type == ThreadType.User ? message.FromUserId : 0);
            log.Id            = new Guid();
            log.RecepientName = thread.Name;
            log.SenderName    = message.FromUserName;
            log.CreatedAt     = message.CreatedAt;
            log.IsArchived    = thread.ArchivedBy.Count == 0 ? false : true;
            if (message.ReadBy.Contains(log.SenderId) && message.ReadBy.Count == 1)
            {
                log.IsRead = false;
            }
            else if (message.ReadBy.Count > 1)
            {
                log.IsRead = true;
            }
            if (log.IsArchived == false)
            {
                log.ArchivedAt = null;
            }
            else
            {
                log.ArchivedAt = thread.ModifiedAt;
            }
            if (log.IsRead == false)
            {
                log.ReadAt = null;
            }
            else
            {
                log.ReadAt = readAt;
            }

            switch (thread.Type)
            {
            case ThreadType.User:
                log.RecipientId = thread.Participants[1];
                break;

            case ThreadType.Group:
                log.RecipientId = 0;
                break;

            case ThreadType.Team:
                log.RecipientId = thread.TeamId;
                break;

            default:
                log.RecipientId = 0;
                break;
            }
            await _logRepository.CreateAsync(log);
        }
コード例 #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 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");
            }

            // 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");
            }

            // 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);
            }

            lblForumName_Header.Text = forum.ForumName;

            if (!Page.IsPostBack)
            {
                bool threadStartedByCurrentUser = (_thread.StartedByUserID == SessionAdapter.GetUserID());
                // 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, 0, 0);
                rptMessages.DataSource = messages;
                rptMessages.DataBind();
            }
        }
コード例 #22
0
        public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
        {
            _threadEntity = CurrentThreadEntity;
            _threadEntity.ControlIndex += 1;
            HTMLContainer _innerHTML = new HTMLContainer(ContentContainer.Encoding);

            if (CurrentPageClass is Page.UserPage)
            {
                Page.UserPage up = (Page.UserPage)CurrentPageClass;
                if (up.CurrentUser != null)
                {
                    if ((_hasPowerIndex > 0 && up.CurrentUser.HasPower(_hasPowerIndex)) || (!string.IsNullOrEmpty(_hasPowerKey) && up.CurrentUser.HasPower(_hasPowerKey)))
                    {
                        if (_inGroupIndex > 0 || !string.IsNullOrEmpty(_inGroupKey))
                        {
                            if (up.CurrentUser.InGroup(_inGroupIndex) || up.CurrentUser.InGroup(_inGroupKey))
                            {
                                _innerHTML.Write(_innerData);
                            }
                        }
                        else
                        {
                            _innerHTML.Write(_innerData);
                        }
                    }
                    else if ((_inGroupIndex > 0 && up.CurrentUser.InGroup(_inGroupIndex)) || (!string.IsNullOrEmpty(_hasPowerKey) && up.CurrentUser.InGroup(_inGroupKey)))
                    {
                        _innerHTML.Write(_innerData);
                    }
                }
            }
            if (_innerHTML.Length == 0 && !string.IsNullOrEmpty(_noPowerMessage))
            {
                ContentContainer.Write(_noPowerMessage);
            }
            else
            {
                if (_enableScript)
                {
                    Control.ControlAnalyze _controls = Cache.PageAnalyze.GetInstance(CurrentThreadEntity, CurrentPageClass, this.Map);
                    if (!_controls.IsHandled || CurrentPageClass.WebSetting.DebugMode)
                    {
                        _controls.SetContent(_innerHTML.ToArray());
                        _controls.Analyze();
                    }
                    _controls.Handle(CurrentPageClass, ContentContainer);
                }
                else
                {
                    ContentContainer.Write(_innerHTML);
                }
            }
            _threadEntity.ControlIndex -= 1;
        }
コード例 #23
0
		/// <summary>
		/// Updates the user/forum/thread statistics after a message insert. Also makes sure if the thread isn't in a queue and the forum has a default support
		/// queue that the thread is added to that queue
		/// </summary>
		/// <param name="threadID">The thread ID.</param>
		/// <param name="userID">The user ID.</param>
		/// <param name="transactionToUse">The transaction to use.</param>
		/// <param name="postingDate">The posting date.</param>
		/// <param name="addToQueueIfRequired">if set to true, the thread will be added to the default queue of the forum the thread is in, if the forum
		/// has a default support queue and the thread isn't already in a queue.</param>
		/// <remarks>Leaves the passed in transaction open, so it doesn't commit/rollback, it just performs a set of actions inside the
		/// passed in transaction.</remarks>
		internal static void UpdateStatisticsAfterMessageInsert(int threadID, int userID, Transaction transactionToUse, DateTime postingDate, bool addToQueueIfRequired, bool subscribeToThread)
		{
			// user statistics
			UserEntity userUpdater = new UserEntity();
			// set the amountofpostings field to an expression so it will be increased with 1. 
			userUpdater.Fields[(int)UserFieldIndex.AmountOfPostings].ExpressionToApply = (UserFields.AmountOfPostings + 1);
			UserCollection users = new UserCollection();
			transactionToUse.Add(users);
			users.UpdateMulti(userUpdater, (UserFields.UserID == userID));	// update directly on the DB. 

			// thread statistics
			ThreadEntity threadUpdater = new ThreadEntity();
			threadUpdater.ThreadLastPostingDate = postingDate;
			threadUpdater.MarkedAsDone = false;
			ThreadCollection threads = new ThreadCollection();
			transactionToUse.Add(threads);
			threads.UpdateMulti(threadUpdater, (ThreadFields.ThreadID == threadID));

			// forum statistics. Load the forum from the DB, as we need it later on. Use a fieldcompareset predicate to fetch the forum as we don't know the 
			// forumID as we haven't fetched the thread
			ForumCollection forums = new ForumCollection();
			transactionToUse.Add(forums);
			// use a fieldcompare set predicate to select the forumid based on the thread. This filter is equal to
			// WHERE ForumID == (SELECT ForumID FROM Thread WHERE ThreadID=@ThreadID)
			var forumFilter = new FieldCompareSetPredicate(
								ForumFields.ForumID, ThreadFields.ForumID, SetOperator.Equal, (ThreadFields.ThreadID == threadID));
			forums.GetMulti(forumFilter);
			ForumEntity containingForum = null;
			if(forums.Count>0)
			{
				// forum found. There's just one.
				containingForum = forums[0];
				containingForum.ForumLastPostingDate = postingDate;
				// save the forum. Just save the collection
				forums.SaveMulti();
			}

			if(addToQueueIfRequired)
			{
				// If the thread involved isn't in a queue, place it in the default queue of the forum (if applicable)
				SupportQueueEntity containingQueue = SupportQueueGuiHelper.GetQueueOfThread(threadID, transactionToUse);
				if((containingQueue == null) && (containingForum != null) && (containingForum.DefaultSupportQueueID.HasValue))
				{
					// not in a queue, and the forum has a default queue. Add the thread to the queue of the forum
					SupportQueueManager.AddThreadToQueue(threadID, containingForum.DefaultSupportQueueID.Value, userID, transactionToUse);
				}
			}

            //subscribe to thread if indicated
            if(subscribeToThread)
            {
				UserManager.AddThreadToSubscriptions(threadID, userID, transactionToUse);
            }
		}
コード例 #24
0
        public IPageSession CreateSession(ThreadEntity threadEntity)
        {
            string Key = Guid.NewGuid().ToString();

            System.Web.HttpContext hcr = threadEntity.WebContext;
            hcr.Response.Cookies.Add(new System.Web.HttpCookie(threadEntity.WebSetting.UserKeyCookieName, Key)
            {
                Expires = DateTime.Now.AddMinutes(threadEntity.WebSetting.SessionOutTime)
            });
            return(CreateSession(Key));
        }
コード例 #25
0
ファイル: IncludeControl.cs プロジェクト: BrookHuang/XYFrame
 public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
 {
     _threadEntity = CurrentThreadEntity;
     _threadEntity.ControlIndex++;
     if (_webSetting == null) _webSetting = CurrentPageClass.WebSetting;
     HTMLContainer _container = new HTMLContainer(_webSetting.Encoding);
     Xy.Web.Page.PageAbstract _page;
     if (string.IsNullOrEmpty(_type)) _type = "Xy.Web,Xy.Web.Page.EmptyPage";
     _page = Runtime.Web.PageClassLibrary.Get(_type);
     _page.Init(CurrentPageClass, _webSetting, _container);
     if (_extValues != null) {
         for (int i = 0; i < _extValues.Count; i++) {
             if (_page.Request.Values[_extValues.Keys[i]] != null) {
                 _page.Request.Values[_extValues.Keys[i]] = _extValues[i];
             } else {
                 _page.Request.Values.Add(_extValues.Keys[i], _extValues[i]);
             }
         }
     }
     string _staticCacheDir = string.Empty, _staticCacheFile = string.Empty, _staticCachePath = string.Empty;
     if (_cached) {
         _staticCacheDir = _webSetting.CacheDir + "IncludeCache\\" + _threadEntity.URL.Dir.Replace('/', '\\');
         _staticCacheFile = _file + _valueString;
         _staticCachePath = _staticCacheDir + _staticCacheFile + ".xycache";
         if (!_page.UpdateCache(_staticCachePath, DateTime.Now)) {
             if (System.IO.File.Exists(_staticCachePath)) {
                 ContentContainer.Write(System.IO.File.ReadAllBytes(_staticCachePath));
                 return;
             }
         }
     }
     if (_innerData != null && _innerData.HasContent) {
         _page.SetContent(_innerData);
     }
     _page.Handle(_map, _file, _enableScript, true);
     if (_cached) {
         Xy.Tools.IO.File.ifNotExistsThenCreate(_staticCachePath);
         using (System.IO.FileStream fs = new System.IO.FileStream(_staticCachePath, System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read)) {
             using (System.IO.StreamWriter sw = new System.IO.StreamWriter(fs)) {
                 try {
                     sw.Write(_container.ToString());
                     sw.Flush();
                 } finally {
                     sw.Close();
                     fs.Close();
                 }
             }
         }
     }
     ContentContainer.Write(_container);
     //ContentContainer.Write(_page.HTMLContainer);
     _threadEntity.ControlIndex--;
 }
コード例 #26
0
        private ForumListingModel BuildForumListing(ThreadEntity thread)
        {
            var forum = thread.Forum;

            return(new ForumListingModel
            {
                Id = forum.Id,
                //ImageUrl = forum.ImageUrl, // Placeholder.
                Title = forum.Title,
                Description = forum.Description
            });
        }
コード例 #27
0
 internal static PageHtmlCacheItem Add(string path, List<byte> datas, ThreadEntity CurrentThreadEntity)
 {
     string _key = GenerateKey(path, CurrentThreadEntity);
     PageHtmlCacheItem temp;
     if (datas == null) {
         temp = new PageHtmlCacheItem(path, CurrentThreadEntity);
     } else {
         temp = new PageHtmlCacheItem(datas, CurrentThreadEntity);
     }
     _list.Add(_key, temp);
     return temp;
 }
コード例 #28
0
        /// <summary>
        /// Overload.
        /// Collects the necessary data, generates then returns a Thread object for a Forum.
        /// </summary>
        /// <param name="thread">ThreadEntity object.</param>
        /// <returns>ForumEntity object: a forum based on the given thread.</returns>
        private ForumListingModel BuildForumListing(ThreadEntity thread)
        {
            var forum = thread.Forum;

            return(BuildForumListing(forum));
            //return new ForumListingModel
            //{
            //	Id = forum.Id,
            //	Title = forum.Title,
            //	Description = forum.Description
            //};
        }
コード例 #29
0
ファイル: ThreadManager.cs プロジェクト: priaonehaha/HnD
        /// <summary>
        /// Marks the thread as done.
        /// </summary>
        /// <param name="threadID">Thread ID.</param>
        /// <returns></returns>
        public static bool MarkThreadAsDone(int threadID)
        {
            // load the entity from the database
            ThreadEntity thread = ThreadGuiHelper.GetThread(threadID);

            if (thread == null)
            {
                // not found
                return(false);
            }

            // get the support queue the thread is in (if any)
            SupportQueueEntity containingSupportQueue = SupportQueueGuiHelper.GetQueueOfThread(threadID);

            thread.MarkedAsDone = true;

            // if the thread is in a support queue, the thread has to be removed from that queue. This is a multi-entity action and therefore we've to start a
            // transaction if that's the case. If not, we can use the easy route and simply save the thread and be done with it.
            if (containingSupportQueue == null)
            {
                // not in a queue, simply save the thread.
                return(thread.Save());
            }

            // in a queue, so remove from the queue and save the entity.
            Transaction trans = new Transaction(IsolationLevel.ReadCommitted, "MarkThreadDone");

            trans.Add(thread);
            try
            {
                // save the thread
                bool result = thread.Save();
                if (result)
                {
                    // save succeeded, so remove from queue, pass the current transaction to the method so the action takes place inside this transaction.
                    SupportQueueManager.RemoveThreadFromQueue(threadID, trans);
                }

                trans.Commit();
                return(true);
            }
            catch
            {
                // rollback transaction
                trans.Rollback();
                throw;
            }
            finally
            {
                trans.Dispose();
            }
        }
コード例 #30
0
ファイル: ThreadManager.cs プロジェクト: alexsiilvaa/credible
        public async Task <ThreadWithMessagesResponseModel> SearchOrCreateThreadAsync(int userId, string participant, ThreadType threadType)
        {
            ThreadEntity thread = null;

            switch (threadType)
            {
            case ThreadType.User:
            {
                if (!int.TryParse(participant, out var participantId))
                {
                    throw new InvalidRequestException(nameof(participant));
                }

                thread = await GetOrCreateUserThreadAsync(userId, participantId);

                break;
            }

            case ThreadType.Group:
            {
                if (!Guid.TryParse(participant, out var participantGuId))
                {
                    throw new InvalidRequestException(nameof(participant));
                }
                thread = await GetOrCreateGroupThreadAsync(participantGuId);

                break;
            }

            case ThreadType.Team:
            {
                if (!Guid.TryParse(participant, out var participantId))
                {
                    throw new InvalidRequestException(nameof(participant));
                }
                thread = await GetOrCreateTeamThreadAsync(participantId);

                break;
            }
            }

            if (thread == null)
            {
                return(new ThreadWithMessagesResponseModel());
            }

            var participantDetails = _mapper.Map <IEnumerable <ChatUser>, IEnumerable <UserContactResponseModel> >(await _contactRepository.GetChatUserDetailsAsync(thread.Participants));
            var messages           = _mapper.Map <IEnumerable <MessageEntity>, IEnumerable <MessageResponseModel> >(await _messageRepository.GetByThreadIdAsync(thread.Id));
            var threadWithMessages = _mapper.Map(messages, _mapper.Map <ThreadEntity, ThreadWithMessagesResponseModel>(thread, options => options.Items[MappingConstants.ThreadRequestUserId] = userId));

            return(_mapper.Map(participantDetails, threadWithMessages));
        }
コード例 #31
0
 public void Init(ThreadEntity threadEntity, WebSetting.WebSettingItem webSetting)
 {
     _threadEntity     = threadEntity;
     _htmlContainer    = new HTMLContainer(_threadEntity.WebSetting.Encoding);
     _server           = _threadEntity.WebContext.Server;
     _url              = threadEntity.URL;
     _updateLocalCache = false;
     _response         = new PageResponse(_threadEntity, _htmlContainer);
     _request          = new PageRequest(_threadEntity);
     _pageData         = new PageData();
     _pageSession      = PageSessionCollection.GetInstance().GetSession(_threadEntity);
     _webSetting       = webSetting;
 }
コード例 #32
0
        internal void Handle(ThreadEntity currentThreadEntity, Page.PageAbstract currentPageClass, HTMLContainer contentContainer)
        {
            switch (Type)
            {
            case AnalyzeResultType.PureHTML:
                contentContainer.Write(PureHTML);
                break;

            case AnalyzeResultType.Control:
                Control.Handle(currentThreadEntity, currentPageClass, contentContainer);
                break;
            }
        }
コード例 #33
0
ファイル: ThreadGuiHelper.cs プロジェクト: priaonehaha/HnD
		/// <summary>
		/// Gets the thread.
		/// </summary>
		/// <param name="ID">Thread ID.</param>
		/// <returns>Thread object or null if not found</returns>
		public static ThreadEntity	GetThread(int ID)
		{
            // load the entity from the database
            ThreadEntity thread = new ThreadEntity(ID);

            //check if the entity is new (not found in the database), then return null.
			if(thread.IsNew == true)
			{
				return null;
			}

            return thread;
		}
コード例 #34
0
ファイル: ThreadGuiHelper.cs プロジェクト: priaonehaha/HnD
        /// <summary>
        /// Gets the thread.
        /// </summary>
        /// <param name="ID">Thread ID.</param>
        /// <returns>Thread object or null if not found</returns>
        public static ThreadEntity      GetThread(int ID)
        {
            // load the entity from the database
            ThreadEntity thread = new ThreadEntity(ID);

            //check if the entity is new (not found in the database), then return null.
            if (thread.IsNew == true)
            {
                return(null);
            }

            return(thread);
        }
コード例 #35
0
 public void Init(PageAbstract page, WebSetting.WebSettingItem webSetting, HTMLContainer container)
 {
     _threadEntity     = page._threadEntity;
     _server           = page._server;
     _updateLocalCache = page._updateLocalCache;
     _request          = page._request;
     _pageData         = page._pageData;
     _pageSession      = page._pageSession;
     _url        = page._url;
     _webSetting = webSetting;
     _response   = page._response;
     _response.SetNewContainer(container);
     _htmlContainer = container;
 }
コード例 #36
0
ファイル: PageAnalyze.cs プロジェクト: Xiaoyang-Huang/XYFrame
        public static Control.ControlAnalyze GetInstance(ThreadEntity currentTheadEntity, Page.PageAbstract currentPageClass, string map, bool useInnerMark = false)
        {
            if (currentPageClass.WebSetting.DebugMode)
            {
                return(new Control.ControlAnalyze(currentTheadEntity, map, useInnerMark));
            }
            string _key = string.Concat(currentPageClass.WebSetting.Name, currentTheadEntity.URLItem.PageClassName, map);

            if (!_controlCenter.ContainsKey(_key))
            {
                _controlCenter.Add(_key, new Control.ControlAnalyze(currentTheadEntity, map, useInnerMark));
            }
            return(_controlCenter[_key]);
        }
コード例 #37
0
        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 userMayDeleteThread = SessionAdapter.HasSystemActionRight(ActionRights.SystemWideThreadManagement);

            if (!userMayDeleteThread)
            {
                // doesn't have the right to delete a thread. 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
                ForumEntity forum = CacheManager.GetForum(_thread.ForumID);
                if (forum == null)
                {
                    // Orphaned thread
                    Response.Redirect("default.aspx", true);
                }
                lblForumName.Text     = forum.ForumName;
                lblThreadSubject.Text = HttpUtility.HtmlEncode(_thread.Subject);
            }
        }
コード例 #38
0
 internal static PageHtmlCacheItem Get(string path, List<byte> datas, ThreadEntity CurrentThreadEntity)
 {
     string _key = GenerateKey(path, CurrentThreadEntity);
     PageHtmlCacheItem _temp;
     if (_list.TryGetValue(_key, out _temp)) {
         return _temp;
     } else {
         if (datas == null) {
             return Add(path, CurrentThreadEntity);
         } else {
             return Add(path, datas, CurrentThreadEntity);
         }
     }
 }
コード例 #39
0
ファイル: PageControl.cs プロジェクト: BrookHuang/XYFrame
 public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass)
 {
     _threadEntity = CurrentThreadEntity;
     _innerHTML.Clear();
     _threadEntity.ControlIndex++;
     Xy.Tools.Web.UrlAnalyzer _url = CurrentThreadEntity.URL;
     if (_webSetting == null)
         _webSetting = CurrentPageClass.WebSetting;
     if (_webSetting.AutoUrl) _webSetting.UpdateDomain(CurrentThreadEntity.URL.Site);
     URLManage.URLItem _urlItem = new URLManage.URLItem(_file, _type, _threadEntity.URLItem.Regex.ToString(), _threadEntity.URLItem.Mime, _enableScript, _enableCache, _threadEntity.URLItem.ContentType.ToString(), _threadEntity.URLItem.Age.Minutes);
     ThreadEntity _entity = new ThreadEntity(CurrentThreadEntity.WebContext, _webSetting, _urlItem, _url, true);
     _entity.Handle(_extValues);
     if (_entity.Content.HasContent)
         _innerHTML.Write(_entity.Content);
     _threadEntity.ControlIndex--;
 }
コード例 #40
0
ファイル: PageRequest.cs プロジェクト: BrookHuang/XYFrame
        internal PageRequest(ThreadEntity entity)
        {
            _innerRequest = entity.WebContext.Request;
            _values = new System.Collections.Specialized.NameValueCollection();
            _groupNvc = new System.Collections.Specialized.NameValueCollection();

            System.Text.RegularExpressions.GroupCollection _groupMatched = entity.URLItem.Regex.Match(entity.URL.Path).Groups;
            for (int i = 0; i < entity.URLItem.URLGroupsName.Length; i++) {
                string _key = entity.URLItem.URLGroupsName[i];
                _groupNvc.Add(_key, _groupMatched[_key].Value);
            }

            _values.Add(_innerRequest.QueryString);
            _values.Add(_innerRequest.Form);
            _values.Add(_groupNvc);
        }
コード例 #41
0
ファイル: ControlHandle.cs プロジェクト: BrookHuang/XYFrame
 public ControlAnalyze(ThreadEntity currentTheadEntity, string map, bool useInnerMark = false)
 {
     if (useInnerMark) {
         _indexStartBytes = AppSetting.INNER_START_MARK;
         _indexEndBytes = AppSetting.INNER_END_MARK;
     } else {
         _indexStartBytes = AppSetting.START_MARK;
         _indexEndBytes = AppSetting.END_MARK;
     }
     _currentThreadEntity = currentTheadEntity;
     _analyzeResultCollection = new Control.AnalyzeResultCollection();
     _controlCollection = new List<IControl>();
     _content = new byte[0];
     _map = map;
     #if DEBUG
     Xy.Tools.Debug.Log.WriteEventLog(_map + " control analyze created");
     #endif
 }
コード例 #42
0
 public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
 {
     _threadEntity = CurrentThreadEntity;
     _threadEntity.ControlIndex += 1;
     HTMLContainer _innerHTML = new HTMLContainer(ContentContainer.Encoding);
     if (CurrentPageClass is Page.UserPage) {
         Page.UserPage up = (Page.UserPage)CurrentPageClass;
         if (up.CurrentUser != null) {
             if ((_hasPowerIndex > 0 && up.CurrentUser.HasPower(_hasPowerIndex)) || (!string.IsNullOrEmpty(_hasPowerKey) && up.CurrentUser.HasPower(_hasPowerKey))) {
                 if (_inGroupIndex > 0 || !string.IsNullOrEmpty(_inGroupKey)) {
                     if (up.CurrentUser.InGroup(_inGroupIndex) || up.CurrentUser.InGroup(_inGroupKey)) {
                         _innerHTML.Write(_innerData);
                     }
                 } else {
                     _innerHTML.Write(_innerData);
                 }
             } else if ((_inGroupIndex > 0 && up.CurrentUser.InGroup(_inGroupIndex)) || (!string.IsNullOrEmpty(_hasPowerKey) && up.CurrentUser.InGroup(_inGroupKey))) {
                 _innerHTML.Write(_innerData);
             }
         }
     }
     if (_innerHTML.Length == 0 && !string.IsNullOrEmpty(_noPowerMessage)) {
         ContentContainer.Write(_noPowerMessage);
     } else {
         if (_enableScript) {
             Control.ControlAnalyze _controls = Cache.PageAnalyze.GetInstance(CurrentThreadEntity, CurrentPageClass, this.Map);
             if (!_controls.IsHandled || CurrentPageClass.WebSetting.DebugMode) {
                 _controls.SetContent(_innerHTML.ToArray());
                 _controls.Analyze();
             }
             _controls.Handle(CurrentPageClass, ContentContainer);
         } else {
             ContentContainer.Write(_innerHTML);
         }
     }
     _threadEntity.ControlIndex -= 1;
 }
コード例 #43
0
 /// <summary> setups the sync logic for member _thread</summary>
 /// <param name="relatedEntity">Instance to set as the related entity of type entityType</param>
 private void SetupSyncThread(IEntityCore relatedEntity)
 {
     if(_thread!=relatedEntity)
     {
         DesetupSyncThread(true, true);
         _thread = (ThreadEntity)relatedEntity;
         this.PerformSetupSyncRelatedEntity( _thread, new PropertyChangedEventHandler( OnThreadPropertyChanged ), "Thread", SD.HnD.DAL.RelationClasses.StaticSupportQueueThreadRelations.ThreadEntityUsingThreadIDStatic, true, ref _alreadyFetchedThread, new string[] {  } );
     }
 }
コード例 #44
0
        /// <summary>Private CTor for deserialization</summary>
        /// <param name="info"></param>
        /// <param name="context"></param>
        protected SupportQueueThreadEntityBase(SerializationInfo info, StreamingContext context)
            : base(info, context)
        {
            _supportQueue = (SupportQueueEntity)info.GetValue("_supportQueue", typeof(SupportQueueEntity));
            if(_supportQueue!=null)
            {
                _supportQueue.AfterSave+=new EventHandler(OnEntityAfterSave);
            }
            _supportQueueReturnsNewIfNotFound = info.GetBoolean("_supportQueueReturnsNewIfNotFound");
            _alwaysFetchSupportQueue = info.GetBoolean("_alwaysFetchSupportQueue");
            _alreadyFetchedSupportQueue = info.GetBoolean("_alreadyFetchedSupportQueue");

            _claimedByUser = (UserEntity)info.GetValue("_claimedByUser", typeof(UserEntity));
            if(_claimedByUser!=null)
            {
                _claimedByUser.AfterSave+=new EventHandler(OnEntityAfterSave);
            }
            _claimedByUserReturnsNewIfNotFound = info.GetBoolean("_claimedByUserReturnsNewIfNotFound");
            _alwaysFetchClaimedByUser = info.GetBoolean("_alwaysFetchClaimedByUser");
            _alreadyFetchedClaimedByUser = info.GetBoolean("_alreadyFetchedClaimedByUser");

            _placedInQueueByUser = (UserEntity)info.GetValue("_placedInQueueByUser", typeof(UserEntity));
            if(_placedInQueueByUser!=null)
            {
                _placedInQueueByUser.AfterSave+=new EventHandler(OnEntityAfterSave);
            }
            _placedInQueueByUserReturnsNewIfNotFound = info.GetBoolean("_placedInQueueByUserReturnsNewIfNotFound");
            _alwaysFetchPlacedInQueueByUser = info.GetBoolean("_alwaysFetchPlacedInQueueByUser");
            _alreadyFetchedPlacedInQueueByUser = info.GetBoolean("_alreadyFetchedPlacedInQueueByUser");
            _thread = (ThreadEntity)info.GetValue("_thread", typeof(ThreadEntity));
            if(_thread!=null)
            {
                _thread.AfterSave+=new EventHandler(OnEntityAfterSave);
            }
            _threadReturnsNewIfNotFound = info.GetBoolean("_threadReturnsNewIfNotFound");
            _alwaysFetchThread = info.GetBoolean("_alwaysFetchThread");
            _alreadyFetchedThread = info.GetBoolean("_alreadyFetchedThread");
            this.FixupDeserialization(FieldInfoProviderSingleton.GetInstance(), PersistenceInfoProviderSingleton.GetInstance());
            // __LLBLGENPRO_USER_CODE_REGION_START DeserializationConstructor
            // __LLBLGENPRO_USER_CODE_REGION_END
        }
コード例 #45
0
 /// <summary> Removes the sync logic for member _thread</summary>
 /// <param name="signalRelatedEntity">If set to true, it will call the related entity's UnsetRelatedEntity method</param>
 /// <param name="resetFKFields">if set to true it will also reset the FK fields pointing to the related entity</param>
 private void DesetupSyncThread(bool signalRelatedEntity, bool resetFKFields)
 {
     this.PerformDesetupSyncRelatedEntity( _thread, new PropertyChangedEventHandler( OnThreadPropertyChanged ), "Thread", SD.HnD.DAL.RelationClasses.StaticSupportQueueThreadRelations.ThreadEntityUsingThreadIDStatic, true, signalRelatedEntity, "SupportQueueThread", resetFKFields, new int[] { (int)SupportQueueThreadFieldIndex.ThreadID } );
     _thread = null;
 }
コード例 #46
0
ファイル: Page.cs プロジェクト: BrookHuang/XYFrame
 public void Init(ThreadEntity threadEntity, WebSetting.WebSettingItem webSetting)
 {
     _threadEntity = threadEntity;
     _htmlContainer = new HTMLContainer(_threadEntity.WebSetting.Encoding);
     _server = _threadEntity.WebContext.Server;
     _url = threadEntity.URL;
     _updateLocalCache = false;
     _response = new PageResponse(_threadEntity, _htmlContainer);
     _request = new PageRequest(_threadEntity);
     _pageData = new PageData();
     _pageSession = PageSessionCollection.GetInstance().GetSession(_threadEntity);
     _webSetting = webSetting;
 }
コード例 #47
0
ファイル: PageResponse.cs プロジェクト: BrookHuang/XYFrame
 internal PageResponse(ThreadEntity entity, HTMLContainer content)
 {
     _innerResponse = entity.WebContext.Response;
     _content = content;
     _entity = entity;
 }
コード例 #48
0
ファイル: Page.cs プロジェクト: BrookHuang/XYFrame
 public void Init(PageAbstract page, WebSetting.WebSettingItem webSetting, HTMLContainer container)
 {
     _threadEntity = page._threadEntity;
     _server = page._server;
     _updateLocalCache = page._updateLocalCache;
     _request = page._request;
     _pageData = page._pageData;
     _pageSession = page._pageSession;
     _url = page._url;
     _webSetting = webSetting;
     _response = page._response;
     _response.SetNewContainer(container);
     _htmlContainer = container;
 }
コード例 #49
0
ファイル: SetDataControl.cs プロジェクト: BrookHuang/XYFrame
        public void Handle(ThreadEntity CurrentThreadEntity, Page.PageAbstract CurrentPageClass, HTMLContainer ContentContainer)
        {
            _threadEntity = CurrentThreadEntity;
            _threadEntity.ControlIndex += 1;
            string _content = string.Empty;
            if (_preEnableScript && _innerData.Length > 0) {
                Control.ControlAnalyze _controls = Cache.PageAnalyze.GetInstance(CurrentThreadEntity, CurrentPageClass, this.Map);
                if (!_controls.IsHandled || CurrentPageClass.WebSetting.DebugMode) {
                    _controls.SetContent(_innerData.ToArray());
                    _controls.Analyze();
                }
                HTMLContainer _temp = new HTMLContainer(_innerData.Encoding);
                _controls.Handle(CurrentPageClass, _temp);
                _content = _temp.ToString();
            } else {
                _content = _innerData.ToString();
            }
            if (_append) {
                string _originalContent = string.Empty;
                if (CurrentPageClass.PageData[_dataName] != null) _originalContent = CurrentPageClass.PageData[_dataName].GetDataString();
                CurrentPageClass.PageData.Add(_dataName, _originalContent + _content);
            } else {
                CurrentPageClass.PageData.Add(_dataName, _content);
            }

            _threadEntity.ControlIndex -= 1;
        }
コード例 #50
0
 internal PageHtmlCacheItem(List<byte> datas, ThreadEntity CurrentThreadEntity)
 {
     _originalHtml = datas;
     _analyzedHtml = new List<byte>(datas);
     _controlCollection = new Control.ControlAnalyze(_analyzedHtml, CurrentThreadEntity).ControlCollection;
 }
コード例 #51
0
ファイル: PageSession.cs プロジェクト: BrookHuang/XYFrame
 public IPageSession CreateSession(ThreadEntity threadEntity)
 {
     string Key = Guid.NewGuid().ToString();
     System.Web.HttpContext hcr = threadEntity.WebContext;
     hcr.Response.Cookies.Add(new System.Web.HttpCookie(threadEntity.WebSetting.UserKeyCookieName, Key) { Expires = DateTime.Now.AddMinutes(threadEntity.WebSetting.SessionOutTime) });
     return CreateSession(Key);
 }
コード例 #52
0
ファイル: PageSession.cs プロジェクト: BrookHuang/XYFrame
 public IPageSession GetSession(ThreadEntity threadEntity)
 {
     if (threadEntity.WebContext.Request.Cookies[threadEntity.WebSetting.UserKeyCookieName] == null) {
         return CreateSession(threadEntity);
     } else {
         string Key = threadEntity.WebContext.Request.Cookies[threadEntity.WebSetting.UserKeyCookieName].Value;
         if (!_sessionCollection.ContainsKey(Key)) {
             return CreateSession(Key);
         }
         return _sessionCollection[Key];
     }
 }
コード例 #53
0
 private static string GenerateKey(string path, ThreadEntity CurrentThreadEntity)
 {
     return path + "_" + CurrentThreadEntity.URLItem.PagePath + "_" + CurrentThreadEntity.WebSetting.Name;
 }
コード例 #54
0
 internal static PageHtmlCacheItem Get(string path, ThreadEntity CurrentThreadEntity)
 {
     return Get(path, null,CurrentThreadEntity);
 }
コード例 #55
0
ファイル: ThreadManager.cs プロジェクト: priaonehaha/HnD
        /// <summary>
        /// Creates a new message in the given thread and closes the thread right after the addition of the message,
        /// which makes the just added message the 'close' message of the thread. Close messages are handy when the
        /// closure of a thread is not obvious.
        /// Caller should validate input parameters.
        /// </summary>
        /// <param name="threadID">Thread wherein the new message will be placed</param>
        /// <param name="userID">User who posted this message</param>
        /// <param name="messageText">Message text</param>
        /// <param name="messageAsHTML">Message text as HTML</param>
        /// <param name="userIDIPAddress">IP address of user calling this method</param>
        /// <param name="messageAsXML">Message text as XML, which is the result of the parse action on MessageText.</param>
        /// <param name="threadUpdatedNotificationTemplate">The thread updated notification template.</param>
        /// <param name="emailData">The email data.</param>
        /// <param name="sendReplyNotifications">Flag to signal to send reply notifications. If set to false no notifications are mailed,
        /// otherwise a notification is mailed to all subscribers to the thread the new message is posted in</param>
        /// <returns>MessageID if succeeded, 0 if not.</returns>
        public static int CreateNewMessageInThreadAndCloseThread(int threadID, int userID, string messageText, string messageAsHTML,
            string userIDIPAddress, string messageAsXML, string threadUpdatedNotificationTemplate, Dictionary<string, string> emailData,
            bool sendReplyNotifications)
        {
            Transaction trans = new Transaction(IsolationLevel.ReadCommitted, "InsertNewMessage");
            int messageID = 0;
            try
            {
                DateTime postingDate = DateTime.Now;
                messageID = InsertNewMessage(threadID, userID, messageText, messageAsHTML, userIDIPAddress, messageAsXML, trans, postingDate);

                MessageManager.UpdateStatisticsAfterMessageInsert(threadID, userID, trans, postingDate, false, false);

                ThreadEntity thread = new ThreadEntity();
                trans.Add(thread);
                thread.FetchUsingPK(threadID);
                thread.IsClosed=true;
                thread.IsSticky=false;
                thread.MarkedAsDone = true;
                bool result = thread.Save();
                if(result)
                {
                    // save succeeded, so remove from queue, pass the current transaction to the method so the action takes place inside this transaction.
                    SupportQueueManager.RemoveThreadFromQueue(threadID, trans);
                }

                trans.Commit();
            }
            catch(Exception)
            {
                trans.Rollback();
                throw;
            }
            finally
            {
                trans.Dispose();
            }

            if(sendReplyNotifications)
            {
                // send notification email to all subscribers. Do this outside the transaction so a failed email send action doesn't terminate the save process
                // of the message.
                ThreadManager.SendThreadReplyNotifications(threadID, userID, threadUpdatedNotificationTemplate, emailData);
            }
            return messageID;
        }
コード例 #56
0
 internal PageHtmlCacheItem(string path, ThreadEntity CurrentThreadEntity)
     : this(ReadOriginalFile(path, CurrentThreadEntity.WebSetting.Encoding),CurrentThreadEntity)
 {
 }
コード例 #57
0
ファイル: NewMessage.aspx.cs プロジェクト: priaonehaha/HnD
        /// <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;
            }
        }
コード例 #58
0
 /// <summary> Retrieves the related entity of type 'ThreadEntity', using a relation of type '1:1'</summary>
 /// <param name="forceFetch">if true, it will discard any changes currently in the currently loaded related entity and will refetch the entity from the persistent storage</param>
 /// <returns>A fetched entity of type 'ThreadEntity' which is related to this entity.</returns>
 public virtual ThreadEntity GetSingleThread(bool forceFetch)
 {
     if( ( !_alreadyFetchedThread || forceFetch || _alwaysFetchThread) && !this.IsSerializing && !this.IsDeserializing && !this.InDesignMode )
     {
         bool performLazyLoading = this.CheckIfLazyLoadingShouldOccur(Relations.ThreadEntityUsingThreadID);
         ThreadEntity newEntity = new ThreadEntity();
         bool fetchResult = false;
         if(performLazyLoading)
         {
             AddToTransactionIfNecessary(newEntity);
             fetchResult = newEntity.FetchUsingPK(this.ThreadID);
         }
         if(fetchResult)
         {
             newEntity = (ThreadEntity)GetFromActiveContext(newEntity);
         }
         else
         {
             if(!_threadReturnsNewIfNotFound)
             {
                 RemoveFromTransactionIfNecessary(newEntity);
                 newEntity = null;
             }
         }
         this.Thread = newEntity;
         _alreadyFetchedThread = fetchResult;
     }
     return _thread;
 }
コード例 #59
0
ファイル: Messages.aspx.cs プロジェクト: priaonehaha/HnD
        /// <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();
            }
        }
コード例 #60
0
ファイル: Attachments.aspx.cs プロジェクト: priaonehaha/HnD
        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;
                }
            }
        }