示例#1
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)));
            }
        }
 protected override void OnStop()
 {
     timer.Stop();
     timer.Dispose();
     PublishingLog.WriteEntry("Comment Publishing Service Stopped.", EventLogEntryType.Information);
     MailControler.MailToWebmaster("Comment Service Stopped", "Comment Publishing Service has stopped.");
 }
示例#3
0
        protected void ResetBtn_Click(object sender, EventArgs e)
        {
            String response = "";
            bool   success  = true;
            String passwd   = RandomizeCB.Checked ? WebhostMySQLConnection.AccountManagement.AccountManagement.GenerateRandomPassword() : NewPasswordInput.Text;

            try
            {
                PasswordReset.ChangeAllPasswords(EmailSelect.SelectedValue, "", passwd, "dublinschool.org", true);
                response = String.Format("Password for {0}@dublinschool.org has been set to {1}{2}Please visit https://webhost.dublinschool.org/PasswordInitialization.aspx to set your own password.", EmailSelect.SelectedValue, passwd, Environment.NewLine);
            }
            catch (GoogleAPICall.GoogleAPIException ge)
            {
                response = ge.Message;
                Exception inner = ge.InnerException;
                while (inner != null)
                {
                    response += Environment.NewLine + inner.Message;
                    inner     = inner.InnerException;
                }
                success = false;
                LogError("Failed to reset password:{0}{0}{1}", Environment.NewLine, response);
            }

            if (success && !ResetInfoEmail.Text.Equals(""))
            {
                MailControler.MailToUser("Password Reset", response, ResetInfoEmail.Text, EmailSelect.SelectedValue);
            }

            MailControler.MailToWebmaster("Password Reset Info", response);
            LogInformation("Password for {0} has been reset by {1}", EmailSelect.SelectedValue, bPage.user.Name);
        }
示例#4
0
 protected override void OnStart(string[] args)
 {
     ServiceEventLog.WriteEntry("Schoology Sync Sevice Starting.", EventLogEntryType.Information);
     SyncTimer.Start();
     AdjustmentTimer.Start();
     MailControler.MailToWebmaster("Schoology Sync Service Started.", "Sync Service is Started!");
 }
示例#5
0
 protected override void OnStop()
 {
     SyncTimer.Stop();
     AdjustmentTimer.Stop();
     SyncTimer.Dispose();
     AdjustmentTimer.Dispose();
     ServiceEventLog.WriteEntry("Schoology Sync Service Is Stopped.", EventLogEntryType.Information);
     MailControler.MailToWebmaster("Schoology Sync Service Stopped.", "The Schoology Sync Service has been Stopped...");
 }
示例#6
0
        void CourseAndSectonsTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            String Report = "";

            ServiceEventLog.WriteEntry("Checking for Changes to Schoology Courses and Sections.", EventLogEntryType.Information);
            Report += SchoologySync.GetCoursesFromSchoology();
            Report += "\n" + SchoologySync.GetSchoologySectionIdsForTerm(DateRange.GetCurrentOrLastTerm());
            ServiceEventLog.WriteEntry(Report, EventLogEntryType.SuccessAudit);
            ServiceEventLog.WriteEntry("Completed Course and Section Sync.", EventLogEntryType.Information);
            MailControler.MailToWebmaster("Schoology Course and Section Sync.", Report);
        }
示例#7
0
        public static String BlockOrderByDayOfWeek(DateTime date)
        {
            String blocks = "ABCDEF";

            if (date.DayOfWeek == DayOfWeek.Wednesday)
            {
                using (WebhostEntities db = new WebhostEntities())
                {
                    if (db.WednesdaySchedules.Where(w => w.Day.Equals(date.Date)).Count() <= 0)
                    {
                        WebhostEventLog.Syslog.LogWarning("I don't know if today is an ABC wednesday or not!");
                        try
                        {
                            MailControler.MailToWebmaster("Wednesday Schedule?", "I don't know if today is ABC or not >_<");
                        }
                        catch
                        {
                            WebhostEventLog.Syslog.LogError("I couldn't send you an email to let you know...");
                        }
                        return(blocks);
                    }

                    WednesdaySchedule wed = db.WednesdaySchedules.Where(w => w.Day.Equals(date.Date)).Single();
                    if (wed.IsABC)
                    {
                        return("ABC");
                    }

                    return("DEF");
                }
            }

            int offset = 0;

            switch (date.DayOfWeek)
            {
            case DayOfWeek.Tuesday: offset = 1; break;

            case DayOfWeek.Thursday: offset = 2; break;

            case DayOfWeek.Friday: offset = 3; break;

            default: offset = 0; break;
            }
            String ordered = "";

            for (int i = 0; i < 6; i++)
            {
                ordered += blocks[(i + offset) % 6];
            }

            return(ordered);
        }
示例#8
0
        protected void GetAccountsBtn_Click(object sender, EventArgs e)
        {
            List <String> files = new List <string>();
            List <CSV>    csvs  = Import.GetNewAccountsCSVs(SelectedIds);

            csvs[0].Save(Server.MapPath("~/Temp/gmail_users.csv"));
            csvs[1].Save(Server.MapPath("~/Temp/ad_users.csv"));
            Response.Redirect(MailControler.PackForDownloading(new List <string>()
            {
                "~/Temp/gmail_users.csv", "~/Temp/ad_users.csv"
            }, "new users", Server));
        }
示例#9
0
        public static String PublishTermByStudent(int termId = -1, List <int> studentIds = null, String SaveDir = "")
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                if (db.Terms.Where(t => t.id == termId).Count() <= 0)
                {
                    termId = Import.GetCurrentOrLastTerm();
                }

                Term          term             = db.Terms.Where(t => t.id == termId).Single();
                String        packFileName     = term.Name.ToLower() + "_term_comments.zip";
                List <String> termCommentFiles = new List <string>();

                if (studentIds == null)
                {
                    studentIds = Import.ActiveStudents(termId);
                }

                foreach (int studentId in studentIds)
                {
                    Student student         = db.Students.Where(s => s.ID == studentId).Single();
                    String  studentFileName = String.Format("[{3}] {0}, {1} {2} Comments.zip", student.LastName, student.FirstName, term.Name, student.GraduationYear);
                    WebhostEventLog.CommentLog.LogInformation("Publishing {0}", studentFileName);
                    List <String> studentFiles = new List <String>();
                    List <int>    commentIds   = student.StudentComments.Where(com => com.CommentHeader.TermIndex == termId).Select(com => com.id).ToList();
                    foreach (int id in commentIds)
                    {
                        studentFiles.Add((new CommentLetter(id)).Publish(SaveDir));
                    }

                    if (SaveDir.Equals(""))
                    {
                        termCommentFiles.Add(MailControler.PackForDownloading(studentFiles, studentFileName, HttpContext.Current.Server));
                    }
                    else
                    {
                        termCommentFiles.Add(MailControler.PackForDownloading(studentFiles, String.Format("{0}\\{1}", SaveDir, studentFileName)));
                    }
                }

                if (SaveDir.Equals(""))
                {
                    return(MailControler.PackForDownloading(termCommentFiles, packFileName, HttpContext.Current.Server));
                }
                else
                {
                    return(MailControler.PackForDownloading(termCommentFiles, String.Format("{0}\\{1}", SaveDir, packFileName)));
                }
            }
        }
 protected void CancelNoteBtn_Click(object sender, EventArgs e)
 {
     LogError(String.Format("User has actively aborted entering requested data for {0}", ClassInfoLabel.Text),
              typeof(Dictionary <int, AttendanceControl.AdditionalInfoRequest>),
              (Dictionary <int, AttendanceControl.AdditionalInfoRequest>)Session["required_update_info"]);
     MailControler.MailToUser("User has actively aborted entering requested data.",
                              String.Format("{0} actively ignored the request for additional information on attendance markings for {1}.  These markings changes have been rejected.",
                                            user.Name, ClassInfoLabel.Text), MailControler.DeanOfStudents.Email, MailControler.DeanOfStudents.Name, user);
     MailControler.MailToUser("Aborted entering requested data.",
                              String.Format("You actively ignored the request for additional information on attendance markings for {1}.  These markings changes have been rejected.",
                                            user.Name, ClassInfoLabel.Text), user);
     Session["required_update_info"] = null;
     Redirect("~/Mobile/Attendance.aspx");
 }
