コード例 #1
0
ファイル: AccountController.cs プロジェクト: haos11/candidate
        public ActionResult Index(NewAccount model)
        {
            if (ModelState.IsValid)
            {
                _userManagement.Create(model.Login, model.NewPassword);
            }

            return View(model);
        }
コード例 #2
0
ファイル: AccountController.cs プロジェクト: haos11/candidate
        public ActionResult Index()
        {
            var user = _userManagement.Current();
            var model = new NewAccount
            {
                Login = user.Login
            };

            return View(model);
        }
コード例 #3
0
ファイル: UnitTest2.cs プロジェクト: jairov4/Braidwood
        public void AddAccount_GivenNewAccount()
        {
            var account = new NewAccount();

            account.Code           = "111";
            account.InitialBalance = 10000;
            account.Name           = "Bancos";
            account.Nature         = AccountNature.Debit;

            uut.AddAccount(account);
        }
コード例 #4
0
ファイル: UnitTest2.cs プロジェクト: jairov4/Braidwood
        public void AddAccount_GivenAlreadyUsedAccountCode_ShouldThrow()
        {
            var account = new NewAccount();

            account.Code           = "111";
            account.InitialBalance = 10000;
            account.Name           = "Bancos";
            account.Nature         = AccountNature.Debit;

            uut.AddAccount(account);
            uut.AddAccount(account);
        }
コード例 #5
0
ファイル: AccountOverview.cs プロジェクト: bin101/SFBoty
        private void btnCreateAccount_Click(object sender, EventArgs e)
        {
            NewAccount   frm    = new NewAccount();
            DialogResult result = frm.ShowDialog();

            if (result == DialogResult.OK)
            {
                AccountSettings s = frm.Setting;
                Settings.Add(s);
                dgvAccountList.Rows.Add(s.Username, s.Server, "gestopt");
            }
        }
コード例 #6
0
 // validate that the database editted the account and that the data is equal to what was returned, and what we sent
 public static void IntegrationTest_CompareAccounts(NewAccount sentData, ReturnableAccount retData, ReturnableAccount dataInDB)
 {
     Assert.NotNull(dataInDB);
     Assert.True(retData.Title == dataInDB.Title && retData.Title == sentData.Title);
     Assert.True(retData.Login == dataInDB.Login && retData.Login == sentData.Login);
     Assert.True(retData.Password == dataInDB.Password && retData.Password == sentData.Password);
     Assert.True(retData.Url == dataInDB.Url && retData.Url == sentData.Url);
     Assert.True(retData.Description == dataInDB.Description && retData.Description == sentData.Description);
     Assert.Equal(retData.LastModified, dataInDB.LastModified);
     Assert.Equal(retData.IsFavorite, dataInDB.IsFavorite);
     Assert.Equal(retData.FolderID, dataInDB.FolderID);
 }
コード例 #7
0
        public void RecommendAFriend(int referrerId, NewAccount friend)
        {
            // validation, open transaction etc
            var command = new RecommendAFriend
            {
                ReferrerId = referrerId,
                Friend     = friend
            };

            Task.Factory.StartNew(() => policy.Apply(command));
            // close transaction - success and failure handled in handlers
        }
コード例 #8
0
        /// <summary>
        /// Create new account with system and server.
        /// </summary>
        /// <param name="item"></param>
        /// <returns></returns>
        public async Task <Guid> CreateNewAccount(NewAccount item, string userExId)
        {
            var system = new Systems
            {
                CompanyName        = item.SystemCompanyName,
                Name               = item.SystemName,
                Version            = item.SystemVersion,
                TechSupportExpDate = item.SystemTechSupportExpDate
            };

            _repo.Systems.Add(system);
            await _repo.SaveChangesAsync();

            int systemId = system.SystemId;

            var server = new Servers
            {
                Name                   = item.ServerName,
                Host                   = item.ServerHost,
                CountryId              = _repo.CountryRegion.Where(c => c.CountryRegionCode == item.ServerCountryRegionCode).Select(c => c.CountryId).SingleOrDefault(),
                Model                  = item.ServerModel,
                SerialNumber           = item.ServerSerialNumber,
                WarrantyExpirationDate = item.ServerWarrantyExpirationDate,
                Cputype                = item.ServerCputype,
                Ram               = item.ServerRam,
                HardDisk          = item.ServerHardDisk,
                Ups               = item.ServerUps,
                AntivirusSoftware = item.ServerAntivirusSoftware
            };

            _repo.Servers.Add(server);
            await _repo.SaveChangesAsync();

            int serverId = server.ServerId;

            var account = new Accounts
            {
                UserId          = _repo.Users.Where(u => u.ExternalId == new Guid(userExId)).Select(u => u.UserId).SingleOrDefault(),
                CountryId       = _repo.CountryRegion.Where(c => c.CountryRegionCode == item.AccountCountryRegionCode).Select(c => c.CountryId).SingleOrDefault(),
                SystemId        = systemId,
                ServerId        = serverId,
                Name            = item.AccountName,
                Description     = item.AccountDescription,
                Type            = item.AccountType,
                PasswordExpires = item.AccountPasswordExpires
            };

            _repo.Accounts.Add(account);
            await _repo.SaveChangesAsync();

            return(_repo.Accounts.Where(a => a.AccountId == account.AccountId).Select(a => a.ExternalId).SingleOrDefault());
        }
