示例#1
0
        private static PollAnswer DBMapping(DBPollAnswer dbItem)
        {
            if (dbItem == null)
                return null;

            PollAnswer item = new PollAnswer();
            item.PollAnswerID = dbItem.PollAnswerID;
            item.PollID = dbItem.PollID;
            item.Name = dbItem.Name;
            item.Count = dbItem.Count;
            item.DisplayOrder = dbItem.DisplayOrder;

            return item;
        }
示例#2
0
        internal static void AddUpdatePollAnswer(PollAnswer answer)
        {
            bool isCreate = answer.Id == Guid.Empty;

            ValidatePollAnswer(answer);

            if (isCreate)
                PublicApi.PollAnswers.Events.OnBeforeCreate(answer);
            else
                PublicApi.PollAnswers.Events.OnBeforeUpdate(answer);

            PollingDataService.AddUpdatePollAnswer(answer);
            ExpirePoll(answer.PollId);

            if (isCreate)
                PublicApi.PollAnswers.Events.OnAfterCreate(answer);
            else
                PublicApi.PollAnswers.Events.OnAfterUpdate(answer);
        }
示例#3
0
        private static void ValidatePollAnswer(PollAnswer answer)
        {
            if (answer.Id == Guid.Empty)
                answer.Id = Guid.NewGuid();

            answer.Name = TEApi.Html.Sanitize(TEApi.Html.EnsureEncoded(answer.Name));
            if (string.IsNullOrEmpty(answer.Name))
                throw new PollException("The name of the poll answer must be defined.");

            Poll poll = GetPoll(answer.PollId);
            if (poll == null)
                throw new PollException("The poll associated to the answer does not exist.");

            var group = TEApi.Groups.Get(poll.ApplicationId);
            if (group == null || group.HasErrors())
                throw new PollException("The group identified on the poll is invalid.");

            if (poll.AuthorUserId != TEApi.Users.AccessingUser.Id.Value && !PollingPermissionService.CanCreatePolls(TEApi.Groups.ContentTypeId, group.ApplicationId))
                throw new PollException("The user does not have permission to create/edit this poll. The user must be the original creator or an have create poll permissions in the group.");
        }
示例#4
0
        protected void btnAddPollAnswer_Click(object sender, EventArgs e)
        {
            try
            {
                var pollAnswer = new PollAnswer()
                {
                    PollId = this.PollId,
                    Name = txtPollAnswerName.Text,
                    DisplayOrder = txtPollAnswerDisplayOrder.Value
                };
                this.PollService.InsertPollAnswer(pollAnswer);

                BindData();
            }
            catch (Exception exc)
            {
                processAjaxError(exc);
            }
        }
