Example #1
0
        //ForumItems laden van de database voor reply op reply
        public ForumItem LoadForumItem(ForumItem replyOnForumItem)
        {
            try
            {
                List <INode> nodeList = new List <INode>();

                var r = ConnectDb("MATCH (p:ForumItem)-[]-(n:ForumItem) WHERE n.ForumItemId=" + replyOnForumItem.ForumItemId + " RETURN p");
                r.Wait();
                int forumItemId = Convert.ToInt32((Int64)r.Result[0].Properties["ForumItemId"]);

                var r2 = ConnectDb("MATCH (p:Person)-[Made]-(n:ForumItem) WHERE n.forumItemId=" + forumItemId + " RETURN p");
                r2.Wait();
                Person owner = new Person();
                nodeList = r2.Result;
                foreach (var record in nodeList)
                {
                    var nodeprops = JsonConvert.SerializeObject(record.As <INode>().Properties);
                    owner = (JsonConvert.DeserializeObject <Person>(nodeprops));
                }


                string content = (string)r.Result[0].Properties["Content"];



                return(new ForumItem(forumItemId, owner, content, replyOnForumItem));
            }
            catch (ArgumentOutOfRangeException)
            {
                return(null);
            }
        }
Example #2
0
        public ActionResult Update(ForumItemModel model)
        {
            ForumItem forumTarget = GetSession.Get <ForumItem>(Convert.ToInt64(Request.Form["Id"]));

            forumTarget.Admin  = GetSession.Get <Employee>(Convert.ToInt64(Request.Form["Admin"]));
            forumTarget.Title  = Request.Form["Title"];
            forumTarget.Active = (Request.Form["Active"] == "on") ? true : false;

            GetSession.Update(forumTarget);


            #region ADO.NET
            //string theTitle = Request.Form["Title"];
            //long theAdmin = Convert.ToInt32(Request.Form["Admin"]);
            //long theId = Convert.ToInt32(Request.Form["Id"]);
            //bool theActive = (Request.Form["Active"] == "on") ? true : false;
            //SqlConnection sqlConnection1 = new SqlConnection(cs);
            //SqlCommand cmd = new SqlCommand();
            //Int32 rowsAffected;
            //cmd.CommandText = "UPDATE portal_ForumItem SET Title = '" + theTitle + "', Admin_id = " + theAdmin + ", Active = '" + theActive + "' WHERE Id = " + theId + "";
            ////cmd.CommandText = "UPDATE portal_ForumItem SET Title = '" + theTitle + "', Admin_id = " + theAdmin + ", Active = '" + theActive + "' WHERE Id = "+theId+"";
            //cmd.CommandType = CommandType.Text;
            //cmd.Connection = sqlConnection1;
            //sqlConnection1.Open();
            //rowsAffected = cmd.ExecuteNonQuery();
            //sqlConnection1.Close();

            #endregion

            return(Redirect("/ForumItems/"));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            btnSearch.Text = DictionaryConstants.GoButtonText;
            txtSearch.Attributes.Add("placeholder", DictionaryConstants.Community_EnterConversation);

            if (!IsPostBack)
            {
                ResultCount = 10;
                Item currItem = Sitecore.Context.Item;
                if (currItem != null)
                {
                    hrfBack.HRef = LinkManager.GetItemUrl(currItem.Parent);
                    litBack.Text = currItem.Parent.Name;
                    ForumItem frmItem = new ForumItem(currItem);
                    Session["forumItem"] = frmItem;
                    if (frmItem != null)
                    {
                        ForumModel frmModel = Forum.ForumModelFactory(frmItem);

                        litForumName.Text = frmModel.Name;
                        if (frmModel != null)
                        {
                            Session["_threads"]  = frmModel.Threads;
                            rptThread.DataSource = frmModel.Threads.Take(ResultSet);
                            rptThread.DataBind();
                        }
                    }
                }
            }
        }