示例#11
0
        protected void Page_Error(object sender, EventArgs e)
        {
            try
            {
                log.WriteLine("Page_Error @ {0}", Request.RawUrl);
            }
            catch (Exception ex)
            {
                LogError("Failed to write to log file: {0}", ex.Message);
            }


            Exception Err = Server.GetLastError();

            //ADUser user = (ADUser)Session[State.AuthUser];
            if (user == null)
            {
                LogError("Page error with no user logged in on {1}.{0}{0}Error details:{0}{2}{0}____________________________{0}{0}Stack Trace:{0}{3}",
                         Environment.NewLine, Request.RawUrl, Err.Message, Err.StackTrace);
                return;
            }
            MailControler.MailToWebmaster("Page Error in Webhost.", "Webhost had an Page error somewhere...", user);

            String ErrString = Err.ToString();

            String StackTrace = Err.StackTrace;

            String AllMessages = Err.Message;

            while (Err.InnerException != null)
            {
                Err          = Err.InnerException;
                AllMessages += "\n\nInner Exception:\n" + Err.Message;
                StackTrace  += "\n\nInner Exception:\n" + Err.StackTrace;
                ErrString   += "\n\nInner Exception:\n" + Err.ToString();
            }
            String Message = "Error Produced by " + user.Name + " at " + DateTime.Now.ToLongTimeString() + "\n"
                             + "Page:\t" + Request.Url + "\n\n"
                             + "Error Details:\n\n" + ErrString + "\n\n"
                             + "__________________________________________________________________________________________________________\n\n"
                             + "All Messages:\n\n" + AllMessages + "\n\n"
                             + "__________________________________________________________________________________________________________\n\n"
                             + "Stack Traces:\n\n" + StackTrace;

            MailControler.MailToWebmaster("Page Error Details on " + Request.Url, Message, user);
            LogError(Message);
        }
        protected void LoadTable()
        {
            Dictionary <String, int> map    = MorningMeetingSeatClicker.MapMarkingToGradeTableEntry();
            Dictionary <int, String> revmap = new Dictionary <int, string>();

            foreach (String key in map.Keys)
            {
                revmap.Add(map[key], key);
            }

            using (WebhostEntities db = new WebhostEntities())
            {
                int     mmid           = AttendanceControl.MorningMeetingSectionId();
                Section morningmeeting = db.Sections.Where(sec => sec.id == mmid).Single();
                if (morningmeeting.SeatingCharts.Count <= 0)
                {
                    MailControler.MailToUser("Morning Meeting Seating Chart.", AttendanceControl.GenerateMorningMeetingSeatingChart(), ((BasePage)Page).user);
                }

                String       rows  = "ABCDEFGHIJKL";
                SeatingChart chart = db.Sections.Where(sec => sec.id == mmid).Single().SeatingCharts.ToList().First();
                foreach (SeatingChartSeat seat in chart.SeatingChartSeats.Where(s => s.StudentId.HasValue).ToList())
                {
                    String id = String.Format("{0}{1}", rows[seat.Row], seat.Column + 1);
                    seatControls.Where(sc => sc.ID.Equals(id)).Single().StudentId = seat.StudentId.Value;
                    seatControls.Where(sc => sc.ID.Equals(id)).Single().ToolTip   = String.Format("{0} {1}", seat.Student.FirstName, seat.Student.LastName);
                    if (morningmeeting.AttendanceMarkings.Where(mk => mk.AttendanceDate.Equals(SelectedDate) && mk.StudentID == seat.StudentId.Value).Count() > 0)
                    {
                        seatControls.Where(sc => sc.ID.Equals(id)).Single().Marking = revmap[morningmeeting.AttendanceMarkings.Where(mk => mk.AttendanceDate.Equals(SelectedDate) && mk.StudentID == seat.StudentId.Value).Single().MarkingIndex];
                    }
                    else
                    {
                        seatControls.Where(sc => sc.ID.Equals(id)).Single().Marking = "OK";
                    }
                }

                foreach (MorningMeetingSeatClicker clicker in seatControls)
                {
                    clicker.Enabled = clicker.StudentId != -1;
                }
            }
        }
示例#13
0
        public Signature(int facultyId)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                Faculty faculty = db.Faculties.Where(f => f.ID == facultyId).Single();
                FacultyId = facultyId;

                if (faculty.SignatureData.Length <= 0)
                {
                    image = null;
                    return;
                }

                MemoryStream str = new MemoryStream();
                str.Seek(0, SeekOrigin.Begin);
                try
                {
                    str.Read(faculty.SignatureData, 0, faculty.SignatureData.Length);
                }
                catch
                {
                    image = null;
                    return;
                }
                MemoryStream mStream = new MemoryStream();
                for (int i = 0; i < faculty.SignatureData.Length; i++)
                {
                    mStream.WriteByte(faculty.SignatureData[i]);
                }

                try
                {
                    image = Image.FromStream(mStream);
                }
                catch (Exception e)
                {
                    MailControler.MailToWebmaster("Signature Image Failed To Load.", String.Format("Comment Letter Signature Image for {0} {1} failed to load properly.\n\nError: {2}", faculty.FirstName, faculty.LastName, e.Message));
                    image = null;
                }
            }
        }
示例#14
0
        protected void PublishCalendarBtn_Click(object sender, EventArgs e)
        {
            try
            {
                WeekendControl.PublishWeekendScheduleToGoogleCalendars(WeekendID, State.log);
                SuccessLabel.Text = "Successfully Posted to Google Calendar";
            }
            catch (Exception er)
            {
                SuccessLabel.Text = "There was a Problem, I'm emailing Jason now!";
                String message = er.Message;
                while (er.InnerException != null)
                {
                    er       = er.InnerException;
                    message += Environment.NewLine + er.Message;
                }
                MailControler.MailToWebmaster("Problem Publishing Weekend Calendar", message, ((BasePage)Page).user);
            }

            SuccessPanel.Visible = true;
        }
