public async Task <IActionResult> Get()
        {
            var token = HttpContext.Request.Headers["Authorization"].Last().Split(" ").Last();

            string[] roles = { "Admin", "SchoolAdmin" };

            if (RoleService.CheckRoles(token, roles, _userManager))
            {
                var repo    = new SchoolRepository();
                var userIds = repo.GetAll()
                              .Select(x => new
                {
                    Name    = x.Name,
                    UserIds = x.Users.Select(x => x.UserId)
                }).ToDictionary(x => x.Name, x => x.UserIds);

                var SchoolsUsers = new Dictionary <string, List <User> >();

                foreach (var school in userIds.Keys)
                {
                    SchoolsUsers.Add(school, userIds[school].Select(x => _userManager.FindByIdAsync(x).Result).ToList());
                }

                var detailsRepo = new UserDetailsRepository();


                //Produces summary for each school with summaries for each of students.
                var result = repo.GetAll().Select(x => new SchoolSummary(x.Id, x.Name, SchoolsUsers[x.Name]
                                                                         .Select(x => UserSummaryFactory.CreateSummary(detailsRepo.GetById(x.DetailsId), x)).ToList())).ToList();

                return(Ok(result));
            }

            return(Unauthorized("Only Admin and SchoolAdmin roles have permission to this controller."));
        }
Esempio n. 2
0
        public async Task <IActionResult> GetUsersInSchool(int id)
        {
            var token = HttpContext.Request.Headers["Authorization"].Last().Split(" ").Last();

            string[] roles      = { "Admin", "SchoolAdmin" };
            var      schoolRepo = new SchoolRepository();

            if (!schoolRepo.GetAll().Select(x => x.Id).Contains(id))
            {
                return(BadRequest("Not such id"));
            }


            if (RoleService.CheckRoles(token, roles, _userManager))
            {
                if (RoleService.CheckRole(token, "Admin", _userManager))
                {
                    if (id == 0)
                    {
                        var detailsRepo = new UserDetailsRepository();
                        var result      = detailsRepo.GetAll().Select(x => UserSummaryFactory
                                                                      .CreateSummary(x, _userManager.FindByIdAsync(x.UserId).Result)).ToList();

                        return(Ok(result));
                    }
                    else
                    {
                        try
                        {
                            var school = schoolRepo.GetAll().First(x => x.Id == id);
                            var result = school.Users.Select(x => UserSummaryFactory
                                                             .CreateSummary(x, _userManager.FindByIdAsync(x.UserId).Result)).ToList();

                            return(Ok(result));
                        }
                        catch (Exception e)
                        {
                            NotFound(e.Message);
                        }
                    }
                }
                else
                {
                    try
                    {
                        var school = schoolRepo.GetAll().First(x => x.Id == id);
                        var result = school.Users.Select(x => UserSummaryFactory
                                                         .CreateSummary(x, _userManager.FindByIdAsync(x.UserId).Result)).ToList();

                        return(Ok(result));
                    }
                    catch (Exception e)
                    {
                        NotFound(e.Message);
                    }
                }
            }

            return(Unauthorized("Only Admin, SchoolAdmin have access to this controller."));
        }
        public void Delete_Normal_Conditions()
        {
            var repo   = new SchoolRepository();
            var school = new School("East High School");
            var count  = repo.GetAll().Count();

            repo.Add(school);
            repo.Delete(school);
            Assert.True(count == repo.GetAll().Count());
        }
        public void GetAllUsersInSchool()
        {
            var repo     = new SchoolRepository();
            var userRepo = new UserDetailsRepository();
            var schoolId = repo.GetAll().Last().Id;

            userRepo.Add(new UserDetails("null", null, schoolId));
            var users = repo.GetAll().Last().Users;

            Assert.True(users.Count > 0);
        }
        public MemoryStream GenerateCSV()
        {
            MemoryStream outStream = new MemoryStream();
            StreamWriter writer    = new StreamWriter(outStream);

            // Headings
            writer.Write("SchoolCode" + delimiter);
            writer.Write("Name" + delimiter);
            writer.Write("SchoolType");
            writer.Write(Environment.NewLine);

            SchoolRepository _schoolRepo = new SchoolRepository(_dbConnectionString);

            foreach (School school in _schoolRepo.GetAll())
            {
                writer.Write(stringContainer + school.DAN + stringContainer + delimiter);
                writer.Write(stringContainer + school.Name + stringContainer + delimiter);
                writer.Write(stringContainer + (school.IsHighSchool ? 1 : 2) + stringContainer);
                writer.Write(Environment.NewLine);
            }

            writer.Flush();
            outStream.Flush();
            return(outStream);
        }
