Beispiel #1
0
        /// <summary>
        /// The ContentDistribution.
        /// </summary>
        /// <param name="model">The model<see cref="Distribution"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task ContentDistribution(Distribution model)
        {
            // Create new content
            var contentDistributionId = String.IsNullOrEmpty(model.Id) ? Guid.NewGuid().ToString() : model.Id;

            var newContent = new Entites.Distribution(model.SchoolId, contentDistributionId)
            {
                ClassId   = model.ClassId,
                ContentId = model.ContentId,
                Active    = true,
                CreatedBy = model.CreatedBy,
                UpdatedOn = DateTime.UtcNow,
                UpdatedBy = model.CreatedBy,
            };

            try
            {
                await _tableStorage.AddAsync("Distribution", newContent);
                await SendPushNotificationToStudent(model);
            }
            catch (Exception ex)
            {
                throw new AppException("Content distribution error: ", ex.InnerException);
            }
        }
        /// <summary>
        /// The CreateStudentAssigments.
        /// </summary>
        /// <param name="model">The model<see cref="StudentAssignment"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task CreateStudentAssigments(StudentAssignment model)
        {
            var studentAssignment = await _tableStorage.GetAllAsync <Entites.StudentAssignment>("StudentAssignment");

            var content = studentAssignment.SingleOrDefault(assignment => assignment.RowKey == model.Id);

            if (content != null)
            {
                content.ReviewStatus = AssignmentReviewStatus.Completed;
                content.UpdatedOn    = DateTime.UtcNow;

                try
                {
                    await _tableStorage.UpdateAsync("StudentAssignment", content);
                }
                catch (Exception ex)
                {
                    throw new AppException("update student assignment error: ", ex.InnerException);
                }
            }
            else
            {
                var assignmentId = String.IsNullOrEmpty(model.Id) ? Guid.NewGuid().ToString() : model.Id;

                var assignment = new Entites.StudentAssignment(model.SchoolId, assignmentId)
                {
                    StudentId     = model.StudentId,
                    StudentName   = model.StudentName,
                    AssignmentId  = model.AssignmentId,
                    AssignmentURL = model.AssignmentURL,
                    ReviewStatus  = AssignmentReviewStatus.UnderReview,

                    Active    = true,
                    CreatedBy = model.StudentId,
                    UpdatedOn = DateTime.UtcNow,
                    UpdatedBy = model.StudentId,
                };

                try
                {
                    await _tableStorage.AddAsync("StudentAssignment", assignment);
                    await SendPushNotificationToTeacher(model);
                }
                catch (Exception ex)
                {
                    throw new AppException("Create student assigment error: ", ex.InnerException);
                }
            }
        }
        /// <summary>
        /// The CreateAssessment.
        /// </summary>
        /// <param name="model">The model<see cref="Assessment"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task CreateAssessment(Assessment model)
        {
            var assessments = await _tableStorage.GetAllAsync <Entites.Assessment>("Assessments");

            var assessment = assessments.SingleOrDefault(assessment => assessment.RowKey == model.Id);

            if (assessment != null)
            {
                assessment.AssessmentDescription = model.AssessmentDescription;
                assessment.AssessmentTitle       = model.AssessmentTitle;
                assessment.SubjectName           = model.SubjectName;
                assessment.Active = model.Active;

                try
                {
                    await _tableStorage.UpdateAsync("Assessments", assessment);
                }
                catch (Exception ex)
                {
                    throw new AppException("update assessment error: ", ex.InnerException);
                }
            }
            else
            {
                var assessmentId = String.IsNullOrEmpty(model.Id) ? Guid.NewGuid().ToString() : model.Id;

                assessment = new Entites.Assessment(model.SchoolId, assessmentId)
                {
                    AssessmentTitle       = model.AssessmentTitle,
                    AssessmentDescription = model.AssessmentDescription,
                    AssessmentQuiz        = JsonConvert.SerializeObject(model.AssessmentQuestions),
                    ClassId     = model.ClassId,
                    SubjectName = model.SubjectName,

                    Active    = true,
                    CreatedBy = model.CreatedBy,
                    UpdatedOn = DateTime.UtcNow,
                    UpdatedBy = model.CreatedBy,
                };
                try
                {
                    await _tableStorage.AddAsync("Assessments", assessment);
                }
                catch (Exception ex)
                {
                    throw new AppException("Create assessment error: ", ex.InnerException);
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// The NonProfitAccountRegistration.
        /// </summary>
        /// <param name="nonProfitAccount">The nonProfitAccount<see cref="Models.NonProfitAccount"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task NonProfitAccountRegistration(Models.NonProfitAccount nonProfitAccount)
        {
            var id      = String.IsNullOrEmpty(nonProfitAccount.Id) ? Guid.NewGuid().ToString() : nonProfitAccount.Id;
            var account = new Entites.NonProfitAccount(nonProfitAccount.RegistrationNo, id)
            {
                Address              = nonProfitAccount.Address,
                Email                = nonProfitAccount.Email,
                Location             = nonProfitAccount.Location,
                NameOfNGO            = nonProfitAccount.NameOfNGO,
                OperationalLocations = nonProfitAccount.OperationalLocations,
                PhoneNo              = nonProfitAccount.PhoneNo,
                RegistrationNo       = nonProfitAccount.RegistrationNo,
                TaxRegistrationNo    = nonProfitAccount.TaxRegistrationNo,
                Active               = false,
                CreatedBy            = "system",
                UpdatedOn            = DateTime.UtcNow,
                UpdatedBy            = "system",
            };

            try
            {
                account.OTP = await GenerateTOPAndSend(account.Email);

                account.OTPDate = DateTime.UtcNow;
                await _tableStorage.AddAsync("NonProfitAccount", account);
            }
            catch (Exception ex)
            {
                throw new AppException("Create non profit account error: ", ex.InnerException);
            }
        }
        /// <summary>
        /// The Register.
        /// </summary>
        /// <param name="model">The model<see cref="RegisterRequest"/>.</param>
        /// <returns>The <see cref="Task{object}"/>.</returns>
        public async Task <object> Register(RegisterRequest model)
        {
            // validate
            var users = await _tableStorage.GetAllAsync <User>("User");

            if (users.Any(x => x.Email == model.Email))
            {
                var resp = new HttpResponseMessage(HttpStatusCode.AlreadyReported)
                {
                    Content      = new StringContent(string.Format($"User { model.Email} already registred!")),
                    ReasonPhrase = "Already registred!"
                };
                throw new HttpResponseException(resp);
            }

            var defaultPasswrod = model.Password ?? "p@ssw0rd";
            var userId          = model.Id ?? Guid.NewGuid().ToString();
            var schoolId        = model.SchoolId ?? userId;

            var newUser = new User(schoolId, userId)
            {
                FirstName     = model.FirstName,
                LastName      = model.LastName,
                Email         = model.Email,
                PasswordHash  = BC.HashPassword(defaultPasswrod),
                Role          = model.Role,
                Active        = true,
                Verified      = DateTime.UtcNow,
                PasswordReset = DateTime.UtcNow,
                CreatedBy     = userId,
                UpdatedOn     = DateTime.UtcNow,
                UpdatedBy     = userId,
                ForceChangePasswordNextLogin = true
            };

            try
            {
                return(await _tableStorage.AddAsync("User", newUser));
            }
            catch (Exception ex)
            {
                throw new AppException("Registration Error: ", ex.InnerException);
            }
        }
        /// <summary>
        /// The UpdateMenus.
        /// </summary>
        /// <param name="roleName">The roleName<see cref="string"/>.</param>
        /// <param name="associateMenus">The associateMenus<see cref="List{AssociateMenu}"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task UpdateMenus(string roleName, List <AssociateMenu> associateMenus)
        {
            var allMenus = await _tableStorage.GetAllAsync <Entites.AssociateMenus>("AssociateMenu");

            var roleAssociateMenus = allMenus.Where(user => user.PartitionKey == roleName.Trim());

            foreach (var menu in associateMenus)
            {
                var associateMenu = roleAssociateMenus.FirstOrDefault(m => m.Id == menu.Id);
                if (associateMenu is null)
                {
                    try
                    {
                        var rowKey  = Guid.NewGuid().ToString();
                        var newMenu = new Entites.AssociateMenus(menu.RoleName.Trim(), rowKey)
                        {
                            Id       = menu.Id,
                            MenuName = menu.MenuName,
                            Active   = menu.Active
                        };
                        await _tableStorage.AddAsync("AssociateMenu", newMenu);
                    }
                    catch (Exception ex)
                    {
                        throw new AppException("AssociateMenu Create Error: ", ex.InnerException);
                    }
                }
                else
                {
                    try
                    {
                        associateMenu.Active = menu.Active;
                        await _tableStorage.UpdateAsync("AssociateMenu", associateMenu);
                    }
                    catch (Exception ex)
                    {
                        throw new AppException("AssociateMenu Update Error: ", ex.InnerException);
                    }
                }
            }
        }
Beispiel #7
0
        public async Task <Product> AddProduct(Product product)
        {
            var addedProduct = await _azureProductRepository.AddAsync(product);

            return(addedProduct);
        }
Beispiel #8
0
        /// <summary>
        /// The CreateUpdate.
        /// </summary>
        /// <param name="model">The model<see cref="SchoolRequest"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task CreateUpdate(SchoolRequest model)
        {
            // validate
            var school = await this.GetSchool(model.Id);

            if (school != null)
            {
                school.Name      = model.Name;
                school.Address1  = model.Address1;
                school.Address2  = model.Address2;
                school.Country   = model.Country;
                school.State     = model.State;
                school.City      = model.City;
                school.Zip       = model.Zip;
                school.Latitude  = model.Latitude;
                school.Longitude = model.Longitude;
                school.CreatedBy = model.CreatedBy;
                school.UpdatedOn = DateTime.UtcNow;
                school.UpdatedBy = model.CreatedBy;
                school.ImageURL  = model.ImageURL;

                try
                {
                    await _tableStorage.UpdateAsync("School", school);
                }
                catch (Exception ex)
                {
                    throw new AppException("update school error: ", ex.InnerException);
                }
            }
            else
            {
                var schoolId  = String.IsNullOrEmpty(model.Id) ? Guid.NewGuid().ToString() : model.Id;
                var newSchool = new Entites.School(schoolId, schoolId)
                {
                    Name      = model.Name,
                    Address1  = model.Address1,
                    Address2  = model.Address2,
                    Country   = model.Country,
                    State     = model.State,
                    City      = model.City,
                    Zip       = model.Zip,
                    Latitude  = model.Latitude,
                    Longitude = model.Longitude,
                    Active    = true,
                    CreatedBy = model.CreatedBy,
                    UpdatedOn = DateTime.UtcNow,
                    UpdatedBy = model.CreatedBy,
                    ImageURL  = model.ImageURL,
                };

                try
                {
                    await _tableStorage.AddAsync("School", newSchool);
                }
                catch (Exception ex)
                {
                    throw new AppException("Create school error: ", ex.InnerException);
                }
            }
        }
Beispiel #9
0
        /// <summary>
        /// The CreateUpdate.
        /// </summary>
        /// <param name="model">The model<see cref="StudentRequest"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task CreateUpdate(StudentRequest model)
        {
            TableQuery <Entites.Student> query = new TableQuery <Entites.Student>()
                                                 .Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, model.Id));
            var studentQuery = await _tableStorage.QueryAsync <Entites.Student>("Student", query);

            var student = studentQuery.SingleOrDefault();

            if (student != null)
            {
                //Update student information
                student.EnrolmentNo = model.EnrolmentNo;
                student.FirstName   = model.FirstName;
                student.LastName    = model.LastName;
                student.Gender      = model.Gender;
                student.ClassId     = model.ClassId;
                student.Address1    = model.Address1;
                student.Address2    = model.Address2;
                student.Country     = model.Country;
                student.State       = model.State;
                student.City        = model.City;
                student.Zip         = model.Zip;
                student.Latitude    = model.Latitude;
                student.Longitude   = model.Longitude;
                student.Active      = true;
                student.CreatedBy   = model.CreatedBy;
                student.UpdatedOn   = DateTime.UtcNow;
                student.UpdatedBy   = model.CreatedBy;

                try
                {
                    await _tableStorage.UpdateAsync("Student", student);
                }
                catch (Exception ex)
                {
                    throw new AppException("update student error: ", ex.InnerException);
                }
            }
            else
            {
                var studentId = String.IsNullOrEmpty(model.Id) ? Guid.NewGuid().ToString() : model.Id;

                var newStudent = new Entites.Student(model.SchoolId, studentId)
                {
                    EnrolmentNo = model.EnrolmentNo,
                    FirstName   = model.FirstName,
                    LastName    = model.LastName,
                    Gender      = model.Gender,
                    ClassId     = model.ClassId,
                    Address1    = model.Address1,
                    Address2    = model.Address2,
                    Country     = model.Country,
                    State       = model.State,
                    City        = model.City,
                    Zip         = model.Zip,
                    Latitude    = model.Latitude,
                    Longitude   = model.Longitude,
                    Active      = true,
                    CreatedBy   = model.CreatedBy,
                    UpdatedOn   = DateTime.UtcNow,
                    UpdatedBy   = model.CreatedBy,
                };
                try
                {
                    await _tableStorage.AddAsync("Student", newStudent);
                }
                catch (Exception ex)
                {
                    throw new AppException("Create student error: ", ex.InnerException);
                }
            }
        }
        /// <summary>
        /// The CreateUpdate.
        /// </summary>
        /// <param name="model">The model<see cref="TeacherRequest"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task CreateUpdate(TeacherRequest model)
        {
            TableQuery <Entites.Teacher> query = new TableQuery <Entites.Teacher>()
                                                 .Where(TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.Equal, model.Id));
            var teacherQuery = await _tableStorage.QueryAsync <Entites.Teacher>("Teacher", query);

            var teacher = teacherQuery.SingleOrDefault();

            if (teacher != null)
            {
                // Update profile
                ProfileUpdateRequest profileUpdateRequest = new ProfileUpdateRequest
                {
                    Email     = model.Email,
                    FirstName = model.FirstName,
                    LastName  = model.LastName,
                    Id        = model.Id
                };

                await _profileService.UpdateProfile(profileUpdateRequest);

                //Update teacher information
                teacher.Gender    = model.Gender;
                teacher.Address1  = model.Address1;
                teacher.Address2  = model.Address2;
                teacher.Country   = model.Country;
                teacher.State     = model.State;
                teacher.City      = model.City;
                teacher.Zip       = model.Zip;
                teacher.Latitude  = model.Latitude;
                teacher.Longitude = model.Longitude;
                teacher.Active    = true;
                teacher.CreatedBy = model.CreatedBy;
                teacher.UpdatedOn = DateTime.UtcNow;
                teacher.UpdatedBy = model.CreatedBy;

                try
                {
                    await _tableStorage.UpdateAsync("Teacher", teacher);
                }
                catch (Exception ex)
                {
                    throw new AppException("update teacher error: ", ex.InnerException);
                }
            }
            else
            {
                // Register user as teacher
                var             userId          = String.IsNullOrEmpty(model.Id) ? Guid.NewGuid().ToString() : model.Id;
                var             defaultPasswrod = "teacher@123"; //SettingConfigurations.GetRandomPassword(10);
                RegisterRequest registerRequest = new RegisterRequest
                {
                    Email           = model.Email,
                    FirstName       = model.FirstName,
                    LastName        = model.LastName,
                    Role            = model.Role,
                    AcceptTerms     = true,
                    Id              = userId,
                    SchoolId        = model.SchoolId,
                    Password        = defaultPasswrod,
                    ConfirmPassword = defaultPasswrod
                };

                var newTeacher = new Entites.Teacher(model.SchoolId, userId)
                {
                    Address1  = model.Address1,
                    Address2  = model.Address2,
                    Country   = model.Country,
                    State     = model.State,
                    City      = model.City,
                    Zip       = model.Zip,
                    Latitude  = model.Latitude,
                    Longitude = model.Longitude,
                    Active    = true,
                    Gender    = model.Gender,
                    CreatedBy = model.CreatedBy,
                    UpdatedOn = DateTime.UtcNow,
                    UpdatedBy = model.CreatedBy,
                };
                try
                {
                    await _profileService.Register(registerRequest);

                    await _tableStorage.AddAsync("Teacher", newTeacher);
                    await NewTeacherNotificationEmail(registerRequest);
                }
                catch (Exception ex)
                {
                    throw new AppException("Create teacher error: ", ex.InnerException);
                }
            }
        }