Example #4
0
            private async Task <PagedForumItem> GetQuestions(ForumItem forum, Contract request, CancellationToken cancellationToken)
            {
                var options = new FindOptions <ForumQuestionItem>()
                {
                    Limit = request.PageSize,
                    Skip  = (request.Page - 1) * request.PageSize
                };

                FilterDefinition <ForumQuestionItem> filters = SetFilters(request);
                var collection = _db.Database.GetCollection <ForumQuestionItem>("EventForumQuestions");

                var query = await collection.FindAsync(filters,
                                                       options : options,
                                                       cancellationToken : cancellationToken
                                                       );

                var queryLast = await collection.FindAsync(filters,
                                                           options : new FindOptions <ForumQuestionItem>(),
                                                           cancellationToken : cancellationToken
                                                           );

                var questions = await query.ToListAsync(cancellationToken);

                foreach (var question in questions)
                {
                    question.Liked   = question.LikedBy.Any(uId => uId == request.UserId);
                    question.Answers = await(await _db.Database
                                             .GetCollection <EventForumAnswer>("EventForumAnswers")
                                             .FindAsync(x => x.QuestionId == question.Id))
                                       .ToListAsync();
                }

                var lastQuestions = await queryLast.ToListAsync(cancellationToken);

                foreach (var lastQuestion in lastQuestions)
                {
                    lastQuestion.Liked   = lastQuestion.LikedBy.Any(uId => uId == request.UserId);
                    lastQuestion.Answers = await(await _db.Database
                                                 .GetCollection <EventForumAnswer>("EventForumAnswers")
                                                 .FindAsync(x => x.QuestionId == lastQuestion.Id))
                                           .ToListAsync();
                }

                lastQuestions = lastQuestions.OrderByDescending(x => x.CreatedAt).Take(4).ToList();

                return(new PagedForumItem()
                {
                    EventId = forum.EventId.ToString(),
                    EventScheduleId = forum.EventScheduleId.ToString(),
                    EventName = forum.EventName,
                    IsInstructor = await CheckEventInstructor(
                        ObjectId.Parse(request.EventScheduleId),
                        ObjectId.Parse(request.UserId),
                        cancellationToken
                        ),
                    ItemsCount = await collection.CountDocumentsAsync(filters),
                    Questions = questions,
                    LastQuestions = lastQuestions
                });
            }
Example #5
0
 public static bool IsItemEditable(this User user, ForumItem item)
 {
     if (user == null)
     {
         return(false);
     }
     return(user.Id == item.OwnerId);
 }
 public ForumModel(ForumItem forumItem, Func <string, List <ThreadModel> > readThreads)
 {
     ForumID        = forumItem.ForumID.Text;
     GroupID        = forumItem.GroupID.Text;
     Description    = forumItem.Description.Text;
     Name           = forumItem.InnerItem.Name;
     readThreadFunc = readThreads;
 }
Example #7
0
        public ActionResult ForumAllowAllUpdate(long id, bool isAvailableTooAll)
        {
            ForumItem forumTarget = GetSession.Get <ForumItem>(id);

            forumTarget.isAvailableTooAll = isAvailableTooAll;

            GetSession.Save(forumTarget);
            return(Redirect("/ForumItems/"));
        }
Example #8
0
        public ActionResult UpdateTitle(long id, string newTitle)
        {
            ForumItem forumTarget = GetSession.Get <ForumItem>(id);

            forumTarget.Title = newTitle;

            GetSession.Save(forumTarget);
            return(Redirect("/ForumItems/"));
        }