示例#15
0
        void SyncTimer_Elapsed(object sender, ElapsedEventArgs e)
        {
            ServiceEventLog.WriteEntry("Syncing Schoology Attendances.", EventLogEntryType.Information);
            long   ticks  = DateTime.Now.Ticks;
            String report = "";

            //this.CanStop = false;
            try
            {
                report = AttendanceControl.PullFromSchoology();
            }
            catch (SchoologyAPICall.SchoologyAPIException apiex)
            {
                String    Message = apiex.Message;
                Exception inner   = apiex.InnerException;
                while (inner != null)
                {
                    Message += Environment.NewLine + "________________________________________" + Environment.NewLine + inner.Message;
                }
                ServiceEventLog.WriteEntry(String.Format("API Call failed:{0}{1}", Environment.NewLine, Message), EventLogEntryType.Error);
                MailControler.MailToWebmaster("Schoology Sync Service Error", String.Format("Schoology Sync Service Failed with the following error:{0}{0}{1}", Environment.NewLine, Message));
            }
            catch (Exception ex)
            {
                String Message = ex.Message;
                while (ex.InnerException != null)
                {
                    ex       = ex.InnerException;
                    Message += Environment.NewLine + "________________________________________" + Environment.NewLine + ex.Message;
                }
                MailControler.MailToWebmaster("Schoology Sync Service Error", String.Format("Schoology Sync Service Failed with the following error:{0}{0}{1}", Environment.NewLine, Message));
                ServiceEventLog.WriteEntry(String.Format(Message), EventLogEntryType.Error);
            }
            //this.CanStop = true;
            ServiceEventLog.WriteEntry(report, EventLogEntryType.Information);
            ticks = DateTime.Now.Ticks - ticks;
            TimeSpan ts = new TimeSpan(ticks);

            ServiceEventLog.WriteEntry(String.Format("Syncronization Complete.  This Sync took {0}.", ts), EventLogEntryType.Information);
        }
示例#16
0
        protected static void ExecuteStudentRequest(XMLTree xml, String saveDir)
        {
            int termId = Convert.ToInt32(xml.Attributes["termid"]);

            List <int> studentIds = new List <int>();

            foreach (XMLTree studentTree in xml.ChildTrees.Where(tree => tree.TagName.Equals("student")).ToList())
            {
                int studentId = Convert.ToInt32(studentTree.Attributes["studentid"]);
                studentIds.Add(studentId);
            }

            String fileName = CommentLetter.PublishTermByStudent(termId, studentIds, saveDir);

            MailControler.MailToUser("Comments Published Successfully",
                                     String.Format("Click the Link to download the comments you requested:{0}{1}",
                                                   Environment.NewLine,
                                                   fileName.Replace("W:", "https://webhost.dublinschool.org").Replace("\\", "/")),
                                     String.Format("{0}@dublinschool.org", xml.Attributes["username"]),
                                     xml.Attributes["name"],
                                     "*****@*****.**", "Comment Bot");
        }
示例#17
0
        /// <summary>
        /// Publish comments via commandline tool.  dumps them in C:\Temp
        /// Defaults to this term, all students.
        /// </summary>
        /// <param name="termId"></param>
        /// <param name="studentIds"></param>
        public static void CommandLinePublish(int termId = -1, List <int> studentIds = null)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                if (db.Terms.Where(t => t.id == termId).Count() <= 0)
                {
                    termId = Import.GetCurrentOrLastTerm();
                }

                Term          term             = db.Terms.Where(t => t.id == termId).Single();
                String        packFileName     = term.Name.ToLower() + "_term_comments";
                List <String> termCommentFiles = new List <string>();


                if (studentIds == null)
                {
                    studentIds = Import.ActiveStudents(termId);
                }

                foreach (int studentId in studentIds)
                {
                    Student student         = db.Students.Where(s => s.ID == studentId).Single();
                    String  studentFileName = String.Format("{0}, {1} [{3}] {2} Comments", student.LastName, student.FirstName, term.Name, student.GraduationYear);
                    Console.WriteLine("Publishing {0}, {1} [2]", student.LastName, student.FirstName, student.GraduationYear);
                    List <String>         studentFiles = new List <string>();
                    List <StudentComment> commentIds   = student.StudentComments.Where(com => com.CommentHeader.TermIndex == termId).ToList();
                    foreach (StudentComment comment in commentIds)
                    {
                        studentFiles.Add((new CommentLetter(comment.id, true)).Publish(true));
                        Console.WriteLine("\t[{0}] {1}", comment.CommentHeader.Section.Block.LongName, comment.CommentHeader.Section.Course.Name);
                    }

                    termCommentFiles.Add(MailControler.PackForDownloading(studentFiles, studentFileName));
                }

                MailControler.PackForDownloading(termCommentFiles, packFileName);
            }
        }
示例#18
0
        protected static void ExecuteClassRequest(XMLTree xml, String saveDir)
        {
            int termId = Convert.ToInt32(xml.Attributes["termid"]);

            List <int>    studentIds = new List <int>();
            List <String> filenames  = new List <string>();

            foreach (XMLTree studentTree in xml.ChildTrees.Where(tree => tree.TagName.Equals("section")).ToList())
            {
                int headerId = Convert.ToInt32(studentTree.Attributes["headerid"]);
                filenames.Add(CommentLetter.PublishClass(headerId, saveDir));
            }

            String zipFile = MailControler.PackForDownloading(filenames, String.Format("{0}\\classes_{1}.zip", saveDir, DateTime.Now.Ticks));

            MailControler.MailToUser("Comments Published Successfully",
                                     String.Format("Click the Link to download the comments you requested:{0}{1}",
                                                   Environment.NewLine,
                                                   zipFile.Replace("W:", "https://webhost.dublinschool.org").Replace("\\", "/")),
                                     String.Format("{0}@dublinschool.org", xml.Attributes["username"]),
                                     xml.Attributes["name"].Replace('_', ' '),
                                     "*****@*****.**", "Comment Bot");
        }