示例#5
0
        public ActionResult EditPostTopic(CreateEditTopicViewModel editPostViewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Get the category
                var category = _categoryService.Get(editPostViewModel.Category);

                // First check this user is allowed to create topics in this category
                var permissions = RoleService.GetPermissions(category, UsersRole);

                // Now we have the category and permissionSet - Populate the optional permissions
                // This is just in case the viewModel is return back to the view also sort the allowedCategories
                // Get the allowed categories for this user
                var allowedAccessCategories = _categoryService.GetAllowedCategories(UsersRole);
                var allowedCreateTopicCategories = _categoryService.GetAllowedCategories(UsersRole, SiteConstants.Instance.PermissionCreateTopics);
                var allowedCreateTopicCategoryIds = allowedCreateTopicCategories.Select(x => x.Id);
                allowedAccessCategories.RemoveAll(x => allowedCreateTopicCategoryIds.Contains(x.Id));
                editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
                editPostViewModel.Categories = _categoryService.GetBaseSelectListCategories(allowedAccessCategories);
                editPostViewModel.IsTopicStarter = editPostViewModel.Id == Guid.Empty;
                if (editPostViewModel.PollAnswers == null)
                {
                    editPostViewModel.PollAnswers = new List<PollAnswer>();
                }

                if (ModelState.IsValid)
                {

                    try
                    {
                        var topicPostInModeration = false;

                        // Check stop words
                        var stopWords = _bannedWordService.GetAll(true);
                        foreach (var stopWord in stopWords)
                        {
                            if (editPostViewModel.Content.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0 ||
                                editPostViewModel.Name.IndexOf(stopWord.Word, StringComparison.CurrentCultureIgnoreCase) >= 0)
                            {

                                ShowMessage(new GenericMessageViewModel
                                {
                                    Message = LocalizationService.GetResourceString("StopWord.Error"),
                                    MessageType = GenericMessages.danger
                                });

                                var p = _postService.Get(editPostViewModel.Id);
                                var t = p.Topic;

                                // Ahhh found a stop word. Abandon operation captain.
                                return Redirect(t.NiceUrl);
                            }
                        }

                        // Quick check to see if user is locked out, when logged in
                        if (LoggedOnReadOnlyUser.IsLockedOut || LoggedOnReadOnlyUser.DisablePosting == true || !LoggedOnReadOnlyUser.IsApproved)
                        {
                            FormsAuthentication.SignOut();
                            return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess"));
                        }

                        // Got to get a lot of things here as we have to check permissions
                        // Get the post
                        var post = _postService.Get(editPostViewModel.Id);

                        // Get the topic
                        var topic = post.Topic;

                        if (post.User.Id == LoggedOnReadOnlyUser.Id || permissions[SiteConstants.Instance.PermissionEditPosts].IsTicked)
                        {

                            // Get the DB user so we can use lazy loading and update
                            var loggedOnUser = MembershipService.GetUser(LoggedOnReadOnlyUser.Id);

                            // Want the same edit date on both post and postedit
                            var dateEdited = DateTime.UtcNow;

                            // Create a post edit
                            var postEdit = new PostEdit
                            {
                                Post = post,
                                DateEdited = dateEdited,
                                EditedBy = loggedOnUser,
                                OriginalPostContent = post.PostContent,
                                OriginalPostTitle = post.IsTopicStarter ? topic.Name : string.Empty
                            };

                            // User has permission so update the post
                            post.PostContent = _bannedWordService.SanitiseBannedWords(editPostViewModel.Content);
                            post.DateEdited = dateEdited;

                            post = _postService.SanitizePost(post);

                            // Update postedit content
                            postEdit.EditedPostContent = post.PostContent;

                            // if topic starter update the topic
                            if (post.IsTopicStarter)
                            {
                                // if category has changed then update it
                                if (topic.Category.Id != editPostViewModel.Category)
                                {
                                    var cat = _categoryService.Get(editPostViewModel.Category);
                                    topic.Category = cat;
                                }
                                topic.IsLocked = editPostViewModel.IsLocked;
                                topic.IsSticky = editPostViewModel.IsSticky;
                                topic.Name = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name));

                                // Update post edit
                                postEdit.EditedPostTitle = topic.Name;

                                // See if there is a poll
                                if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count(x => !string.IsNullOrEmpty(x?.Answer)) > 1 && permissions[SiteConstants.Instance.PermissionCreatePolls].IsTicked)
                                {
                                    // Now sort the poll answers, what to add and what to remove
                                    // Poll answers already in this poll.
                                    //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList();
                                    var postedIds = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x?.Answer)).Select(x => x.Id);

                                    // This post might not have a poll on it, if not they are creating a poll for the first time
                                    var topicPollAnswerIds = new List<Guid>();
                                    var pollAnswersToRemove = new List<PollAnswer>();
                                    if (topic.Poll == null)
                                    {
                                        // Create a new Poll
                                        var newPoll = new Poll
                                        {
                                            User = loggedOnUser
                                        };

                                        // Create the poll
                                        _pollService.Add(newPoll);

                                        // Save the poll in the context so we can add answers
                                        unitOfWork.SaveChanges();

                                        // Add the poll to the topic
                                        topic.Poll = newPoll;
                                    }
                                    else
                                    {
                                        topicPollAnswerIds = topic.Poll.PollAnswers.Select(p => p.Id).ToList();
                                        pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();
                                    }

                                    // Set the amount of days to close the poll
                                    topic.Poll.ClosePollAfterDays = editPostViewModel.PollCloseAfterDays;

                                    var existingAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && topicPollAnswerIds.Contains(x.Id)).ToList();
                                    var newPollAnswers = editPostViewModel.PollAnswers.Where(x => !string.IsNullOrEmpty(x.Answer) && !topicPollAnswerIds.Contains(x.Id)).ToList();

                                    // Loop through existing and update names if need be
                                    //TODO: Need to think about this in future versions if they change the name
                                    //TODO: As they could game the system by getting votes and changing name?
                                    foreach (var existPollAnswer in existingAnswers)
                                    {
                                        // Get the existing answer from the current topic
                                        var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id);
                                        if (pa != null && pa.Answer != existPollAnswer.Answer)
                                        {
                                            // If the answer has changed then update it
                                            pa.Answer = existPollAnswer.Answer;
                                        }
                                    }

                                    // Loop through and remove the old poll answers and delete
                                    foreach (var oldPollAnswer in pollAnswersToRemove)
                                    {
                                        // Delete
                                        _pollAnswerService.Delete(oldPollAnswer);

                                        // Remove from Poll
                                        topic.Poll.PollAnswers.Remove(oldPollAnswer);
                                    }

                                    // Poll answers to add
                                    foreach (var newPollAnswer in newPollAnswers)
                                    {
                                        if (newPollAnswer != null)
                                        {
                                            var npa = new PollAnswer
                                            {
                                                Poll = topic.Poll,
                                                Answer = newPollAnswer.Answer
                                            };
                                            _pollAnswerService.Add(npa);
                                            topic.Poll.PollAnswers.Add(npa);
                                        }
                                    }
                                }
                                else
                                {
                                    // Need to check if this topic has a poll, because if it does
                                    // All the answers have now been removed so remove the poll.
                                    if (topic.Poll != null)
                                    {
                                        //Firstly remove the answers if there are any
                                        if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any())
                                        {
                                            var answersToDelete = new List<PollAnswer>();
                                            answersToDelete.AddRange(topic.Poll.PollAnswers);
                                            foreach (var answer in answersToDelete)
                                            {
                                                // Delete
                                                _pollAnswerService.Delete(answer);

                                                // Remove from Poll
                                                topic.Poll.PollAnswers.Remove(answer);
                                            }
                                        }

                                        // Now delete the poll
                                        var pollToDelete = topic.Poll;
                                        _pollService.Delete(pollToDelete);

                                        // Remove from topic.
                                        topic.Poll = null;
                                    }
                                }

                                // Tags
                                topic.Tags.Clear();
                                if (!string.IsNullOrEmpty(editPostViewModel.Tags))
                                {
                                    _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic);
                                }

                                // if the Category has moderation marked then the topic needs to
                                // go back into moderation
                                if (topic.Category.ModerateTopics == true)
                                {
                                    topic.Pending = true;
                                    topicPostInModeration = true;
                                }

                                // Sort the post search field
                                post.SearchField = _postService.SortSearchField(post.IsTopicStarter, topic, topic.Tags);
                            }
                            else
                            {
                                // if the Category has moderation marked then the post needs to
                                // go back into moderation
                                if (topic.Category.ModeratePosts == true)
                                {
                                    post.Pending = true;
                                    topicPostInModeration = true;
                                }
                            }

                            // Add the post edit too
                            _postEditService.Add(postEdit);

                            // Commit the changes
                            unitOfWork.Commit();

                            if (topicPostInModeration)
                            {
                                // If in moderation then let the user now
                                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                {
                                    Message = LocalizationService.GetResourceString("Moderate.AwaitingModeration"),
                                    MessageType = GenericMessages.info
                                };
                            }
                            else
                            {
                                TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                                {
                                    Message = LocalizationService.GetResourceString("Post.Updated"),
                                    MessageType = GenericMessages.success
                                };
                            }

                            // redirect back to topic
                            return Redirect($"{topic.NiceUrl}?postbadges=true");
                        }
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LoggingService.Error(ex);
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message = LocalizationService.GetResourceString("Errors.GenericError"),
                            MessageType = GenericMessages.danger
                        };
                    }

                    return ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission"));
                }
            }
            return View(editPostViewModel);
        }
