Пример #1
0
        public async Task InsertSampleData(int userId)
        {
            var user = await _userRepository.GetByIdAsync(userId);

            var programs = await _programRepository.GetAllAsync(user.SiteId);

            int prereaderProgramId = ProgramIdSearch(programs, "Prereader");
            int kidsProgramId      = ProgramIdSearch(programs, "Kid");
            int teensProgramId     = ProgramIdSearch(programs, "Teen");
            int adultProgramId     = ProgramIdSearch(programs, "Adult");

            //insert sample data
            var challenge = new Challenge
            {
                SiteId          = user.SiteId,
                RelatedSystemId = user.SystemId,
                BadgeId         = null,
                Name            = "Get Along",
                Description     = "This is a challenge encourging you to get along with others!",
                IsActive        = false,
                IsDeleted       = false,
                IsValid         = true,
                PointsAwarded   = 10,
                TasksToComplete = 2,
                RelatedBranchId = user.BranchId
            };

            challenge = await _challengeRepository.AddSaveAsync(userId, challenge);

            int positionCounter = 1;
            await _challengeTaskRepository.AddSaveAsync(userId, new ChallengeTask
            {
                ChallengeId       = challenge.Id,
                Title             = "Be excellent to each other",
                ChallengeTaskType = ChallengeTaskType.Action,
                Position          = positionCounter++
            });

            await _challengeTaskRepository.AddSaveAsync(userId, new ChallengeTask
            {
                ChallengeId       = challenge.Id,
                Title             = "Party on, dudes!",
                ChallengeTaskType = ChallengeTaskType.Action,
                Position          = positionCounter++
            });

            challenge = new Challenge
            {
                SiteId          = user.SiteId,
                BadgeId         = null,
                RelatedSystemId = user.SystemId,
                Name            = "Science Fiction reading list",
                Description     = "Read some excellent science fiction!",
                IsActive        = false,
                IsDeleted       = false,
                IsValid         = true,
                PointsAwarded   = 10,
                TasksToComplete = 2,
                RelatedBranchId = user.BranchId
            };

            challenge = await _challengeRepository.AddSaveAsync(userId, challenge);

            positionCounter = 0;

            await _challengeTaskRepository.AddSaveAsync(userId, new ChallengeTask
            {
                ChallengeId       = challenge.Id,
                Title             = "Slaughterhouse-Five, or The Children's Crusade: A Duty-Dance with Death",
                Author            = "Kurt Vonnegut",
                Isbn              = "978-0385333849",
                ChallengeTaskType = ChallengeTaskType.Book,
                Position          = positionCounter++
            });

            await _challengeTaskRepository.AddSaveAsync(userId, new ChallengeTask
            {
                ChallengeId       = challenge.Id,
                Title             = "Stories of Your Life and Others",
                Author            = "Ted Chiang",
                Isbn              = "978-1101972120",
                ChallengeTaskType = ChallengeTaskType.Book,
                Position          = positionCounter++
            });

            await _challengeTaskRepository.AddSaveAsync(userId, new ChallengeTask
            {
                ChallengeId       = challenge.Id,
                Title             = "Have Space Suit - Will Travel",
                Author            = "Robert A. Heinlein",
                Isbn              = "978-1416505495",
                ChallengeTaskType = ChallengeTaskType.Book,
                Position          = positionCounter++
            });

            var district = await _schoolService.AddDistrict(new SchoolDistrict()
            {
                Name = "International Confederation of Wizards"
            });

            var typeInstitute = await _schoolService.AddSchoolType("Institute");

            var typeAcademy = await _schoolService.AddSchoolType("Academy");

            var typeSchool = await _schoolService.AddSchoolType("School of Witchcraft and Wizardry");

            var schoolHogwarts = await _schoolService.AddSchool("Hogwarts", district.Id, typeSchool.Id);

            await _schoolService.AddSchool("Ilvermorny", district.Id, typeSchool.Id);

            var schoolBeauxbatons = await _schoolService.AddSchool("Beauxbatons", district.Id, typeAcademy.Id);

            var schoolDurmstrang = await _schoolService.AddSchool("Durmstrang", district.Id, typeInstitute.Id);

            var userCheck = await _userRepository.GetByUsernameAsync("aweasley");

            if (userCheck == null)
            {
                // add some family users
                var newUser = new User
                {
                    SiteId    = user.SiteId,
                    BranchId  = user.BranchId,
                    SystemId  = user.SystemId,
                    ProgramId = adultProgramId,
                    FirstName = "Arthur",
                    LastName  = "Weasley",
                    Username  = "******"
                };

                var arthur = await _userRepository.AddSaveAsync(userId, newUser);

                await _userRepository.SetUserPasswordAsync(userId, arthur.Id, "123123");

                await _mailRepository.AddSaveAsync(userId, new Mail
                {
                    Body     = "Thanks for joining our reading program, Arthur. You're the best!",
                    ToUserId = arthur.Id,
                    IsNew    = true,
                    Subject  = "Welcome to the program!",
                    SiteId   = arthur.SiteId
                });

                await _activityService.LogActivityAsync(arthur.Id, 1);

                await _activityService.AddBookAsync(arthur.Id, new Book
                {
                    Author = "Kurt Vonnegut",
                    Title  = "Slaughterhouse-Five, or The Children's Crusade: A Duty-Dance with Death"
                });

                await _activityService.LogActivityAsync(arthur.Id, 1);

                await _activityService.AddBookAsync(arthur.Id, new Book
                {
                    Author = "Kurt Vonnegut",
                    Title  = "Breakfast of Champions, or Goodbye Blue Monday"
                });

                newUser.FirstName           = "Molly";
                newUser.Username            = null;
                newUser.HouseholdHeadUserId = arthur.Id;
                var molly = await _userRepository.AddSaveAsync(userId, newUser);

                await _activityService.LogActivityAsync(molly.Id, 1);

                await _activityService.AddBookAsync(molly.Id, new Book
                {
                    Author = "Kurt Vonnegut",
                    Title  = "Cat's Cradle"
                });

                newUser.FirstName = "Bill";
                await _userRepository.AddAsync(userId, newUser);

                newUser.FirstName = "Charlie";
                newUser.SchoolId  = schoolHogwarts.Id;
                newUser.ProgramId = teensProgramId;
                await _userRepository.AddAsync(userId, newUser);

                newUser.FirstName = "Fred";
                await _userRepository.AddAsync(userId, newUser);

                newUser.FirstName = "George";
                await _userRepository.AddAsync(userId, newUser);

                newUser.FirstName = "Percy";
                newUser.ProgramId = adultProgramId;
                newUser.SchoolId  = default(int?);
                await _userRepository.AddAsync(userId, newUser);

                await _userRepository.SaveAsync();

                newUser.FirstName           = "Ron";
                newUser.HouseholdHeadUserId = null;
                var ron = await _userRepository.AddSaveAsync(userId, newUser);

                newUser.FirstName           = "Hermione";
                newUser.LastName            = "Granger";
                newUser.HouseholdHeadUserId = ron.Id;
                var hermione = await _userRepository.AddSaveAsync(userId, newUser);

                await _activityService.LogActivityAsync(ron.Id, 1);

                await _activityService.LogActivityAsync(hermione.Id, 1);

                await _activityService.LogActivityAsync(hermione.Id, 1);

                await _activityService.LogActivityAsync(hermione.Id, 1);

                await _activityService.LogActivityAsync(hermione.Id, 1);

                await _activityService.LogActivityAsync(hermione.Id, 1);

                newUser.ProgramId = kidsProgramId;
                newUser.FirstName = "Rose";
                newUser.LastName  = "Granger-Weasley";
                newUser.SchoolId  = schoolBeauxbatons.Id;
                await _userRepository.AddAsync(userId, newUser);

                newUser.ProgramId = prereaderProgramId;
                newUser.FirstName = "Hugo";
                await _userRepository.AddAsync(userId, newUser);

                await _userRepository.SaveAsync();

                newUser.FirstName           = "Harry";
                newUser.LastName            = "Potter";
                newUser.ProgramId           = adultProgramId;
                newUser.HouseholdHeadUserId = null;
                newUser.SchoolId            = default(int?);
                var harry = await _userRepository.AddSaveAsync(userId, newUser);

                newUser.FirstName           = "Ginevra";
                newUser.HouseholdHeadUserId = harry.Id;
                var ginny = await _userRepository.AddSaveAsync(userId, newUser);

                await _activityService.LogActivityAsync(harry.Id, 1);

                await _activityService.LogActivityAsync(harry.Id, 1);

                await _activityService.LogActivityAsync(ginny.Id, 1);

                newUser.FirstName = "James";
                newUser.ProgramId = teensProgramId;
                newUser.SchoolId  = schoolDurmstrang.Id;
                await _userRepository.AddAsync(userId, newUser);

                newUser.FirstName = "Albus";
                newUser.ProgramId = kidsProgramId;
                newUser.SchoolId  = schoolHogwarts.Id;
                await _userRepository.AddAsync(userId, newUser);

                newUser.FirstName = "Lily";
                newUser.SchoolId  = default(int?);
                await _userRepository.AddAsync(userId, newUser);

                await _userRepository.SaveAsync();
            }
        }