Example #9
0
        public ActionResult ForumActiveUpdate(long id, bool isActive)
        {
            ForumItem forumTarget = GetSession.Get <ForumItem>(id);

            forumTarget.Active = isActive;

            GetSession.Save(forumTarget);
            return(Redirect("/ForumItems/"));
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            rqdDropDownFName.Enabled = String.IsNullOrEmpty(txtFName.Text);
            txtFName.Text            = HiddenText;
            if (!IsPostBack)
            {
                ddlForums.Items.Add(new ListItem()
                {
                    Value = "0", Text = InitialDropDownText
                });
                txtFName.Attributes.Add("placeholder", InitialTextBoxText);
                ddlForums.ValidationGroup        = validation_group;
                txtFName.ValidationGroup         = validation_group;
                btnSubmit.ValidationGroup        = validation_group;
                rqdDropDownFName.ValidationGroup = validation_group;
                rqdDiscussion.ValidationGroup    = validation_group;

                rqdSubject.ValidationGroup = validation_group;


                //Are we on a forum or Group??
                Item currItem = Sitecore.Context.Item;



                if (currItem.TemplateID.ToString().Equals(GroupItem.TemplateId))
                {
                    GroupItem grpItem = new GroupItem(currItem);
                    Session["_item"] = grpItem;
                    GroupCardModel    grpModel = Groups.GroupCardModelFactory(grpItem);
                    List <ForumModel> frms     = currItem.Children.Select(x => Forum.ForumModelFactory(new ForumItem(x))).ToList <ForumModel>();
                    if (grpModel != null)
                    {
                        ddlForums.DataSource = frms;
                        ddlForums.DataBind();
                    }
                }
                else
                {
                    if (currItem.TemplateID.ToString().Equals(ForumItem.TemplateId))
                    {
                        ForumItem frmItem = new ForumItem(currItem);
                        Session["_item"] = frmItem;
                        //Disable forum selection and select
                        ddlForums.Enabled = false;
                        ddlForums.Visible = false;

                        txtFName.Visible = true;
                        txtFName.Text    = frmItem.DisplayName;
                        txtFName.Enabled = false;
                    }
                }
            }
        }
Example #11
0
        public JavaScriptResult UpdateAdmin(long forumId, long adminId)
        {
            ForumItem forumTarget = GetSession.Get <ForumItem>(forumId);

            Employee temp = GetSession.Get <Employee>(adminId);

            forumTarget.Admin = temp;

            GetSession.Save(forumTarget);
            string js = @"alert('מנהל פורום עודכן בהצלחה!')";

            return(JavaScript(js));
        }
Example #12
0
        public IActionResult Forum(string Content, string fid, string del)
        {
            int ForumId = Convert.ToInt32(fid);

            try
            {
                if (del != null)
                {
                    DeleteForumItem(Convert.ToInt32(del));
                }
                ForumId = Convert.ToInt32(HttpContext.Request.Query["id"].ToString());
            }
            catch (System.FormatException)
            {
            }
            if (ForumId != 0)
            {
                CurrentForum = LoadForum(ForumId);
            }
            if (ViewBag.Forum != null)
            {
                CurrentForum = ViewBag.forum;
            }
            if ((Forum)TempData["Forum"] != null)
            {
                CurrentForum = (Forum)TempData["Forum"];
            }
            Person u = new PersonController().GetPerson(1);

            List <ForumItem> ItemList = GetAllReplies(CurrentForum);

            if (Content != null)
            {
                Response.Redirect("Forum?id=" + ForumId);
                if (ItemList.Count == 0)
                {
                    ForumItem forumItem = new ForumItem(GetNewForumItemId(), u, Content, CurrentForum);
                    SaveForumItem(forumItem);
                }
                else
                {
                    ForumItem forumItem = new ForumItem(GetNewForumItemId(), u, Content, ItemList[ItemList.Count - 1]);
                    SaveForumItem(forumItem);
                }
            }


            ViewBag.Forum = CurrentForum;

            return(View());
        }