示例#6
0
        /// <summary>
        /// Record a Response...........................................
        /// Check to see which answer button was selected and update the 
        /// record. After update, hide panel1 and display panel2 write a 
        /// cookie to the users computer.
        /// </summary>
        /// <param name="sender"> </param>
        /// <param name="e"> </param>
        public void Btn_Click(object sender, System.EventArgs e)
        {
            HtmlInputRadioButton m_Rdo;
            // Walk through all of the buttons
            for (int i=0; i<RdoValues.Count; i++)
            {
                // Get Each button in the array
                m_Rdo = (HtmlInputRadioButton)RdoValues[i];
                if (m_Rdo.Checked) // This is the response
                {
                    alAnswers        = pQ.alAnswers;
                    pA               = (PollAnswer)alAnswers[i];
                    pA.Count        += 1;   // Update the Response Count
                    pQ.TotalAnswers += 1;   // Increment Total Count
                    pA.UpdAnswer(m_connString); // Results to File

                    // Create and Write Cookie
                    HttpCookie Cookie = new HttpCookie(CookieName,CookieValue);
                    Cookie.Expires    = DateTime.Now.AddDays(30);
                    Response.Cookies.Add(Cookie);
                }
            }
            ShowResults(); // Now Show the results
        }
示例#7
0
        public ActionResult Vote(PollPageModel model)
        {
            if (!model.token.HasValue || model.token == Guid.Empty)
            {
                return(Json(new { result = "error", message = "Please log in" }));
            }
            var   answers = new List <PollAnswer>();
            Order order   = null;
            Shop  shop    = null;

            if (model.ShopID > 0)
            {
                shop = ShoppingService.GetShopByID(model.ShopID);
            }
            foreach (var fp in Request.Form.AllKeys)
            {
                if (fp.StartsWith("poll"))
                {
                    int pollID        = 0;
                    int pollVariantID = 0;
                    int.TryParse(fp.Replace("poll", ""), out pollID);
                    if (pollID > 0)
                    {
                        int.TryParse(Request.Form[fp], out pollVariantID);
                        if (pollVariantID > 0)
                        {
                            //get poll
                            var poll = _db.Polls.FirstOrDefault(x => x.ID == pollID);
                            if (poll != null)
                            {
                                //validation
                                if (poll.AssignType == PollAssignType.Order && model.OrderID == 0)
                                {
                                    continue;//no order set
                                }
                                if (poll.AssignType == PollAssignType.Shop && model.ShopID == 0)
                                {
                                    continue;//no shop set
                                }
                                if (poll.AssignType == PollAssignType.Product && model.ProductID == 0)
                                {
                                    continue;//no product set
                                }
                                if (model.OrderID > 0)
                                {
                                    if (HttpContext.Items["CurrentOrder"] == null)
                                    {
                                        HttpContext.Items["CurrentOrder"] = _db.Orders.FirstOrDefault(x => x.ID == model.OrderID);
                                        //saving for next block child action
                                    }
                                    order = HttpContext.Items["CurrentOrder"] as Order;
                                    if (poll.AssignType == PollAssignType.Order &&
                                        (
                                            order == null || order.UserID != model.token.Value)
                                        )
                                    {
                                        continue;// it`s not your order!!!
                                    }
                                }
                                //create or update poll vote
                                var voteQuery = _db.PollAnswers.Where(x => x.PollID == pollID &&
                                                                      x.UserID == model.token.Value
                                                                      );
                                if (poll.AssignType == PollAssignType.Order)
                                {
                                    voteQuery = voteQuery.Where(x => x.OrderID == model.OrderID);
                                }
                                if (poll.AssignType == PollAssignType.Shop)
                                {
                                    voteQuery = voteQuery.Where(x => x.ShopID == model.ShopID);
                                }
                                if (poll.AssignType == PollAssignType.Product)
                                {
                                    voteQuery = voteQuery.Where(x => x.ProductID == model.ProductID);
                                }
                                var vote = voteQuery.FirstOrDefault();
                                if (vote != null)
                                {
                                    vote.Rate          = pollVariantID;
                                    vote.PollVariantID = pollVariantID;

                                    _db.SaveChanges();
                                }
                                else
                                {
                                    vote = new PollAnswer()
                                    {
                                        PollID        = pollID,
                                        PollVariantID = pollVariantID,
                                        Rate          = pollVariantID,
                                        UserID        = model.token.Value
                                    };
                                    if (poll.AssignType == PollAssignType.Order)
                                    {
                                        vote.OrderID = model.OrderID;
                                    }
                                    if (poll.AssignType == PollAssignType.Shop)
                                    {
                                        vote.ShopID = model.ShopID;
                                    }
                                    if (poll.AssignType == PollAssignType.Product)
                                    {
                                        vote.ProductID = model.ProductID;
                                    }
                                    _db.PollAnswers.Add(vote);
                                    _db.SaveChanges();
                                }
                                vote.Poll = poll;
                                if (!poll.IsRating)
                                {
                                    vote.PollVariant = _db.PollVariants.FirstOrDefault(x => x.ID == vote.PollVariantID);
                                }
                                answers.Add(vote);
                            }
                        }
                    }
                }
            }
            if (answers.Count > 0)
            {
                var messService = new MessageService(_db);
                messService.OrderQuestionedToMember(order, shop, answers);
            }
            return(Json(new { result = "ok", message = "Thank you for your vote" }));
        }