コード例 #9
0
        public ActionResult Index(NewAccount account)
        {
            if (ModelState.IsValid)
            {
                _userManagement.Create(account.Login, account.NewPassword);
                _authentication.AuthenticateUser(account.Login);
                _environment.Prepare(Server.MapPath("~/Content/Resources"));

                return RedirectToAction("index", new { area = "dashboard", controller = "dashboard" });
            }

            return View(account);
        }
コード例 #10
0
 public ActionResult Create(NewAccount newAccount)
 {
     if (!IsAdminLogin())
     {
         return(RedirectToAction("Login"));
     }
     if (ModelState.IsValid)
     {
         // check email existed
         accountDB.Register(newAccount.Email, newAccount.NewPassword, newAccount.Name);
         return(RedirectToAction("CreateAccountSuccess"));
     }
     return(View());
 }
コード例 #11
0
        public IActionResult Post([FromBody] NewAccount newAccount)
        {
            var account = new Entities.Account()
            {
                Username  = newAccount.Username,
                Password  = newAccount.Password,
                CreatedBy = "Guest",
                CreatedOn = DateTime.Now
            };

            Context.Accounts.Add(account);
            Context.SaveChanges();

            return(Created($"/api/accounts/{account.AccountId}", account));
        }
コード例 #12
0
        public void TestCreateNewAccountWithInvalidCustomer()
        {
            // Set account repository mock.
            CustomerModel customer   = new CustomerModel(1010, "John", "Doe");
            AccountModel  newAccount = new AccountModel(0, customer, 0);

            this.accountRepository.Save(newAccount).ReturnsForAnyArgs(1001);
            this.customerRepository.GetById(1010).ReturnsForAnyArgs(a => null);

            NewAccount envelope = new NewAccount();

            envelope.CustomerId    = 1010;
            envelope.InitialCredit = 0;

            Assert.IsNotInstanceOfType(this.accountController.CreateNewAccountForExistingUser(envelope).Result, typeof(CreatedResult));
        }
コード例 #13
0
        public ActionResult Edit()
        {
            string     Email       = ((AccountLogin)Session[Constants.USER_SESSION]).Email;
            AccountDAO accountDAO  = new AccountDAO();
            var        account     = accountDAO.GetAccount(Email);
            var        editAccount = new NewAccount
            {
                Email    = account.Email,
                Name     = account.Name,
                Password = account.Password,
                Confirm  = account.Password,
                DoB      = account.DoB.Value,
                Phone    = account.Phone,
            };

            return(View(editAccount));
        }
コード例 #14
0
        public ResponseInfo TaoAccount(NewAccount newAccount)
        {
            DbContextTransaction transaction = context.Database.BeginTransaction();

            try
            {
                ResponseInfo result = new ResponseInfo();
                TblUser      user   = new TblUser
                {
                    Ho          = newAccount.Ho,
                    Ten         = newAccount.Ten,
                    Avatar      = "http://2.bp.blogspot.com/-Fl8NZJZFq6w/U02LSHQ7iII/AAAAAAAAAHg/zpzikQfynpM/s1600/WAPHAYVL.MOBI-CONDAU+(11).gif",
                    GioiTinh    = newAccount.GioiTinh,
                    NgaySinh    = newAccount.NgaySinh,
                    SoDienThoai = "0167229145",
                    CMND        = "192095142",
                    DiaChi      = "Hue"
                };
                TblAccount account = new TblAccount
                {
                    Username         = newAccount.Username,
                    Password         = Common.GetMD5(newAccount.Password),
                    Email            = newAccount.Email,
                    TokenActive      = Common.GetToken(0),
                    IsActived        = false,
                    SoLanDangNhapSai = 0,
                    KhoaTaiKhoanDen  = DateTime.Now
                };
                account.GroupOfAccount.Add(new TblGroupOfAccount
                {
                    IdGroup = 3
                });
                user.Account.Add(account);
                context.User.Add(user);
                context.SaveChanges();
                transaction.Commit();
                SendEmailRegister(account);
                return(result);
            }
            catch (Exception e)
            {
                transaction.Rollback();
                throw e;
            }
        }