Пример #2
0
        public async Task <(ImportStatus, string)> FromCsvAsync(StreamReader csvStream)
        {
            var notes = new List <string>();

            using (var csv = new CsvHelper.CsvReader(csvStream))
            {
                try
                {
                    int recordCount    = 0;
                    int issues         = 0;
                    int typesAdded     = 0;
                    int districtsAdded = 0;
                    int schoolsAdded   = 0;
                    var types          = await _schoolService.GetTypesAsync();

                    var districts = await _schoolService.GetDistrictsAsync();

                    var schools = await _schoolService.GetSchoolsAsync();

                    var typeIndex     = types.ToDictionary(_ => _.Name, _ => _.Id);
                    var districtIndex = types.ToDictionary(_ => _.Name, _ => _.Id);

                    foreach (var record in csv.GetRecords <SchoolImportExport>())
                    {
                        try
                        {
                            if (string.IsNullOrEmpty(record.Type))
                            {
                                throw new Exception($"School type is blank on record {recordCount + 2}");
                            }
                            if (string.IsNullOrEmpty(record.District))
                            {
                                throw new Exception($"School district is blank on record {recordCount + 2}");
                            }
                            if (string.IsNullOrEmpty(record.Name))
                            {
                                throw new Exception($"School name is blank on record {recordCount + 2}");
                            }

                            if (record.Type.Length > 255)
                            {
                                record.Type = record.Type.Substring(0, 255);
                                string warning = $"<li>Type too long, truncated: <strong>{record.Type}</strong>.</li>";
                                if (!notes.Contains(warning))
                                {
                                    notes.Add(warning);
                                }
                            }

                            if (record.District.Length > 255)
                            {
                                record.Type = record.District.Substring(0, 255);
                                string warning = $"<li>District too long, truncated: <strong>{record.District}</strong>.</li>";
                                if (!notes.Contains(warning))
                                {
                                    notes.Add(warning);
                                }
                            }

                            if (record.Name.Length > 255)
                            {
                                record.Name = record.Name.Substring(0, 255);
                                string warning = $"<li>Type too long, truncated: <strong>{record.Name}</strong>.</li>";
                                if (!notes.Contains(warning))
                                {
                                    notes.Add(warning);
                                }
                            }

                            int typeId;
                            if (typeIndex.Keys.Contains(record.Type.Trim()))
                            {
                                typeId = typeIndex[record.Type.Trim()];
                            }
                            else
                            {
                                _logger.LogDebug($"Adding school type: {record.Type.Trim()}");
                                var type = await _schoolService.AddSchoolType(record.Type.Trim());

                                typeIndex.Add(record.Type.Trim(), type.Id);
                                typeId = type.Id;
                                typesAdded++;
                            }

                            int districtId;
                            if (districtIndex.Keys.Contains(record.District.Trim()))
                            {
                                districtId = districtIndex[record.District.Trim()];
                            }
                            else
                            {
                                _logger.LogDebug($"Adding school district: {record.District.Trim()}");
                                var district = await _schoolService.AddDistrict(new SchoolDistrict()
                                {
                                    Name = record.District.Trim()
                                });

                                districtIndex.Add(record.District.Trim(), district.Id);
                                districtId = district.Id;
                                districtsAdded++;
                            }

                            var schoolExists = schools.Where(_ => _.SchoolDistrictId == districtId &&
                                                             _.Name == record.Name.Trim()).Any();

                            if (!schoolExists)
                            {
                                _logger.LogDebug($"Adding school: {record.Name.Trim()}");
                                await _schoolService
                                .AddSchool(record.Name.Trim(), districtId, typeId);

                                schoolsAdded++;
                            }

                            recordCount++;
                        }
                        catch (Exception rex)
                        {
                            issues++;
                            if (rex.InnerException != null)
                            {
                                _logger.LogError($"School import error: {rex.InnerException.Message}");
                                notes.Add($"<li>Problem inserting record {recordCount + 2}: {rex.InnerException.Message}</li>");
                            }
                            else
                            {
                                _logger.LogError($"School import error: {rex.Message}");
                                notes.Add($"<li>Problem inserting record {recordCount + 2}: {rex.Message}</li>");
                            }
                        }
                    }
                    var returnMessage = new StringBuilder($"<p><strong>Imported {recordCount} records ({typesAdded} types, {districtsAdded} districts, {schoolsAdded} schools) and skipped {issues} rows due to issues.</strong></p>");
                    foreach (var note in notes)
                    {
                        returnMessage.AppendLine(note);
                    }
                    if (issues > 0)
                    {
                        return(ImportStatus.Warning, returnMessage.ToString());
                    }
                    if (notes.Count > 0)
                    {
                        return(ImportStatus.Info, returnMessage.ToString());
                    }
                    return(ImportStatus.Success, returnMessage.ToString());
                }
                catch (Exception ex)
                {
                    string error = $"CSV parsing error: {ex.Message}";
                    _logger.LogError(error);
                    return(ImportStatus.Danger, error);
                }
            }
        }