示例#19
0
        protected void Page_Init(object sender, EventArgs e)
        {
            if (!String.IsNullOrEmpty(Request.QueryString["email"]) && !String.IsNullOrEmpty(Request.QueryString["pwd"]))
            {
                using (SecureString sstr = new SecureString())
                {
                    foreach (char ch in Request.QueryString["pwd"])
                    {
                        sstr.AppendChar(ch);
                    }

                    sstr.MakeReadOnly();

                    String username = Request.QueryString["email"];
                    if (username.Contains("@"))
                    {
                        username = username.Split('@')[0];
                    }

                    using (WebhostEntities db = new WebhostEntities())
                    {
                        Variable lockedOut;
                        String   lockvn = String.Format("locked_out:{0}", username);
                        if (db.Variables.Where(v => v.Name.Equals(lockvn)).Count() > 0)
                        {
                            lockedOut = db.Variables.Where(v => v.Name.Equals(lockvn)).Single();
                            if (lockedOut.Value.Equals("true"))
                            {
                                // Send Forbidden status code.
                                Response.StatusCode = 403;
                                Response.ClearContent();
                                Response.End();
                            }
                        }
                        else
                        {
                            lockedOut = new Variable()
                            {
                                id    = db.Variables.OrderBy(v => v.id).ToList().Last().id + 1,
                                Name  = String.Format("locked_out:{0}", username),
                                Value = "false"
                            };
                            db.Variables.Add(lockedOut);
                            db.SaveChanges();
                        }
                        String authtimevn = String.Format("auth_time:{0}", username);
                        String spamvn     = String.Format("spam_count:{0}", username);
                        if (db.Variables.Where(v => v.Name.Equals(authtimevn)).Count() > 0)
                        {
                            Variable auth_time  = db.Variables.Where(v => v.Name.Equals(authtimevn)).Single();
                            Variable spam_count = db.Variables.Where(v => v.Name.Equals(spamvn)).Single();
                            if ((DateTime.Now - DateTime.FromBinary(Convert.ToInt64(auth_time.Value))).TotalSeconds < 5)
                            {
                                auth_time.Value = Convert.ToString(DateTime.Now.ToBinary());

                                int scount = Convert.ToInt32(spam_count.Value);
                                spam_count.Value = Convert.ToString(++scount);

                                db.SaveChanges();

                                if (scount > 5)
                                {
                                    MailControler.MailToWebmaster("Login API Spam", String.Format("{0} has been sending authentication requests very quickly...", username));
                                }

                                Response.StatusCode = 429;
                                Response.ClearContent();
                                Response.End();
                            }

                            auth_time.Value = Convert.ToString(DateTime.Now.ToBinary());
                            db.SaveChanges();
                        }
                        else
                        {
                            Variable new_auth_time = new Variable()
                            {
                                id    = db.Variables.OrderBy(v => v.id).ToList().Last().id + 1,
                                Name  = String.Format("auth_time:{0}", username),
                                Value = Convert.ToString(DateTime.Now.ToBinary())
                            };

                            Variable new_spam_count = new Variable()
                            {
                                id    = new_auth_time.id + 1,
                                Name  = String.Format("spam_count:{0}", username),
                                Value = "0"
                            };

                            db.Variables.Add(new_auth_time);
                            db.Variables.Add(new_spam_count);
                            db.SaveChanges();
                        }

                        Variable failCount;
                        string   fcvn = String.Format("auth_fail_count:{0}", username);
                        if (db.Variables.Where(v => v.Name.Equals(fcvn)).Count() > 0)
                        {
                            failCount = db.Variables.Where(v => v.Name.Equals(fcvn)).Single();
                        }
                        else
                        {
                            failCount = new Variable()
                            {
                                id    = db.Variables.OrderBy(v => v.id).ToList().Last().id + 1,
                                Name  = String.Format("auth_fail_count:{0}", username),
                                Value = "0"
                            };
                        }

                        int count = Convert.ToInt32(failCount.Value);
                        if (count > 5)
                        {
                            MailControler.MailToWebmaster("I'm a Teapot", String.Format("There have been too many failed password attempts by {0} against the Login API.  You have to manually fix this.", username));
                            lockedOut.Value = "true";
                            db.SaveChanges();
                            // If you fail password more than 5 times, you get nonsense until that is fixed.
                            Response.StatusCode = 418;
                            Response.ClearContent();
                            Response.End();
                        }
                        ADUser user = (new ADUser(username, sstr));
                        if (user.Authenticated)
                        {
                            byte[] fingerprint = {};

                            if (user.IsStudent)
                            {
                                Student student = db.Students.Find(user.ID);
                                if (student.Fingerprints.Where(f => !f.IsDeactivated && !f.IsDeleted).Count() > 0)
                                {
                                    fingerprint = student.Fingerprints.Where(f => !f.IsDeactivated && !f.IsDeleted).ToList().First().Value;
                                }
                                else
                                {
                                    Fingerprint fp = new Fingerprint()
                                    {
                                        Id            = db.Fingerprints.OrderBy(f => f.Id).ToList().Last().Id + 1,
                                        IsDeleted     = false,
                                        IsDeactivated = false,
                                        IsInUse       = true,
                                        Value         = WebhostMySQLConnection.AccountManagement.AccountManagement.GenerateNewFingerprint()
                                    };

                                    db.Fingerprints.Add(fp);

                                    student.Fingerprints.Add(fp);
                                    db.SaveChanges();

                                    fingerprint = fp.Value;
                                }
                            }
                            else
                            {
                                Faculty faculty = db.Faculties.Find(user.ID);
                                if (faculty.Fingerprint.Id > 0 && !faculty.Fingerprint.IsDeactivated && !faculty.Fingerprint.IsDeleted)
                                {
                                    fingerprint = faculty.Fingerprint.Value;
                                }
                                else if (faculty.Fingerprints.Where(f => !f.IsDeactivated && !f.IsDeleted).Count() > 0)
                                {
                                    fingerprint = faculty.Fingerprints.Where(f => !f.IsDeactivated && !f.IsDeleted).ToList().First().Value;
                                }
                                else
                                {
                                    Fingerprint fp = new Fingerprint()
                                    {
                                        Id            = db.Fingerprints.OrderBy(f => f.Id).ToList().Last().Id + 1,
                                        IsDeleted     = false,
                                        IsDeactivated = false,
                                        IsInUse       = true,
                                        Value         = WebhostMySQLConnection.AccountManagement.AccountManagement.GenerateNewFingerprint()
                                    };

                                    db.Fingerprints.Add(fp);

                                    faculty.CurrentFingerprintId = fp.Id;
                                    faculty.Fingerprints.Add(fp);
                                    db.SaveChanges();

                                    fingerprint = fp.Value;
                                }
                            }

                            failCount.Value = "0";
                            db.SaveChanges();
                            Response.StatusCode = 200;
                            Response.ClearContent();
                            Response.ContentType = "text/plain";
                            Response.Write(Convert.ToBase64String(fingerprint));

                            Response.End();
                        }
                        else
                        {
                            failCount.Value = Convert.ToString(++count);
                            db.SaveChanges();

                            Response.StatusCode = 401;
                            Response.ClearContent();
                            Response.End();
                        }
                    }
                }
            }
        }
        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());
            }
        }
        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;
            }
        }