コード例 #15
0
ファイル: OutBound.cs プロジェクト: Bayonetta5/Solution
        public static void NewAccount()
        {
            NewAccount P = new NewAccount
            {
                AccountID    = NewAccountDialog.AccountIDTextBox.Text,
                Password     = NewAccountDialog.Password1TextBox.Text,
                EMailAddress = NewAccountDialog.EMailTextBox.Text ?? string.Empty,
                BirthDate    =
                    !string.IsNullOrEmpty(NewAccountDialog.BirthDateTextBox.Text)
                        ? DateTime.Parse(NewAccountDialog.BirthDateTextBox.Text)
                        : DateTime.MinValue,
                UserName       = NewAccountDialog.UserNameTextBox.Text ?? string.Empty,
                SecretQuestion = NewAccountDialog.QuestionTextBox.Text ?? string.Empty,
                SecretAnswer   = NewAccountDialog.AnswerTextBox.Text ?? string.Empty
            };

            Network.Enqueue(P);
        }
コード例 #16
0
        public ActionResult <string> CreateNewAccountForExistingUser(NewAccount account)
        {
            // Verify if the parameter is valid.
            if (VerifyAccountModel(account))
            {
                long accountNumber = _accountService.CreateNewAccountForExistingUser(account);
                if (accountNumber == 0)
                {
                    this._logger.LogError("---> Error creating new account - Customer not found.");
                    return(BadRequest("Account not created - Customer not found.")); //HTTP Code 400
                }

                this._logger.LogInformation("---> New account created with number " + accountNumber);
                return(Created(accountNumber.ToString(), accountNumber.ToString())); //HTTP Code 201 - Created
            }
            this._logger.LogError("---> Error creating new account - Bad Request.");
            return(BadRequest("[ERROR] Invalid object provided for account creation.")); //HTTP Code 400
        }
コード例 #17
0
        public async Task <object> New(NewAccount newAccount)
        {
            var account = new Account
            {
                FirstName = newAccount.FirstName,
                LastName  = newAccount.LastName
            };

            _dbContext.Accounts.Add(account);
            await _dbContext.SaveChangesAsync();

            return(new Account
            {
                AccountId = account.AccountId,
                FirstName = account.FirstName,
                LastName = account.LastName
            });
        }
コード例 #18
0
ファイル: AccountDao.cs プロジェクト: PercyODI/Stage2.BankBer
        public Account InsertAccount(NewAccount accountToInsert)
        {
            using (var db = new LiteDatabase(BankBerDbLocation))
            {
                var accountCol = db.GetCollection <Account>("Accounts");

                var account = new Account()
                {
                    Id     = Guid.NewGuid(),
                    Name   = accountToInsert.Name,
                    Type   = accountToInsert.Type,
                    UserId = accountToInsert.UserId
                };

                accountCol.Insert(account);

                return(account);
            }
        }
コード例 #19
0
    private void CheckNewAccount(NewAccount vAccount)
    {
        string vSQLStr = "Select * FROM UserData WHERE (Account='" + vAccount.Account + "')";
        //是否有找到同樣帳號
        bool vFind = false;

        using (SqlConnection vCon = new SqlConnection("Data Source=184.168.47.10;Integrated Security=False;User ID=MobileDaddy;PASSWORD=Aa54380438!;Connect Timeout=15;Encrypt=False;Packet Size=4096"))
        {
            vCon.Open();

            using (SqlCommand cmd = new SqlCommand(vSQLStr, vCon))
            {
                SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    vFind = true;//有重複的
                }

                dr.Close();
            }

            if (vFind == true)
            {
                Response.Write("1");//這帳號重複
            }
            else
            {
                //將帳號寫入
                string vInsertStr = "INSERT INTO UserData(Account,Password,Mail,IPAddress) " +
                                    "VALUES('" + vAccount.Account + "','" + vAccount.Password + "','"
                                    + vAccount.Email + "','" + vAccount.IPAddress + "')";

                using (SqlCommand cmd = new SqlCommand(vInsertStr, vCon))
                {
                    cmd.ExecuteNonQuery();
                }

                Response.Write("0");
            }
        }
    }