Example #13
0
        public ActionResult Create(ForumItemModel model)
        {
            var  results = Request.Form["ForumUsers[]"];
            long adminId;

            if (!string.IsNullOrEmpty(Request.Form["Admin"]))
            {
                adminId = Convert.ToInt64(Request.Form["Admin"]);
            }
            else
            {
                adminId = GetEmployeeId;
            }

            ForumItem newForum = new ForumItem()
            {
                Title      = !string.IsNullOrEmpty(Request.Form["Title"]) ? Request.Form["Title"] : " פורום חדש",
                Active     = (Request.Form["Active"] == "on") ? true : false,
                ForumUsers = Request.Form["ForumUsers[]"],



                Admin = GetSession.Get <Employee>(adminId)
            };

            GetSession.Save(newForum);
            #region ado.net



            //string theTitle = Request.Form["Title"];
            //long theAdmin = Convert.ToInt32(Request.Form["Admin"]);
            //bool theActive = (Request.Form["Active"] == "on") ? true : false;
            //SqlConnection sqlConnection1 = new SqlConnection(cs);
            //SqlCommand cmd = new SqlCommand();
            //Int32 rowsAffected;
            //cmd.CommandText = "INSERT into portal_ForumItem(Title,Active,Admin_id,ForumUsers) values ('" + theTitle + "', '" + theActive + "', " + theAdmin + ", '" + results + "')";
            //cmd.CommandType = CommandType.Text;
            //cmd.Connection = sqlConnection1;
            //sqlConnection1.Open();
            //rowsAffected = cmd.ExecuteNonQuery();
            //sqlConnection1.Close();
            #endregion
            return(Redirect("/ForumItems/"));
        }
Example #14
0
        private S1ListItem BuildGroup(ForumItem g, ForumItem[] forumItem)
        {
            var group = new S1ListItem {Title = S1Resource.HttpUtility.HtmlDecode(g.Name)};
            var forums =
                from f in forumItem
                where f.Fup == g.Fid && !string.IsNullOrEmpty(f.Name)
                select new S1ListItem(S1Resource.HttpUtility.HtmlDecode(f.Name), f.Fid,
                    (from sub in forumItem
                        where sub.Fup == f.Fid && !string.IsNullOrEmpty(sub.Name)
                        select new S1ListItem
                        {
                            Title = S1Resource.HttpUtility.HtmlDecode(sub.Name),
                            Id = sub.Fid
                        }));

            group.AddRange(forums);
            return group;
        }
Example #15
0
        private S1ListItem BuildGroup(ForumItem g, ForumItem[] forumItem)
        {
            var group = new S1ListItem {
                Title = S1Resource.HttpUtility.HtmlDecode(g.Name)
            };
            var forums =
                from f in forumItem
                where f.Fup == g.Fid && !string.IsNullOrEmpty(f.Name)
                select new S1ListItem(S1Resource.HttpUtility.HtmlDecode(f.Name), f.Fid,
                                      (from sub in forumItem
                                       where sub.Fup == f.Fid && !string.IsNullOrEmpty(sub.Name)
                                       select new S1ListItem
            {
                Title = S1Resource.HttpUtility.HtmlDecode(sub.Name),
                Id = sub.Fid
            }));

            group.AddRange(forums);
            return(group);
        }
Example #16
0
        //ForumItems saven naar de database
        public void SaveForumItem(ForumItem forumItem)
        {
            var r = ConnectDb("CREATE (F:ForumItem {ForumItemId: " + forumItem.ForumItemId + ",Content: '" + forumItem.Content + "'}) RETURN F");

            r.Wait();
            var r2 = ConnectDb("MATCH (p:Person),(f:ForumItem) WHERE p.PersonId = " + forumItem.Owner.PersonId + " AND f.ForumItemId = " + forumItem.ForumItemId + " CREATE(p) -[r: Made]->(f) RETURN p, f");

            r2.Wait();

            if (forumItem.ReplyOnForum == null)
            {
                var r3 = ConnectDb("MATCH (p:ForumItem),(f:ForumItem) WHERE p.ForumItemId = " + forumItem.ForumItemId + " AND f.ForumItemId = " + forumItem.ReplyOnForumItem.ForumItemId + " CREATE(p) -[r: RepliedOnForumItem]->(f) RETURN p, f");
                r3.Wait();
            }
            else
            {
                var r3 = ConnectDb("MATCH (p:ForumItem),(f:Forum) WHERE p.ForumItemId = " + forumItem.ForumItemId + " AND f.ForumId = " + forumItem.ReplyOnForum.ForumId + " CREATE(p) -[r: RelpiedOnForum]->(f) RETURN p, f");
                r3.Wait();
            }
        }
