}//End of UpdateOneAccountDetail() method public bool AreThereAnyAccountDetail(InstructorAccount inOneInstructorAccount, /*, AccountDetail inOneAccountDetail,*/ List <AccountDetail> inAccountDetailList, out object result) { //The following two objects are used to build an anonymous type result var anyAccountDetailList = new List <object>(); List <object> accountDetailList = new List <object>(); var accountDetailsQueryResult = Database.AccountDetails .Where(input => (input.CustomerAccountId == inOneInstructorAccount.CustomerAccountId)) .AsNoTracking() .ToList(); foreach (var oneAccountDetail in accountDetailsQueryResult) { accountDetailList.Add(new { accountDetailId = oneAccountDetail.AccountDetailId, startTimeInMinutes = oneAccountDetail.StartTimeInMinutes, dayOfWeekNumber = oneAccountDetail.DayOfWeekNumber, endTimeInMinutes = oneAccountDetail.EndTimeInMinutes, startTimeInHHMM = ConvertFromMinutesToHHMM(oneAccountDetail.StartTimeInMinutes), endTimeInHHMM = ConvertFromMinutesToHHMM(oneAccountDetail.EndTimeInMinutes), effectiveStartDate = oneAccountDetail.EffectiveStartDate, effectiveEndDate = oneAccountDetail.EffectiveEndDate, isVisible = oneAccountDetail.IsVisible }); }//end of foreach loop which builds the accountList List container . if (accountDetailList.Count == 0) { result = new { //inspectedData = intendedData, anyAccountDetailList = accountDetailList, message = "No AccountDetail was created for this Account, Instructor might be unable to generate Timesheet Data" }; return(false); } else { result = new { //inspectedData = intendedData, anyAccountDetailList = accountDetailList, //message = "Existing Account Details that Instructor can teach for:" +anyAccountDetailList }; return(true); } }
public IActionResult Post([FromForm] IFormCollection data) { //API Data Validation int testInt = 0; bool testBool = false; decimal testDecimal = 0; bool validDates = true; bool validIDs = true; List <String> errorMessages = new List <string>(); if (!data.ContainsKey("customerId")) { errorMessages.Add("Customer Account ID is missing. "); } if (!data.ContainsKey("instructorId")) { errorMessages.Add("Instructor ID is missing. "); } if (!data.ContainsKey("wageRate")) { errorMessages.Add("Wage Rate is missing. "); } if (!int.TryParse(data["customerId"].ToString(), out testInt)) { errorMessages.Add("Customer Account ID MUST be numeric. "); validIDs = false; } if (Database.CustomerAccounts.SingleOrDefault(ca => ca.CustomerAccountId == testInt) == null) { errorMessages.Add("Customer does not exist. "); } if (!int.TryParse(data["instructorId"].ToString(), out testInt)) { errorMessages.Add("Instructor ID MUST be numeric. "); validIDs = false; } if (Database.AppUsers.Where(au => au.RoleId == 2).SingleOrDefault(au => au.Id == testInt) == null) { errorMessages.Add("Instructor does not exist. "); } if (!decimal.TryParse(data["wageRate"].ToString(), out testDecimal)) { errorMessages.Add("Wage Rate MUST be a decimal. "); } if (validIDs) { if (Database.InstructorAccounts.Where(ia => ia.CustomerAccountId == int.Parse(data["customerId"].ToString())).SingleOrDefault(ia => ia.InstructorAccountId == int.Parse(data["customerId"].ToString())) != null) { errorMessages.Add("Instructor Already Assigned to Customer. "); } } string errorString = ""; errorString = string.Concat(errorMessages); if (errorMessages.Count > 0) { return(BadRequest(new { message = errorString })); } int userId = int.Parse(User.FindFirst("userid").Value); //Retireve the user id of the current logged in user try { //Populate InstructorAccount with data from sent by client InstructorAccount newIA = new InstructorAccount(); newIA.CustomerAccountId = int.Parse(data["customerId"]); newIA.InstructorId = int.Parse(data["instructorId"]); newIA.WageRate = decimal.Parse(data["wageRate"]); newIA.CreatedAt = _appDateTimeService.GetCurrentDateTime(); newIA.CreatedById = userId; //Save changes to database Database.InstructorAccounts.Add(newIA); Database.SaveChanges(); return(Ok(new { message = "Successfully assigned instructor" })); } catch (SqlException ex) { return(StatusCode(StatusCodes.Status500InternalServerError, new { message = "Something wrong has occured. Please contact the administrators." })); //If any database related operation occur, return ISE } catch (Exception ex) { return(BadRequest(new { message = "There are issues with the request." })); } }
public IActionResult GetAllInstructorPaginated(int id, [FromQuery] QueryPagingParametersForInstructorAccount inParameters) { try { CustomerAccount ca = Database.CustomerAccounts.Include(c => c.CreatedBy).Include(c => c.UpdatedBy).SingleOrDefault(c => c.CustomerAccountId == id); //Check if the specific CustomerAccount exist in the database if (ca == null) //If CustomerAccount does not exist in database, return 404 Not Found { return(NotFound(new { message = "Customer could not be found" })); } //Pagination parameters int pageSize = 10; int currentPage = 0; string sortOrder = "ASC"; string searchTerm = ""; int totalPage = 0; int startRecord = 0; int endRecord = 0; int totalRecords = 0; if (ModelState.IsValid) //if query params is valid load the data into pagination parameters { currentPage = Int32.Parse(inParameters.page_number.ToString()); pageSize = Int32.Parse(inParameters.per_page.ToString()); sortOrder = inParameters.sort_order; searchTerm = inParameters.search_term; } else { currentPage = 1; pageSize = 10; sortOrder = "ASC"; searchTerm = ""; } if (currentPage == 1) //Calculate the page's first record's index { startRecord = 1; } else { startRecord = ((currentPage - 1) * pageSize) + 1; } List <AppUser> instrctors; //Declare a list to store all the Instructor records related to the customer from the database if (sortOrder.Equals("ASC")) { //Query the database for Instructor AppUser records related to the customer in the ascending order of Id if (String.IsNullOrEmpty(searchTerm)) { instrctors = Database.AppUsers.Where(au => au.RoleId == 2).OrderBy(au => au.Id).ToList(); } else { instrctors = Database.AppUsers.Where(au => au.RoleId == 2).Where(au => au.FullName.Contains(searchTerm)).OrderBy(au => au.Id).ToList(); } } else if (sortOrder.Equals("DESC")) { //Query the database for Instructor AppUser records related to the customer in the descending order of Id if (String.IsNullOrEmpty(searchTerm)) { instrctors = Database.AppUsers.Where(au => au.RoleId == 2).OrderByDescending(au => au.Id).ToList(); } else { instrctors = Database.AppUsers.Where(au => au.RoleId == 2).Where(au => au.FullName.Contains(searchTerm)).OrderByDescending(au => au.Id).ToList(); } } else { //return BadRequest for invalid sort order return(BadRequest(new { message = "Invalid Sort Order" })); } totalRecords = instrctors.Count; //Get the total no of AppUser records from the datebase totalPage = (int)Math.Ceiling((double)totalRecords / pageSize); //Calculate the total number of pages if (totalRecords == 0) { //If no records are found for the customer return(Ok(new { accountName = ca.AccountName, totalRecordCount = totalRecords, totalCurrentPgRec = 0, currentPage = 0, totalPage = 0, records = new List <object>(), from = 0, to = 0 })); //Return the response object } //Calculate the index of the last of the records on the current page if ((currentPage == totalPage) && (totalRecords % pageSize != 0)) { endRecord = startRecord + (totalRecords % pageSize) - 1; } else { endRecord = startRecord + pageSize - 1; } //Iterate through the list of Instructor AppUsers, and cherry pick the data to return List <object> cusInstructorAccountRateByPage = new List <object>(); for (int i = startRecord - 1; i <= endRecord - 1; i++) { int recordNo = -1; if (sortOrder.Equals("ASC")) { recordNo = i + 1; } else if (sortOrder.Equals("DESC")) { recordNo = totalRecords - i; } //Find the list of Customer Assigned to the Instructor string assignedCusAccounts = ""; List <InstructorAccount> iaCusAssigned = Database.InstructorAccounts.Where(ia => ia.InstructorId == instrctors[i].Id).Include(ia => ia.CustomerAccount).ToList(); foreach (InstructorAccount iar in iaCusAssigned) { assignedCusAccounts += iar.CustomerAccount.AccountName + ","; } if (!string.IsNullOrEmpty(assignedCusAccounts)) { assignedCusAccounts = assignedCusAccounts.Remove(assignedCusAccounts.Length - 1); } //Check if the instructor is already assigned to Customer bool assigned = false; decimal? wage = null; InstructorAccount iaRec = Database.InstructorAccounts.Where(c => c.CustomerAccountId == id).SingleOrDefault(ia => ia.InstructorId == instrctors[i].Id); if (iaRec != null) { assigned = true; wage = iaRec.WageRate; } cusInstructorAccountRateByPage.Add(new { no = recordNo, id = instrctors[i].Id, name = instrctors[i].FullName, email = instrctors[i].UserName, isAlreadyAssignedToCustomer = assigned, wageRate = wage, accountsAssigned = assignedCusAccounts }); } //Craft the response object to return object result = new { accountName = ca.AccountName, totalRecordCount = totalRecords, totalCurrentPgRec = cusInstructorAccountRateByPage.Count, currentPage = currentPage, totalPage = totalPage, records = cusInstructorAccountRateByPage, from = startRecord, to = endRecord }; return(Ok(result)); //Return the response object } catch (SqlException ex) { return(StatusCode(StatusCodes.Status500InternalServerError, new { message = "Something wrong has occured. Please contact the administrators." })); //If any database related operation occur, return ISE } catch (Exception ex) { return(BadRequest(new { message = "There are issues with the request." })); //Return BadRequest for any general exception occured } }
//[ValidateAntiForgeryToken] public IActionResult AssignOneInstructorToCustomerAccount(IFormCollection inFormData) { string customMessage = ""; //No need to fetch user id value because this AccountRate is not going to capture this value. InstructorAccount oneNewInstructorAccount = new InstructorAccount(); string userLoginId = _userManager.GetUserName(User); int userInfoId = Database.UserInfo.Single(input => input.LoginUserName == userLoginId).UserInfoId; oneNewInstructorAccount.EffectiveStartDate = DateTime.ParseExact(inFormData["effectiveStartDate"], "d/M/yyyy", CultureInfo.InvariantCulture); if (inFormData["effectiveEndDate"] != "") { //If the there are values for the effectiveEndDate then start copying into the EffectiveEndDate property oneNewInstructorAccount.EffectiveEndDate = DateTime.ParseExact(inFormData["effectiveEndDate"], "d/M/yyyy", CultureInfo.InvariantCulture); } oneNewInstructorAccount.InstructorId = Int32.Parse(inFormData["instructorId"]); oneNewInstructorAccount.CustomerAccountId = Int32.Parse(inFormData["customerAccountId"]); oneNewInstructorAccount.WageRate = Decimal.Parse(inFormData["wageRate"]); oneNewInstructorAccount.Comments = inFormData["comments"]; //oneNewInstructorAccount.IsCurrent = bool.Parse(inFormData["isCurrent"]); List <AccountDetail> existingAccountDetailList = Database.AccountDetails .Where(input => input.CustomerAccountId == Int32.Parse(inFormData["customerAccountId"])) .AsNoTracking().ToList <AccountDetail>(); try { Database.InstructorAccounts.Add(oneNewInstructorAccount); Database.SaveChanges(); } catch (Exception ex) { { String innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : ""; //should have unique constraint whereby unable to assign instructor to acc due to //already existing assignment. customMessage = "Unable to assign Instructor to Account."; object httpFailRequestResultMessage = new { message = customMessage + " : " + innerMessage }; //Return a bad http request message to the client return(BadRequest(httpFailRequestResultMessage)); } }//End of try .. catch block on saving data object result; AreThereAnyAccountDetail(oneNewInstructorAccount, existingAccountDetailList, out result); ////Construct a custom message for the client ////Create a success message anonymous object which has a ////message member variable (property) var successRequestResultMessage = new { message = "Successfully Assigned Instructor to Account.", anyAccountDetailRecords = result, }; //Create a OkObjectResult class instance, httpOkResult. //When creating the object, provide the previous message object into it. OkObjectResult httpOkResult = new OkObjectResult(successRequestResultMessage); //Send the OkObjectResult class object back to the client. return(httpOkResult); }//End of CreateAccountRate() method
public IActionResult DeleteInstructorAccount(IFormCollection inFormData, string inInstructorAccountId) { // public void Delete(int id) //{ // [HttpPut("UpdateAssignmentOfInstructorToCustomerAccount/{inInstructorAccountId}")] //[ValidateAntiForgeryToken] //public IActionResult UpdateAssignmentOfInstructorToCustomerAccount(IFormCollection inFormData, string inInstructorAccountId) //{ /// <summary> /// HTTP type is PUT and URL is /api/AccountDetails/UpdateOneAccountDetail /// The web api method takes in IFormCollection type object which has all the account detail /// information sent from the client-side. The web api updates an existing account detail in the database /// </summary> string customMessage = ""; int instructorAccountId = Int32.Parse(inInstructorAccountId); //Int32.Parse(inFormData["instructorAccountId"]); InstructorAccount foundOneInstructorAccount = Database.InstructorAccounts .Where(input => input.InstructorAccountId == instructorAccountId).Single(); int customerAccountId = foundOneInstructorAccount.CustomerAccountId; //int customerAccountId = Int32.Parse(inFormData["customerAccountId"]); //Obtain the user id id of the user who has logon string userLoginName = _userManager.GetUserName(User); int userInfoId = Database.UserInfo.Single(input => input.LoginUserName == userLoginName).UserInfoId; //int instructorIdInInt; //Obtain an exisiting record and map it into the foundOneAccountDetail instance //By having the foundOneInstructorAccount instance representing the information //,begin update the necessary properties. Avoid touching the CustomerAccountId property //if (Int32.TryParse(inFormData["instructorId"], out instructorIdInInt)) //{ // foundOneInstructorAccount.InstructorId = instructorIdInInt; //} //foundOneInstructorAccount.InstructorId = Int32.Parse(inFormData["instructorId"]); //foundOneInstructorAccount.CustomerAccountId = Int32.Parse(inFormData["customerAccountId"]); //foundOneInstructorAccount.EffectiveStartDate = DateTime.ParseExact(inFormData["effectiveStartDate"], "d/M/yyyy", CultureInfo.InvariantCulture); //if (inFormData["effectiveEndDate"] != "") //{ // //If the there are values for the effectiveEndDate then start copying into the EffectiveEndDate property // foundOneInstructorAccount.EffectiveEndDate = DateTime.ParseExact(inFormData["effectiveEndDate"], "d/M/yyyy", CultureInfo.InvariantCulture); //} //foundOneInstructorAccount.Comments = inFormData["comments"]; //foundOneInstructorAccount.WageRate = Decimal.Parse(inFormData["wageRate"]); //foundOneInstructorAccount.IsCurrent = bool.Parse(inFormData["isCurrent"]); //Find the parent record to update the UpdatedAt property and UpdatedById property CustomerAccount foundParentCustomerAccount = Database.CustomerAccounts.Where(input => input.CustomerAccountId == customerAccountId).Single(); foundParentCustomerAccount.UpdatedAt = DateTime.Now; foundParentCustomerAccount.UpdatedById = userInfoId; object result = null; try { // AreThereAnyOverlappingAccountDetail(foundOneAccountDetail, accountDetailsQueryResult, out result); Database.InstructorAccounts.Remove(foundOneInstructorAccount); Database.SaveChanges(); } catch (Exception ex) { { String innerMessage = (ex.InnerException != null) ? ex.InnerException.Message : ""; customMessage = "Unable to remove assignment of Instructor from Account"; object httpFailRequestResultMessage = new { message = customMessage + " : " + innerMessage }; //Return a bad http request message to the client return(BadRequest(httpFailRequestResultMessage)); } }//End of try .. catch block on saving data //Construct a custom message for the client //Create a success message anonymous object which has a //Message member variable (property) var successRequestResultMessage = new { message = "Successfully removed Instructor assignment from Account", anyAccountDetailRecords = result, }; //Create a OkObjectResult class instance, httpOkResult. //When creating the object, provide the previous message object into it. OkObjectResult httpOkResult = new OkObjectResult(successRequestResultMessage); //Send the OkObjectResult class object back to the client. return(httpOkResult); }//End of UpdateOneAccountDetail() method