Пример #1
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!");
 }
Пример #2
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);
        }
 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.");
 }
Пример #4
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...");
 }
Пример #5
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);
        }
Пример #6
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);
        }
Пример #7
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);
        }
Пример #8
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;
                }
            }
        }
Пример #9
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;
        }
Пример #10
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);
        }
Пример #11
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;
            }
        }
 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.");
 }
Пример #13
0
        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();
            }
        }
Пример #14
0
        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());
            }
        }
Пример #15
0
        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;
            }
        }
Пример #16
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);
            }
        }
Пример #17
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;
        }
Пример #18
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();
                        }
                    }
                }
            }
        }
Пример #19
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;
        }