Example #17
0
        public JavaScriptResult UpdateUsers(ForumItemModel model, string[] users, long id)
        {
            string result = "";

            if (users != null)
            {
                if (users.Length > 0)
                {
                    result = string.Join(",", users);
                    //return Redirect("/ForumItems/");
                }
            }



            ForumItem forumTarget = GetSession.Get <ForumItem>(id);

            forumTarget.ForumUsers = result;

            GetSession.Save(forumTarget);

            #region ado.net
            //string theTitle = Request.Form["Title"];
            //long theAdmin = Convert.ToInt32(Request.Form["Admin"]);
            //long theId = Convert.ToInt32(Request.Form["Id"]);
            //bool theActive = (Request.Form["Active"] == "on") ? true : false;
            //SqlConnection sqlConnection1 = new SqlConnection(cs);
            //SqlCommand cmd = new SqlCommand();
            //Int32 rowsAffected;
            //cmd.CommandText = "UPDATE portal_ForumItem SET Title = '" + theTitle + "', Admin_id = " + theAdmin + ", Active = '" + theActive + "', ForumUsers = '" + result + "' WHERE Id = " + theId + "";
            ////cmd.CommandText = "UPDATE portal_ForumItem SET Title = '" + theTitle + "', Admin_id = " + theAdmin + ", Active = '" + theActive + "' WHERE Id = "+theId+"";
            //cmd.CommandType = CommandType.Text;
            //cmd.Connection = sqlConnection1;
            //sqlConnection1.Open();
            //rowsAffected = cmd.ExecuteNonQuery();
            //sqlConnection1.Close();
            #endregion
            //return RedirectToAction("index");
            string js = @"alert('עודכן בהצלחה')";
            return(JavaScript(js));
        }
Example #18
0
        public static ForumModel ForumModelFactory(ForumItem item)
        {
            ForumModel frm = new ForumModel(item, TelligentService.TelligentService.ReadThreadList);

            return(frm);
        }
