/// <summary>
        ///
        /// </summary>
        /// <param name="sectionId"></param>
        /// <param name="termId"></param>
        public CommentReviewPDF(int sectionId, int termId) : base()
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                studentParagraphs = new List <SmallComment>();
                Section section = db.Sections.Where(sec => sec.id == sectionId).Single();
                className = String.Format("[{0}] {1}", section.Block.LongName, section.Course.Name);
                if (section.CommentHeaders.Where(h => h.TermIndex == termId).Count() > 0)
                {
                    CommentHeader header = section.CommentHeaders.Where(h => h.TermIndex == termId).Single();
                    headerHTML = CommentLetter.CleanTags(header.HTML);
                    foreach (StudentComment comment in header.StudentComments)
                    {
                        SmallComment smc = new SmallComment()
                        {
                            studentName = String.Format("{0} {1}", comment.Student.FirstName, comment.Student.LastName),
                            html        = CommentLetter.CleanTags(comment.HTML),
                            finalGrade  = comment.FinalGrade.Name,
                            effortGrade = comment.EffortGrade.Name,
                            termGrade   = comment.TermGrade.Name,
                            examGrade   = comment.ExamGrade.Name
                        };

                        studentParagraphs.Add(smc);
                    }
                }
                else
                {
                    throw new CommentException(String.Format("No Header Paragraph for {0}", className));
                }
            }
        }
        public static CSV BySection(int termid)
        {
            CSV csv = new CSV();

            using (WebhostEntities db = new WebhostEntities())
            {
                Term term = db.Terms.Where(t => t.id == termid).Single();
                foreach (Section section in term.Sections.Where(sec => sec.CommentHeaders.Where(h => h.TermIndex == termid).Count() > 0).ToList())
                {
                    CommentHeader   header = section.CommentHeaders.Where(c => c.TermIndex == termid).Single();
                    ClassGradeStats stats  = new ClassGradeStats(header.id);

                    Dictionary <String, String> row = new Dictionary <string, string>()
                    {
                        { "Class", String.Format("[{0}-Block] {1}", section.Block.Name, section.Course.Name) },
                        { "Median", Convert.ToString(stats.Median) },
                        { "Average", Convert.ToString(stats.Average) },
                        { "Max", Convert.ToString(stats.Max) },
                        { "Min", Convert.ToString(stats.Min) },
                        { "Count", Convert.ToString(stats.Count) }
                    };

                    for (int i = 0; i < section.Teachers.Count; i++)
                    {
                        row.Add(String.Format("Teacher{0}", i == 0 ? "" : (" " + i)), String.Format("{0} {1}", section.Teachers.ToList()[i].FirstName, section.Teachers.ToList()[i].LastName));
                    }

                    csv.Add(row);
                }
            }
            return(csv);
        }