コード例 #20
0
 public AccountsListViewModel()
 {
     App.DB.Accounts.Load();
     Accounts = new CollectionViewSource {
         Source = App.DB.Accounts.Local
     }.View;
     AddAccountCommand = new DelegateCommand <RoutedEventArgs>((e) => {
         var newaw = new NewAccount();
         newaw.ShowDialog();
     }, () => true);
     DeleteAccountCommand = new DelegateCommand <Account>((account) =>
     {
         if (account != null)
         {
             App.DB.Accounts.Remove(account);
             App.DB.SaveChanges();
             Accounts.Refresh();
         }
     }, () => true);
 }
コード例 #21
0
        public HttpResponseMessage CreateAccount(NewAccount account)
        {
            ResponseInfo response = new ResponseInfo();
            var          resp     = Request.CreateResponse(HttpStatusCode.InternalServerError, response);

            try
            {
                if (ModelState.IsValid)
                {
                    response         = new RegisterModel().TaoAccount(account);
                    response.IsValid = true;
                    if (response.Code == 200)
                    {
                        resp = Request.CreateResponse(HttpStatusCode.OK, response);
                    }
                    else
                    {
                        resp = Request.CreateResponse(HttpStatusCode.BadRequest, response);
                        Request.CreateResponse(response);
                    }
                }
                else
                {
                    response.Code = (int)ConstantsEnum.CodeResponse.NotValidate;
                    var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.DuLieuNhapSai);
                    response.TypeMsgError = errorMsg.Type;
                    response.MsgError     = errorMsg.Msg;
                }
            }
            catch (Exception e)
            {
                response.Code = (int)ConstantsEnum.CodeResponse.ServerError;
                var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.ServerError);
                response.TypeMsgError    = errorMsg.Type;
                response.MsgError        = errorMsg.Msg;
                response.ThongTinBoSung1 = e.Message;
                resp = Request.CreateResponse(HttpStatusCode.InternalServerError, response);
                Request.CreateResponse(response);
            }
            return(resp);
        }
コード例 #22
0
        public async Task <IActionResult> ValidateLogin([Bind("Mail,Password")] NewAccount account)
        {
            //we check wether the user exists and has the same password
            var users = await _context.Users.FindAsync(account.Mail);

            if (users == null)
            {
                return(RedirectToAction("Login"));
            }
            if (users.PasswordHash == EncodePassword(account.Password))
            {
                //Cookie Instanciation
                var claims = new List <Claim>
                {
                    new Claim(ClaimTypes.Name, account.Mail),
                    new Claim(ClaimTypes.Email, account.Mail),
                    //new Claim(ClaimTypes.Role, "Administrator"),
                };

                var claimsIdentity = new ClaimsIdentity(
                    claims, CookieAuthenticationDefaults.AuthenticationScheme);

                var authProperties = new AuthenticationProperties
                {
                    AllowRefresh = true,
                    ExpiresUtc   = DateTimeOffset.UtcNow.AddMinutes(10),
                    IsPersistent = true,
                };

                await HttpContext.SignInAsync(
                    CookieAuthenticationDefaults.AuthenticationScheme,
                    new ClaimsPrincipal(claimsIdentity),
                    authProperties);

                return(RedirectToAction("Index", "Home")); //success
            }
            else
            {
                return(RedirectToAction("Login")); //error
            }
        }