Esempio n. 6
0
        public async Task <JsonResult> Update(MSchool school, string id)
        {
            ErrorCodes result;
            string     html       = "";
            var        schoolinfo = TempData.Get <MSchool>("schoolitem");

            schoolinfo.CopySchoolInfo(school);
            try
            {
                result = SchoolRepository.Update(ref schoolinfo, GetLogedinUser(), id);
            }
            catch (ENovateException eex)
            {
                Log.Logger.Error(eex, "Failed to update the school name: " + school.MsName);
                result = eex.ErrorCode;
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Failed to update the shool.");
                result = ErrorCodes.SaveFailure;
            }
            if (result == ErrorCodes.None)
            {
                List <MSchool> schools = SchoolRepository.GetAll();
                html = await ViewRenderService.RenderViewToStringAsync("~/Areas/Admin/Views/School/_List.cshtml", schools);

                TempData.Put("AllSchools", schools);
            }
            string msg = (result == ErrorCodes.None) ? StringLocalizer["I.HSP-M002.0017"].Value
                                                     : StringLocalizer[result.GetResourceKey()].Value;

            return(Json(new { status = (result == ErrorCodes.None) ? Result.Success : Result.Failure, message = msg, html }));
        }
Esempio n. 7
0
        public async Task <JsonResult> LoadTable()
        {
            List <MSchool> schools  = SchoolRepository.GetAll();
            string         htmlform = await ViewRenderService.RenderViewToStringAsync("~/Areas/Admin/Views/School/_List.cshtml", schools);

            return(Json(new { status = 0, htmlform }));
        }
Esempio n. 8
0
        public async Task <JsonResult> Delete(string ids)
        {
            ErrorCodes result;
            string     html = "";

            try
            {
                result = SchoolRepository.Delete(ids, GetLogedinUser());
            }
            catch (ENovateException eex)
            {
                Log.Logger.Error(eex, "Failed to delete the school.");
                result = eex.ErrorCode;
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Failed to delete the shool.");
                result = ErrorCodes.SaveFailure;
            }
            if (result == ErrorCodes.None)
            {
                List <MSchool> schools = SchoolRepository.GetAll();
                html = await ViewRenderService.RenderViewToStringAsync("~/Areas/Admin/Views/School/_List.cshtml", schools);
            }
            string msg = (result == ErrorCodes.None) ? StringLocalizer["I.HSP-M002.0005"].Value
                                                     : StringLocalizer[result.GetResourceKey()].Value;

            return(Json(new { status = (result == ErrorCodes.None) ? Result.Success : Result.Failure, message = msg, html }));
        }
Esempio n. 9
0
 public JsonResult GetAll()
 {
     using (var schoolRepository = new SchoolRepository())
     {
         return(Json(schoolRepository.GetAll(), JsonRequestBehavior.AllowGet));
     }
 }
Esempio n. 10
0
        public void GetSchools()
        {
            IRepositoryContext uow = new EntityFrameworkRepositoryContext();
            var repo   = new SchoolRepository(uow);
            var result = repo.GetAll();

            Assert.IsTrue(result.Count() > 0);
        }
Esempio n. 11
0
        public IActionResult SchoolList()
        {
            var schools = SchoolRepository
                          .GetAll()
                          .Select(x => Mapper.Map <SchoolViewModel>(x))
                          .ToList();

            return(View(schools));
        }
Esempio n. 12
0
        public void Edit_Normal_Conditions()
        {
            var repo   = new SchoolRepository();
            var school = new School("Scotland High School");

            repo.Add(school);
            school.Name = "South High School";
            repo.Edit(school);
            Assert.True(repo.GetAll().Last().Name == "South High School");
        }