示例#8
0
        /// <summary>
        /// Updates the poll answer
        /// </summary>
        /// <param name="pollAnswer">Poll answer</param>
        public void UpdatePollAnswer(PollAnswer pollAnswer)
        {
            if (pollAnswer == null)
                throw new ArgumentNullException("pollAnswer");

            pollAnswer.Name = CommonHelper.EnsureNotNull(pollAnswer.Name);
            pollAnswer.Name = CommonHelper.EnsureMaximumLength(pollAnswer.Name, 400);

            if (!_context.IsAttached(pollAnswer))
                _context.PollAnswers.Attach(pollAnswer);

            _context.SaveChanges();

            if (this.CacheEnabled)
            {
                _cacheManager.RemoveByPattern(POLLS_PATTERN_KEY);
                _cacheManager.RemoveByPattern(POLLANSWERS_PATTERN_KEY);
            }
        }
示例#9
0
        /// <summary>
        /// Creates a table and inserts the Poll Questions and the
        /// submt button
        /// </summary>
        /// <returns></returns>
        protected bool MkControls()
        {
            HtmlTable				m_Table;
            HtmlTableRow			m_Row;
            HtmlTableCell			m_Cell;
            HtmlInputRadioButton    m_Rdo;
            Button					m_Btn;

            //Set the table properties
            m_Table				=	new HtmlTable();
            m_Table.Border		=	1;
            m_Table.CellPadding	=	1;
            m_Table.CellSpacing	=	0;
            m_Table.BorderColor =	"#000000";
            m_Table.BgColor		=	"#FFFFEE";
            m_Table.Width		=	"160px";

            // Get Poll Question
            pQ = new PollQuestion(m_whichPoll,m_connString);

            // If there isn't a valid Poll then exit
            if (pQ.Found!=true) return false;

            // Get the Question Answers
            alAnswers = pQ.alAnswers;

            // First Table Row for Question
            m_Row  = new HtmlTableRow();
            m_Cell = new HtmlTableCell();
            m_Cell.ColSpan   = 2;
            m_Cell.Align     = "center";
            m_Cell.InnerHtml = "<font size='1' face='arial'><b>"+pQ.Question+"</b></font>";
            m_Row.Cells.Add(m_Cell);
            m_Table.Rows.Add(m_Row);

            // Poll Answers
            RdoValues = new ArrayList();		// New Array for Poll Answers
            for (int i=0;i<pQ.NumberAnswers;i++)
            {
                pA				= (PollAnswer)alAnswers[i];
                m_Row           = new HtmlTableRow();

                // This cell shows the checkbox
                m_Rdo			= new HtmlInputRadioButton();
                m_Rdo.ID		= String.Format("R{0}",i);
                m_Rdo.Name		= "G1"; // Group Name
                RdoValues.Add(m_Rdo);
                m_Cell	        = new HtmlTableCell();
                m_Cell.Align	= "center";
                m_Cell.Controls.Add(m_Rdo);
                m_Row.Cells.Add(m_Cell);

                // This cell shows the Answer
                m_Cell = new HtmlTableCell();
                m_Cell.InnerHtml = "&nbsp<font size='1' face='arial'>"+pA.Answer+"</font>";
                m_Row.Cells.Add(m_Cell);

                // Add the Row to the table
                m_Table.Rows.Add(m_Row);
            }

            // Show Previous Number of Responses
            m_Row			= new HtmlTableRow();
            m_Cell			= new HtmlTableCell();
            m_Cell.ColSpan	= 2;
            m_Cell.Align    = "center";
            m_Label  	    = new Label();
            m_Label.Text   += string.Format("<font size='1' face='arial'>{0} Responses</font>",pQ.TotalAnswers);
            m_Cell.Controls.Add(m_Label);
            m_Row.Cells.Add(m_Cell);
            m_Table.Rows.Add(m_Row);

            // Add the Submit Button
            m_Row			= new HtmlTableRow();
            m_Cell			= new HtmlTableCell();
            m_Cell.ColSpan	= 3;
            m_Cell.Align    = "center";
            m_Btn		    = new Button();
            m_Btn.Click	   += new System.EventHandler (this.Btn_Click);
            m_Btn.Text      = "Submit";
            m_Btn.ForeColor = Color.White;
            m_Btn.BackColor = Color.DarkBlue;
            m_Btn.Font.Bold = true;
            m_Btn.Font.Name = "Arial";
            m_Btn.Font.Size = 8;

            m_Cell.Controls.Add(m_Btn);
            m_Row.Cells.Add(m_Cell);
            m_Table.Rows.Add(m_Row);
            Ph.Controls.Add(m_Table);  // Add the Poll Table
            return true;
        }