Beispiel #3
0
        public static String PublishClass(int headerId, String SaveDir = "")
        {
            List <int>    commentIds   = new List <int>();
            List <String> fileNames    = new List <string>();
            String        packFileName = "";

            using (WebhostEntities db = new WebhostEntities())
            {
                CommentHeader header = db.CommentHeaders.Find(headerId);
                packFileName = String.Format("{0} {1} comments", header.Section.Block.LongName, header.Section.Course.Name).ToLower();
                WebhostEventLog.CommentLog.LogInformation("Publishing {0}", packFileName);
                packFileName = packFileName.Replace(" ", "_");
                packFileName = packFileName.Replace("\"", "");
                Regex disalowedChars = new Regex(@"(\.|:|&|#|@|\*|~|\?|<|>|\||\^|( ( )+)|/)");
                foreach (Match match in disalowedChars.Matches(packFileName))
                {
                    packFileName = packFileName.Replace(match.Value, "");
                }

                foreach (int id in header.StudentComments.Select(c => c.id))
                {
                    fileNames.Add((new CommentLetter(id)).Publish(SaveDir));
                }
            }

            if (SaveDir.Equals(""))
            {
                return(MailControler.PackForDownloading(fileNames, packFileName, HttpContext.Current.Server));
            }
            else
            {
                return(MailControler.PackForDownloading(fileNames, String.Format("{0}\\{1}.zip", SaveDir, packFileName)));
            }
        }
        public IHttpActionResult PutUpdatedCommentHeader(int section_id, int term_id, [FromBody] String content)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                int header = -1;
                try
                {
                    header = db.CommentHeaders.Where(h => h.SectionIndex == section_id && h.TermIndex == term_id).Single().id;
                }
                catch (Exception e)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e)));
                }

                CommentHeader headerParagraph = db.CommentHeaders.Find(header);

                content = CommentLetter.ConvertFromBase64String(content);

                headerParagraph.HTML = CommentLetter.CleanTags(content);

                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, e)));
                }

                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new CommentHeaderInfo(header))));
            }
        }
        /// <summary>
        /// Request a set of classes be published in bulk.
        /// </summary>
        /// <param name="user">requesting user</param>
        /// <param name="SectionIds">List of Section.id's</param>
        /// <param name="filename">file name given by the Server.MapPath() method.</param>
        /// <param name="TermId">default to the current term</param>
        public static void RequestByClass(ADUser user, List <int> SectionIds, String filename, int TermId = -1)
        {
            WebhostEventLog.Syslog.LogInformation("{0} has requested Comment Letters for {1} sections", user.Name, SectionIds.Count);
            if (TermId == -1)
            {
                TermId = DateRange.GetCurrentOrLastTerm();
            }

            LogEntry log = new LogEntry();

            XMLTree xml = new XMLTree()
            {
                TagName    = "publishrequest",
                Attributes = new Dictionary <string, string>()
                {
                    { "username", user.UserName },
                    { "name", XMLTree.MakeXMLAttributeValueSafe(user.Name) },
                    { "id", user.ID.ToString() },
                    { "type", "class" },
                    { "termid", TermId.ToString() },
                    { "timestamp", DateTime.Now.Ticks.ToString() }
                }
            };

            using (WebhostEntities db = new WebhostEntities())
            {
                foreach (int sectionId in SectionIds)
                {
                    Section section = db.Sections.Where(sec => sec.id == sectionId).Single();
                    if (section.CommentHeaders.Where(c => c.TermIndex == TermId).Count() != 1)
                    {
                        throw new WebhostException(String.Format("No comment header for Term id={0} of {1} ({2})", TermId, section.Course.Name, sectionId));
                    }

                    CommentHeader header = section.CommentHeaders.Where(c => c.TermIndex == TermId).Single();

                    XMLTree sectionTree = new XMLTree()
                    {
                        TagName    = "section",
                        Attributes = new Dictionary <string, string>()
                        {
                            { "headerid", header.id.ToString() }
                        }
                    };

                    foreach (int comid in header.StudentComments.Select(c => c.id).ToList())
                    {
                        sectionTree.ChildNodes.Add(new SimpleXMLTag()
                        {
                            TagName = "comment",
                            Value   = comid.ToString()
                        });
                    }

                    xml.ChildTrees.Add(sectionTree);
                }
            }

            xml.Save(filename + ".pubreq");
        }
Beispiel #6
0
        public IHttpActionResult CreateNewCommentHeader(int section_id, [FromBody] String content)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                Section section = db.Sections.Find(section_id);
                if (section == null)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Invalid Section Id."))));
                }

                WebhostUserPrinciple principal = (WebhostUserPrinciple)ActionContext.RequestContext.Principal;
                int id = ((WebhostIdentity)principal.Identity).User.Id;

                Faculty self = db.Faculties.Find(id);

                if (!self.Sections.Contains(section))
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new UnauthorizedAccessException("You are not a teacher for this class."))));
                }

                int termId = DateRange.GetCurrentOrLastTerm();

                if (section.CommentHeaders.Where(h => h.TermIndex == termId).Count() > 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Header Already Exists.  Use PUT to Update."))));
                }

                CommentHeader newHeader = new CommentHeader()
                {
                    id           = db.CommentHeaders.OrderBy(h => h.id).ToList().Last().id + 1,
                    SectionIndex = section_id,
                    TermIndex    = termId,
                    HTML         = ""
                };

                content = CommentLetter.ConvertFromBase64String(content);

                newHeader.HTML = CommentLetter.CleanTags(content);

                try
                {
                    db.CommentHeaders.Add(newHeader);
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, e)));
                }

                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.Created, new CommentHeaderInfo(newHeader.id), "text/json")));
            }
        }
            public ClassGradeStats(int chid)
            {
                this.commentHeaderId = chid;
                using (WebhostEntities db = new WebhostEntities())
                {
                    CommentHeader header = db.CommentHeaders.Where(h => h.id == chid).Single();
                    List <int>    grlst  = new List <int>();
                    foreach (StudentComment comment in header.StudentComments)
                    {
                        grlst.Add(comment.FinalGrade.Value);
                    }

                    this.grades = grlst;
                    grlst.Sort();
                }
            }
