public HttpResponseMessage RequestRegistrationBranchStudent([FromBody] BranchStudentDto branchStudentDto) { //private StudentController db = new StudentController(); try { BranchStudent branchStud = Converters.Convert(branchStudentDto); if (!ValidateModel.IsValid(new List <object>() { branchStud })) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ValidateModel.ModelsResults)); } Students s = StudentManager.GetStudents(Student.Includes.Address | Student.Includes.Bank | Student.Includes.Children, null, null); int f = 0; //foreach (var item in s.students) //{ // if (item.IdentityNumber == branchStud.Student.IdentityNumber) // { // branchStud.Student.Id = item.Id; // f = 1; // } //} //if(f==0) // return Request.CreateResponse(HttpStatusCode.BadRequest); BranchStudentManager.RequestRregistration(branchStud); return(Request.CreateResponse(HttpStatusCode.OK, branchStud.Id)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Failed to insert the student to branch, {ex.Message}")); } }
protected override Task <AuthenticateResult> HandleAuthenticateAsync() { _module = new JWTModule(); _validateModel = new ValidateModel(); var headerValue = Request.Headers["AuthJWT"]; if (String.IsNullOrWhiteSpace(headerValue)) { //Invalid Authorization header return(Task.FromResult(AuthenticateResult.Fail("Cannot read authorization header."))); } string secrect = "F4760D"; var validateResult = _module.VerifyToken(headerValue, secrect); if (validateResult.Status.Trim().ToUpper() == "FAILED") { return(Task.FromResult(AuthenticateResult.Fail(validateResult.Content))); } var identities = new List <ClaimsIdentity> { new ClaimsIdentity("custom auth type") }; var ticket = new AuthenticationTicket(new ClaimsPrincipal(identities), Options.Scheme); return(Task.FromResult(AuthenticateResult.Success(ticket))); }
/// <summary> /// Immplement the function to Update an existing object in repository. /// This method only updates Name, LastName ,Email, and picture /// of exisiting user based on given id /// the UserName and Joined date cannot be update /// </summary> /// <param name="id">a long type named id, contains the id of a specific object to be deleted</param> /// <param name="person">an object that used its field during the update data</param> /// <returns>an integer as the execution status code </returns> public int Update(long id, Person person) { try { var personInDb = GetById(id); if (personInDb == null) { return(ReturnCodeReference.NotUpdated_IdNotExist); } personInDb.Name = person.Name; personInDb.LastName = person.LastName; if (!ValidateModel.IsAgeFormat(person.Age.ToString())) { personInDb.Age = person.Age; } if (ValidateModel.IsValidEmail(person.Email)) { personInDb.Email = person.Email; } personInDb.picture = person.picture; _context.SaveChanges(); } catch (Exception) { return(ReturnCodeReference.NotUpdated_UnknownReason); } return(ReturnCodeReference.Updated_SuccessFully); }
/// <summary> /// Implement the function which creates and inserts a new instance of type <T> to the existing repository /// </summary> /// <param name="entity"> a person type object, which is created and inserted into repository or null if it could not act</param> /// <returns>an integer as the execution status code </returns> public int Create(Person person) { try { if (!ValidateModel.IsValidEmail(person.Email)) { return(ReturnCodeReference.NotCreated_EmailFormatProblem); } if (CheckUserNameExistance(person.UserName)) { return(ReturnCodeReference.NotCreated_UsernameExist); } Person newPerson = GetByUserName(person.UserName); if (newPerson == null) { _context.Persons.Add(person); _context.SaveChanges(); } else { return(ReturnCodeReference.NotCreated_UnknownReason); } } catch (Exception ex) { Console.WriteLine(ex.Message); return(ReturnCodeReference.NotCreated_UnknownReason); } return(ReturnCodeReference.Created_SuccessFully); }
public ActionResult SQLValidation(Guid id) { if (!CheckLogin()) { return(RedirectToAction("Login", "User")); } ValidateModel sourceValidate = new ValidateModel(); if (id == null) { return(RedirectToAction("Index", "Error")); } try { Source source = _sourceFactory.GetSource(id); if (source != null) { sourceValidate.SourceId = source.SourceId; sourceValidate.SourceName = source.SourceName; sourceValidate.SourceType = source.SourceType; sourceValidate.ValidationResult = new List <ValidateItem>(); try { Guid userId = (Guid)Session[DSEConstant.UserId]; //sourceValidate.ValidationResult = _sourceFactory.GetValidationResult(id, userId); sourceValidate.ValidationTable = _sourceFactory.GetValidationTable(id, userId); if (sourceValidate.ValidationTable != null && sourceValidate.ValidationTable.Rows.Count > 0) { ViewBag.ErrorMessage = "Validation failed"; source.Status = false; source.LastRun = DateTime.Now; _sourceFactory.Update(source); } else { ViewBag.SuccessMessage = "Your data is validated. "; source.Status = true; source.LastRun = DateTime.Now; _sourceFactory.Update(source); } } catch (Exception ex) { log.Error("Validation error", ex); ViewBag.ErrorMessage = "Validation progress end with error(s)" + System.Environment.NewLine + ex.Message; } } } catch (Exception ex) { log.Error("Get source in Validation", ex); ViewBag.ErrorMessage = "Validation progress end with error(s)" + System.Environment.NewLine + ex.Message; } return(View(sourceValidate)); }
public ValidateModel Valid() { var validate = new ValidateModel(); if (string.IsNullOrEmpty(Identification)) { validate.NotValid("Identificação Obrigatória."); } return(validate); }
public Steps?Validate(ValidateModel model) { //TODO: Check authentication code if (model.Code != "1111") { return(null); } var prospect = _prospectRepository.Find(model.Uid); return(prospect?.LastStep); }
public IActionResult Post(string uid, [FromBody] ValidateModel model) { model.Uid = uid; var step = _validate.Validate(model); if (step is null) { return(StatusCode(401)); } return(Ok(step)); }
public static ValidateModel ToValidateModel(this CaptchaVerifyModel captcha) { if (captcha == null) { return(new ValidateModel()); } var model = new ValidateModel(); model.Code = captcha.Code; model.Points = captcha.Points; return(model); }
/// <summary> /// Validate validation code of user. /// </summary> /// <param name="validateModel">Model of validation user.</param> /// <returns> /// Validated user registration profile. /// </returns> /// <exception cref="System.ArgumentException">When one of params invalid.</exception> /// <exception cref="System.UnauthorizedAccessException">When user id of description != current user id.</exception> public async Task <User> ValidateEmail(ValidateModel validateModel, long currentUserId) { validateModel.CheckArgumentException(); var user = await _userRepository.GetAsync(validateModel.UserId); user.EmailIsValidated = user.Id == currentUserId? validateModel.ValidationCode.ValidateCode(user.Email) : throw new UnauthorizedAccessException(); return((await _userRepository.EditAsync(user)) .GetSkillsToUser(_userSkillRepository, _skillRepository)); }
public ValidateForm() { if (DesignMode) { return; } validateModel = new ValidateModel(); validateModel.OnDataExported += ValidateModel_OnDataExported; InitializeComponent(); }
/// <summary> /// Validate validation code of user. /// </summary> /// <param name="validateModel">Model of validation user.</param> /// <returns> /// Validated user registration profile. /// </returns> /// <exception cref="System.ArgumentException">When one of params invalid.</exception> /// <exception cref="System.ArgumentNullException">When user not found.</exception> public async Task <User> ValidateRegistration(ValidateModel validateModel) { validateModel.CheckArgumentException(); var user = await _userRepository .GetAsync(validateModel.UserId); user.TelephoneNumberIsValidated = validateModel .ValidationCode .ValidateCode(user.TelephoneNumber); return(await _userRepository.EditAsync(user)); }
public async Task <IActionResult> CreateAsync([FromForm] News news) { try { news.NewsTranslates = JsonSerializer.Deserialize <ICollection <NewsTranslate> >(news.Translates); if (!ModelState.IsValid) { return(StatusCode(StatusCodes.Status500InternalServerError, new Response { Status = "Error", Messages = new Message[] { new Message { Lang_id = 1, MessageLang = "Model state isn't valid!" }, new Message { Lang_id = 2, MessageLang = "Состояние модели недействительно!" }, new Message { Lang_id = 3, MessageLang = "Model vəziyyəti etibarsızdır!" } } })); } ValidateModel res = news.Photo.PhotoValidate(); if (!res.Success) { return(StatusCode(StatusCodes.Status500InternalServerError, res.Response)); } string folder = Path.Combine("Site", "images", "news"); string fileName = await news.Photo.SaveImage(_env.WebRootPath, folder); news.Image = fileName; _newsContext.Add(news); foreach (NewsTranslate item in news.NewsTranslates) { item.NewsId = news.Id; _newsTranslateContext.Add(item); } return(Ok()); } catch (Exception e) { return(StatusCode(StatusCodes.Status500InternalServerError, e.Message)); } }
public static ValidateModel CheckIfUserNameExist(string username, List <User> all_users) { string message; ValidateModel response; foreach (var user in all_users) { if (user.username == username) { message = ""; response = new ValidateModel(true, message); return(response); } } message = ""; response = new ValidateModel(false, message); return(response); }
public async Task <ValidateModel> AccepTermAsync() { var result = new ValidateModel(false); try { if (await _userRepository.AccepTermAsync(_sessionUser.Id) == 1) { result.IsValid(); } } catch (Exception e) { result.NotValid(e.GetBaseException().Message); } return(result); }
public async Task <ValidateModel> KeepConnectedAsync(bool keepConnected) { var result = new ValidateModel(false); try { if (await _userRepository.KeepConnectedAsync(keepConnected, _sessionUser.Id) == 1) { result.IsValid(); } } catch (Exception e) { result.NotValid(e.GetBaseException().Message); } return(result); }
public static ValidateModel CheckIfUserPhoneExist(string phone, List <User> all_users) { string message; ValidateModel response; foreach (var user in all_users) { if (user.phone_no == phone) { message = ""; response = new ValidateModel(true, message); return(response); } } message = ""; response = new ValidateModel(false, message); return(response); }
public static ValidateModel CheckIfUserEmailExist(string email, List <User> all_users) { string message; ValidateModel response; foreach (var user in all_users) { if (user.email == email) { message = ""; response = new ValidateModel(true, message); return(response); } } message = ""; response = new ValidateModel(false, message); return(response); }
public static int UpdateStudent(Student student) { try { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { //if (StudentDataManager.IsExistIdentityNumber(student.IdentityNumber, student.Id)) // throw new Exception("The identity number is already exist."); AddressManager.UpdateAddress(student.Address); BankManager.UpdateBank(student.Bank); student.ChildrenNumber = getNumberNotMarriedChildren(student.StudentChildren); student.MarriedChildrenNumber = getNumberMarriedChildren(student.StudentChildren); int update = StudentDataManager.UpdateStudent(student); if (student.StudentChildren != null) { foreach (StudentChildren child in student.StudentChildren) { if (!ValidateModel.IsValid(new List <object>() { child })) { throw new Exception("not valid child field/s"); } //if (child.Id > 0) // update = StudentChildrenDataManager.UpdateStudentChildren(child); //else //{ // child.Student.Id = student.Id; // child.Id = StudentChildrenDataManager.InsertStudentChildren(child); //} } } scope.Complete(); return(update); } } catch (Exception ex) { _logger.Debug($"Failed to update student {student.Id}.", ex); throw; } }
public static int InsertPendingStudent(Student student, int branchId, int?studyPathId) { try { using (TransactionScope scope = new TransactionScope(TransactionScopeAsyncFlowOption.Enabled)) { if (StudentDataManager.IsExistIdentityNumber(student.IdentityNumber, student.Id)) { throw new Exception("The identity number is already exist."); } student.Address.Id = AddressManager.InsertAddress(student.Address); student.Bank.Id = BankManager.InsertBank(student.Bank); //student.ChildrenNumber = getNumberNotMarriedChildren(student.StudentChildren); //student.MarriedChildrenNumber = getNumberMarriedChildren(student.StudentChildren); int insert = student.Id = StudentDataManager.InsertPendingStudent(student); if (student.StudentChildren != null) { foreach (StudentChildren child in student.StudentChildren) { if (!ValidateModel.IsValid(new List <object>() { child })) { throw new Exception("not valid child field/s"); } //i had this line child.Student = student; child.Student.Id = student.Id; child.Id = StudentChildrenDataManager.InsertStudentChildren(child); } } //BranchStudentManager.RequestRregistration(student.Id, branchId, studyPathId); scope.Complete(); return(insert); } } catch (Exception ex) { _logger.Debug($"Failed to insert pending student.", ex); throw; } }
public HttpResponseMessage UpdateStudent([FromBody] StudentDto studentDto) { try { Student student = Converters.Convert(studentDto); if (!ValidateModel.IsValid(new List <object>() { student })) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ValidateModel.ModelsResults)); } int update = StudentManager.UpdateStudent(student); return(Request.CreateResponse(HttpStatusCode.OK, update)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Failed to update student, studentId:{studentDto.Id}")); } }
public HttpResponseMessage InsertStudentPayment([FromBody] StudentPaymentDto studentPaymentDto) { try { StudentPayment studentPayment = Converters.Convert(studentPaymentDto); if (!ValidateModel.IsValid(new List <object>() { studentPayment })) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ValidateModel.ModelsResults)); } StudentManager.InsertStudentPayment(studentPayment); return(Request.CreateResponse(HttpStatusCode.OK)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Failed to insert the payment of student, {ex.Message}")); } }
public HttpResponseMessage InsertLoans([FromBody] LoansDto loanDto) { try { LoanSupportRequest loan = Converters.Convert(loanDto); if (!ValidateModel.IsValid(new List <object>() { loan })) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ValidateModel.ModelsResults)); } LoanManager.InsertLoan(loan); return(Request.CreateResponse(HttpStatusCode.OK, loan.Id)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Failed to insert the loan, {ex.Message}")); } }
public HttpResponseMessage UpdateBranch([FromBody] BranchDto branchDto) { try { Branch branch = Converters.Convert(branchDto); if (!ValidateModel.IsValid(new List <object>() { branch })) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ValidateModel.ModelsResults)); } int rowsAffected = BranchManager.Update(branch); return(Request.CreateResponse(HttpStatusCode.Created, rowsAffected)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"failed to update branch {ex.Message}")); } }
public IHttpActionResult Update(long id, PersonDto personDto) { if (!ModelState.IsValid) { return(BadRequest(ModelState)); } try { Person personReceived = new Person(); if (!ValidateModel.IsAgeFormat(personDto.Age)) { return(BadRequest("Age can only be between 00 to 99 Format is incorrect")); } Mapper.Map <PersonDto, Person>(personDto, personReceived); // personReceived.Age = int.Parse(personDto.Age); int res = Repo.Update(id, personReceived); switch (res) { case ReturnCodeReference.Updated_SuccessFully: return(Ok(personDto)); case ReturnCodeReference.NotUpdated_EmailDormatProblem: return(BadRequest("Email Format is incorrect")); case ReturnCodeReference.NotUpdated_IdNotExist: return(NotFound()); case ReturnCodeReference.NotUpdated_UsernameExist: return(BadRequest("UserName can not be changed")); default: throw new Exception("Cannot Add new user at this moment: code 12000"); } } catch (Exception) { throw; } }
public async Task <IActionResult> Validate([FromBody] ValidateModel model) { var problem = await _context.Problem.FirstOrDefaultAsync(i => i.Id == model.Id); if (problem == null) { return(Content("Problem doesn't exist.")); } using var engine = factory.CreateEngine(); try { var script = engine.Precompile(problem.ServerSideScript ?? string.Empty); engine.Execute(script); var result = engine.CallFunction <string>("run", model.Param); engine.CollectGarbage(); return(Content(result)); } catch (Exception exception) { var sb = new StringBuilder(); Exception?ex = exception; while (ex != null) { sb.AppendLine($"Exception: {ex.Message}"); sb.AppendLine($"Source: {ex.Source}"); sb.AppendLine($"Stack trace: {ex.StackTrace}"); if (ex.Data.Count != 0) { var keys = ex.Data.Keys.Cast <object>().ToList(); var values = ex.Data.Values.Cast <object>().ToList(); sb.AppendLine("Addition data: "); for (var i = 0; i < keys.Count; i++) { sb.AppendLine($"{keys[i]} = {values[i]}"); } } ex = ex.InnerException; } return(Content(sb.ToString())); } }
public HttpResponseMessage InsertPendingStudent([FromBody] StudentDto studentDto, [FromUri] int branchId, [FromUri] int?studyPathId = null) { try { Student student = Converters.Convert(studentDto); if (!ValidateModel.IsValid(new List <object>() { student })) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ValidateModel.ModelsResults)); } StudentManager.InsertPendingStudent(student, branchId, studyPathId); return(Request.CreateResponse(HttpStatusCode.OK, student.Id)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Failed to insert the pending student, {ex.Message}")); } }
public HttpResponseMessage InsertFinancialSupportRequest([FromBody] FinancialSupportRequestDto financialSupportRequestDto, [FromUri] int studentId) { try { FinancialSupportRequest financialSupportRequest = Converters.Convert(financialSupportRequestDto); if (!ValidateModel.IsValid(new List <object>() { financialSupportRequest })) { return(Request.CreateResponse(HttpStatusCode.BadRequest, ValidateModel.ModelsResults)); } FinancialSupportManager.InsertFinancialSupportRequest(financialSupportRequest); return(Request.CreateResponse(HttpStatusCode.OK, financialSupportRequest.Id)); } catch (Exception ex) { return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, $"Failed to insert the financial support request, {ex.Message}")); } }
public ValidateModel Valid(string password = "") { var validate = new ValidateModel(); if (string.IsNullOrEmpty(Identification)) { validate.NotValid("Identificação Obrigatória."); } if (string.IsNullOrEmpty(Email)) { validate.NotValid("Email Obrigatória."); } else { if (!IsValidEmail(Email)) { validate.NotValid("Email inválido."); } } if (string.IsNullOrEmpty(Password)) { validate.NotValid("Senha Obrigatória."); } else if (!string.IsNullOrEmpty(password)) { var regex = new Regex(@"^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"); Match match = regex.Match(password); if (!match.Success) { validate.NotValid("Senha deve ter no mínimo de oito caracteres, pelo menos, uma letra maiúscula, uma letra minúscula, um número e um caractere especial."); } } return(validate); }
public void OnActionExecuting(ActionExecutingContext context) { if (!String.IsNullOrWhiteSpace(context.HttpContext.Request?.Headers["DMAUTH"])) { string token = System.Uri.UnescapeDataString(context.HttpContext.Request?.Headers["DMAUTH"]); string secrect = "F4760D"; JWTModule module = new JWTModule(); ValidateModel validateModel = new ValidateModel(); validateModel.Issuer = "*****@*****.**"; var verifyResult = module.VerifyToken(token, secrect, validateModel); if (verifyResult.Status != "OK") { context.Result = new BadRequestObjectResult(verifyResult.Content); } } else { context.Result = new BadRequestObjectResult("Authorization Token is missing from the Request "); } }