Esempio n. 13
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="request"></param>
        /// <returns></returns>
        public List <SchoolModel> GetSchools()
        {
            var items = SchoolRepository.GetAll();

            if (items != null)
            {
                return(items.Select(p => p.ToModel()).ToList());
            }
            return(new List <SchoolModel>());
        }
Esempio n. 14
0
        public IActionResult Index()
        {
            List <MSchool> schools;

            try
            {
                schools = SchoolRepository.GetAll();
            }
            catch (Exception ex)
            {
                Log.Logger.Error(ex, "Get all schools from database");
                schools = new List <MSchool>();
            }
            TempData.Put("AllSchools", schools);
            return(View(schools));
        }
Esempio n. 15
0
        /// <summary>
        /// When the page loads, fetch all the schools
        /// </summary>
        /// <returns></returns>
        protected override async Task OnInitializedAsync()
        {
            try
            {
                Loading = true;

                var data = await SchoolRepository.GetAll().ConfigureAwait(false);

                SchoolList = data.ToList();

                Loading = false;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
                showError    = true;
            }
        }
        public MemoryStream GenerateCSV()
        {
            MemoryStream outStream = new MemoryStream();
            StreamWriter writer    = new StreamWriter(outStream);

            // Headings
            writer.Write("SchoolCode" + delimiter);
            writer.Write("CourseCode" + delimiter);
            writer.Write("CourseName" + delimiter);
            writer.Write("CreditValue" + delimiter);
            writer.Write("GradeLower" + delimiter);
            writer.Write("GradeUpper");
            writer.Write(Environment.NewLine);

            // HIGH SCHOOL CLASSES ONLY
            // - Or more specifically, courses that offer more than zero credits

            // Get all classes
            // Make a list of all courses offered

            SchoolClassRepository classRepository  = new SchoolClassRepository(_dbConnectionString);
            CourseRepository      courseRepository = new CourseRepository(_dbConnectionString);
            SchoolRepository      schoolRepo       = new SchoolRepository(_dbConnectionString);

            List <Course> coursesWithCredits = courseRepository.GetAll().Where(x => x.Credits > 0 && x.CurrentlyOffered).ToList();

            foreach (School school in schoolRepo.GetAll().Where(x => x.IsHighSchool))
            {
                foreach (Course course in coursesWithCredits)
                {
                    writer.Write(stringContainer + school.GovernmentID + stringContainer + delimiter);
                    writer.Write(stringContainer + course.CourseCode + stringContainer + delimiter);
                    writer.Write(stringContainer + course.Name + stringContainer + delimiter);
                    writer.Write(stringContainer + course.Credits + stringContainer + delimiter);
                    writer.Write(stringContainer + course.LowGrade + stringContainer + delimiter);
                    writer.Write(stringContainer + course.HighGrade + stringContainer);
                    writer.Write(Environment.NewLine);
                }
            }

            writer.Flush();
            outStream.Flush();
            return(outStream);
        }
 public IEnumerable <School> Get()
 {
     return(repository.GetAll());
 }