Beispiel #8
0
        /// <summary>
        /// Task for adding a comment
        /// </summary>
        /// <param name="model">The comment to add</param>
        /// <returns>Task for adding a comment</returns>
        public async Task AddCommentAsync(CommentAddModel model)
        {
            CommentHeader header = new CommentHeader
            {
                UserId           = model.UserId,
                CommentRevisions = new CommentRevision[]
                {
                    new CommentRevision
                    {
                        CreatedDate = DateTime.UtcNow,
                        Text        = model.Text
                    }
                }
            };

            _context.CommentHeaders.Add(header);
            await _context.SaveChangesAsync();
        }
Beispiel #9
0
        public IHttpActionResult GetStudentComment(int section_id, int student_id)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                Section section = db.Sections.Find(section_id);
                if (section == null)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Invalid Section Id."))));
                }

                if (section.Students.Where(s => s.ID == student_id).Count() <= 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Invalid Student Id."))));
                }

                WebhostUserPrinciple principal = (WebhostUserPrinciple)ActionContext.RequestContext.Principal;
                int id = ((WebhostIdentity)principal.Identity).User.Id;

                Faculty self = db.Faculties.Find(id);

                if (!self.Sections.Contains(section))
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new UnauthorizedAccessException("You are not a teacher for this class."))));
                }

                int termId = DateRange.GetCurrentOrLastTerm();

                if (section.CommentHeaders.Where(h => h.TermIndex == termId).Count() <= 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NoContent, new ArgumentException("No Comment Header for this Term is saved."))));
                }

                CommentHeader header = section.CommentHeaders.Where(h => h.TermIndex == termId).Single();

                if (header.StudentComments.Where(comment => comment.StudentID == student_id).Count() <= 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NoContent, new ArgumentException("No Student Comment saved for this student."))));
                }


                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new StudentCommentInfo(header.StudentComments.Where(com => com.StudentID == student_id).Single().id))));
            }
        }
        /// <summary>
        /// Initialize Info object.
        /// </summary>
        /// <param name="id"></param>
        /// <param name="includeStudentCommentData"></param>
        public CommentHeaderInfo(int id, bool includeStudentCommentData = false)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                CommentHeader header = db.CommentHeaders.Find(id);
                if (header == null)
                {
                    throw new ArgumentException("Invalid Comment Header Id.");
                }

                Id           = id;
                SectionId    = header.SectionIndex;
                TermId       = header.TermIndex;
                Term         = string.Format("{0} {1}", header.Term.Name, header.Term.StartDate.Year);
                SectionTitle = String.Format("[{0}] {1}", header.Section.Block.LongName, header.Section.Course.Name);

                // Convert HTML to Base64String.
                if (header.RTF.Length <= 0)
                {
                    HtmlContent = CommentLetter.ConvertToBase64String(header.HTML);
                }
                else
                {
                    RtfContnet = header.RTF;
                }

                StudentCommentIds = header.StudentComments.Select(com => com.id).ToList();

                if (includeStudentCommentData)
                {
                    StudentComments = new List <StudentCommentInfo>();
                    foreach (int comId in StudentCommentIds)
                    {
                        StudentComments.Add(new StudentCommentInfo(comId));
                    }
                }
            }
        }
        public async Task <IHttpActionResult> PostNewCommentHeader(int section_id, int term_id)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                if (db.CommentHeaders.Where(h => h.SectionIndex == section_id && h.TermIndex == term_id).Count() > 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, new ArgumentException("Comment Header already Exists."))));
                }

                CommentHeader headerParagraph = new CommentHeader()
                {
                    id           = db.CommentHeaders.OrderBy(h => h.id).ToList().Last().id + 1,
                    SectionIndex = section_id,
                    TermIndex    = term_id
                };

                String content = await Request.Content.ReadAsStringAsync();

                content = CommentLetter.ConvertFromBase64String(content);

                headerParagraph.HTML = CommentLetter.CleanTags(content);

                db.CommentHeaders.Add(headerParagraph);

                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, e)));
                }

                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new CommentHeaderInfo(headerParagraph.id))));
            }
        }