示例#10
0
 public void Delete(PollAnswer pollAnswer)
 {
     _context.PollAnswer.Remove(pollAnswer);
 }
示例#11
0
 public PollAnswer Add(PollAnswer pollAnswer)
 {
     pollAnswer.Answer = StringUtils.SafePlainText(pollAnswer.Answer);
     return _context.PollAnswer.Add(pollAnswer);
 }
示例#12
0
 public PollAnswer UpdatePollAnswer(PollAnswer entity)
 {
     return(_iPollAnswerRepository.UpdatePollAnswer(entity));
 }
        public ActionResult EditPost(EditPostViewModel editPostViewModel)
        {
            using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
            {
                // Got to get a lot of things here as we have to check permissions
                // Get the post
                var post = ServiceFactory.PostService.Get(editPostViewModel.Id);

                // Get the topic
                var topic    = post.Topic;
                var category = ServiceFactory.CategoryService.Get(topic.CategoryId);
                topic.Category = category;

                // get the users permissions
                var permissions = ServiceFactory.PermissionService.GetPermissions(category, _membersGroups);

                if (post.MemberId == CurrentMember.Id || permissions[AppConstants.PermissionModerate].IsTicked)
                {
                    // User has permission so update the post
                    post.PostContent = AppHelpers.GetSafeHtml(ServiceFactory.BannedWordService.SanitiseBannedWords(editPostViewModel.Content));
                    post.DateEdited  = DateTime.UtcNow;

                    // if topic starter update the topic
                    if (post.IsTopicStarter)
                    {
                        // if category has changed then update it
                        if (topic.Category.Id != editPostViewModel.Category)
                        {
                            var cat = ServiceFactory.CategoryService.Get(editPostViewModel.Category);
                            topic.Category = cat;
                        }

                        topic.IsLocked = editPostViewModel.IsLocked;
                        topic.IsSticky = editPostViewModel.IsSticky;
                        topic.Name     = AppHelpers.GetSafeHtml(ServiceFactory.BannedWordService.SanitiseBannedWords(editPostViewModel.Name));

                        // See if there is a poll
                        if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0)
                        {
                            // Now sort the poll answers, what to add and what to remove
                            // Poll answers already in this poll.
                            var postedIds = editPostViewModel.PollAnswers.Select(x => x.Id);
                            //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList();
                            var existingAnswers     = editPostViewModel.PollAnswers.Where(x => topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var newPollAnswers      = editPostViewModel.PollAnswers.Where(x => !topic.Poll.PollAnswers.Select(p => p.Id).Contains(x.Id)).ToList();
                            var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();

                            // Loop through existing and update names if need be
                            //TODO: Need to think about this in future versions if they change the name
                            //TODO: As they could game the system by getting votes and changing name?
                            foreach (var existPollAnswer in existingAnswers)
                            {
                                // Get the existing answer from the current topic
                                var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id);
                                if (pa != null && pa.Answer != existPollAnswer.Answer)
                                {
                                    // If the answer has changed then update it
                                    pa.Answer = existPollAnswer.Answer;
                                }
                            }

                            // Loop through and remove the old poll answers and delete
                            foreach (var oldPollAnswer in pollAnswersToRemove)
                            {
                                // Delete
                                ServiceFactory.PollService.Delete(oldPollAnswer);

                                // Remove from Poll
                                topic.Poll.PollAnswers.Remove(oldPollAnswer);
                            }

                            // Poll answers to add
                            foreach (var newPollAnswer in newPollAnswers)
                            {
                                var npa = new PollAnswer
                                {
                                    Poll   = topic.Poll,
                                    Answer = newPollAnswer.Answer
                                };
                                ServiceFactory.PollService.Add(npa);
                                topic.Poll.PollAnswers.Add(npa);
                            }
                        }
                        else
                        {
                            // Need to check if this topic has a poll, because if it does
                            // All the answers have now been removed so remove the poll.
                            if (topic.Poll != null)
                            {
                                //Firstly remove the answers if there are any
                                if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any())
                                {
                                    var answersToDelete = new List <PollAnswer>();
                                    answersToDelete.AddRange(topic.Poll.PollAnswers);
                                    foreach (var answer in answersToDelete)
                                    {
                                        // Delete
                                        ServiceFactory.PollService.Delete(answer);

                                        // Remove from Poll
                                        topic.Poll.PollAnswers.Remove(answer);
                                    }
                                }

                                // Now delete the poll
                                var pollToDelete = topic.Poll;
                                ServiceFactory.PollService.Delete(pollToDelete);

                                // Remove from topic.
                                topic.Poll = null;
                            }
                        }
                    }

                    // redirect back to topic
                    var message = new GenericMessageViewModel
                    {
                        Message     = "Post Updated",
                        MessageType = GenericMessages.Success
                    };
                    try
                    {
                        unitOfWork.Commit();
                        ShowMessage(message);
                        return(Redirect(topic.Url));
                    }
                    catch (Exception ex)
                    {
                        unitOfWork.Rollback();
                        LogError(ex);
                        throw new Exception(Lang("Errors.GenericError"));
                    }
                }

                return(NoPermission(topic));
            }
        }