Esempio n. 18
0
        static void Main(string[] args)
        {
            if (args.Any())
            {
                string        fileName = string.Empty;
                string        date     = string.Empty;
                List <string> grades   = new List <string>()
                {
                    "pk", "k", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"
                };
                bool          allSchools = false;
                List <string> options    = new List <string>();

                List <string> selectedSchoolIDs = new List <string>();

                foreach (string argument in args)
                {
                    if (argument.ToLower().StartsWith("/schoolid:"))
                    {
                        foreach (string enteredID in argument.Substring(10, argument.Length - 10).Split(new char[] { ';', ',' }))
                        {
                            if (!string.IsNullOrEmpty(enteredID))
                            {
                                selectedSchoolIDs.Add(enteredID);
                            }
                        }
                    }
                    else if (argument.ToLower().StartsWith("/allschools"))
                    {
                        options.Add("allschools");
                        allSchools = true;
                    }
                    else if (argument.ToLower().StartsWith("/filename:"))
                    {
                        fileName = argument.Substring(10, argument.Length - 10);
                    }
                    else if (argument.ToLower().StartsWith("/logfilename:"))
                    {
                        Log.LogFileName = argument.Substring(13, argument.Length - 13);
                    }
                    else if (argument.ToLower().StartsWith("/date:"))
                    {
                        date = argument.Substring(6, argument.Length - 6);
                        if (date.ToLower().Equals("today"))
                        {
                            date = DateTime.Today.ToString();
                        }
                        if (date.ToLower().Equals("yesterday"))
                        {
                            date = Helpers.GetPreviousBusinessDay(DateTime.Today).ToString();
                        }
                        if (date.ToLower().Equals("now"))
                        {
                            date = DateTime.Now.ToString();
                        }
                    }
                    else if (argument.ToLower().StartsWith("/grades:"))
                    {
                        string gradesRaw = argument.Substring(8, argument.Length - 8).Trim('\"').Trim();
                        grades = new List <string>();
                        Log.ToLog("Limiting student selection to specific grades");
                        foreach (string ss in gradesRaw.Split(','))
                        {
                            if (string.IsNullOrEmpty(ss))
                            {
                                grades.Add(ss.ToLower());

                                Log.ToLog(" Adding grade \"" + ss + "\"");
                            }
                        }
                    }
                }

                if (((selectedSchoolIDs.Count <= 0) && (!allSchools)) || (string.IsNullOrEmpty(fileName)) || (string.IsNullOrEmpty(date)))
                {
                    SendSyntax();
                }
                else
                {
                    if (Config.ConfigFileExists())
                    {
                        DateTime parsedDate = Helpers.ParseDate(date);

                        try
                        {
                            Log.ToLog("----------------------------------------------------------------");
                            Log.Info("Started: " + DateTime.Now);
                            Log.Info("Date: " + date);
                            Log.Info("Output: " + fileName);
                            Log.Info("Grades: " + grades.ToCommaSeparatedString());
                            Log.Info("Options: " + options.ToCommaSeparatedString());
                            Log.Info("Schools: " + (allSchools ? "ALL" : selectedSchoolIDs.ToCommaSeparatedString()));

                            List <Student> reportStudents  = new List <Student>();
                            List <School>  selectedSchools = new List <School>();

                            ContactRepository contactRepo = new ContactRepository();
                            StudentRepository studentRepo = new StudentRepository();
                            using (SqlConnection connection = new SqlConnection(Config.dbConnectionString_SchoolLogic))
                            {
                                SchoolRepository schoolRepo = new SchoolRepository(connection);

                                if (allSchools)
                                {
                                    selectedSchools = schoolRepo.GetAll();
                                }
                                else
                                {
                                    selectedSchools = schoolRepo.Get(selectedSchoolIDs);
                                }

                                Log.Info("Loading students");
                                foreach (School school in selectedSchools)
                                {
                                    List <Student> schoolStudents = studentRepo.LoadForSchool(connection, school,
                                                                                              parsedDate).Where(s => grades.Contains(s.Grade.ToLower())).ToList();

                                    Log.Info("Loaded " + schoolStudents.Count + " students for school " +
                                             school.Name);

                                    // Load student contacts
                                    Log.Info("Loading student contacts");
                                    foreach (Student student in schoolStudents)
                                    {
                                        student.Contacts = contactRepo.LoadForStudent(connection, student.DatabaseID);
                                    }
                                    reportStudents.AddRange(schoolStudents);
                                }
                            }


                            Log.Info("Creating CSV data");
                            MemoryStream csvContents = AddressBookCSV.GenerateCSV(reportStudents);
                            Log.Info("Saving CSV file (" + fileName + ")");
                            if (FileHelpers.FileExists(fileName))
                            {
                                FileHelpers.DeleteFile(fileName);
                            }
                            FileHelpers.SaveFile(csvContents, fileName);
                            Log.Info("Done!");
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.Message);
                        }
                    }
                    else
                    {
                        Log.Error("Configuration file not found");
                        Log.Info("Creating new config file (" + Config.configFileName + ")...");
                        Log.Info("Please edit the file and try again");
                        Config.CreateNewConfigFile();
                    }
                }
            }
            else
            {
                // If any argument is missing, send the syntax
                SendSyntax();
            }
        }
