public async Task<RegisterResponse> RegisterAsync (RegisterRequest request) { await Task.Delay (2000); return new RegisterResponse { Succeeded = true, Result = true }; }
public void RegisterAsync(Uri notificationUri, IDictionary<string, string> extraInfo) { Uri registerUri = new Uri(_registrationServiceUri + RegisterMethodPath); var client = _webClientFactory.CreateWebClient(); client.SendCompleted += OnRegisterCompleted; var reg = new RegisterRequest() { uniqueId = UniqueNotificationId, notificationChannel = notificationUri.ToString(), extraInfo = extraInfo }.ToJson(); client.SendStringAsync(registerUri, reg, JsonContentType); }
public async Task ShouldResponse400_WhenConflictEmail() { var userRepoMock = new Mock <IUserRepository>(); var controller = new AuthController(AutoMapperConfig.Instance, null, userRepoMock.Object); userRepoMock.Setup(x => x.IsExistEmail(It.IsAny <string>())) .Returns(true); var model = new RegisterRequest { Name = "test", Email = "*****@*****.**", Password = "******" }; var result = await controller.Register(model); var response = Assert.IsType <BadRequestObjectResult>(result); Assert.Equal(ErrorResponse.EmailConflict, response.Value); }
public override Task <RegisterResponse> Register(RegisterRequest request, ServerCallContext context) { config = new ConfigurationBuilder() .SetBasePath(new DirectoryInfo(Directory.GetCurrentDirectory()).Parent.FullName + "/config") .AddJsonFile("config.json", optional: false) .Build(); string id = Guid.NewGuid().ToString(); Console.WriteLine(request); saveToRedis(id + "_description", request.Description); saveToRedis(id + "_data", request.Data); publishEvent(id); var resp = new RegisterResponse { Id = id }; _jobs[id] = request.Description; return(Task.FromResult(resp)); }
[Route("register")] //api/authentication/register public async Task <ActionResult> RegisterUser(RegisterRequest registerRequest) { var user = new ApplicationUser { Email = registerRequest.Email, UserName = registerRequest.Email, SecurityStamp = Guid.NewGuid().ToString() }; var result = await _userManager.CreateAsync(user, registerRequest.Password); var confirmationToken = await _userManager.GenerateEmailConfirmationTokenAsync(user); if (result.Succeeded) { return(Ok(new RegisterResponse { ConfirmationToken = user.SecurityStamp })); } return(BadRequest(result.Errors)); }
public async void OnRegisterClick() { if (!ValidateForm()) { return; } // try to save te new user RegisterRequest request = new RegisterRequest() { fullName = _fullName.GetValue(), nickname = _nickname.GetValue(), email = _email.GetValue(), password = _password.GetValue(), }; RegisterResponse response; try { response = await Global.RestClient.Post <RegisterResponse>("/account/register", request); } catch (ResponseException e) { _title.SetMessage(e.Message, MessageType.Error); return; } ResetForm(); _title.SetMessage($"Thanks {response.Nickname}!"); // await Task.Delay(3000); ResetForm(); OnSignInClick(); }
public CommentsControllerTest() { var logFactory = LoggerFactory.Create(builder => builder.AddConsole()); var logger = logFactory.CreateLogger <CommentsController>(); var notificationServiceFake = new NotificationServiceFake(); var databaseService = new DatabaseServiceFake(); var requestModel = new RegisterRequest() { Email = "*****@*****.**", Name = "Tester", Password = "******" }; var user = new User(requestModel) { Id = ObjectId.GenerateNewId().ToString() }; var currentUser = databaseService.SaveUserAsync(user).Result; var articleRequest = new ArticleBasicInfo() { Title = "title", Abstract = "abstract", Content = "content" }; var article = new Article(articleRequest, currentUserId); article.Id = SAMPLE_ARTICLE_ID; var sampleArticle = databaseService.SaveArticleAsync(article).Result; var claims = new[] { new Claim(ClaimTypes.Name, currentUser.Name), new Claim(ClaimTypes.NameIdentifier, currentUser.Id) }; var httpContextAccessFake = new HttpContextAccessorFake(claims); currentUserId = httpContextAccessFake.HttpContext.User.FindFirst(ClaimTypes.NameIdentifier)?.Value; commentsController = new CommentsController(httpContextAccessFake, databaseService, logger); }
/// <summary> /// 更新成員資訊 - 人員管理專用 /// </summary> /// <param name="data"></param> /// <param name="file"></param> /// <returns></returns> public bool UpdateMemberInfo(RegisterRequest data, FileViewModel file) { try { var db = _uow.DbContext; var encryptionService = new Encryption(); //取得目前DB人員資料 var memberInfo = db.Members.FirstOrDefault(t => t.Id == data.Id); if (memberInfo == null) { return(false); } memberInfo.Account = data.Account; memberInfo.Name = data.Name; memberInfo.Email = data.Email; memberInfo.Updated = TimeData.Create(DateTime.UtcNow); memberInfo.UpdateUser = data.Id; memberInfo.Enable = data.Enable; if (data.Pwd != null) { var deCodePwd = encryptionService.DecryptString(data.Pwd, appKey); memberInfo.PassWord = encryptionService.StringToSHA256(deCodePwd); } if (file != null) { if (file.ContentLength > 0) { memberInfo.Photo = memberPhotoProxy(data.Id, file); } } db.SaveChanges(); return(true); } catch (Exception ex) { return(false); } }
public async Task <ApiResult <bool> > RegisterUser(RegisterRequest registerRequest) { var client = _httpClientFactory.CreateClient(); client.BaseAddress = new Uri(_configuration["BaseAddress"]); var sessions = _httpContextAccessor.HttpContext.Session.GetString("Token"); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", sessions); var json = JsonConvert.SerializeObject(registerRequest); var httpContent = new StringContent(json, Encoding.UTF8, "application/json"); var response = await client.PostAsync($"/api/users", httpContent); var result = await response.Content.ReadAsStringAsync(); if (response.IsSuccessStatusCode) { return(JsonConvert.DeserializeObject <ApiSuccessResult <bool> >(result)); } return(JsonConvert.DeserializeObject <ApiErrorResult <bool> >(result)); }
public async Task SignUp_TooSimplePassword_Error() { // Arrange var randomEmail = TestUserFactory.GenerateRandomEmail(); RegisterRequest request = new RegisterRequest { Email = randomEmail, FirstName = TestUserFactory.FirstName, LastName = TestUserFactory.LastName, Password = "******" }; // Act var responseMessage = await HttpClient.PostAsync("/api/Account/SignUp", request); // Assert Assert.False(responseMessage.IsSuccessStatusCode); ErrorResponse errorResponse = await responseMessage.ReadContentAsync <ErrorResponse>(); Assert.Contains(errorResponse.Errors, err => err.Code == "PasswordTooShort"); }
public async Task <IActionResult> Register(RegisterRequest model) { var user = new AppIdentityUser { UserName = model.UserName, Email = model.Email, }; var result = await userManager.CreateAsync(user, model.Password); if (!result.Succeeded) { foreach (var validateItem in result.Errors) { ModelState.AddModelError("", validateItem.Description); } return(View(model)); } return(Redirect("~/administrator/login")); }
public async Task <ApiResult <bool> > Update(RegisterRequest request, int userId) { var user = await _context.Users.FindAsync(userId); var role = await _context.Roles.FindAsync(request.RoleId); if (user == null) { return(new ApiResultErrors <bool>("Not found")); } user.Email = request.Email; user.FirstName = request.FirstName; user.LastName = request.LastName; user.Role = role; user.Gender = request.Gender; user.WorkPlace = request.WorkPlace; user.PhoneNumber = request.PhoneNumber; user.Address = request.Address; await _context.SaveChangesAsync(); return(new ApiResultSuccess <bool>()); }
public void Register_PasswordMisMatch_ReturnsValidationError() { //test to see if both passwords match on input when registering var model = new RegisterRequest { Email = "*****@*****.**", FirstName = "Homer", LastName = "", Password = "******", ConfirmPassword = "******", LicenceNumber = "123456789", DateOfBirth = new DateTime(2000, 1, 1) }; Controller.Validate(model); var response = Controller.Register(model); Assert.AreEqual("Form has validation errors", response.Message); Assert.IsTrue(response.Errors.Contains( "The password and confirmation password do not match.", StringComparer.InvariantCultureIgnoreCase)); }
public async Task <IActionResult> Register(string login, string password, string firstName, string lastName, string surName) { RegisterRequest registerRequest = new RegisterRequest() { Login = login, Password = password, FirstName = firstName, LastName = lastName, SurName = surName }; try { await _usersService.Register(registerRequest); return(Ok()); } catch (Exception err) { return(BadRequest(err.Message)); } }
private (bool, string) ValidateForm(RegisterRequest model) { if (string.IsNullOrEmpty(model.Name)) { return(false, "Имя не заполнено"); } if (string.IsNullOrEmpty(model.Surname)) { return(false, "Фамилия не заполнена"); } if (model.DateOfBirth.Year == 0001) { return(false, "Дата не заполнена"); } if (model.DateOfBirth.Year > 2010) { return(false, "Некорректная дата"); } //if (string.IsNullOrEmpty(model.Username)) //{ // return (false, "Логин не заполнен"); //} if (string.IsNullOrEmpty(model.Email)) { return(false, "Почта не заполнена"); } //if (string.IsNullOrEmpty(model.Password)) //{ // return (false, "Почта не заполнена"); //} return(true, string.Empty); }
public async Task <IActionResult> Register(RegisterRequest request) { if (!ModelState.IsValid) { return(View(request)); } request.origin = Request.Headers["origin"]; var result = await _userApiClient.RegisterUser(request); if (!result.IsSuccessed) { ModelState.AddModelError("", result.Message); return(View()); } var loginResult = await _userApiClient.Authenticate(new LoginRequest() { UserName = request.UserName, Password = request.Password, RememberMe = true }); var userPrincipal = this.ValidateToken(loginResult.ResultObj); //xác thực và thời hạn của phiên đăng nhập var authProperties = new AuthenticationProperties { ExpiresUtc = DateTimeOffset.UtcNow.AddMinutes(20), IsPersistent = false }; HttpContext.Session.SetString(SystemConstants.AppSettings.Token, loginResult.ResultObj); await HttpContext.SignInAsync( CookieAuthenticationDefaults.AuthenticationScheme, userPrincipal, authProperties); _notyf.Success($"Xin chào {request.UserName}"); return(RedirectToAction("Index", "Home")); }
public async Task <bool> Register(RegisterRequest request) { var user = new AppUser() { Dob = request.Dob, Email = request.Email, FirstName = request.FirstName, LastName = request.LastName, UserName = request.UserName, PhoneNumber = request.PhoneNumber }; var result = await _userManager.CreateAsync(user, request.Password); if (result.Succeeded) { return(true); } else { return(false); } }
public async Task <IActionResult> Register(RegisterRequest registerRequest) { if (registerRequest.Password != registerRequest.PasswordConfirmation) { return(Failure()); } var user = new User() { Email = registerRequest.Email, UserName = registerRequest.Email }; var registerResult = await _userManager.CreateAsync(user, registerRequest.Password); if (!registerResult.Succeeded) { return(Failure()); } return(Success()); }
public bool RegisterClient(RegisterRequest request) { try { context.Clients.Add(new Models.Client { FirstName = request.FirstName, LastName = request.LastName, Email = request.Email, Phone = request.Phone, Login = request.Login, Password = request.Password, Salt = request.Salt }); context.SaveChanges(); return(true); } catch (Exception) { return(false); } }
public void Register_UserIsRegistered_PasswordIsEncrypted() { //check on password encrpytion is correct by passing //clear text password Console.WriteLine("Starting test"); var model = new RegisterRequest { Email = "*****@*****.**", FirstName = "Homer", LastName = "Simpson", Password = "******", ConfirmPassword = "******", LicenceNumber = "123456789", DateOfBirth = new DateTime(1970, 1, 1) }; Console.WriteLine("Validating model"); Controller.Validate(model); Console.WriteLine("Registering model"); var registerResponse = Controller.Register(model); Console.WriteLine("Response was"); Console.WriteLine(JsonConvert.SerializeObject(registerResponse, Formatting.Indented)); Assert.IsTrue(registerResponse.Success); Console.WriteLine("Find user by email"); var user = UserRepository.FindByEmail(model.Email); Console.WriteLine( JsonConvert.SerializeObject(user, Formatting.Indented)); Console.WriteLine("Comparing {0} to {1}", model.Password, user.Password); Assert.IsFalse(model.Password.Equals(user.Password, StringComparison.InvariantCultureIgnoreCase)); }
public async Task <AuthenticateResponse> Register(RegisterRequest model) { var user = await db.Users.Find(item => item.Email == model.Email).FirstOrDefaultAsync(); if (user != null) { return(null); } var newUser = new User { Name = model.Name, Email = model.Email, Password = model.Password }; CreatePasswordHash(model.Password, newUser); await db.Users.InsertOneAsync(newUser); return(new AuthenticateResponse(newUser, GenerateJwtToken(newUser))); }
public async Task <string> Register(RegisterRequest resigerInfo) { var user = new VehicleTrackingUser() { UserName = resigerInfo.UserName, Email = resigerInfo.Email }; var createResult = await _userManager.CreateAsync(user, resigerInfo.Password); if (!createResult.Succeeded) { throw new CreateUserFailException(ErrorCode.E003); } //Set default Role is vehicleTrackingUser await _userManager.AddToRoleAsync(user, "VehicleTrackingUser"); var token = await GenerateJWT(user); return(new JwtSecurityTokenHandler().WriteToken(token)); }
public async Task Register_CreateAndRegisterUserInApplication_NewUserShouldBeSavedInDb() { var registerRequest = new RegisterRequest { Login = "******", Password = "******", Email = "*****@*****.**" }; HttpContent httpContent = new StringContent( JsonConvert.SerializeObject(registerRequest), Encoding.UTF8, "application/json"); var response = await httpClient.PostAsync($"/api/register", httpContent); response.EnsureSuccessStatusCode(); var dbUserName = dbContext.Users.SingleOrDefault(x => x.Login == registerRequest.Login); Assert.NotNull(dbUserName); Assert.Equal(dbUserName.Email, registerRequest.Email, true); }
public Task <HttpResponseMessage> Register([FromBody] RegisterRequest registerRequest) { var user = new UserDto() { Username = registerRequest.Username, Password = registerRequest.Password, FullName = registerRequest.FullName, Email = registerRequest.Email }; user = userRepository.Create(user); var response = new { UserId = user.Id, Username = user.Username, FullName = user.FullName, Email = user.Email }; return(Task.FromResult(Request.CreateResponse(HttpStatusCode.Created, response))); }
private void RegisterHandler(string requestInJson) { RegisterRequest registerRequest = JsonSerializer.Deserialize <RegisterRequest>(requestInJson); var response = new RegisterResponse { RequestId = registerRequest.Id }; try { User newUser = new User(registerRequest.Sender, registerRequest.Password, UserState.Authorized); server.UserRepository.Add(newUser); response.Code = StatusCode.Ok; response.UserName = newUser.Name; CurrentUserName = newUser.Name; Console.WriteLine($"{CurrentUserName} signed up successfully."); } catch (NedoGramException nedoGramException) { response.Code = StatusCode.ClientError; response.Message = nedoGramException.Message; Console.WriteLine($"{registerRequest.Action}: {registerRequest.Sender} - {nedoGramException.Message}"); } catch (Exception exception) { response.Code = StatusCode.ServerError; response.Message = "Internal error"; Console.WriteLine($"{registerRequest.Action}: {registerRequest.Sender} - {exception.Message}"); } finally { SendMessageAesEncrypted(response, ClientAesKey); } }
protected override void OnInit() { closeButton = transform.GetInstance <Button>("CloseButton"); closeButton.onClick.AddListener(OnCloseClick); userInput = transform.GetInstance <InputField>("UserName/InputField"); pwdInput = transform.GetInstance <InputField>("PassWord/InputField"); rePwdInput = transform.GetInstance <InputField>("RePassWord/InputField"); registerButton = transform.GetInstance <Button>("RegisterButton"); registerButton.onClick.AddListener(OnRegisterClick); registerRequest = GetComponent <RegisterRequest>(); #region MyRegion // transform.GetInstance("CloseButton",out closeButton); // transform.GetInstance("UserName/InputField",out userInput); // transform.GetInstance("PassWord/InputField", out pwdInput); // transform.GetInstance("RePassWord/InputField", out rePwdInput); // transform.GetInstance("RegisterButton", out registerButton); #endregion }
public async Task RegisterPreAuthTest() { var client = new IpayClient("test_api", "test_api1"); var data = new RegisterRequest { Currency = IPayCurrency.RON, Description = "Test", Amount = 1519525,// => 15.195,25 ReturnUrl = "https://ecclients.btrl.ro:5443/payment/merchants/Test_BT/finish.html", //JsonParams = "{\"tipPlata\":\"IT\" , \"18\":\"8590\" , \"98\":\"2356\" , \"154\":\"167\"}", OrderBundle = new OrderBundle { CustomerDetails = new CustomerDetails { Phone = "+045 435 3453 45345345", //Email = "email", Contact = "Vasile Ion ăîîasdsadşţâîăpş", BillingInfo = new BillingInfo { City = "Cluj", PostAddress = "Dumbrăvii 101 " + Environment.NewLine + " cevăăîş aa", }, DeliveryInfo = new DeliveryInfo { City = "Iasi" + Environment.NewLine + " cevăăîş aa", PostAddress = "M. Eminescu" + Environment.NewLine + " cevăăîş aa", } } } //OrderBundle = "{\"orderCreationDate\":\"2019-05-12\",\"customerDetails\":{\"email\":\"[email protected]\",\"phone\":\"4073119839\",\"contact\":\"contact_text\",\"deliveryInfo\":{\"deliveryType\":\"thistype\",\"country\":\"642\",\"city\":\"Cluj\",\"postAddress\":\"Strada Speraneti nr 132\",\"postalCode\":\"12345\"},\"billingInfo\":{\"deliveryType\":\"thistype\",\"country\":\"642\",\"city\":\"Cluj\",\"postAddress\":\"Strada Speraneti nr 132\",\"postAddress2\":\"Strada Speraneti nr 132\",\"postAddress3\":\"Strada Speraneti nr 132\",\"postalCode\":\"12345\"}}}" }; var response = await client.Register(data); response.Should().NotBeNull(); response.ErrorCode.Should().Be(ErrorCode.Success); response.FormUrl.Should().NotBeEmpty(); }
[AllowAnonymous] // This method does not require authorization token public async Task <IActionResult> Register([FromBody] RegisterRequest request) { using (logger.BeginScope(nameof(Register))) { var user = new ApplicationUser { UserName = request.UserName, Email = request.Email, }; var result = await userManager.CreateAsync(user, request.Password); if (result.Succeeded) { logger.LogInformation("User {0} created", request.UserName); return(Ok()); } logger.LogError("User {0} registration failed", request.UserName); return(NotFound(result.Errors)); } }
private async Task <ResponseMessage> RegisterClient(RegisterRequest registerRequest) { ApplicationUser user = await _userManager.FindByEmailAsync(registerRequest.Email); UsuarioRegistradoIntegrationEvent registeredUser = new UsuarioRegistradoIntegrationEvent(Guid.NewGuid(), registerRequest.Name, registerRequest.Email, registerRequest.Cpf); UsuarioRegistradoSendMailIntegrationEvent registeredUserSendMail = new UsuarioRegistradoSendMailIntegrationEvent(Guid.NewGuid(), registerRequest.Name, registerRequest.Email, registerRequest.Cpf); try { RetryPolicy policy = Policy.Handle <Exception>() .WaitAndRetry(15, retryAttempt => TimeSpan.FromSeconds(Math.Pow(2, retryAttempt)), (outcome, timespan, retryCount, context) => { Console.WriteLine($"Tentando pela {retryCount} vez!"); }); var result = await policy.Execute(async() => await _bus.RequestAsync <UsuarioRegistradoIntegrationEvent, ResponseMessage>(registeredUser)); if (result.ValidationResult.IsValid) { await policy.Execute(async() => await _bus.PublishAsync(registeredUserSendMail)); } return(result); } catch (Exception e) { await _userManager.DeleteAsync(user); throw; } }
public async Task <Responce <RegistrationDTO> > Register(string Name, string Email, string City, string Mobile, string Password, string ConfirmPassword, int CityId) { try { RegisterRequest registerRequest = new RegisterRequest(); registerRequest.City = City; registerRequest.Name = Name.Trim(); registerRequest.Email = Email.Trim(); registerRequest.PhoneNumber = Mobile; registerRequest.Password = Password.Trim(); registerRequest.Cityid = CityId; registerRequest.ConfirmPassword = ConfirmPassword.Trim(); string Json = JsonConvert.SerializeObject(registerRequest); var result = await restapiHelper.PosyAsync <Responce <RegistrationDTO> >(EndPoint.Account.Register, Json); return(result); } catch (Exception ex) { return(null); } }
public async Task <IActionResult> Register([FromBody] RegisterRequest model) { var user = new ApplicationUser(); user.Email = model.Email; user.UserName = model.UserName; user.Location = model.Location; user.Latitude = model.Latitude; user.Longitude = model.Longitude; user.IsStore = model.IsStore; if (model.IsStore == true) { var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { return(Ok()); } else { return(BadRequest()); } } else { var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { return(Ok()); } else { return(BadRequest()); } } }
public IHttpActionResult Register(RegisterRequest request) { BaseViewModel viewmodel = new BaseViewModel(); UserDataController dataCtrl = new UserDataController(); try { Boolean checkEmail = dataCtrl.CheckExistingEmail(request.Email); Boolean checkNickname = dataCtrl.CheckExistingNickname(request.Nickname); if (checkEmail) { return(Warning(viewmodel, "Eingegebene Email wird bereits verwendet.")); } else if (checkNickname) { return(Warning(viewmodel, "Eingegebener Nickname wird bereits verwendet.")); } else { if (request.Password1 == request.Password2) { String Salt; String HashedPassword = PasswordHelper.CreatePassword(request.Password1, out Salt); dataCtrl.Insert(request.ToModel(HashedPassword, Salt)); } else { return(Warning(viewmodel, "Die eingegebenen Passwörter stimmen nicht überein.")); } } } catch (Exception ex) { return(Error(viewmodel, ex)); } return(Ok(viewmodel, "Registrierung erfolgreich. Du kannst dich nun einloggen.")); }
/// <summary> /// Begins the payment. /// </summary> /// <param name="paymentSystem">The payment System.</param> /// <param name="paymentArgs">The payment arguments.</param> public override void Invoke([NotNull] PaymentSystem paymentSystem, [NotNull] PaymentArgs paymentArgs) { Assert.IsNotNull(paymentSystem, "Payment method is null"); Assert.ArgumentNotNull(paymentArgs, "paymentArgs"); Assert.IsNotNull(paymentArgs.ShoppingCart, "Shopping cart is null"); PaymentSettingsReader configuration = new PaymentSettingsReader(paymentSystem); string merchantId = paymentSystem.Username; string token = paymentSystem.Password; string amount = paymentArgs.ShoppingCart.Totals.TotalPriceIncVat.ToCents(); string currencyCode = this.Currency(paymentArgs.ShoppingCart.Currency.Code); string orderNumber = paymentArgs.ShoppingCart.OrderNumber; string redirectUrl = paymentArgs.PaymentUrls.ReturnPageUrl; string paymentSystemCode = paymentSystem.Code; string webServicePlatform = configuration.GetSetting("webServicePlatform"); string language = configuration.GetSetting("language"); RegisterRequest request = new RegisterRequest { Order = new Order { Amount = amount, OrderNumber = orderNumber, CurrencyCode = currencyCode }, Terminal = new Terminal { Language = language, RedirectUrl = redirectUrl }, Environment = new Services.Environment { WebServicePlatform = webServicePlatform } }; Netaxept client = new Netaxept(); try { RegisterResponse response = client.Register(merchantId, token, request); NameValueCollection data = new NameValueCollection { { "MerchantID", merchantId }, { "TransactionID", response.TransactionId } }; ITransactionData transactionDataProvider = Context.Entity.Resolve<ITransactionData>(); transactionDataProvider.SaveStartValues(orderNumber, amount, currencyCode, paymentSystemCode); this.PostData(paymentSystem.PaymentUrl, data); } catch (Exception exception) { Log.Error(exception.Message, this); HttpContext.Current.Session["paymentErrorMessage"] = exception.Message; HttpContext.Current.Response.Redirect(paymentArgs.PaymentUrls.FailurePageUrl, false); HttpContext.Current.ApplicationInstance.CompleteRequest(); } }
public void WillInvalidateModelStateAndShowTheViewWhenAnEntityExceptionIsThrow() { var controller = GetController<AuthenticationController>(); GetMock<IUserService>() .Setup(x => x.Create(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<string>())) .Throws(new EntityException("aMessage")); var request = new RegisterRequest { Username = "******", Password = "******", EmailAddress = "theEmailAddress", }; var result = controller.Register(request, null); ResultAssert.IsView(result); Assert.False(controller.ModelState.IsValid); Assert.Equal("aMessage", controller.ModelState[String.Empty].Errors[0].ErrorMessage); }
public RegisterViewModel Get(RegisterRequest request) { return new RegisterViewModel(); }
public static void DoRegister(string username, string password, StreamWriter sw, StreamReader sr) { try { //controllo che username e password non siano nulli if (String.IsNullOrEmpty(username) || String.IsNullOrEmpty(password)) { //TODO eccezzione ad hoc per campi invalidi throw new Exception("Username o password hanno campi invalidi"); } //Fillo una nuova richiesta di registrazione e la invio RegisterRequest register = new RegisterRequest(username, password); NetworkWriteLine(sw,register.ToJSON()); string receive = NetworkReadLine(sr); //Parso la risposta e leggo l'esito della risposta Response res = Response.fromJson(receive); if (res.Result != 200) { throw new Exception(BadRegistrationResponse.fromJson(receive).Msg); } Console.WriteLine("Registrazione avvenuta con successo."); } catch (Exception e) { throw new RegisterExceptionU(e.Message); } }
//Attempts to register a user based on the information on the form. //RegisterInfo is collected. //Then the registration is attempted. //The response is passed back on the response paramater. private void RegisterUser() { try { this.Cursor = Cursors.WaitCursor; JabberID JID = new JabberID(UserNameTextBox.Text, ServerNameTextBox.Text, ResourceTextBox.Text); //get registration info RegisterInfoResponse IQRegisterInfoResponse = GetRegistrationInfo(JID); RegisterRequest IQRegister = new RegisterRequest(new JabberID(ServerNameTextBox.Text), JID.UserName, PasswordTextBox.Text, IQRegisterInfoResponse.Key); _SessionManager.Send(IQRegister, 30000); } finally { this.Cursor = Cursors.Default; } }
public static LoginResponse RegisterRequest(string ip, string email, string username, string password, string mobile, int shopId, int companyId, string idCard = "", string realName = "", string province = "", string city = "", string area="") { var register = new RegisterRequest { Ip = ip, Email = email, UserName = username, Password = password, RegisterType = 0, Mobile = mobile, AppSecret = YunClient.AppSecret, CompanyId = companyId, ShopId = shopId, IdCard = idCard, RealName = realName, Province = province, City = city, Area = area }; var r = YunClient.Instance.Execute(register); return r.IsError ? new LoginResponse() : r; }
protected bool Equals(RegisterRequest other) { return string.Equals(Version, other.Version) && string.Equals(Challenge, other.Challenge) && string.Equals(AppId, other.AppId) && string.Equals(SessionId, other.SessionId); }
public SignInOrRegisterRequest(RegisterRequest request) { RegisterRequest = request; }