示例#14
0
        public ActionResult EditPostTopic(CreateEditTopicViewModel editPostViewModel)
        {
            // Get the category
            var category = _categoryService.Get(editPostViewModel.Category);

            // First check this user is allowed to create topics in this category
            var permissions = RoleService.GetPermissions(category, UsersRole);

            // Now we have the category and permissionSet - Populate the optional permissions
            // This is just in case the viewModel is return back to the view also sort the allowedCategories
            var allowedCategories = _categoryService.GetAllowedCategories(UsersRole);

            editPostViewModel.OptionalPermissions = GetCheckCreateTopicPermissions(permissions);
            editPostViewModel.Categories          = GetBaseSelectListCategories(allowedCategories);
            editPostViewModel.IsTopicStarter      = editPostViewModel.Id == Guid.Empty;
            if (editPostViewModel.PollAnswers == null)
            {
                editPostViewModel.PollAnswers = new List <PollAnswer>();
            }
            /*---- End Re-populate ViewModel ----*/

            if (ModelState.IsValid)
            {
                // Quick check to see if user is locked out, when logged in
                if (LoggedOnUser.IsLockedOut || LoggedOnUser.DisablePosting == true || !LoggedOnUser.IsApproved)
                {
                    FormsAuthentication.SignOut();
                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoAccess")));
                }

                using (var unitOfWork = UnitOfWorkManager.NewUnitOfWork())
                {
                    // Got to get a lot of things here as we have to check permissions
                    // Get the post
                    var post = _postService.Get(editPostViewModel.Id);

                    // Get the topic
                    var topic = post.Topic;

                    if (post.User.Id == LoggedOnUser.Id || permissions[AppConstants.PermissionEditPosts].IsTicked)
                    {
                        // User has permission so update the post
                        post.PostContent = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Content));
                        post.DateEdited  = DateTime.UtcNow;

                        // if topic starter update the topic
                        if (post.IsTopicStarter)
                        {
                            // if category has changed then update it
                            if (topic.Category.Id != editPostViewModel.Category)
                            {
                                var cat = _categoryService.Get(editPostViewModel.Category);
                                topic.Category = cat;
                            }

                            topic.IsLocked = editPostViewModel.IsLocked;
                            topic.IsSticky = editPostViewModel.IsSticky;
                            topic.Name     = StringUtils.GetSafeHtml(_bannedWordService.SanitiseBannedWords(editPostViewModel.Name));

                            // See if there is a poll
                            if (editPostViewModel.PollAnswers != null && editPostViewModel.PollAnswers.Count > 0)
                            {
                                // Now sort the poll answers, what to add and what to remove
                                // Poll answers already in this poll.
                                //var existingAnswers = topic.Poll.PollAnswers.Where(x => postedIds.Contains(x.Id)).ToList();
                                var postedIds           = editPostViewModel.PollAnswers.Select(x => x.Id);
                                var topicPollAnswerIds  = topic.Poll.PollAnswers.Select(p => p.Id).ToList();
                                var existingAnswers     = editPostViewModel.PollAnswers.Where(x => topicPollAnswerIds.Contains(x.Id)).ToList();
                                var newPollAnswers      = editPostViewModel.PollAnswers.Where(x => !topicPollAnswerIds.Contains(x.Id)).ToList();
                                var pollAnswersToRemove = topic.Poll.PollAnswers.Where(x => !postedIds.Contains(x.Id)).ToList();

                                // Loop through existing and update names if need be
                                //TODO: Need to think about this in future versions if they change the name
                                //TODO: As they could game the system by getting votes and changing name?
                                foreach (var existPollAnswer in existingAnswers)
                                {
                                    // Get the existing answer from the current topic
                                    var pa = topic.Poll.PollAnswers.FirstOrDefault(x => x.Id == existPollAnswer.Id);
                                    if (pa != null && pa.Answer != existPollAnswer.Answer)
                                    {
                                        // If the answer has changed then update it
                                        pa.Answer = existPollAnswer.Answer;
                                    }
                                }

                                // Loop through and remove the old poll answers and delete
                                foreach (var oldPollAnswer in pollAnswersToRemove)
                                {
                                    // Delete
                                    _pollAnswerService.Delete(oldPollAnswer);

                                    // Remove from Poll
                                    topic.Poll.PollAnswers.Remove(oldPollAnswer);
                                }

                                // Poll answers to add
                                foreach (var newPollAnswer in newPollAnswers)
                                {
                                    var npa = new PollAnswer
                                    {
                                        Poll   = topic.Poll,
                                        Answer = newPollAnswer.Answer
                                    };
                                    _pollAnswerService.Add(npa);
                                    topic.Poll.PollAnswers.Add(npa);
                                }
                            }
                            else
                            {
                                // Need to check if this topic has a poll, because if it does
                                // All the answers have now been removed so remove the poll.
                                if (topic.Poll != null)
                                {
                                    //Firstly remove the answers if there are any
                                    if (topic.Poll.PollAnswers != null && topic.Poll.PollAnswers.Any())
                                    {
                                        var answersToDelete = new List <PollAnswer>();
                                        answersToDelete.AddRange(topic.Poll.PollAnswers);
                                        foreach (var answer in answersToDelete)
                                        {
                                            // Delete
                                            _pollAnswerService.Delete(answer);

                                            // Remove from Poll
                                            topic.Poll.PollAnswers.Remove(answer);
                                        }
                                    }

                                    // Now delete the poll
                                    var pollToDelete = topic.Poll;
                                    _pollService.Delete(pollToDelete);

                                    // Remove from topic.
                                    topic.Poll = null;
                                }
                            }

                            // Tags
                            topic.Tags.Clear();
                            if (!string.IsNullOrEmpty(editPostViewModel.Tags))
                            {
                                _topicTagService.Add(editPostViewModel.Tags.ToLower(), topic);
                            }
                        }

                        // redirect back to topic
                        TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                        {
                            Message     = LocalizationService.GetResourceString("Post.Updated"),
                            MessageType = GenericMessages.success
                        };
                        try
                        {
                            unitOfWork.Commit();
                            return(Redirect(string.Format("{0}?postbadges=true", topic.NiceUrl)));
                        }
                        catch (Exception ex)
                        {
                            unitOfWork.Rollback();
                            LoggingService.Error(ex);
                            TempData[AppConstants.MessageViewBagName] = new GenericMessageViewModel
                            {
                                Message     = LocalizationService.GetResourceString("Errors.GenericError"),
                                MessageType = GenericMessages.danger
                            };
                        }
                    }

                    return(ErrorToHomePage(LocalizationService.GetResourceString("Errors.NoPermission")));
                }
            }
            return(View(editPostViewModel));
        }