コード例 #23
0
        /// <summary>
        /// create a new account
        /// </summary>
        private void NewAccount()
        {
            var model = new NewAccount
            {
                ConcordTerms    = cb_terms.Checked,
                ConfirmPassword = Txt_ConfPassword_create.Text,
                Password        = Txt_Password_create.Text,
                PasswordHint    = Txt_PasswordHint_create.Text,
                UserName        = Txt_username_create.Text
            };

            if (ModelIsValid(model))
            {
                Properties.ActiveUser = new User
                {
                    UserName     = model.UserName,
                    Password     = model.Password,
                    PasswordHint = model.PasswordHint,
                    FileSettings = string.Empty
                };

                new FoldersBackup(new SettingsModel
                {
                    FoldersBackupModels = new List <FoldersBackupModel>()
                }).WriteSettings();

                Txt_username_create.Clear();
                Txt_Password_create.Clear();
                Txt_PasswordHint_create.Clear();
                Txt_ConfPassword_create.Clear();
                cb_terms.Checked = false;

                ChangeGB();
                Txt_username.Text = model.UserName;
                MessageBox.Show("Por favor, confirme a sua senha para continuar.", "Cadastro realizado com sucesso!", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);

                Txt_password.Focus();

                Startup();
            }
        }
コード例 #24
0
        public async Task <ActionResult <NewAccount> > CreateNewAccount(NewAccount account)
        {
            string data;

            try
            {
                data = Convert.ToString(await new GlobalRepositoryData().CreateNewAccount(account, _userEx));
                _logger.LogInformation($"CreateNewAccount {data} for {_userEx}");
                if (data == null)
                {
                    _logger.LogWarning($"No data found for {_userEx}");
                    return(NotFound(new { message = $"No data found for user : {_userEx} and account : {account}" }));
                }
            }
            catch (System.Exception ex)
            {
                _logger.LogError($"An error has occurred during data processing. For : {_userEx}. Error : {ex.Message}");
                return(StatusCode(500, $"An error has occurred during data processing. For : {_userEx}. Error : {ex.Message}"));
            }
            return(Ok(data));
        }
コード例 #25
0
        public async Task <object> CreateAccount(HttpRequestMessage requestBody)
        {
            try
            {
                string     body             = requestBody.Content.ReadAsStringAsync().Result;
                NewAccount deserial_account = null;

                //build a new entry for account table
                WarcraftAcct new_entry = new WarcraftAcct();
                deserial_account = JsonConvert.DeserializeObject <NewAccount>(body);

                //try to map JSON to account obj will throw on invalid
                //inputs or format
                if (body.Contains(",") || deserial_account == null ||
                    !acct_model.AccountEntryIsValid(deserial_account.name))
                {
                    throw new InvalidOperationException();
                }
                new_entry.account_name = FirstToUpper(deserial_account.name);
                new_entry.active       = true;

                List <int> account_match = await(from q in _db.WarcraftAccts
                                                 where q.account_name == new_entry.account_name
                                                 select q.account_id).ToListAsync();
                //check for name collisions

                if (account_match.FirstOrDefault() == 0)
                {
                    _db.WarcraftAccts.Add(new_entry);
                    await _db.SaveChangesAsync();

                    return(new { account_id = new_entry.account_id });
                }
            }
            catch (Exception ex)
            {
                return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Request Error: Account or Request Body Invalid"));
            }
            return(Request.CreateErrorResponse(HttpStatusCode.BadRequest, "Account Error: Account Name Already Exists"));
        }
コード例 #26
0
 public ActionResult Edit(NewAccount account)
 {
     if (ModelState.IsValid)
     {
         AccountDAO accountDAO   = new AccountDAO();
         var        AccountModel = accountDAO.GetAccount(account.Email);
         AccountModel.Name     = account.Name;
         AccountModel.Password = account.Password;
         AccountModel.Phone    = account.Phone;
         bool result = accountDAO.UpdateAccount(AccountModel);
         if (result)
         {
             return(RedirectToAction("Index", "Home"));
         }
         else
         {
             ModelState.AddModelError("", "Can not update!");
             return(View("Edit"));
         }
     }
     return(View("Edit"));
 }
コード例 #27
0
ファイル: UnitTest2.cs プロジェクト: jairov4/Braidwood
        public void AddTransaction_GivenOneEntry_ShouldThrow()
        {
            var account = new NewAccount();

            account.Code           = "111";
            account.InitialBalance = 10000;
            account.Name           = "Bancos";
            account.Nature         = AccountNature.Debit;

            uut.AddAccount(account);

            var transaction = new NewTransaction();

            transaction.Holder  = "holder";
            transaction.Entries = new List <AccountTransactionEntry>();
            transaction.Entries.Add(new AccountTransactionEntry()
            {
                AccountCode = "001", Value = 200
            });

            uut.AddTransaction(transaction);
        }