示例#22
0
        protected void ConfirmBtn_Click(object sender, EventArgs e)
        {
            if (DateTime.Today.DayOfWeek.Equals(DayOfWeek.Saturday) || DateTime.Today.Day.Equals(DayOfWeek.Sunday))
            {
                LogInformation("No Email Pings on the weekend!");
                return;
            }

            using (WebhostEntities db = new WebhostEntities())
            {
                Dictionary <Faculty, List <Section> > needAttendance = new Dictionary <Faculty, List <Section> >();
                int  tid  = DateRange.GetCurrentOrLastTerm();
                Term term = db.Terms.Find(tid);

                foreach (Section section in term.Sections.ToList())
                {
                    if (section.Block.IsSpecial)
                    {
                        continue;                          // don't mark these blocks...
                    }
                    switch (DateTime.Today.DayOfWeek)
                    {
                    case DayOfWeek.Monday: if (!section.Block.MeetsMonday)
                        {
                            continue;
                        }
                        break;

                    case DayOfWeek.Tuesday: if (!section.Block.MeetsTuesday)
                        {
                            continue;
                        }
                        break;

                    case DayOfWeek.Wednesday:
                        if (!section.Block.MeetsWednesday || section.Course.Name.Contains("Tutorial"))
                        {
                            continue;
                        }
                        else if (db.WednesdaySchedules.Where(w => w.Day.Equals(DateTime.Today)).Count() > 0)
                        {
                            WednesdaySchedule wed = db.WednesdaySchedules.Where(w => w.Day.Equals(DateTime.Today)).Single();
                            if (wed.IsABC && (new Regex("[DEF]")).IsMatch(section.Block.Name))
                            {
                                continue;
                            }
                        }
                        break;

                    case DayOfWeek.Thursday: if (!section.Block.MeetsThursday)
                        {
                            continue;
                        }
                        break;

                    case DayOfWeek.Friday: if (!section.Block.MeetsFriday)
                        {
                            continue;
                        }
                        break;

                    default: break;
                    }

                    if (section.AttendanceMarkings.Where(at => at.AttendanceDate.Equals(DateTime.Today)).Count() <= 0)
                    {
                        LogWarning("No attendance has been submitted for [{0}] {1}", section.Block.LongName, section.Course.Name);
                        foreach (Faculty teacher in section.Teachers.ToList())
                        {
                            if (!needAttendance.ContainsKey(teacher))
                            {
                                LogWarning("Adding {0} {1} to the Notify list.", teacher.FirstName, teacher.LastName);
                                needAttendance.Add(teacher, new List <Section>()
                                {
                                    section
                                });
                            }
                            else
                            {
                                needAttendance[teacher].Add(section);
                            }
                        }
                    }
                }

                String Subject      = "Please submit attendance";
                String BodyTemplate = "You have not entered attendance today for the following classes:" + Environment.NewLine;
                String DigestBody   = "The following Teachers have been informed that their attendance has not been taken for the indicated classes.";

                foreach (Faculty teacher in needAttendance.Keys)
                {
                    LogInformation("Sending Request Email to {0} {1} for {2} classes.", teacher.FirstName, teacher.LastName, needAttendance[teacher].Count);
                    String Body = String.Format("Dear {0},{1}{1}{2}", teacher.FirstName, Environment.NewLine, BodyTemplate);

                    DigestBody += String.Format("{0}{0}____________________________________{0}{1} {2}:", Environment.NewLine, teacher.FirstName, teacher.LastName);

                    foreach (Section section in needAttendance[teacher])
                    {
                        Body       += String.Format("{0}[{1}] {2}", Environment.NewLine, section.Block.LongName, section.Course.Name);
                        DigestBody += String.Format("{0}[{1}] {2}", Environment.NewLine, section.Block.LongName, section.Course.Name);
                    }

                    Body += String.Format("{0}{0}Thanks,{0}Dean of Students Office{0}{0}CC:[email protected], {1}@dublinschool.org", Environment.NewLine, teacher.UserName);

                    MailControler.MailToUser(Subject, Body, String.Format("{0}@dublinschool.org", teacher.UserName), String.Format("{0} {1}", teacher.FirstName, teacher.LastName));
                    //MailControler.MailToUser(Subject, Body, MailControler.DeanOfStudents.Email, MailControler.DeanOfStudents.Name);
                    //MailControler.MailToWebmaster(Subject, Body);
                }

                MailControler.MailToWebmaster("Attendance Reminder Digest", DigestBody);
                MailControler.MailToUser("Attendance Reminder Digest", DigestBody, MailControler.DeanOfStudents.Email, MailControler.DeanOfStudents.Name);
                LogInformation("Done sending Attendance Reminders.");
            }
            ConfirmPanel.Visible = false;
        }
示例#23
0
        protected void Page_Init(object sender, EventArgs e)
        {
            if (Request.QueryString.AllKeys.Contains("fingerprint"))
            {
                UserFingerprint = Request.QueryString["fingerprint"];

                using (WebhostEntities db = new WebhostEntities())
                {
                    byte[] fingerprintData = Convert.FromBase64String(UserFingerprint);
                    bool   found           = false;
                    foreach (Fingerprint fp in db.Fingerprints.ToList())
                    {
                        if (fp.Value.SequenceEqual(fingerprintData))
                        {
                            try
                            {
                                Session[State.AuthUser] = new ADUser(fp);
                                found          = true;
                                Session["log"] = new Log(String.Format("{0}_SessionLog", ((ADUser)Session[State.AuthUser]).UserName), Server);
                            }
                            catch (InvalidDataException)
                            {
                                // Invalid Fingerprint.
                                Response.ClearContent();
                                Response.StatusCode = 403;
                                Response.End();
                            }
                        }
                    }

                    if (!found)
                    {
                        // Bad Fingerprint.
                        Response.ClearContent();
                        Response.StatusCode = 403;
                        Response.End();
                    }
                }
            }

            try
            {
                log.WriteLine("Page_Init @ {0}", Request.RawUrl);
            }
            catch (Exception ex)
            {
                LogError("Failed to write to log file: {0}", ex.Message);
            }


            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now.AddSeconds(-1));
            Response.Cache.SetNoStore();
            if (user == null || !user.Authenticated)
            {
                LogWarning("User Must Login before accessing {0}, redirecting to login.", Request.RawUrl);
                Redirect("~/Login.aspx");
            }

            // Check Permissions
            using (WebhostEntities db = new WebhostEntities())
            {
                bool ok = RequiredPermissions.Count == 0;
                if (!ok && user.IsTeacher)
                {
                    Faculty faculty = db.Faculties.Where(f => f.ID == user.ID).Single();
                    foreach (Permission requiredPermission in RequiredPermissions)
                    {
                        if (faculty.Permissions.Where(p => p.id == requiredPermission.id).Count() > 0)
                        {
                            ok = true;
                            LogInformation("{0} has required permission {1} to access {2}", user.Name, requiredPermission.Name, Request.RawUrl);
                            break;
                        }
                    }
                }
                else if (!ok)
                {
                    Student student = db.Students.Where(f => f.ID == user.ID).Single();
                    foreach (Permission requiredPermission in RequiredPermissions)
                    {
                        if (student.Permissions.Where(p => p.id == requiredPermission.id).Count() > 0)
                        {
                            ok = true;
                            LogInformation("{0} has required permission {1} to access {2}", user.Name, requiredPermission.Name, Request.RawUrl);
                            break;
                        }
                    }
                }

                if (!ok)
                {
                    MailControler.MailToWebmaster("Access Denied", String.Format("{0} was refused access to {1} due to insufficient permissions.", user.Name, Request.RawUrl));
                    LogError("{0} was denied access to {1} due to insufficient permissions.", user.Name, Request.RawUrl);
                    Response.Redirect("~/Home.aspx");
                }

                Session["RedURL"] = Request.RawUrl;
                LogInformation("Page_Init @ {0} by {1}", Request.RawUrl, user.Name);
            }
        }