示例#15
0
        /// <summary>
        /// Show the Poll Results after submission or if
        /// the Poll was previously answered
        /// </summary>
        protected void ShowResults()
        {
            HtmlTable				m_Table;
            HtmlTableRow			m_Row;
            HtmlTableCell			m_Cell;

            // Clear the Panel for the Show Results Table ----------------
            Ph.Controls.Clear();

            //Set the table properties -----------------------------------
            m_Table             = new HtmlTable();
            m_Table.Border      = 1;
            m_Table.CellPadding = 1;
            m_Table.CellSpacing = 0;
            m_Table.BorderColor = "#000000";
            m_Table.BgColor     = "#FFFFEE";
            m_Table.Width       = "160px";

            // Get Answers
            alAnswers           = pQ.alAnswers;

            // First Table Row for Question ------------------------------
            m_Row  = new HtmlTableRow();
            m_Cell = new HtmlTableCell();
            m_Cell.ColSpan   = 2;
            m_Cell.Align     = "center";
            m_Cell.InnerHtml = "<font size='1' face='arial'><b>"+pQ.Question+"</b></font>";
            m_Row.Cells.Add(m_Cell);
            m_Table.Rows.Add(m_Row);

            for (int i=0;i<pQ.NumberAnswers;i++)
            {
                pA				= (PollAnswer)alAnswers[i];
                m_Row           = new HtmlTableRow();

                // This cell shows the Answer
                m_Cell = new HtmlTableCell();
                m_Cell.InnerHtml = "<font size='1' face='arial'>"+pA.Answer+"</font>";
                m_Row.Cells.Add(m_Cell);

                // This cell shows the percentage results
                m_Cell = new HtmlTableCell();
                if (pQ.TotalAnswers>0) m_Cell.InnerHtml = String.Format("<font size='1' face='arial'>{0:f0}%</font>",(double)pA.Count/(double)pQ.TotalAnswers*100.0);
                 else                  m_Cell.InnerHtml = "<font size='1' face='arial'>0%</font>";
                m_Cell.Align="right";
                m_Row.Cells.Add(m_Cell);
                m_Table.Rows.Add(m_Row);
            }

            m_Row			= new HtmlTableRow();
            m_Cell			= new HtmlTableCell();
            m_Cell.ColSpan	= 2;
            m_Cell.Align    = "center";
            m_Label  	    = new Label();
            m_Label.Text   += string.Format("<font size='1' face='arial'>{0} Responses</font>",pQ.TotalAnswers);
            m_Cell.Controls.Add(m_Label);
            m_Row.Cells.Add(m_Cell);
            m_Table.Rows.Add(m_Row);

            Ph.Controls.Add(m_Table);  // Add the Poll Table
        }
