public async Task <IActionResult> PostSessionSynopsis([FromBody] SessionSynopsis sessionSynopsis) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { _context.SessionSynopses.Add(sessionSynopsis); await _context.SaveChangesAsync(); } catch (DbUpdateException e) when(e.InnerException.Message.Contains("SessionSynopsis_SessionSynopsisName_UniqueConstraint")) { var response = new { message = "A session synopsis with the same name already exists." }; return(StatusCode(409, response)); } catch (Exception e) { return(BadRequest(e.Message)); } return(CreatedAtAction("GetSessionSynopsis", new { id = sessionSynopsis.SessionSynopsisId }, sessionSynopsis)); }
public IActionResult Delete(int id) { string databaseInnerExceptionMessage = ""; List <object> messages = new List <object>(); bool status = true; //This variable is used to track the overall success of all the database operations object response = null; SessionSynopsis oneSessionSynopsis = (SessionSynopsis)Database.SessionSynopses .Where(sessionSynopsisItem => sessionSynopsisItem.SessionSynopsisId == id).FirstOrDefault(); try { try { Database.SessionSynopses.Remove(oneSessionSynopsis); Database.SaveChanges(); response = new { status = "success", message = "Deleted session synopsis record." }; } catch (DbUpdateException ex) { databaseInnerExceptionMessage = ex.InnerException.Message; status = false; messages.Add(databaseInnerExceptionMessage); } } catch (Exception outerException) { object httpFailRequestResultMessage = new { message = "Unable to delete session synopsis record." }; //Return a bad http request message to the client return(BadRequest(httpFailRequestResultMessage)); } return(new JsonResult(response)); } //End of Delete()
public IActionResult Post([FromForm] IFormCollection webFormData) { var identity = HttpContext.User.Identity as ClaimsIdentity; int userId = 0; if (identity != null) { IEnumerable <Claim> claims = identity.Claims; userId = Int32.Parse(identity.FindFirst("userid").Value); SessionSynopsis newSession = new SessionSynopsis(); if (webFormData["sessionName"].ToString() == null || Convert.ToBoolean(webFormData["visibility"]) == null) { string customMessage = "Unable to save record. Please try again"; object httpFailRequestResultMessage = new { message = customMessage }; return(BadRequest(httpFailRequestResultMessage)); } newSession.SessionSynopsisName = webFormData["sessionName"]; newSession.IsVisible = Convert.ToBoolean(webFormData["visibility"]); newSession.CreatedById = userId; newSession.UpdatedById = userId; try { Console.Write(newSession); Database.SessionSynopses.Add(newSession); Database.SaveChanges(); } catch (Exception ex) { if (ex.InnerException != null) { if (ex.InnerException.Message.Contains("SessionSynopses_SessionSynopsisName_UniqueConstraint") == true) { string customMessage = "Unable to save record due to another session having the same name: " + webFormData["sessionName"]; object httpFailRequestResultMessage = new { message = customMessage }; return(BadRequest(httpFailRequestResultMessage)); } } return(BadRequest(ex)); }//end try catch return(Ok(new { message = "Create Web API is called. The extracted Id is " + userId.ToString() + ". Created a record " + newSession.SessionSynopsisName })); } else { return(BadRequest(new { message = "Unable to create record" })); } }
public IActionResult CreateSessionSynopsis(IFormCollection inFormData) { string customMessage = ""; //Obtain the user id of the user who has logon string email = _userManager.GetUserName(User); int userInfoId = Database.UserInfo.Single(input => input.Email == email).UserInfoId; SessionSynopsis oneNewSessionSynopsis = new SessionSynopsis(); //After creating a new SessionSynopsis type instance, fill it up with the incoming values oneNewSessionSynopsis.SessionSynopsisName = inFormData["sessionSynopsisName"]; oneNewSessionSynopsis.IsVisible = bool.Parse(inFormData["isVisible"]); oneNewSessionSynopsis.CreatedById = userInfoId; oneNewSessionSynopsis.UpdatedById = userInfoId; try { Database.SessionSynopses.Add(oneNewSessionSynopsis); Database.SaveChanges(); } catch (Exception ex) { if (ex.InnerException.Message .Contains("SessionSynopsis_SessionSynopsisName_UniqueConstraint") == true) { customMessage = "Unable to save session synopsis record due " + "to another record having the same name : " + oneNewSessionSynopsis.SessionSynopsisName; //Create a fail message anonymous object that has one property, message. //This anonymous object's Message property contains a simple string message object httpFailRequestResultMessage = new { message = customMessage }; //Return a bad http request message to the client return(BadRequest(httpFailRequestResultMessage)); } else { object httpFailRequestResultMessage = new { message = ex.InnerException.Message }; //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 = "Saved session synopsis record" }; //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 CreateSessionSynopsis method
public IActionResult Post([FromBody] string value) { string customMessage = ""; var sessionNewInput = JsonConvert.DeserializeObject <dynamic>(value); SessionSynopsis newSession = new SessionSynopsis(); int userId = GetUserIdFromUserInfo(); newSession.SessionSynopsisName = sessionNewInput.SessionSynopsisName.Value; Convert.ToBoolean(sessionNewInput.IsVisible.Value); Boolean dd = Convert.ToBoolean(sessionNewInput.IsVisible.Value); newSession.IsVisible = dd; newSession.CreatedById = userId; newSession.UpdatedById = userId; try { Database.SessionSynopses.Add(newSession); Database.SaveChanges(); } catch (Exception ex) { if (ex.InnerException.Message .Contains("SessionSynopsis_SessionSynopsisName_UniqueConstraint") == true) { customMessage = "Unable to save session record due " + "to another record having the same name : " + sessionNewInput.SessionSynopsisName.Value; object httpFailRequestResultMessage = new { message = customMessage }; //Return a HTTP response of Bad Request status //and embed the anonymous object's content within the message-body segmet. return(BadRequest(httpFailRequestResultMessage)); } } var successRequestResultMessage = new { message = "Saved session record" }; //Create a OkObjectResult class instance, httpOkResult. //When creating the OkObjectResult class instance, provide //the anonymous object, successRequestResultMessage into it. OkObjectResult httpOkResult = new OkObjectResult(successRequestResultMessage); //Send the OkObjectResult class object back to the client. return(httpOkResult); }
public IActionResult Post([FromForm] IFormCollection inFormData) { string returnMessage = ""; SessionSynopsis a = new SessionSynopsis(); a.SessionSynopsisName = inFormData["sessionSynopsisName"]; var identity = HttpContext.User.Identity as ClaimsIdentity; ClaimsPrincipal user = HttpContext.User; int userId = 0; if (identity != null) { IEnumerable <Claim> claims = identity.Claims; userId = Int32.Parse(identity.FindFirst("userid").Value); SessionSynopsis newSessionSynopsis = new SessionSynopsis(); try { newSessionSynopsis.SessionSynopsisName = inFormData["sessionSynopsisName"]; newSessionSynopsis.IsVisible = Convert.ToBoolean(inFormData["isVisible"]); newSessionSynopsis.CreatedById = userId; newSessionSynopsis.UpdatedById = userId; Database.SessionSynopses.Add(newSessionSynopsis); Database.SaveChanges(); } catch (Exception exceptionObject) { if (exceptionObject.InnerException.Message.Contains("SessionSynopsis_SessionSynopsisName_UniqueConstraint") == true) { returnMessage = "yo we screwed up yo"; } } var successRequestResultMessage = new { message = returnMessage == "" ? "Saved session synopsis record" : returnMessage, ok = returnMessage == "" }; OkObjectResult httpOkResult = new OkObjectResult(successRequestResultMessage); return(httpOkResult); } return(null); }
public async Task <IActionResult> Edit(int id, [Bind("SessionSynopsisName,IsVisible")] SessionSynopsis session) { if (ModelState.IsValid) { // Get the synopsis that is requested to be updated SessionSynopsis updateSession = await _context.SessionSynopses.SingleAsync(s => s.SessionSynopsisId == id); // Get current user var loginIdName = _userManager.GetUserName(User); UserInfo currentUser = await _context.UserInfo .Where(userId => userId.LoginUserName == loginIdName) .SingleAsync(); // https://docs.microsoft.com/en-us/aspnet/core/data/ef-mvc/crud?view=aspnetcore-2.1#update-the-edit-page // Copy pasta from here! if (await TryUpdateModelAsync <SessionSynopsis>( updateSession, "", s => s.SessionSynopsisName, s => s.IsVisible)) { try { updateSession.UpdatedById = currentUser.UserInfoId; await _context.SaveChangesAsync(); TempData["Success"] = "Your session synopsis has been updated successfully"; } catch (DbUpdateException) { ModelState.AddModelError("Update Error", "The session synopsis has already been created."); return(View()); } } // End of if return(RedirectToAction("Index")); } // End of if else { ModelState.AddModelError("Unknown Error", "Some of the field has invalid data."); return(View()); } }
public async Task <IActionResult> Create([Bind("SessionSynopsisName,IsVisible")] SessionSynopsis session) { //var user = await GetCurrentUserAsync(); var loginIdName = _userManager.GetUserName(User); UserInfo currentUser = await _context.UserInfo .Where(userId => userId.LoginUserName == loginIdName) .SingleAsync(); // Create new session SessionSynopsis newSession = new SessionSynopsis(); newSession.SessionSynopsisName = session.SessionSynopsisName; newSession.SessionSynopsisId = session.SessionSynopsisId; newSession.UpdatedBy = currentUser; newSession.UpdatedById = session.UpdatedById; newSession.CreatedBy = currentUser; newSession.CreatedById = session.CreatedById; newSession.IsVisible = session.IsVisible; if (ModelState.IsValid) { try { _context.Add(newSession); await _context.SaveChangesAsync(); TempData["Success"] = "Your session synopsis has been successfully created!"; return(RedirectToAction("Index")); } catch (DbUpdateException) { ModelState.AddModelError("Update Error", "The session synopsis has already been created."); return(View()); } } else { ModelState.AddModelError("Unknown Error", "Some of the field has invalid data."); return(View()); } }
public async Task <IActionResult> PutSessionSynopsis([FromRoute] int id, [FromBody] SessionSynopsis sessionSynopsis) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } if (id != sessionSynopsis.SessionSynopsisId) { return(BadRequest()); } _context.Entry(sessionSynopsis).State = EntityState.Modified; try { await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!SessionSynopsisExists(id)) { return(NotFound()); } throw; } catch (DbUpdateException e) when(e.InnerException.Message.Contains("SessionSynopsis_SessionSynopsisName_UniqueConstraint")) { var response = new { message = "A session synopsis with the same name already exists." }; return(StatusCode(409, response)); } catch (Exception e) { return(BadRequest(e.Message)); } return(Ok(sessionSynopsis.SessionSynopsisName)); }
public async Task <IActionResult> Post([FromBody] string value) { var sessionSypnosisNewInput = JsonConvert.DeserializeObject <dynamic>(value); object response = null; var newSessionSypnosis = new SessionSynopsis(); string currentUserId = sessionSypnosisNewInput.CreatedById; UserInfo currentUser = Database.UserInfo .Where(item => item.LoginUserName == currentUserId).FirstOrDefault(); newSessionSypnosis.SessionSynopsisName = sessionSypnosisNewInput.SessionSynopsisName; newSessionSypnosis.IsVisible = sessionSypnosisNewInput.IsVisible; newSessionSypnosis.CreatedById = sessionSypnosisNewInput.CreatedById; newSessionSypnosis.CreatedBy = currentUser; newSessionSypnosis.UpdatedById = sessionSypnosisNewInput.UpdatedById; newSessionSypnosis.UpdatedBy = currentUser; //await userManager.FindByIdAsync(currentUserId); try { try { Database.SessionSynopses.Add(newSessionSypnosis); Database.SaveChanges(); response = new { status = "success", message = "Saved new session synopsis record." }; } catch (DbUpdateException ex) { response = new { status = "fail", message = ex.InnerException.Message + "Please enter a unique value" }; } } catch (Exception outerException) { response = new { status = "fail", message = outerException.InnerException.Message }; } return(new JsonResult(response)); }//End of Post()
public IActionResult Get(int id) { try { SessionSynopsis oneSessionSynopsis = Database.SessionSynopses .Where(sessionSynopsisItem => sessionSynopsisItem.SessionSynopsisId == id).FirstOrDefault(); var response = new { sessionSynopsisId = oneSessionSynopsis.SessionSynopsisId, sessionSynopsisName = oneSessionSynopsis.SessionSynopsisName, visible = oneSessionSynopsis.IsVisible, createdBy = oneSessionSynopsis.CreatedBy, updatedBy = oneSessionSynopsis.UpdatedBy, };//end of creation of the response object return(new JsonResult(response)); } catch (Exception ex) { object httpFailRequestResultMessage = new { message = "Unable to retrive session synopsis record." }; //Return a bad http request message to the client return(BadRequest(httpFailRequestResultMessage)); } }//end of httpget by id
// With reference to https://www.codeproject.com/Articles/1204076/ASP-NET-Core-MVC-Remote-Validation // Edit page also can use cause of https://stackoverflow.com/questions/36122038/asp-net-mvc-remote-validation-logic-on-edit public IActionResult Verify([Bind(nameof(SessionSynopsis.SessionSynopsisName), nameof(SessionSynopsis.SessionSynopsisId))] SessionSynopsis sessionSynopsis) { bool isViewNameValid; if (sessionSynopsis.SessionSynopsisId == 0) { isViewNameValid = !_context.SessionSynopses.Any(x => x.SessionSynopsisName == sessionSynopsis.SessionSynopsisName); if (isViewNameValid == false) { return(Json($"{sessionSynopsis.SessionSynopsisName} is already in use!")); } } else { isViewNameValid = !_context.SessionSynopses.Any(x => x.SessionSynopsisName == sessionSynopsis.SessionSynopsisName && x.SessionSynopsisId != sessionSynopsis.SessionSynopsisId); } return(Json(isViewNameValid)); //if (sessionSynopsis == null) //{ // return Json(true); //} }
public IActionResult Post(IFormCollection value) { string customMessage = ""; /* * object httpFailRequestResultMessage = new { message = "abc" }; * //Return a bad http request message to the client * return BadRequest(httpFailRequestResultMessage); */ int userId = GetUserIdFromUserInfo(); //Reconstruct a useful object from the input string value. //dynamic sessionNewInput = JsonConvert.DeserializeObject<dynamic>(value); SessionSynopsis newSession = new SessionSynopsis(); try { newSession.CreatedById = userId; newSession.UpdatedById = userId; //newSession.SessionSynopsisName = sessionNewInput.sessionSynopsisName.Value; newSession.SessionSynopsisName = value["sessionSynopsisName"]; //System.Diagnostics.Debug.WriteLine("Lok Message: ok here 111"); //System.Diagnostics.Debug.WriteLine(newSession.SessionSynopsisName); newSession.IsVisible = Boolean.Parse(value["visibility"]); //When I add this Course instance, newCourse into the //Courses Entity Set, it will turn into a Course entity waiting to be mapped //as a new record inside the actual Course table. Database.SessionSynopses.Add(newSession); Database.SaveChanges();//Telling the database model to save the changes } catch (Exception exceptionObject) { System.Diagnostics.Debug.WriteLine("LJ"); //System.Diagnostics.Debug.WriteLine(exceptionObject.Message); try { if (exceptionObject.InnerException.Message .Contains("SessionSynopsis_SessionSynopsisName_UniqueConstraint") == true) { System.Diagnostics.Debug.WriteLine(newSession.SessionSynopsisName); customMessage = "Unable to save Session Sypnosis record due " + "to another record having the same name : " + newSession.SessionSynopsisName; //Create an anonymous type object that has one property, message. //This anonymous object's message property contains a simple string message object httpFailRequestResultMessage = new { message = customMessage }; //Return a bad http request message to the client return(BadRequest(httpFailRequestResultMessage)); } } catch { customMessage = "Unable to save Session Sypnosis record due to unknown reasons"; object httpFailRequestResultMessage = new { message = customMessage }; return(BadRequest(httpFailRequestResultMessage)); } }//End of Try..Catch block //If there is no runtime error in the try catch block, the code execution //should reach here. Sending success message back to the client. //****************************************************** //Construct a custom message for the client //Create a success message anonymous type object which has a //message member variable (property) var successRequestResultMessage = new { message = "Saved Session Sypnosis record" }; //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); }