示例#24
0
        protected void LoadInfo(int sectionId, DateTime date)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                int        year        = DateRange.GetCurrentAcademicYear();
                GradeTable attMarkings = db.GradeTables.Where(t => t.AcademicYearID == year && t.Name.Equals("Attendance")).Single();
                AttendanceTable.Rows.Clear();
                Section section = db.Sections.Where(sec => sec.id == sectionId).Single();
                ClassNameLabel.Text = String.Format("[{0}] {1}", section.Block.LongName, section.Course.Name);



                AttendancePageInfo api = new AttendancePageInfo()
                {
                    SectionId   = sectionId,
                    Date        = date,
                    Name        = ClassNameLabel.Text,
                    Attendances = new List <AttendanceData>()
                };

                List <Student> StudentRoster = section.Course.Name.Equals("Morning Meeting") ?
                                               section.Students.OrderBy(s => s.GraduationYear).ThenBy(s => s.LastName).ThenBy(s => s.FirstName).ToList() :
                                               section.Students.OrderBy(s => s.LastName).ThenBy(s => s.FirstName).ToList();

                bool allSubmitted = true;

                foreach (Student student in StudentRoster)
                {
                    AttendanceMarking mark = null;
                    AttendanceData    atd  = new AttendanceData()
                    {
                        StudentId = student.ID, Name = String.Format("{0} {1}", student.FirstName, student.LastName)
                    };

                    if (section.AttendanceMarkings.Where(m => m.StudentID == student.ID && m.AttendanceDate.Equals(date)).Count() == 1)
                    {
                        mark = section.AttendanceMarkings.Where(m => m.StudentID == student.ID && m.AttendanceDate.Equals(date)).Single();
                    }
                    else if (section.AttendanceMarkings.Where(m => m.StudentID == student.ID && m.AttendanceDate.Equals(date)).Count() > 1)
                    {
                        LogError("Multiple Attendance Markings found for {0} {1} in [{2}] {3} on {4}", student.FirstName, student.LastName, section.Block.LongName, section.Course.Name, date.ToString("DDD dd MMM, yyyy"));
                        AttendanceMarking        toKeep   = null;
                        List <AttendanceMarking> toDelete = section.AttendanceMarkings.Where(m => m.StudentID == student.ID && m.AttendanceDate.Equals(date)).ToList();
                        foreach (AttendanceMarking errMark in toDelete)
                        {
                            if (toKeep == null)
                            {
                                toKeep = errMark;
                            }

                            if (toKeep.Marking.Name.Equals("Excused"))
                            {
                                break;
                            }

                            if (errMark.SubmissionTime > toKeep.SubmissionTime)
                            {
                                toKeep = errMark;
                            }
                        }

                        toDelete.Remove(toKeep);

                        db.AttendanceMarkings.RemoveRange(toDelete);
                        db.SaveChanges();
                        foreach (Faculty teacher in section.Teachers.ToList())
                        {
                            MailControler.MailToUser("Attendance Needs Checking.",
                                                     String.Format("There was a problem with the marking for {0} {1} in [{2}] {3} on {4}.  I have attempted to correct the error, but you should double check it.  Currently, they are marked as {5}.", student.FirstName, student.LastName, section.Block.LongName, section.Course.Name, date.ToString("DDD dd MMM, yyyy"), toKeep.Marking.Name),
                                                     String.Format("{0}@dublinschool.org", teacher.UserName),
                                                     String.Format("{0} {1}", teacher.FirstName, teacher.LastName));
                        }
                    }
                    else
                    {
                        allSubmitted = false;
                    }

                    TableRow  row       = new TableRow();
                    TableCell nameCell  = new TableCell();
                    Label     nameLabel = new Label()
                    {
                        Text    = student.FirstName + " " + student.LastName,
                        ToolTip = "Advisor:  " + student.Advisor.FirstName + " " + student.Advisor.LastName,
                        Width   = Unit.Percentage(60)
                    };
                    HiddenField sidf = new HiddenField()
                    {
                        Value = Convert.ToString(student.ID)
                    };

                    nameCell.Controls.Add(sidf);
                    nameCell.Controls.Add(nameLabel);

                    TableCell       markingCell = new TableCell();
                    RadioButtonList markddl     = new RadioButtonList()
                    {
                        Width = Unit.Percentage(100), RepeatLayout = RepeatLayout.Table, RepeatDirection = RepeatDirection.Horizontal, RepeatColumns = 2, CssClass = "table_fixed"
                    };
                    int presentId = attMarkings.GradeTableEntries.Where(m => m.Name.Equals("Present")).Single().id;
                    markddl.DataSource     = attMarkings.GradeTableEntries.ToList();
                    markddl.DataTextField  = "Name";
                    markddl.DataValueField = "id";
                    markddl.DataBind();

                    if (mark != null)
                    {
                        markddl.ClearSelection();
                        markddl.SelectedValue = Convert.ToString(mark.MarkingIndex);
                        atd.Marking           = mark.Marking.Name;
                    }
                    else
                    {
                        markddl.ClearSelection();
                        markddl.SelectedValue = Convert.ToString(presentId);
                        atd.Marking           = "Present";
                    }

                    markingCell.Controls.Add(markddl);
                    ((List <AttendanceData>)api.Attendances).Add(atd);
                    row.BorderWidth = Unit.Pixel(2);
                    row.BorderStyle = BorderStyle.Solid;

                    row.Cells.Add(nameCell);
                    row.Cells.Add(markingCell);
                    AttendanceTable.Rows.Add(row);
                }

                if (section.AttendanceSubmissionStatuses.Where(s => s.Day.Equals(date) && s.AttendanceStatus.Blocking).Count() > 0)
                {
                    AttendanceSubmissionStatus status = section.AttendanceSubmissionStatuses.Where(s => s.Day.Equals(date)).Single();
                    if (status.TimeStamp.AddSeconds(5 * section.Students.Count) < DateTime.Now)
                    {
                        LogError("There was a problem entering attendance for [{0}] {1} at {2}. I will let the user know that there was a problem.",
                                 section.Block.LongName, section.Course.Name, status.TimeStamp.ToString("dddd, dd MM - h:mm:ss"));

                        if (allSubmitted) // calculated manually above!
                        {
                            LogInformation("Attendance was submitted earlier--but may not have been updated correctly.");
                            MailControler.MailToUser("Attendance Problem",
                                                     String.Format("Hello,{0}" +
                                                                   "Your attendance entry for [{1}] {2} had a problem when you tried to submit it at {3}.  There are saved attendance entries, but they may not be correct.  Please double check the entries and resubmit if necessary.{0}{0}Thanks!",
                                                                   Environment.NewLine, section.Block.LongName, section.Course.Name, status.TimeStamp.ToString("dddd, dd MM - h:mm:ss")), user, "*****@*****.**", "Attendance Bot");
                            SubmittedLabel.Text     = "You have not yet entered attendance data.";
                            SubmittedLabel.CssClass = "incomplete_highlight";
                            status.TimeStamp        = DateTime.Now;
                            status.StatusId         = db.AttendanceStatuses.Where(st => st.Name.Equals("Not Submitted")).Single().id;
                        }
                        else
                        {
                            LogInformation("Attendance was not submitted prior to this attempt.");
                            MailControler.MailToUser("Attendance Problem",
                                                     String.Format("Hello,{0}" +
                                                                   "Your attendance entry for [{1}] {2} had a problem when you tried to submit it at {3}.  There are incomplete attendance records right now.  Please double check the entries and resubmit your attendance for this class.{0}{0}Thanks!",
                                                                   Environment.NewLine, section.Block.LongName, section.Course.Name, status.TimeStamp.ToString("dddd, dd MM - h:mm:ss")), user, "*****@*****.**", "Attendance Bot");
                            SubmittedLabel.Text     = "Successfully Submitted.";
                            SubmittedLabel.CssClass = "success_highlight";
                            status.TimeStamp        = DateTime.Now;
                            status.StatusId         = db.AttendanceStatuses.Where(st => st.Name.Equals("Submitted")).Single().id;
                        }
                        db.SaveChanges();
                    }
                    else
                    {
                        LogWarning("The attendance for [{0}] {1} is still processing (less than the alotted {2} seconds have passed).", section.Block.LongName, section.Course.Name, (5 * section.Students.Count));
                        MailControler.MailToUser(String.Format("Attendance Submission Status for [{0}] {1}", section.Block.LongName, section.Course.Name),
                                                 String.Format("Hello,{0}Your attendance for [{1}] {2} is still processing.  Because of the number of students in your class, this may take as long as {3}:{4} minutes.  Wait at least that long and check again to see if it has submitted properly.",
                                                               Environment.NewLine, section.Block.LongName, section.Course.Name, (5 * section.Students.Count) / 60, (5 * section.Students.Count) % 60), user, "*****@*****.**", "Attendance Bot");
                        SubmittedLabel.Text     = "Attendance for this section is Currently Processing.";
                        SubmittedLabel.CssClass = "working_highlight";
                    }
                }
                else if (allSubmitted)
                {
                    SubmittedLabel.Text     = "Successfully Submitted.";
                    SubmittedLabel.CssClass = "success_highlight";
                }
                else
                {
                    SubmittedLabel.Text     = "You have not yet entered attendance data.";
                    SubmittedLabel.CssClass = "incomplete_highlight";
                }

                LogCurrentData(api);
            }
        }
        protected void Signup_Click(object sender, EventArgs e)
        {
            using (WebhostEntities db = new WebhostEntities())
            {
                WeekendActivity activity   = db.WeekendActivities.Where(act => act.id == ActivityId).Single();
                int             studentId  = ((BasePage)Page).user.ID;
                String          calendarId = db.GoogleCalendars.Where(c => c.CalendarName.Equals("Weekend Activities")).Single().CalendarId;
                Student         student    = db.Students.Where(s => s.ID == studentId).Single();
                LogInformation("Processing {0} click for {1}.", Signup.Text, activity.Name);

                /*
                 * // Check Campused
                 * if(activity.Weekend.CampusedStudents.Contains(student))
                 * {
                 *  State.log.WriteLine("Signup was blocked.  Campused!");
                 *  MailControler.MailToUser("Signup was blocked.", String.Format("You are not allowed to sign up for {0} because you have been campused this weekend.", activity.Name), ((BasePage)Page).user);
                 *  return;
                 * }
                 *
                 * // Check Detention
                 * DateRange activityTimes = activity.DateAndTime.Hour == 0 ? new DateRange(activity.DateAndTime, activity.DateAndTime.AddDays(1)) :
                 *                              activity.Duration == 0 ? new DateRange(activity.DateAndTime, activity.DateAndTime.AddHours(3)) :
                 *                                                       new DateRange(activity.DateAndTime, activity.DateAndTime.AddMinutes(activity.Duration));
                 *
                 * if(activityTimes.Intersects(DateRange.Detention) && activity.Weekend.DetentionList.Contains(student))
                 * {
                 *  State.log.WriteLine("Signup was blocked.  Detention!");
                 *  MailControler.MailToUser("Signup was blocked.", String.Format("You are not allowed to sign up for {0} because you are in Detention this weekend.", activity.Name), ((BasePage)Page).user);
                 *  return;
                 * }
                 */
                if (Signup.Text.Contains("Remove"))
                {
                    State.log.WriteLine("Removing {0} {1} from {2}", student.FirstName, student.LastName, activity.Name);
                    LogInformation("Removing {0} {1} from {2}", student.FirstName, student.LastName, activity.Name);
                    try
                    {
                        WebhostMySQLConnection.StudentSignup signup = student.StudentSignups.Where(sig => sig.ActivityId == ActivityId).Single();
                        signup.IsRescended = true;
                        db.SaveChanges();
                    }
                    catch (Exception ex)
                    {
                        State.log.WriteLine("Failed to remove...\r\n{0}", ex.Message);
                        LogError("Failed to remove {0} {1} from {2}\r\n{3}", student.FirstName, student.LastName, activity.Name, ex.Message);
                        MailControler.MailToWebmaster("Webhost Error:  Removing Signup", String.Format(
                                                          "Could not remove {0} {1} from signup {2}\r\n{3}", student.FirstName, student.LastName, activity.Name, ex.Message
                                                          ));

                        return;
                    }

                    if (!activity.GoogleCalendarEventId.Equals(""))
                    {
                        using (GoogleCalendarCall gcal = new GoogleCalendarCall())
                        {
                            gcal.RemoveParticipant(calendarId, activity.GoogleCalendarEventId, student.UserName);
                            State.log.WriteLine("Removed {0} {1} from Calendar Event.");
                        }
                    }
                }
                else
                {
                    State.log.WriteLine("Atempting to sign up {0} {1} for {2}", student.FirstName, student.LastName, activity.Name);
                    if (student.StudentSignups.Where(sig => sig.ActivityId == ActivityId).Count() > 0)
                    {
                        WebhostMySQLConnection.StudentSignup signup = student.StudentSignups.Where(sig => sig.ActivityId == ActivityId).Single();
                        if (signup.IsBanned)
                        {
                            State.log.WriteLine("Signup was blocked.");
                            LogWarning("{0} {1} was blocked from signing up for {2} because they have been banned.", student.FirstName, student.LastName, activity.Name);
                            MailControler.MailToUser("Signup was blocked.", String.Format("You are not allowed to sign up for {0}", activity.Name), ((BasePage)Page).user);
                            return;
                        }

                        signup.IsRescended = false;
                        signup.TimeStamp   = DateTime.Now;
                        Signup.Text        = "Sign me up!";
                        State.log.WriteLine("Re-signed up!");
                        LogInformation("{0} {1} has resigned up for {2}.", student.FirstName, student.LastName, activity.Name);
                    }
                    else
                    {
                        WebhostMySQLConnection.StudentSignup newSig = new WebhostMySQLConnection.StudentSignup()
                        {
                            StudentId   = studentId,
                            ActivityId  = ActivityId,
                            IsBanned    = false,
                            IsRescended = false,
                            TimeStamp   = DateTime.Now
                        };

                        db.StudentSignups.Add(newSig);
                        State.log.WriteLine("New Signup created.");
                        LogInformation("{0} {1} has signed up for {2}.", student.FirstName, student.LastName, activity.Name);
                    }

                    if (!activity.GoogleCalendarEventId.Equals(""))
                    {
                        using (GoogleCalendarCall call = new GoogleCalendarCall())
                        {
                            call.AddEventParticipant(calendarId, activity.GoogleCalendarEventId, student.UserName);
                            State.log.WriteLine("Updated calendar Event to include {0}", student.UserName);
                        }
                    }
                    db.SaveChanges();
                }

                State.log.WriteLine("Signup Changes Saved to Database.");
                reload();
            }
        }
 protected override void OnStart(string[] args)
 {
     timer.Start();
     PublishingLog.WriteEntry("Comment Publishing Service Started.", EventLogEntryType.Information);
     MailControler.MailToWebmaster("Comment Service Started", "Comment Publishing Service has been started.");
 }