Example #19
0
        private List <ForumItem> GetForumData()
        {
            string key  = "mn_forum_cache";
            var    data = new List <ForumItem>();

            if (!SiteConfig.Cache.TryGetValue(key, out data))
            {
                var _list = CategoryBLL.LoadItems(_context, new CategoryEntity()
                {
                    type     = (int)CategoryBLL.Types.Forum,
                    ispublic = true,
                    iscache  = false,
                    order    = "title asc",
                    pagesize = 50
                }).Result;
                var _Data = new List <ForumItem>();
                if (_list.Count > 0)
                {
                    foreach (var Item in _list)
                    {
                        var _data = new ForumItem()
                        {
                            Type      = 12,
                            Title     = Item.title,
                            Term      = Item.term,
                            ForumList = ForumBLLC.LoadItems(_context, new ForumEntity()
                            {
                                order        = "priority desc",
                                categoryname = Item.term,
                                //categories_str = Item.term,
                                iscache = false
                            }).Result
                        };
                        // attach last post id
                        foreach (var Itm in _data.ForumList)
                        {
                            Itm.lastpost = new List <JGN_ForumTopics>();
                            if (Itm.lastpostid != null && Itm.lastpostid > 0)
                            {
                                Itm.lastpost = ForumTopicBLL.Load_Last_Post(_context, (long)Itm.lastpostid);
                            }
                        }
                        _Data.Add(_data);
                    }
                }

                var cacheEntryOptions = new MemoryCacheEntryOptions()
                                        // Keep in cache for this time, reset time if accessed.
                                        .SetSlidingExpiration(TimeSpan.FromSeconds(3600));

                data = _Data;
                // Save data in cache.
                SiteConfig.Cache.Set(key, _Data, cacheEntryOptions);
            }
            else
            {
                data = (List <ForumItem>)SiteConfig.Cache.Get(key);
            }

            return(data);
        }
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            //Client side validation passed
            if (CurrentMember != null && !String.IsNullOrEmpty(CurrentMember.ScreenName))
            {
                //Grab information from fields
                string subject   = txtSubject.Text;
                string body      = txtBody.Text;
                string frmItemID = String.Empty;
                try
                {
                    GroupItem grpItem = Session["_item"] as GroupItem;
                    ForumItem frmItem = Session["_item"] as ForumItem;
                    if (grpItem != null)
                    {
                        ///Go through selection process
                        if (!ddlForums.SelectedValue.Equals("0")) //If forum was selected
                        {
                            frmItemID = ddlForums.SelectedIndex > -1 ? ddlForums.SelectedValue : String.Empty;
                        }
                        else if (!String.IsNullOrEmpty(txtFName.Text)) //If a name was input
                        {
                            frmItemID = new ForumItem(Forum.ConvertForumNametoSitecoreItem(txtFName.Text)).ForumID;
                            //Create forum and return ForumID
                            //    ForumModel frmModel = TelligentService.CreateForum(CurrentMember.ScreenName, grpItem.GroupID.Text, txtFName.Text);
                            //    if (frmModel != null)
                            //    {
                            //        Item frmItemLocal = Forum.CreateSitecoreForum(frmModel, grpItem, Sitecore.Context.Language);
                            //        if (frmItemLocal != null)
                            //        {
                            //            //Success
                            //            frmItemID = frmModel.ForumID;
                            //            //Publish sitecore item
                            //            PublishItem(frmItemLocal);
                            //        }
                            //        else
                            //        {
                            //            //Delete Telligent Forum
                            //            TelligentService.DeleteForum(frmModel.ForumID);
                            //            var msg = "Error creating forum item in sitecore";
                            //            Sitecore.Diagnostics.Error.LogError(msg);
                            //            error_msg.Text = msg;
                            //            error_msg.Visible = true;
                            //            ShowClientSideForm();
                            //            return;
                            //        }
                            //    }
                            //    else
                            //    {
                            //        var msg = "Error creating forum item in Telligent.";
                            //        Sitecore.Diagnostics.Error.LogError(msg);
                            //        error_msg.Text = msg;
                            //        error_msg.Visible = true;
                            //        ShowClientSideForm();
                            //        return;
                            //    }
                        }
                        else
                        {
                            var msg = DictionaryConstants.ErrorSelectingForumMessage;
                            Sitecore.Diagnostics.Error.LogError(msg);
                            error_msg.Text    = msg;
                            error_msg.Visible = true;
                            ShowClientSideForm(HiddenText);
                            return;
                        }
                    }
                    if (frmItem != null)
                    {
                        frmItemID  = frmItem.ForumID.Text;
                        HiddenText = frmItem.DisplayName;
                    }

                    Item threadItem = null;
                    if (!String.IsNullOrEmpty(frmItemID))
                    {
                        try
                        {
                            //Create item in Telligent
                            ThreadModel thModel = TelligentService.CreateForumThread(CurrentMember.ScreenName, frmItemID, subject, body);
                            if (thModel != null)
                            {
                                //Create item in sitecore with returned forumID and threadID
                                threadItem = Discussion.CreateSitecoreForumThread(thModel, frmItemID, Sitecore.Context.Language);
                                if (threadItem != null)
                                {
                                    error_msg.Visible = false;

                                    //Redirect to discussion
                                    //Publish thread item
                                    PublishItem(threadItem);
                                    //Sitecore.Web.WebUtil.Redirect(Sitecore.Links.LinkManager.GetItemUrl(threadItem));
                                    ///  clientsideScript("alert('" +String.Format( DictionaryConstants.ForumCreateConfirmation,subject)+"');");
                                    Page.Response.Redirect(Page.Request.Url.ToString(), false);
                                }
                                else
                                {
                                    //Delete from Telligent
                                    TelligentService.DeleteForumThread(frmItemID, thModel.ThreadID);
                                    error_msg.Text    = DictionaryConstants.FailedToCreateDiscussionError;
                                    error_msg.Visible = true;
                                    ShowClientSideForm(HiddenText);
                                }
                            }
                            else
                            {
                                //The assumption is that if the Thread is null, then there was an error in telligent API call and nothing was created
                                error_msg.Text    = DictionaryConstants.FailedToCreateDiscussionError;
                                error_msg.Visible = true;
                                ShowClientSideForm(HiddenText);
                            }
                        }
                        catch (Exception ex)
                        {
                            Sitecore.Diagnostics.Error.LogError(ex.Message);
                            error_msg.Text    = DictionaryConstants.FailedToCreateDiscussionError;
                            error_msg.Visible = true;
                            ShowClientSideForm(HiddenText);
                        }
                    }
                }
                catch (Exception ex)
                {
                    Sitecore.Diagnostics.Error.LogError("Error creating forum item in btnSubmit_Click.\nError:\n " + ex.Message);
                    error_msg.Text    = DictionaryConstants.DiscussionCriticalErrorMessage;
                    error_msg.Visible = true;
                    ShowClientSideForm(HiddenText);
                }
            }
            else
            {
                error_msg.Text    = "You are not logged on.";
                error_msg.Visible = true;
                ShowClientSideForm(HiddenText);
            }
        }