コード例 #28
0
        /// <summary>
        /// check if model new account is valid and set errors in errorprovider
        /// </summary>
        /// <param name="newAccount"></param>
        /// <returns>true if model is valid</returns>
        private bool ModelIsValid(NewAccount newAccount)
        {
            var validationResults = new List <ValidationResult>();
            var contexto          = new ValidationContext(newAccount, null, null);

            Validator.TryValidateObject(newAccount, contexto, validationResults, true);
            errorProvider1.Clear();
            foreach (var item in validationResults)
            {
                switch (item.MemberNames.First())
                {
                case nameof(newAccount.UserName):
                    errorProvider1.SetError(Txt_username_create, item.ErrorMessage);
                    break;

                case nameof(newAccount.Password):
                    errorProvider1.SetError(Txt_Password_create, item.ErrorMessage);
                    break;

                case nameof(newAccount.ConfirmPassword):
                    errorProvider1.SetError(Txt_ConfPassword_create, item.ErrorMessage);
                    break;

                case nameof(newAccount.PasswordHint):
                    errorProvider1.SetError(Txt_PasswordHint_create, item.ErrorMessage);
                    break;

                case nameof(newAccount.ConcordTerms):
                    errorProvider1.SetError(cb_terms, item.ErrorMessage);
                    break;

                default:
                    errorProvider1.SetError(Gb_newAcc, item.ErrorMessage);
                    break;
                }
            }

            return(!validationResults.Any());
        }
コード例 #29
0
        /// <summary>
        /// Tạo tài khoản theo thông tin người dùng đưa lên.
        /// Author       :   QuyPN - 17/06/2018 - create
        /// </summary>
        /// <param name="account">Thông tin tài khoản đăng ký mà người dùng nhập vào</param>
        /// <returns>Chỗi Json chứa kết quả của việc tạo tài khoản</returns>
        /// <remarks>
        /// Method: POST
        /// RouterName: homeCreateAccount
        /// </remarks>
        public JsonResult CreateAccount(NewAccount account)
        {
            ResponseInfo response = new ResponseInfo();

            try
            {
                if (ModelState.IsValid)
                {
                }
                else
                {
                    response.Code      = (int)CodeResponse.NotValidate;
                    response.ListError = ModelState.GetModelErrors();
                }
            }
            catch (Exception e)
            {
                response.Code            = (int)CodeResponse.ServerError;
                response.MsgNo           = (int)MsgNO.ServerError;
                response.ThongTinBoSung1 = e.Message;
            }
            return(Json(response, JsonRequestBehavior.AllowGet));
        }
コード例 #30
0
        public async Task <ActionResult> Post([FromBody] NewAccount account)
        {
            if (ModelState.IsValid)
            {
                //check customer exists
                var customer = await _repoCustomer.GetCustomerInfoAsync(_config.Value.CustomerBaseUrl, account.CustomerId);

                if (customer == null)
                {
                    throw new NotFoundException(string.Format("Customer with id '{0}' not found!", account.CustomerId));
                }

                //create account
                var created = await _repoFactory.CreateRepository().CreateAccountAsync(account.CustomerId);

                if (created == null)
                {
                    throw new SimpleWebApiException(HttpStatusCode.InternalServerError, "Unable to create account for customer!");
                }

                var responseUrl = string.Format(@"{0}/{1}", _config.Value.CustomerDetailsUrl, account.CustomerId);

                //check initial credit
                if (!account.InitialCredit.HasValue || account.InitialCredit.Value == 0d)
                {
                    return(Created(responseUrl, created.AccountId));
                }
                //register initial credit and wait for transaction status
                await MakeInitialCreditTransaction(created.AccountId, account.InitialCredit.Value);

                return(Created(responseUrl, created.AccountId));
            }
            else
            {
                throw new ValidationException("Please provide valid cusotmer id!", null);
            }
        }
コード例 #31
0
        public async Task <IActionResult> ValidateSignup([Bind("Mail,Password")] NewAccount newAccount)
        {
            Users users = new Users()
            {
                Mail         = newAccount.Mail,
                PasswordHash = EncodePassword(newAccount.Password)
            };

            if (ModelState.IsValid)
            {
                bool invalidUsername = false;
                try
                {
                    // checks if the data can be written
                    _context.Add(users);
                    await _context.SaveChangesAsync();
                }
                catch (DbUpdateException)
                {
                    invalidUsername = true;
                }
                catch (Npgsql.PostgresException)
                {
                    invalidUsername = true;
                }
                if (invalidUsername)
                {
                    return(RedirectToAction("Signup"));
                }
                else
                {
                    return(RedirectToAction("SignupSuccess"));
                }
            }
            return(RedirectToAction("Signup"));
        }