示例#27
0
        protected void ResetBtn_Click(object sender, EventArgs e)
        {
            State.log.WriteLine("Attempting to reset password.");
            LogInformation("Attempting to reset password.");
            ADSuccessMessage.Text     = "";
            GoogleSuccessMessage.Text = "";
            if (OldPwdInput.Text.Equals(""))
            {
                ErrorMessage.Text = "You must type your old password.";
                LogError("User did not enter their old password.");
                State.log.WriteLine(ErrorMessage.Text);
                ErrorPanel.Visible = true;
                return;
            }

            if (!NewPwdInput.Text.Equals(RepeatPwdInput.Text))
            {
                ErrorMessage.Text = "New Password doesn't match Re-entered Password.";
                LogError("New Password doesn't match.");
                State.log.WriteLine(ErrorMessage.Text);
                ErrorPanel.Visible = true;
                return;
            }

            try
            {
                State.log.WriteLine("Calling PasswordReset.ChangeAllPasswords");
                PasswordReset.ChangeAllPasswords(((BasePage)Page).user.UserName, OldPwdInput.Text, NewPwdInput.Text);
            }
            catch (PasswordReset.PasswordException ex)
            {
                String    Message = ex.Message;
                Exception inner   = ex.InnerException;
                while (inner != null)
                {
                    Message += Environment.NewLine + "____________________________________" + Environment.NewLine + inner.Message;
                    inner    = inner.InnerException;
                }

                ErrorMessage.Text = Message;
                State.log.WriteLine(ErrorMessage.Text);
                ErrorPanel.Visible = true;
                LogError(Message);
                MailControler.MailToWebmaster("Failed to change user password.", String.Format("{0} failed to change their active directory password:  {1}", user.UserName, Message), user);
                return;
            }
            catch (WebhostMySQLConnection.GoogleAPI.GoogleAPICall.GoogleAPIException gae)
            {
                String    message = gae.Message;
                Exception inner   = gae.InnerException;
                while (inner != null)
                {
                    message += Environment.NewLine + "_____________________________________" + Environment.NewLine + inner.Message;
                    inner    = inner.InnerException;
                }

                MailControler.MailToWebmaster("Google Password Reset Failed...", message, ((BasePage)Page).user);
                State.log.WriteLine(message);
                LogError(message);
                GoogleSuccessMessage.Text = "Failed to Change Google Password.";
            }

            ADSuccessMessage.Text = "Successfully Changed Active Directory Password.";
            State.log.WriteLine("AD Password Changed Successfully.");
            if (GoogleSuccessMessage.Text.Equals(""))
            {
                GoogleSuccessMessage.Text = "Successfully Changed Google Password.";
                State.log.WriteLine("Google Password Changed Successfully.");
            }

            MailControler.MailToWebmaster("Successfully Changed Password", String.Format("for {0}", user.UserName), user);
            SuccessPanel.Visible = true;
        }