Esempio n. 19
0
        public MemoryStream GenerateCSV()
        {
            MemoryStream outStream = new MemoryStream();
            StreamWriter writer    = new StreamWriter(outStream);

            // Headings
            writer.Write("School_id" + delimiter);
            writer.Write("School_name" + delimiter);
            writer.Write("School_number" + delimiter);

            writer.Write("State_id" + delimiter);
            writer.Write("Low_grade" + delimiter);
            writer.Write("High_grade" + delimiter);
            writer.Write("Principal" + delimiter);
            writer.Write("Principal_email" + delimiter);
            writer.Write("School_address" + delimiter);
            writer.Write("School_city" + delimiter);
            writer.Write("School_state" + delimiter);
            writer.Write("School_zip" + delimiter);
            writer.Write("School_phone" + delimiter);

            writer.Write(Environment.NewLine);

            SchoolRepository _schoolRepo = new SchoolRepository(_dbConnectionString);
            List <School>    schools     = _schoolRepo.GetAll();

            foreach (School school in schools.Where(x => x.isFake == false))
            {
                writer.Write(stringContainer + school.DAN + stringContainer + delimiter);
                writer.Write(stringContainer + school.Name + stringContainer + delimiter);
                writer.Write(stringContainer + school.DAN + stringContainer + delimiter);

                writer.Write(stringContainer + "" + stringContainer + delimiter); // State ID

                // Parse K and PreK into what Clever expects
                string lowGrade = school.LowGrade;
                if (lowGrade.ToLower() == "pk")
                {
                    lowGrade = "PreKindergarten";
                }

                if ((lowGrade.ToLower() == "0k") || (lowGrade.ToLower() == "k"))
                {
                    lowGrade = "Kindergarten";
                }

                if (string.IsNullOrEmpty(lowGrade))
                {
                    lowGrade = "Ungraded";
                }

                string highGrade = school.HighGrade;
                if (highGrade.ToLower() == "pk")
                {
                    highGrade = "PreKindergarten";
                }

                if ((highGrade.ToLower() == "0k") || (highGrade.ToLower() == "k"))
                {
                    highGrade = "Kindergarten";
                }

                if (string.IsNullOrEmpty(highGrade))
                {
                    highGrade = "Ungraded";
                }

                writer.Write(stringContainer + lowGrade + stringContainer + delimiter);      // Low grade
                writer.Write(stringContainer + highGrade + stringContainer + delimiter);     // High greade
                writer.Write(stringContainer + "" + stringContainer + delimiter);            // Principal
                writer.Write(stringContainer + "" + stringContainer + delimiter);            // Principal email
                writer.Write(stringContainer + "" + stringContainer + delimiter);            // School address
                writer.Write(stringContainer + "" + stringContainer + delimiter);            // School city
                writer.Write(stringContainer + school.Region + stringContainer + delimiter); // School state
                writer.Write(stringContainer + "" + stringContainer + delimiter);            // School ZIP
                writer.Write(stringContainer + "" + stringContainer + delimiter);            // School phone

                writer.Write(Environment.NewLine);
            }

            writer.Flush();
            outStream.Flush();
            return(outStream);
        }