示例#16
0
 internal static void DeletePollAnswer(PollAnswer answer)
 {
     ValidatePollAnswer(answer);
     PublicApi.PollAnswers.Events.OnBeforeDelete(answer);
     PollingDataService.DeletePollAnswer(answer.Id);
     ExpirePoll(answer.PollId);
     PublicApi.PollAnswers.Events.OnAfterDelete(answer);
 }
示例#17
0
            /// <summary>
            /// This function is called by public PollQuestion(int pId) 
            /// after it is successfull in retreiving the Question
            /// Retreives the Answers to the Poll and places them
            /// in an arraylist that is a private member of the class
            /// </summary>
            protected void GetAnswers(string cnStr)
            {
                string sql,Query;
                sql   = "SELECT * FROM aPollAnswers WHERE PollID={0} ";
                Query = String.Format(sql, m_Id);

                SqlConnection  m_Connection     = new SqlConnection(cnStr);
                SqlDataAdapter m_SqlDataAdapter = new SqlDataAdapter(Query,m_Connection);
                try
                {
                    DataSet Ds = new DataSet();
                    m_SqlDataAdapter.Fill(Ds,"Answers");
                    PollAnswer pA;
                    m_TotalAnswers = 0;
                    m_NuAnswers    = Ds.Tables["Answers"].Rows.Count;
                    // Place each answer in an array
                    for (int i=0;i<m_NuAnswers;i++)
                    {   pA			    = new PollAnswer();
                        pA.Id			= Convert.ToInt32(Ds.Tables["Answers"].Rows[i]["Id"].ToString());
                        pA.Count	    = Convert.ToInt32(Ds.Tables["Answers"].Rows[i]["AnswerCount"].ToString());
                        pA.Answer		= Ds.Tables["Answers"].Rows[i]["Answer"].ToString();
                        pA.PollId	    = m_Id;
                        m_TotalAnswers += pA.Count;
                        m_alAnswers.Add( pA );
                    }
                    m_Connection.Close();
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
示例#18
0
 public void AddPollAnswer(PollAnswer pollAnswer)
 {
     pollAnswer.AnswerDate = DateTime.Now;
     this.catalog.PollAnswers.AddPollAnswer(pollAnswer);
 }
示例#19
0
 public Task <int> AddAnswerAsync(PollAnswer pollAnswer)
 {
     return(_databaseRepository.GetAsync <int>(Functions.PollAnswerRepository.Add,
                                               DbParameterHelper.Create(nameof(pollAnswer.PollOptionId), pollAnswer.PollOptionId),
                                               DbParameterHelper.Create(nameof(pollAnswer.UserId), pollAnswer.UserId)));
 }