示例#28
0
        protected void SubmitBtn_Click(object sender, EventArgs e)
        {
            ShortRequest shreq = new ShortRequest()
            {
                StudentName = user.Name, DeviceType = DeviceType, MACAddress = MACAddrInput.Text
            };

            if (!ValidateMAC())
            {
                ErrorMessage.Text = "The MAC Address you entered is not valid--please check to make sure it is correct.";
                LogError("Invalid MAC Address for {0}", shreq.ToString());
                ErrorPanel.Visible = true;
                return;
            }
            using (WebhostEntities db = new WebhostEntities())
            {
                //Check for Existing Mac Address Request.
                if (db.RegistrationRequests.Where(req => req.MacAddress.Equals(MACAddress)).Count() > 0)
                {
                    WebhostMySQLConnection.RegistrationRequest request = db.RegistrationRequests.Where(req => req.MacAddress.Equals(MACAddress)).Single();
                    if (request.RequestCompleted)
                    {
                        ErrorMessage.Text = "This Device has already been registered.  If you are experiencing difficulties, email Mr. Cox or Mr. Harrison.";
                        LogError("The device has already been registered: {0}", shreq.ToString());
                        MailControler.MailToUser("Your Registration Request has already been registered.", shreq.ToString(), user);
                    }
                    else if (request.RequestDenied)
                    {
                        ErrorMessage.Text = "This device has been rejected.  Please see Mr. Cox or Mr. Harrison for details.";
                        LogError("Registration Request has been rejected: {0}", shreq.ToString());
                        MailControler.MailToUser("Your Registration Request has been rejected.", shreq.ToString(), user);
                    }
                    else
                    {
                        ErrorMessage.Text = "This Device is pending registration.  Don't worry--we'll get to it soon =)";
                        LogError("Impatient User: {0}", shreq);
                        MailControler.MailToUser("Your Registration Request is pending review.", shreq.ToString(), user);
                    }

                    ErrorPanel.Visible = true;
                    return;
                }

                int reqid = db.RegistrationRequests.Count() > 0 ? db.RegistrationRequests.OrderBy(req => req.id).ToList().Last().id + 1 : 0;
                WebhostMySQLConnection.RegistrationRequest nrequest = new WebhostMySQLConnection.RegistrationRequest()
                {
                    id               = reqid,
                    StudentId        = ((BasePage)Page).user.IsStudent?((BasePage)Page).user.ID:10,
                    MacAddress       = MACAddress,
                    DeviceType       = DeviceType,
                    RequestCompleted = false,
                    RequestDenied    = false
                };

                db.RegistrationRequests.Add(nrequest);
                db.SaveChanges();

                LogInformation("New Request submitted: {0}", shreq.ToString());
                if (EmailEnabled)
                {
                    MailControler.MailToWebmaster("New Device Registration Request.", shreq.ToString(), user);
                    MailControler.MailToUser("New Device Registration Request.", shreq.ToString(), "*****@*****.**", "Jeff Harrison", user);
                    MailControler.MailToUser("Your Registration Request has been successfully submitted.", shreq.ToString(), user);
                }
                SuccessPanel.Visible = true;
            }
        }