Esempio n. 20
0
        static void Main(string[] args)
        {
            if (args.Any())
            {
                string        fileName = string.Empty;
                string        date     = string.Empty;
                List <string> grades   = new List <string>()
                {
                    "pk", "k", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"
                };
                // There aren't nearly this many blocks in a day, but this future proofs it. It can't pull absences for blocks that dont exist
                List <int> softBlocks = new List <int>()
                {
                    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
                };
                List <int> hardBlocks = new List <int>()
                {
                    1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
                };
                bool          allSchools           = false;
                bool          onlyPeriodAttendance = false;
                bool          onlyDailyAttendance  = false;
                List <string> options = new List <string>();

                List <string> selectedSchoolIDs = new List <string>();

                foreach (string argument in args)
                {
                    if (argument.ToLower().StartsWith("/schoolid:"))
                    {
                        foreach (string enteredID in argument.Substring(10, argument.Length - 10).Split(new char[] { ';', ',' }))
                        {
                            if (!string.IsNullOrEmpty(enteredID))
                            {
                                selectedSchoolIDs.Add(enteredID);
                            }
                        }
                    }
                    else if (argument.ToLower().StartsWith("/filename:"))
                    {
                        fileName = argument.Substring(10, argument.Length - 10);
                    }
                    else if (argument.ToLower().StartsWith("/allschools"))
                    {
                        options.Add("allschools");
                        allSchools = true;
                    }
                    else if (argument.ToLower().StartsWith("/justperiodattendance"))
                    {
                        options.Add("justperiodattendance");
                        onlyPeriodAttendance = true;
                    }
                    else if (argument.ToLower().StartsWith("/justdailyattendance"))
                    {
                        options.Add("justdailyattendance");
                        onlyDailyAttendance = true;
                    }
                    else if (argument.ToLower().StartsWith("/date:"))
                    {
                        date = argument.Substring(6, argument.Length - 6);
                        if (date.ToLower().Equals("today"))
                        {
                            date = DateTime.Today.ToString();
                        }
                        if (date.ToLower().Equals("yesterday"))
                        {
                            date = Helpers.GetPreviousBusinessDay(DateTime.Today).ToString();
                        }
                        if (date.ToLower().Equals("now"))
                        {
                            date = DateTime.Now.ToString();
                        }
                    }
                    else if (argument.ToLower().StartsWith("/logfilename:"))
                    {
                        Log.LogFileName = argument.Substring(13, argument.Length - 13);
                    }
                    else if (argument.ToLower().StartsWith("/blocks:"))
                    {
                        string        blob           = argument.Substring(8, argument.Length - 8);
                        char[]        splitChars     = { ',', ';' };
                        List <string> unparsedBlocks = blob.Split(splitChars).ToList();
                        softBlocks.Clear();
                        foreach (string s in unparsedBlocks)
                        {
                            if (!string.IsNullOrEmpty(s))
                            {
                                int parsed = 0;
                                if (int.TryParse(s, out parsed))
                                {
                                    if (parsed > 0)
                                    {
                                        softBlocks.Add(parsed);
                                    }
                                }
                            }
                        }
                    }
                    else if (argument.ToLower().StartsWith("/hardblocks:"))
                    {
                        string        blob           = argument.Substring(12, argument.Length - 12);
                        char[]        splitChars     = { ',', ';' };
                        List <string> unparsedBlocks = blob.Split(splitChars).ToList();
                        hardBlocks.Clear();
                        foreach (string s in unparsedBlocks)
                        {
                            if (!string.IsNullOrEmpty(s))
                            {
                                int parsed = 0;
                                if (int.TryParse(s, out parsed))
                                {
                                    if (parsed > 0)
                                    {
                                        hardBlocks.Add(parsed);
                                    }
                                }
                            }
                        }
                    }
                    else if (argument.ToLower().StartsWith("/grades:"))
                    {
                        string gradesRaw = argument.Substring(8, argument.Length - 8).Trim('\"').Trim();
                        grades = new List <string>();
                        Log.Info("Limiting student selection to specific grades");
                        foreach (string ss in gradesRaw.Split(','))
                        {
                            if (!string.IsNullOrEmpty(ss))
                            {
                                grades.Add(ss.ToLower());
                                Log.Info(" Adding grade \"" + ss + "\"");
                            }
                        }
                    }
                }

                if (((selectedSchoolIDs.Count <= 0) && (!allSchools)) || (string.IsNullOrEmpty(fileName)) || (string.IsNullOrEmpty(date)))
                {
                    SendSyntax();
                }
                else
                {
                    if (Config.ConfigFileExists())
                    {
                        DateTime parsedDate = Helpers.ParseDate(date);

                        try
                        {
                            Log.ToLog("----------------------------------------------------------------");
                            Log.Info("Started: " + DateTime.Now);
                            Log.Info("Date: " + date);
                            Log.Info("Output: " + fileName);
                            Log.Info("Grades: " + grades.ToCommaSeparatedString());
                            Log.Info("Soft Blocks: " + softBlocks.ToCommaSeparatedString());
                            Log.Info("Hard Blocks: " + hardBlocks.ToCommaSeparatedString());
                            Log.Info("Options: " + options.ToCommaSeparatedString());
                            Log.Info("Schools: " + (allSchools ? "ALL" : selectedSchoolIDs.ToCommaSeparatedString()));

                            Dictionary <Student, List <Absence> > studentsWithAbsences = new Dictionary <Student, List <Absence> >();
                            List <School>     selectedSchools = new List <School>();
                            AbsenceRepository absenceRepo     = new AbsenceRepository();
                            StudentRepository studentRepo     = new StudentRepository();
                            using (
                                SqlConnection connection = new SqlConnection(Config.dbConnectionString_SchoolLogic))
                            {
                                SchoolRepository schoolRepo = new SchoolRepository(connection);

                                if (allSchools)
                                {
                                    selectedSchools = schoolRepo.GetAll();
                                }
                                else
                                {
                                    selectedSchools = schoolRepo.Get(selectedSchoolIDs);
                                }

                                Log.Info("Loading students");
                                foreach (School school in selectedSchools)
                                {
                                    List <Student> schoolStudents = studentRepo.LoadForSchool(connection, school, parsedDate).Where(s => grades.Contains(s.Grade.ToLower())).ToList();

                                    if (onlyDailyAttendance && !onlyPeriodAttendance)
                                    {
                                        Log.Info("Only using daily attendance students");
                                        schoolStudents = schoolStudents.Where(s => s.IsTrackDaily == true).ToList();
                                    }

                                    if (onlyPeriodAttendance && !onlyDailyAttendance)
                                    {
                                        Log.Info("Only using period attendance students");
                                        schoolStudents = schoolStudents.Where(s => s.IsTrackDaily == false).ToList();
                                    }

                                    Log.Info("Loaded " + schoolStudents.Count + " students for school " + school.Name);

                                    int schoolAbsenceCount = 0;

                                    // Load student absences
                                    foreach (Student student in schoolStudents)
                                    {
                                        List <Absence> studentAbsences = absenceRepo.LoadAbsencesFor(connection, school, student,
                                                                                                     parsedDate, parsedDate.AddHours(23.5)).Where(abs => hardBlocks.Contains(abs.BlockNumber)).ToList();
                                        if (studentAbsences.Count > 0)
                                        {
                                            studentsWithAbsences.Add(student, studentAbsences);
                                        }
                                        schoolAbsenceCount += studentAbsences.Count;
                                    }
                                    Log.Info(" Loaded " + schoolAbsenceCount + " absences for school " + school.Name);
                                }
                            }

                            Log.Info("Creating CSV data");

                            MemoryStream csvContents = AbsenceCSV.GenerateCSV(studentsWithAbsences, softBlocks);
                            Log.Info("Saving CSV file (" + fileName + ")");
                            if (FileHelpers.FileExists(fileName))
                            {
                                FileHelpers.DeleteFile(fileName);
                            }
                            FileHelpers.SaveFile(csvContents, fileName);
                            Log.Info("Done!");
                        }
                        catch (Exception ex)
                        {
                            Log.Error(ex.Message);
                        }
                    }
                    else
                    {
                        Log.Error("Configuration file not found");
                        Log.Info("Creating new config file (" + Config.configFileName + ")...");
                        Log.Info("Please edit the file and try again");
                        Config.CreateNewConfigFile();
                    }
                }
            }
            else
            {
                // If any argument is missing, send the syntax
                SendSyntax();
            }
        }
 public void GetSchools()
 {
     IRepositoryContext uow = new EntityFrameworkRepositoryContext();
     var repo = new SchoolRepository(uow);
     var result = repo.GetAll();
     Assert.IsTrue(result.Count() > 0);
 }
Esempio n. 22
0
 public List <School> GetAll()
 {
     return(repository.GetAll(db).ToList());
 }