コード例 #32
0
        /// <summary>
        ///     Creates or gets an existing account.
        /// </summary>
        /// <param name="username">Unique user name.</param>
        /// <param name="password">Password string.</param>
        /// <returns>Created or existing account with username.</returns>
        public Account CreateAccount(
            string username,
            string password)
        {
            if (Accounts.ContainsKey(username))
            {
                Logger.Trace(
                    "Found an account with name:{0} returning.",
                    username);
                return(Accounts[username]);
            }

            Logger.Trace("Creating a new account with name:{0}", username);
            var a = new Account(username, password);

            Accounts.Add(username, a);

            if (NewAccount != null)
            {
                NewAccount.Invoke(a);
            }

            return(a);
        }
コード例 #33
0
ファイル: Refer_a_friend.cs プロジェクト: elbandit/PPPDDD
 public void ReferAFriend(int referrerId, NewAccount friend)
 {
     // ***** Activity 1 - implement this if you want to make the tests pass
 }
コード例 #34
0
        /// <summary>
        /// Tạo tài khoản cho người dùng dựa vào thông tin đã cung cấp.
        /// Author       :   HoangNM - 28/02/2019 - create
        /// </summary>
        /// <param name="newAccount">Thông tin tạo tài khoản của người dùng</param>
        /// <returns>Thông tin về việc tạo tài khoản thành công hay thất bại</returns>
        public ResponseInfo TaoAccount(NewAccount newAccount)
        {
            //DbContextTransaction transaction = context.Database.BeginTransaction();
            try
            {
                ResponseInfo result = new ResponseInfo();
                // Kiểm tra xem username đã tồn tại hay chưa
                TblTaiKhoan taiKhoan = context.TaiKhoans.FirstOrDefault(x => x.Username == newAccount.Username && !x.DelFlag);
                if (taiKhoan == null)
                {
                    // Kiểm tra xem email đã tồn tại hay chưa
                    taiKhoan = context.TaiKhoans.FirstOrDefault(x => x.Email == newAccount.Email && !x.DelFlag);
                    if (taiKhoan == null)
                    {
                        // Tạo user mới
                        TblThongTinNguoiDung user = new TblThongTinNguoiDung
                        {
                            Ten      = newAccount.Ten,
                            GioiTinh = newAccount.GioiTinh,
                            NgaySinh = newAccount.NgaySinh,
                        };
                        context.ThongTinNguoiDungs.Add(user);
                        context.SaveChanges();



                        string salt = BaoMat.GetSalt();

                        //// Tạo tài khoản đăng nhập cho user
                        taiKhoan = new TblTaiKhoan
                        {
                            Id_User      = user.Id,
                            Username     = newAccount.Username,
                            salt_Pass    = salt,
                            hash_Pass    = BaoMat.GetMD5(BaoMat.GetSimpleMD5(newAccount.Password), salt),
                            Email        = newAccount.Email,
                            Id_TrangThai = 1,
                            Id_NhomDich  = 1,
                            Id_Face      = "",
                            Id_Google    = "",
                            Id_PhanQuyen = 5
                        };



                        context.TaiKhoans.Add(taiKhoan);
                        // Lưu vào CSDL
                        context.SaveChanges();



                        result.Code      = 200;
                        result.IsSuccess = true;
                        result.IsValid   = true;

                        var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.TaoTaiKhoanThanhCong);
                        result.TypeMsgError = errorMsg.Type;
                        result.MsgError     = errorMsg.Msg;
                    }
                    else
                    {
                        result.Code = 400;
                        var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.EmailDaTonTai);
                        result.TypeMsgError = errorMsg.Type;
                        result.MsgError     = errorMsg.Msg;
                    }
                }
                else
                {
                    result.Code = 400;
                    var errorMsg = new GetErrorMsg().GetMsg((int)MessageEnum.MsgNO.UserNameDaDung);
                    result.TypeMsgError = errorMsg.Type;
                    result.MsgError     = errorMsg.Msg;
                }
                //transaction.Commit();
                return(result);
            }
            catch (Exception e)
            {
                throw e;
            }
        }