Beispiel #11
0
        /// <summary>
        /// The CreateUpdate.
        /// </summary>
        /// <param name="model">The model<see cref="ClassRoom"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task CreateUpdate(ClassRoom model)
        {
            var classRooms = await _tableStorage.GetAllAsync <Entites.ClassRoom>("ClassRoom");

            var classRoom = classRooms.SingleOrDefault(user => user.RowKey == model.ClassId);

            // Validate class room availabilty
            if (!String.IsNullOrEmpty(model.ClassRoomName))
            {
                var isClassAvailable = classRooms.Any(
                    cls => cls.PartitionKey == model.SchoolId &&
                    cls.ClassRoomName.ToLower() == model.ClassRoomName.ToLower() &&
                    cls.ClassDivision.ToLower() == model.ClassDivision.ToLower()
                    );
                if (isClassAvailable)
                {
                    var resp = new HttpResponseMessage(HttpStatusCode.Conflict)
                    {
                        Content = new StringContent(string.Format($"Class is not available in ${ model.SchoolId } school.")),
                    };
                    throw new HttpResponseException(resp);
                }
            }

            if (classRoom != null)
            {
                //Update class information
                classRoom.ClassDivision = model.ClassDivision;
                classRoom.ClassRoomName = model.ClassRoomName;
                classRoom.Active        = true;
                classRoom.UpdatedOn     = DateTime.UtcNow;
                classRoom.UpdatedBy     = model.CreatedBy;

                try
                {
                    await _tableStorage.UpdateAsync("ClassRoom", classRoom);
                }
                catch (Exception ex)
                {
                    throw new AppException("update class room error: ", ex.InnerException);
                }
            }
            else
            {
                // Register new class
                var classRoomId = String.IsNullOrEmpty(model.ClassId) ? Guid.NewGuid().ToString() : model.ClassId;

                var newClassRoom = new Entites.ClassRoom(model.SchoolId, classRoomId)
                {
                    ClassDivision = model.ClassDivision,
                    ClassRoomName = model.ClassRoomName,
                    Active        = true,
                    CreatedBy     = model.CreatedBy,
                    UpdatedOn     = DateTime.UtcNow,
                    UpdatedBy     = model.CreatedBy,
                };
                try
                {
                    await _tableStorage.AddAsync("ClassRoom", newClassRoom);
                }
                catch (Exception ex)
                {
                    throw new AppException("Create class room error: ", ex.InnerException);
                }
            }
        }
        /// <summary>
        /// The ProcessAttendance.
        /// </summary>
        /// <param name="queueDataMessage">The queueDataMessage<see cref="QueueDataMessage"/>.</param>
        /// <param name="_log">The _log<see cref="ILogger"/>.</param>
        /// <returns>The <see cref="Task"/>.</returns>
        public async Task ProcessAttendance(QueueDataMessage queueDataMessage, ILogger _log)
        {
            // Call the Face API.
            try
            {
                BlobStorageRequest blobStorage = await _azureBlobService.GetSasUri("attendance");

                _log.LogInformation($"APIErrorException BlobStorageRequest: {blobStorage.StorageUri}");

                var blobUriBuilder = new System.UriBuilder($"{blobStorage.StorageUri}attendance/{queueDataMessage.PictureURLs[0]}")
                {
                    Query = blobStorage.StorageAccessToken
                };

                _log.LogInformation($"APIErrorException blobUriBuilder: {blobUriBuilder.Uri.AbsoluteUri}");


                _log.LogInformation($"Start DetectWithUrlAsync");

                IList <DetectedFace> faceList =
                    await _faceClient.Face.DetectWithUrlAsync(blobUriBuilder.Uri.AbsoluteUri, true, true, recognitionModel : "recognition_01", returnRecognitionModel : true).ConfigureAwait(false);

                _log.LogInformation($"End DetectWithUrlAsync: { faceList}");


                var detectedFaceGroups = faceList
                                         .Select((face, i) => new { DetectedFace = face.FaceId.Value, Index = i })
                                         .GroupBy(x => x.Index / 10, x => x.DetectedFace);

                List <IdentifyResult> IdentifyResults = new List <IdentifyResult>();

                foreach (var face in detectedFaceGroups)
                {
                    List <Guid?> sourceFaceIds = new List <Guid?>();

                    foreach (var detectedFace in face)
                    {
                        sourceFaceIds.Add(detectedFace);
                    }

                    var identifiedResult = await _faceClient.Face.IdentifyAsync(sourceFaceIds, queueDataMessage.SchoolId).ConfigureAwait(false);

                    IdentifyResults.AddRange(identifiedResult);
                }

                IList <string> presentStudetns = new List <string>();

                foreach (var identifyResult in IdentifyResults)
                {
                    _log.LogInformation($"identifyResult = {identifyResult}");

                    if (identifyResult.Candidates.Count() == 0)
                    {
                        _log.LogInformation($"No one identified");
                    }
                    else
                    {
                        // Get top 1 among all candidates returned
                        _log.LogInformation($"Get top 1 among all candidates returned");
                        var candidateId = identifyResult.Candidates[0].PersonId;
                        _log.LogInformation($"candidateId: {candidateId}");

                        var person = await _faceClient.PersonGroupPerson.GetAsync(queueDataMessage.SchoolId, candidateId).ConfigureAwait(false);

                        _log.LogInformation($"Identified as: {person.Name}");

                        var studentId = person.Name;
                        presentStudetns.Add(studentId);
                    }
                }

                var allStudents = await _studentService.GetAll(queueDataMessage.SchoolId, queueDataMessage.ClassId);

                foreach (var student in allStudents)
                {
                    var attaintance = new Attentdance(queueDataMessage.SchoolId, Guid.NewGuid().ToString())
                    {
                        StudentId   = student.Id,
                        ClassRoomId = queueDataMessage.ClassId,
                        TeacherId   = queueDataMessage.TeacherId,
                        CreatedBy   = queueDataMessage.TeacherId,
                        UpdatedBy   = queueDataMessage.TeacherId,
                        UpdatedOn   = DateTime.UtcNow,
                        Timestamp   = queueDataMessage.PictureTimestamp,
                        Latitude    = queueDataMessage.Latitude,
                        Longitude   = queueDataMessage.Longitude,
                        Present     = presentStudetns.Contains(student.Id)
                    };
                    _log.LogInformation($"Attentdance AddAsync: {attaintance}");

                    await _tableStorage.AddAsync("Attentdance", attaintance);

                    _log.LogInformation($"Done Attentdance AddAsync: {attaintance}");
                }
                _log.LogInformation($"Done Attentdance..");
            }
            // Catch and display Face API errors.
            catch (APIErrorException ex)
            {
                _log.LogError(ex, "ProcessAttendance Exception");

                throw new AppException("APIErrorException: ", ex.InnerException);
            }
            // Catch and display all other errors.
            catch (Exception ex)
            {
                _log.LogError(ex, "ProcessAttendance Exception");

                throw new AppException("Process Attendance Cognitive Service Error: ", ex.InnerException);
            }
        }