Example #21
0
        public void AddNewFormItem()
        {
            ForumItem item = new ForumItem();
            item.Title = txtTitle.Text;
            int x;
            int.TryParse(hiddenItemId.Value.ToString(), out x);
            item.PerentIdSpecified = true;
            item.PerentId = x;
            item.CourseIdSpecified = true;
            item.Content = taContent.Text.Replace("\r\n","<br>");
            item.OwnerIdSpecified = true;
            item.OwnerId = UserID;
            item.CourseId = CurrentCourse;

            if (CourseMatesWS.AddNewForumItem(SessionID, UserID, item))
            {
                txtTitle.Text = "";
                taContent.Text = "";
                winNewComment.Hide();
                LoadForum();
            }
            else
            {
                ShowMessage("Add Comment", "Failed", MessageBox.Icon.ERROR, MessageBox.Button.OK);
            }
        }
Example #22
0
        public static Item CreateSitecoreForumThread(ThreadModel thModel, ForumItem frmItem, Language lang)
        {
            Item newItem = null;

            try
            {
                if (thModel != null && frmItem != null && lang != null)
                {
                    //Again we need to handle security
                    //In this example we just disable it
                    using (new SecurityDisabler())
                    {
                        //First get the parent item from the master database
                        Database masterDb   = global:: Sitecore.Configuration.Factory.GetDatabase("master");
                        Item     parentItem = masterDb.Items[frmItem.InnerItem.Paths.Path, lang];


                        //Now we need to get the template from which the item is created (Forum Thread Template)
                        TemplateItem template = masterDb.GetTemplate(ThreadModel.TemplateID);

                        //StringBuilder sb = new StringBuilder(ItemName.Trim());

                        // string newName = ItemName.Replace('.', '_');//.Substring(0, ItemName.LastIndexOf("."));
                        // if(newName.Contains("."))
                        //     newName=newName.Substring(newName.IndexOf(".") + 1);

                        newItem = masterDb.GetItem(parentItem.Paths.Path + "/" + thModel.Subject, lang);
                        if (newItem == null)
                        {
                            //Now we can add the new item as a child to the parent
                            newItem = parentItem.Add(thModel.Subject, template);
                        }


                        //We can now manipulate the fields and publish as in the previous example
                        //Item item = masterDb.GetItem(newItem);
                        //Begin editing
                        newItem.Editing.BeginEdit();
                        try
                        {
                            //perform the editing
                            newItem.Fields["ForumID"].Value  = thModel.ForumID;
                            newItem.Fields["ThreadID"].Value = thModel.ThreadID;
                            newItem.Fields["Body"].Value     = thModel.Body;
                            newItem.Fields["Subject"].Value  = thModel.Subject;
                            // errorState = true;
                        }
                        catch (Exception ex)
                        {
                            // errorState = false;
                            throw ex;
                        }
                        finally
                        {
                            //Close the editing state
                            newItem.Editing.EndEdit();
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //Elmah.ErrorSignal.FromCurrentContext().Raise(new Exception("Error with :" + ItemName + " (" + lang.Name + ")\n Details:\n" + ex.Message));
                Sitecore.Diagnostics.Error.LogError("Error with :" + thModel.Subject + " (" + lang.Name + ")\n Details:\n" + ex.Message);
                newItem = null;
            }

            return(newItem);
        }
Example #23
0
        private void ZkDataContextOnAfterEntityChange(object sender, ZkDataContext.EntityEntry entityEntry)
        {
            if (entityEntry.State == EntityState.Deleted || entityEntry.State == EntityState.Unchanged)
            {
                return;
            }

            var entity = entityEntry.Entity;

            if (entity is ForumPost && entityEntry.State == EntityState.Added)
            {
                // forum post got added, distribute to connected users
                var post            = (ForumPost)entity;
                var changedThreadID = post.ForumThreadID;

                using (var db = new ZkDataContext())
                {
                    var t = db.ForumThreads.Find(changedThreadID);
                    if (t != null)
                    {
                        var item = new ForumItem()
                        {
                            Time   = t.LastPost ?? t.Created,
                            Url    = $"{GlobalConst.BaseSiteUrl}/Forum/Thread/{t.ForumThreadID}",
                            Header = t.Title,
                            IsRead = false
                        };

                        foreach (var user in server.ConnectedUsers.Values.Where(x => x != null && x.IsLoggedIn))
                        {
                            var list     = GetCurrentForumList(user.User.AccountID);
                            var existing = list.ForumItems.FirstOrDefault(x => x.Url == item.Url);
                            if (existing != null)
                            {
                                existing.Header = item.Header;
                                existing.IsRead = post.AuthorAccountID == user.User.AccountID;
                                existing.Time   = item.Time;
                            }
                            else
                            {
                                list.ForumItems.Add(item);
                            }

                            list.ForumItems = list.ForumItems.OrderByDescending(x => x.Time).ToList();

                            user.SendCommand(list);
                        }
                    }
                }
            }
            else if (entity is ForumThreadLastRead)
            {
                // someone read some thread
                var changedAccountID = ((ForumThreadLastRead)entity).AccountID;
                var readThreadID     = ((ForumThreadLastRead)entity).ForumThreadID;


                var conus = server.ConnectedUsers.Values.FirstOrDefault(x => x != null && x.User.AccountID == changedAccountID && x.IsLoggedIn);
                if (conus != null)
                {
                    var list = GetCurrentForumList(changedAccountID);

                    if (list.ForumItems.Any(x => x.ThreadID == readThreadID)) // the thread is in top 10, update list
                    {
                        list = CachePrivateForumList(changedAccountID);
                        conus.SendCommand(list);
                    }
                }
            }
            else if (entity is ForumThread)
            {
                var thread = (ForumThread)entity;
                if (entityEntry.State == EntityState.Added) // thread added force refresh
                {
                    CachePublicForumList();
                }
                else
                {
                    var existing = cachedPublicForumList.ForumItems.FirstOrDefault(x => x.ThreadID == thread.ForumThreadID);
                    if (existing != null) // top 10 thread modified
                    {
                        if (existing.Time < thread.LastPost)
                        {
                            CachePublicForumList();                                  // it gotten a new post, update
                        }
                    }
                    else
                    {
                        if (thread.LastPost >= cachedPublicForumList.ForumItems.Min(x => (DateTime?)x.Time))
                        {
                            CachePublicForumList();                                                                                // its a modified post and its date belongs to top 10, update
                        }
                    }
                }
            }
        }