Beispiel #12
0
        public IHttpActionResult PutUpdatedStudentComment(int section_id, int student_id, [FromBody] StudentCommentInfo info, [FromUri] String format = "rtf")
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                Section section = db.Sections.Find(section_id);
                if (section == null)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Invalid Section Id."))));
                }

                if (section.Students.Where(s => s.ID == student_id).Count() <= 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Invalid Student Id."))));
                }

                WebhostUserPrinciple principal = (WebhostUserPrinciple)ActionContext.RequestContext.Principal;
                int id = ((WebhostIdentity)principal.Identity).User.Id;

                Faculty self = db.Faculties.Find(id);

                if (!self.Sections.Contains(section))
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new UnauthorizedAccessException("You are not a teacher for this class."))));
                }

                int termId = DateRange.GetCurrentOrLastTerm();

                if (section.CommentHeaders.Where(h => h.TermIndex == termId).Count() <= 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NoContent, new ArgumentException("No Comment Header for this Term is saved."))));
                }

                CommentHeader header = section.CommentHeaders.Where(h => h.TermIndex == termId).Single();

                if (header.StudentComments.Where(com => com.StudentID == student_id).Count() <= 0)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, new ArgumentException("No Comment for this student saved."))));
                }

                StudentComment comment = header.StudentComments.Where(com => com.StudentID == student_id).Single();

                Dictionary <String, int> GradeEntries = CommentLetter.GetGradeTableEntryData();

                comment.EffortGradeID = GradeEntries[info.Grades.EngagementGrade];
                comment.ExamGradeID   = GradeEntries[info.Grades.ExamGrade];
                comment.TermGradeID   = GradeEntries[info.Grades.TrimesterGrade];
                comment.FinalGradeID  = GradeEntries[info.Grades.FinalGrade];

                if (format.Equals("html"))
                {
                    comment.HTML = CommentLetter.ConvertFromBase64String(info.HtmlContent);
                }
                else
                {
                    comment.RTF = info.RtfContent;
                }

                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, e)));
                }

                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new StudentCommentInfo(header.StudentComments.Where(com => com.StudentID == student_id).Single().id))));
            }
        }
        protected void ClassSelectCmbBx_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (Saving)
            {
                State.log.WriteLine("{1} {0}:  Aborted Changing Comment while Saving.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
                WebhostEventLog.CommentLog.LogWarning("Aborted changing comment while saving.");
                return;
            }
            State.log.WriteLine("{1} {0}:  Loading Selected Course.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
            try
            {
                SelectedSectionId = Convert.ToInt32(ClassSelectCmbBx.SelectedValue);
            }
            catch (Exception ex)
            {
                State.log.WriteLine("{1} {0}:  Failed:  {2}", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString(), ex.Message);
                WebhostEventLog.CommentLog.LogError("Failed to select section:  {0}", ex.Message);
                return;
            }

            StudentSelectCmbBx.Visible = true;
            int term = SelectedTermId == -1 ? Import.GetCurrentOrLastTerm() : SelectedTermId;

            using (WebhostEntities db = new WebhostEntities())
            {
                Section section = db.Sections.Find(SelectedSectionId);
                if (section == null)
                {
                    WebhostEventLog.CommentLog.LogError("Unable to locate section id {0}.", SelectedSectionId);
                    throw new InvalidOperationException("Invalid Section Id");
                }
                State.log.WriteLine("{1} {0}:  Loading Section [{2}] {3}", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString(), section.Block.LongName, section.Course.Name);
                WebhostEventLog.CommentLog.LogInformation("Loading Section [{0}] {1}", section.Block.LongName, section.Course.Name);
                // Load Header Paragraph.
                if (section.CommentHeaders.Where(hdr => hdr.TermIndex == term).Count() > 0)
                {
                    if (section.CommentHeaders.Where(hdr => hdr.TermIndex == term).Count() > 1)  // PROBLEM!
                    {
                        MailControler.MailToWebmaster("Class has Too Many header paragraphs....", String.Format("{0} objects match header paragraph for [{1}] {2} {3} comments.",
                                                                                                                section.CommentHeaders.Where(hdr => hdr.TermIndex == term).Count(), section.Block.LongName, section.Course.Name, section.Terms.Where(t => t.id == term).Single().Name), ((BasePage)Page).user);

                        State.log.WriteLine("{1} {0}:  Too many Class header paragraphs are stored in the database!!!", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());

                        /*********************************************************************
                        * TODO:
                        * Handle This some how!
                        *
                        * Make a pop-up to choose which to keep.
                        *
                        *********************************************************************/

                        State.log.WriteLine("{1} {0}:  Aborting the defunct Header Loader.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
                        WebhostEventLog.CommentLog.LogError("Too many Class Header paragraphs stored for section {0} in term id {1}", SelectedSectionId, term);
                        return;
                    }


                    State.log.WriteLine("{1} {0}:  Getting Comment Header HTML.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
                    CommentHeader header = section.CommentHeaders.Where(hdr => hdr.TermIndex == term).Single();

                    LoadedHeaderId = header.id;

                    HeaderHTML           = header.HTML;
                    HeaderEditor.Content = header.HTML;

                    State.log.WriteLine("{1} {0}:  Done.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
                    WebhostEventLog.CommentLog.LogInformation("Successfully Loaded header id {0}", LoadedHeaderId);
                }
                else
                {
                    State.log.WriteLine("{0} {1}:  No Header exisits--creating new header.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                    WebhostEventLog.CommentLog.LogInformation("Creating a new header paragraph object.");
                    // Create Paragraph!
                    CommentHeader header = new CommentHeader()
                    {
                        id           = db.CommentHeaders.Count() > 0 ? db.CommentHeaders.OrderBy(h => h.id).ToList().Last().id + 1 : 0,
                        HTML         = "",
                        SectionIndex = SelectedSectionId,
                        TermIndex    = term
                    };
                    db.CommentHeaders.Add(header);
                    db.SaveChanges();

                    LoadedHeaderId       = header.id;
                    HeaderEditor.Content = "";

                    State.log.WriteLine("{0} {1}:  Saved new blank header to database.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                }

                State.log.WriteLine("{1} {0}:  Loading Student Roster.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());

                StudentPanel.Visible          = false;
                StudentSelectCmbBx.DataSource = (from student in section.Students
                                                 orderby student.LastName, student.FirstName
                                                 select new
                {
                    Name = student.FirstName + " " + student.LastName,
                    ID = student.ID
                }).ToList();
                StudentSelectCmbBx.DataTextField  = "Name";
                StudentSelectCmbBx.DataValueField = "ID";
                StudentSelectCmbBx.DataBind();

                EditorLabel.Text = "Editing Comment Header.  Select a Student to load the Individual Comment.";

                PreviewBtn.Visible       = false;
                DownloadClassBtn.Visible = true;
                ClassReviewBtn.Visible   = true;
                HeaderPanel.Visible      = true;
                HeaderBtn.Visible        = false;
                State.log.WriteLine("{0} {1}:  Completed Loading Class Header.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
            }
        }
Beispiel #14
0
        public IHttpActionResult PutUpdatedCommentHeader(int section_id, [FromBody] String content, [FromUri] String format = "rtf")
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                Section section = db.Sections.Find(section_id);
                if (section == null)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, new ArgumentException("Invalid Section Id."))));
                }

                WebhostUserPrinciple principal = (WebhostUserPrinciple)ActionContext.RequestContext.Principal;
                int id = ((WebhostIdentity)principal.Identity).User.Id;

                Faculty self = db.Faculties.Find(id);

                if (!self.Sections.Contains(section))
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Unauthorized, new UnauthorizedAccessException("You are not a teacher for this class."))));
                }

                int termId = DateRange.GetCurrentOrLastTerm();

                CommentHeader header;

                if (section.CommentHeaders.Where(h => h.TermIndex == termId).Count() <= 0)
                {
                    header = new CommentHeader()
                    {
                        id           = db.CommentHeaders.OrderBy(h => h.id).ToList().Last().id + 1,
                        HTML         = "",
                        SectionIndex = section_id,
                        TermIndex    = termId
                    };
                    db.CommentHeaders.Add(header);
                }
                else
                {
                    header = section.CommentHeaders.Where(h => h.TermIndex == termId).Single();
                }

                content = CommentLetter.ConvertFromBase64String(content);

                if (format.Equals("html"))
                {
                    header.HTML = CommentLetter.ConvertFromBase64String(content);
                }
                else
                {
                    header.RTF = Convert.FromBase64String(content);
                }

                try
                {
                    db.SaveChanges();
                }
                catch (Exception e)
                {
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.Conflict, e)));
                }

                return(ResponseMessage(Request.CreateResponse(HttpStatusCode.OK, new CommentHeaderInfo(header.id), "text/json")));
            }
        }
        protected void StudentSelectCmbBx_SelectedIndexChanged(object sender, EventArgs e)
        {
            CommentGrades.ResetBar();
            State.log.WriteLine("{0} {1}:  Loading new student selection.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
            if (Saving)
            {
                State.log.WriteLine("{1} {0}:  Aborted Changing Comment while Saving.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
                WebhostEventLog.CommentLog.LogWarning("Aborted changing comment while saving.");
                return;
            }
            if (LoadedHeaderId == -1)
            {
                State.log.WriteLine("{0} {1}:  No Header is Loaded... There's a problem...", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                StudentSelectCmbBx.DataSource = new List <string>();
                StudentSelectCmbBx.DataBind();
                WebhostEventLog.CommentLog.LogError("Cannot Select a student while no Header is loaded...");
                return;
            }

            try
            {
                SelectedStudentId = Convert.ToInt32(StudentSelectCmbBx.SelectedValue);
            }
            catch (Exception ex)
            {
                State.log.WriteLine("{1} {0}:  Failed:  {2}", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString(), ex.Message);
                WebhostEventLog.CommentLog.LogError("Failed to select Student: {0}", ex.Message);
                return;
            }

            using (WebhostEntities db = new WebhostEntities())
            {
                CommentHeader header = db.CommentHeaders.Where(hdr => hdr.id == LoadedHeaderId).Single();
                // check for existing comments.
                if (header.StudentComments.Where(com => com.StudentID == SelectedStudentId).Count() > 0)
                {
                    // check for multiples.
                    if (header.StudentComments.Where(com => com.StudentID == SelectedStudentId).Count() > 1)
                    {
                        State.log.WriteLine("{1} {0}:  Something went wrong!  Too many comments for Student.id={2} and CommentHeader.id={3}", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString(), SelectedStudentId, LoadedHeaderId);
                        MailControler.MailToWebmaster("Class has Too Many comment paragraphs....", String.Format("{0} objects match comment paragraph for Student.id={4} in [{1}] {2} {3} comments.",
                                                                                                                 header.StudentComments.Where(com => com.StudentID == SelectedStudentId).Count(), header.Section.Block.LongName, header.Section.Course.Name, header.Term.Name), ((BasePage)Page).user);

                        WebhostEventLog.CommentLog.LogError("Something went wrong!  Too many comments for Student.id={0} and CommentHeader.id={1}", SelectedStudentId, LoadedHeaderId);

                        /*********************************************************************
                        * TODO:
                        * Handle This some how!
                        *
                        * Make a pop-up to choose which to keep.
                        *
                        *********************************************************************/

                        State.log.WriteLine("{1} {0}:  Aborting the defunct Header Loader.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
                        return;
                    }

                    // Load the unique comment.

                    StudentComment comment = header.StudentComments.Where(com => com.StudentID == SelectedStudentId).Single();
                    LoadedCommentId = comment.id;

                    State.log.WriteLine("{0} {1}:  Loading unique comment id={2}", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString(), LoadedCommentId);
                    WebhostEventLog.CommentLog.LogInformation("Loaded Comment id {0}", LoadedCommentId);
                    StudentCommentHTML             = comment.HTML;
                    CommentGrades.EffortGradeID    = comment.EffortGradeID;
                    CommentGrades.FinalGradeID     = comment.FinalGradeID;
                    CommentGrades.ExamGradeID      = comment.ExamGradeID;
                    CommentGrades.TrimesterGradeID = comment.TermGradeID;
                    StudentEditor.Content          = comment.HTML;

                    StudentNameLabel.Text = String.Format("Comment for {0} {1}", comment.Student.FirstName, comment.Student.LastName);
                }
                else
                {
                    // Create new blank comment.
                    State.log.WriteLine("{0} {1}:  Creating a new Student Comment paragraph.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                    WebhostEventLog.CommentLog.LogInformation("Creating new student comment.");
                    StudentComment comment = new StudentComment()
                    {
                        id            = db.StudentComments.Count() > 0 ? db.StudentComments.OrderBy(com => com.id).ToList().Last().id + 1 : 0,
                        StudentID     = SelectedStudentId,
                        Student       = db.Students.Where(s => s.ID == SelectedStudentId).Single(),
                        HeaderIndex   = header.id,
                        HTML          = "",
                        TermGradeID   = CommentGrades.AFDefault,
                        EffortGradeID = CommentGrades.EffortDefault,
                        FinalGradeID  = CommentGrades.AFDefault,
                        ExamGradeID   = CommentGrades.AFDefault
                    };


                    db.StudentComments.Add(comment);
                    db.SaveChanges();
                    LoadedCommentId       = comment.id;
                    comment               = db.StudentComments.Where(c => c.id == LoadedCommentId).Single();
                    StudentEditor.Content = "";
                    StudentNameLabel.Text = String.Format("Comment for {0} {1}", comment.Student.FirstName, comment.Student.LastName);
                    State.log.WriteLine("{0} {1}:  New blank comment is saved to the database.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                }

                EditorLabel.Text     = "Editing Student Individual Comment.";
                HeaderBtn.Visible    = true;
                HeaderPanel.Visible  = false;
                StudentPanel.Visible = true;
                PreviewBtn.Visible   = true;
            }
        }
        public static void Initialise(UserManager <IdentityUser> userManager, ApplicationDbContext context)
        {
            var user = userManager.FindByNameAsync(_User).Result;

            if (user == null)
            {
                user = new IdentityUser {
                    UserName = _User, Email = _User
                };
                var result = userManager.CreateAsync(user, _Password).Result;
                if (!result.Succeeded)
                {
                    throw new Exception("Unable to create dummy user");
                }

                DateTime now      = DateTime.UtcNow;
                DateTime yearAgo  = now.AddYears(-1);
                DateTime monthAgo = now.AddMonths(-1);
                DateTime dayAgo   = now.AddDays(-1);

                CommentHeader[] commentHeaders = new CommentHeader[]
                {
                    new CommentHeader
                    {
                        User             = user,
                        CommentRevisions = new CommentRevision[]
                        {
                            new CommentRevision
                            {
                                CreatedDate = yearAgo,
                                Text        = "This is my first comment"
                            }
                        }
                    },
                    new CommentHeader
                    {
                        User             = user,
                        CommentRevisions = new CommentRevision[]
                        {
                            new CommentRevision
                            {
                                CreatedDate = monthAgo,
                                Text        = "This is my second comment"
                            },
                            new CommentRevision
                            {
                                CreatedDate = dayAgo,
                                Text        = "This is my second comment which has been edited"
                            },
                            new CommentRevision
                            {
                                CreatedDate = now,
                                Text        = "This is my second comment which has been edited twice"
                            }
                        }
                    }
                };

                context.CommentHeaders.AddRange(commentHeaders);
                context.SaveChanges();
            }
        }
        protected void SaveBtn_Click(object sender, EventArgs e)
        {
            if (SelectedSectionId == -1)
            {
                State.log.WriteLine("{0} {1}:  Cannot Save with no section selected.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                LogWarning("Cannot save with no section selected.");
                return;
            }
            if (Saving)
            {
                State.log.WriteLine("{1} {0}:  Aborted multiple Saving attempts.", DateTime.Now.ToLongTimeString(), DateTime.Today.ToShortDateString());
                LogWarning("Aborted multiple Saving Attempts.");
                return;
            }
            using (WebhostEntities db = new WebhostEntities())
            {
                Saving = true;
                if (HeaderPanel.Visible)
                {
                    CommentHeader header = db.CommentHeaders.Where(h => h.id == LoadedHeaderId).Single();
                    State.log.WriteLine("{0} {1}:  Saving Header Paragraph.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                    // Save the Header!
                    if (HeaderEditor.Content.Length < header.HTML.Length)
                    {
                        State.log.WriteLine("{0} {1}:  Warning--suspicious overwrite:{2}Original:{2}{3}{2}Replacement:{2}{4}", DateTime.Today.ToShortDateString(),
                                            DateTime.Now.ToLongTimeString(), Environment.NewLine, header.HTML, HeaderEditor.Content);
                        WebhostEventLog.CommentLog.LogWarning("Suspicious Overwrite:{0}Original:{0}{1}{0}========================================================{0}Replacement:{0}{2}",
                                                              Environment.NewLine, header.HTML, HeaderEditor.Content);
                    }

                    String html = HeaderEditor.Content;
                    String temp = html;
                    html = CommentLetter.CleanTags(html);

                    if (!temp.Equals(html))
                    {
                        WebhostEventLog.CommentLog.LogWarning("CleanTags method changed:{0}{1}{0}============================================================={0}Into:{0}{2}",
                                                              Environment.NewLine, temp, html);
                    }

                    WebhostEventLog.CommentLog.LogInformation("Saving Header:{0}{1}", Environment.NewLine, html);

                    HeaderEditor.Content = html;

                    header.HTML = HeaderEditor.Content;
                    HeaderHTML  = HeaderEditor.Content;
                }

                if (LoadedCommentId != -1)
                {
                    State.log.WriteLine("{0} {1}:  Saving Student Comment.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                    StudentComment comment = db.StudentComments.Where(com => com.id == LoadedCommentId).Single();

                    if (StudentEditor.Content.Length < comment.HTML.Length)
                    {
                        State.log.WriteLine("{0} {1}:  Warning--suspicious overwrite:{2}Original:{2}{3}{2}Replacement:{2}{4}", DateTime.Today.ToShortDateString(),
                                            DateTime.Now.ToLongTimeString(), Environment.NewLine, comment.HTML, StudentEditor.Content);
                        WebhostEventLog.CommentLog.LogWarning("Suspicious Overwrite:{0}Original:{0}{1}{0}========================================================{0}Replacement:{0}{2}",
                                                              Environment.NewLine, comment.HTML, StudentEditor.Content);
                    }


                    String html = StudentEditor.Content;

                    String temp = html;
                    html = CommentLetter.CleanTags(html);

                    if (!temp.Equals(html))
                    {
                        WebhostEventLog.CommentLog.LogWarning("CleanTags method changed:{0}{1}{0}============================================================={0}Into:{0}{2}",
                                                              Environment.NewLine, temp, html);
                    }

                    WebhostEventLog.CommentLog.LogInformation("Saving Comment for {2} {3}:{0}{1}", Environment.NewLine, html, comment.Student.FirstName, comment.Student.LastName);

                    StudentEditor.Content = html;

                    comment.HTML          = StudentEditor.Content;
                    comment.EffortGradeID = CommentGrades.EffortGradeID;
                    comment.FinalGradeID  = CommentGrades.FinalGradeID;
                    comment.TermGradeID   = CommentGrades.TrimesterGradeID;
                    comment.ExamGradeID   = CommentGrades.ExamGradeID;
                    StudentCommentHTML    = StudentEditor.Content;
                }

                db.SaveChanges();
                State.log.WriteLine("{0} {1}:  Changes saved to the Database.", DateTime.Today.ToShortDateString(), DateTime.Now.ToLongTimeString());
                WebhostEventLog.CommentLog.LogInformation("Save Complete.");
            }

            Saving = false;
        }
        public IHttpActionResult GetMyComments(string term, int year)
        {
            if (!(new List <String>()
            {
                "Fall", "Winter", "Spring"
            }).Contains(term))
            {
                return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.NotAcceptable, new ArgumentOutOfRangeException(nameof(term)))));
            }

            using (WebhostEntities db = new WebhostAPI.WebhostEntities())
            {
                Term theTerm = null;
                try
                {
                    theTerm = db.Terms.Where(t => t.Name.Equals(term) && t.StartDate.Year == year).Single();
                }
                catch (Exception e)
                {  // Invalid term.
                    return(ResponseMessage(Request.CreateErrorResponse(HttpStatusCode.BadRequest, e)));
                }

                WebhostUserPrinciple principal = (WebhostUserPrinciple)ActionContext.RequestContext.Principal;
                int id = ((WebhostIdentity)principal.Identity).User.Id;

                byte[] zipData = null;

                using (MemoryStream ms = new MemoryStream())
                {
                    using (ZipArchive archive = new ZipArchive(ms, ZipArchiveMode.Create, true))
                    {
                        List <int> CommentIds = new List <int>();

                        if (((WebhostIdentity)(principal.Identity)).User.IsTeacher())
                        {
                            Faculty teacher = db.Faculties.Find(((WebhostIdentity)(principal.Identity)).User.Id);
                            foreach (Section section in teacher.Sections.Where(s => s.CommentHeaders.Where(ch => ch.TermIndex == theTerm.id).Count() > 0).ToList())
                            {
                                CommentHeader header = section.CommentHeaders.Where(ch => ch.TermIndex == theTerm.id).Single();
                                CommentIds.AddRange(header.StudentComments.Select(c => c.id).ToList());
                            }
                        }
                        else
                        {
                            Student student = db.Students.Find(((WebhostIdentity)(principal.Identity)).User.Id);
                            CommentIds.AddRange(student.StudentComments.Where(com => com.CommentHeader.TermIndex == theTerm.id).Select(com => com.id).ToList());
                        }

                        foreach (int cid in CommentIds)
                        {
                            CommentLetter   letter  = new CommentLetter(cid);
                            byte[]          pdfData = letter.Publish().Save();
                            ZipArchiveEntry entry   = archive.CreateEntry(CommentLetter.EncodeSafeFileName(letter.Title) + ".pdf");
                            using (Stream stream = entry.Open())
                            {
                                stream.Write(pdfData, 0, pdfData.Length);
                            }
                        }
                    }

                    ms.Seek(0, SeekOrigin.Begin);
                    zipData = new byte[ms.Length];
                    for (long i = 0; i < ms.Length; i++)
                    {
                        zipData[i] = (byte)ms.ReadByte();
                    }
                }

                HttpResponseMessage response = Request.CreateResponse(HttpStatusCode.OK);
                response.Content = new ByteArrayContent(zipData);
                response.Content.Headers.ContentDisposition = new System.Net.Http.Headers.ContentDispositionHeaderValue("inline")
                {
                    FileName = "comments.zip"
                };
                response.Content.Headers.ContentType = System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/octet-stream");

                return(ResponseMessage(response));
            }
        }