public async Task TestGetUserByIdAsync_CheckLastAccessedUpdated() { var accountStatus = new AccountStatus { AccountStatusId = 1, Status = "hello" }; var id = Guid.NewGuid(); var principal = new Principal(); var userAccount = new UserAccount(); principal.UserAccount = userAccount; userAccount.Principal = principal; userAccount.AdGuid = id; userAccount.AccountStatus = accountStatus; context.UserAccounts.Add(userAccount); context.AccountStatuses.Add(accountStatus); Assert.IsFalse(userAccount.LastAccessed.HasValue); Assert.AreEqual(0, context.SaveChangesCount); Assert.AreEqual(0, context.SaveChangesAsyncCount); var result = await service.GetUserByIdAsync(id); DateTimeOffset.Now.Should().BeCloseTo(userAccount.LastAccessed.Value, 2000); Assert.AreEqual(0, context.SaveChangesCount); Assert.AreEqual(1, context.SaveChangesAsyncCount); }
public AccountState WithStatus(AccountStatus newStatus) => new AccountState( Status: newStatus, Currency: this.Currency, AllowedOverdraft: this.AllowedOverdraft, Transactions: this.TransactionHistory );
protected BankAccount() { _number = ""; _owner = ""; _balance = 0.00M; _status = AccountStatus.Opened; }
static void Main(string[] args) { //var dc = new DiscountManager(); //var dc = new DiscountManager(new DefaultAccountDiscountCalculatorFactory(), new DefaultLoyaltyDiscountCalculator()); var discountsDictionary = new Dictionary <AccountStatus, IAccountDiscountCalculator> { { AccountStatus.NotRegistered, new NotRegisteredDiscountCalculator() }, { AccountStatus.SimpleCustomer, new SimpleCustomerDiscountCalculator() }, { AccountStatus.ValuableCustomer, new ValuableCustomerDiscountCalculator() }, { AccountStatus.MostValuableCustomer, new MostValuableCustomerDiscountCalculator() } }; var dc = new DiscountManager(new DictionarableAccountDiscountCalculatorFactory(discountsDictionary), new DefaultLoyaltyDiscountCalculator()); Action <DiscountManager, AccountStatus> perform = PerformCalculation; AccountStatus status = AccountStatus.NotRegistered; perform(dc, status); status = AccountStatus.SimpleCustomer; perform(dc, status); status = AccountStatus.ValuableCustomer; perform(dc, status); status = AccountStatus.MostValuableCustomer; perform(dc, status); Console.ReadKey(); }
public void Properties() { var user = new BinanceApiUser("api-key"); var commissions = new AccountCommissions(10, 10, 0, 0); var status = new AccountStatus(true, true, true); var time = DateTimeOffset.FromUnixTimeMilliseconds(DateTime.UtcNow.ToTimestamp()).UtcDateTime; var balances = new[] { new AccountBalance("BTC", 0.1m, 0.2m) }; var account = new AccountInfo(user, commissions, status, time); Assert.Equal(commissions, account.Commissions); Assert.Equal(status, account.Status); Assert.Equal(time, account.Time); Assert.NotNull(account.Balances); Assert.Empty(account.Balances); account = new AccountInfo(user, commissions, status, time, balances); Assert.Equal(commissions, account.Commissions); Assert.Equal(status, account.Status); Assert.Equal(time, account.Time); Assert.NotNull(account.Balances); Assert.NotEmpty(account.Balances); Assert.Equal(balances[0].Asset, account.Balances.First().Asset); }
/// <summary> /// Calculates the discount. /// </summary> /// <param name="amount">Given amount.</param> /// <param name="accountStatus">Account status.</param> /// <param name="years">Years registered.</param> /// <returns>Returns the discounted amount.</returns> public decimal Calculate(decimal amount, AccountStatus accountStatus, int years) { decimal result = 0; decimal disc = GetDiscountPercentage(years); switch (accountStatus) { case AccountStatus.NotRegistered: result = amount; break; case AccountStatus.SimpleCustomer: result = (amount - (0.1m * amount)) - disc * (amount - (0.1m * amount)); break; case AccountStatus.ValuableCustomer: result = (0.7m * amount) - disc * (0.7m * amount); break; case AccountStatus.MostValuableCustomer: result = (amount - (0.5m * amount)) - disc * (amount - (0.5m * amount)); break; default: throw new NotImplementedException(); } return(result); }
private void filter_user_by_account_status(AccountStatus status) { var specification = new AccountStatusSpecifications(status); var users = DataSpecificationProcessor <User> .BuildQuery(_users.AsQueryable(), specification); users.ToList().Should().HaveCount(1); }
public bool UpdateAccountStatusByAccountNumber(string accountNumber, AccountStatus status) { var connection = ConnectionHelper.GetConnection(); try { connection.Open(); var updateStringCmd = $"UPDATE `accounts` SET `status` = {(int) status} WHERE `accounts`.`accountNumber` = {accountNumber};"; var sqlCmd = new MySqlCommand(updateStringCmd, connection); int numberOfRecord = sqlCmd.ExecuteNonQuery(); if (numberOfRecord == 0) { Console.WriteLine($"số tài khoản {accountNumber} không tồn tại !"); return(false); } Console.WriteLine("Đã cập nhật trạng thái của tài khoản thành công !"); connection.Close(); return(true); } catch (Exception e) { Console.WriteLine("Lỗi khi truy vấn database " + e.Message); connection.Close(); return(false); } }
public User(string userName, string password, AccountStatus status) { UserName = userName; Password = password; Status = status; _role = new Role(DateTime.Now, "Admin", this); }
public AccountState WithStatus(AccountStatus newStatus) => new AccountState( Currency: this.Currency, Status: newStatus, Balance: this.Balance, AllowedOverdraft: this.AllowedOverdraft );
public decimal ApplyDiscount(decimal price, AccountStatus accountStatus, int timeofHavingAccountInYears) { decimal priceAfterDiscount = 0; priceAfterDiscount = _factory.GetAccountDiscountCalculator(accountStatus).ApplyDiscount(price); return(_loyaltyDiscountCalculator.ApplyDiscount(price, timeofHavingAccountInYears)); }
public AccountNumModel(string[] linesOfPrints) { AccountNumChars = new CharModel[9]; AccountNum = new int[9]; ParseOneAccountEntry(linesOfPrints); Status = ValidateAccountNumber(AccountNum); }
public decimal ApplyDiscount(decimal price, AccountStatus accountStatus, int timeOfHavingAccountInYears) { decimal priceAfterDiscount; switch (accountStatus) { case AccountStatus.NotRegistered: priceAfterDiscount = price; break; case AccountStatus.SimpleCustomer: priceAfterDiscount = price.ApplyDiscountForAccountStatus(constants.DiscountForSimpleCustomers); break; case AccountStatus.ValuableCustomer: priceAfterDiscount = price.ApplyDiscountForAccountStatus(constants.DiscountForValuableCustomers); break; case AccountStatus.MostValuableCustomer: priceAfterDiscount = price.ApplyDiscountForAccountStatus(constants.DiscountForMostValuableCustomers); break; default: throw new NotImplementedException(); } if (accountStatus != AccountStatus.NotRegistered) { priceAfterDiscount = priceAfterDiscount.ApplyDiscountForTimeOfHavingAccount(timeOfHavingAccountInYears); } return(priceAfterDiscount); }
public AccountAlreadyOpened(AccountType type, Int64 number, Decimal balance, AccountStatus status) { AccountType = type; AccountNumber = number; Balance = balance; Status = status; }
public decimal ApplyDiscount(decimal price, AccountStatus accountStatus, int timeOfHavingAccountInYears) { decimal priceAfterDiscount = 0; decimal discountForLoyaltyInPercentage = (timeOfHavingAccountInYears > 5) ? (decimal) 5/100 : (decimal) timeOfHavingAccountInYears/100; switch (accountStatus) { case AccountStatus.NotRegistered: priceAfterDiscount = price; break; case AccountStatus.SimpleCustomer: priceAfterDiscount = (price - (0.1m*price)) - (discountForLoyaltyInPercentage*(price - (0.1m*price))); break; case AccountStatus.ValuableCustomer: priceAfterDiscount = (0.7m*price) - (discountForLoyaltyInPercentage*(0.7m*price)); break; case AccountStatus.MostValuableCustomer: priceAfterDiscount = (price - (0.5m*price)) - (discountForLoyaltyInPercentage*(price - (0.5m*price))); break; default: throw new NotImplementedException(); } return priceAfterDiscount; }
public void SetInfo(int rank, string name, bool isOnline, AccountStatus status) { _rank = rank; player_name = name; _isOnline = isOnline; _status = status; }
private LookUpRes GetLookupRes(AccountStatus stat, string message) { return(new LookUpRes() { Message = message, Status = (int)stat }); }
public decimal ApplyDiscount(decimal basePrice, AccountStatus accountStatus, int timeOfHavingAccountInYears) { decimal priceAfterDiscount = 0; switch (accountStatus) { case AccountStatus.NotRegistered: priceAfterDiscount = price; break; case AccountStatus.SimpleCustomer: priceAfterDiscount = price.ApplyDiscountForAccountStatus(Constants.DISCOUNT_FOR_SIMPLE_CUSTOMERS); break; case AccountStatus.ValuableCustomer: priceAfterDiscount = price.ApplyDiscountForAccountStatus(Constants.DISCOUNT_FOR_VALUABLE_CUSTOMERS); break; case AccountStatus.MostValuableCustomer: priceAfterDiscount = price.ApplyDiscountForAccountStatus(Constants.DISCOUNT_FOR_MOST_VALUABLE_CUSTOMERS); break; default: throw new NotImplementedException(); } priceAfterDiscount = priceAfterDiscount.ApplyDiscountForTimeOfHavingAccount(timeOfHavingAccountInYears); return(priceAfterDiscount); }
public async Task <IActionResult> Edit(int id, [Bind("Id,AccountStatusName")] AccountStatus accountStatus) { if (id != accountStatus.Id) { return(NotFound()); } if (ModelState.IsValid) { try { _context.Update(accountStatus); await _context.SaveChangesAsync(); } catch (DbUpdateConcurrencyException) { if (!AccountStatusExists(accountStatus.Id)) { return(NotFound()); } else { throw; } } return(RedirectToAction(nameof(ListAccountStatuses))); } return(View(accountStatus)); }
public IAccountDiscountCalculator GetAccountDiscountCalculator(AccountStatus accountStatus) { IAccountDiscountCalculator calculator; switch (accountStatus) { case AccountStatus.NotRegistered: calculator = new NotRegisteredDiscountCalculator(); break; case AccountStatus.SimpleCustomer: calculator = new SimpleCustomerDiscountCalculator(); break; case AccountStatus.ValuableCustomer: calculator = new ValuableCustomerDiscountCalculator(); break; case AccountStatus.MostValuableCustomer: calculator = new MostValuableCustomerDiscountCalculator(); break; default: throw new NotImplementedException(); } return(calculator); }
public AccountState(Guid customerId, string accountNumber, AccountType type, AccountStatus status) { CustomerId = customerId; AccountNumber = accountNumber; Type = type; Status = status; }
public void Properties() { var user = new BinanceApiUser("api-key"); var commissions = new AccountCommissions(10, 10, 0, 0); var status = new AccountStatus(true, true, true); long updateTime = 1234567890; var balances = new[] { new AccountBalance("BTC", 0.1m, 0.2m) }; var account = new AccountInfo(user, commissions, status, updateTime); Assert.Equal(commissions, account.Commissions); Assert.Equal(status, account.Status); Assert.Equal(updateTime, account.Timestamp); Assert.NotNull(account.Balances); Assert.Empty(account.Balances); account = new AccountInfo(user, commissions, status, updateTime, balances); Assert.Equal(commissions, account.Commissions); Assert.Equal(status, account.Status); Assert.Equal(updateTime, account.Timestamp); Assert.NotNull(account.Balances); Assert.NotEmpty(account.Balances); Assert.Equal(balances[0].Asset, account.Balances.First().Asset); }
public IdentityUserInfo(IEnumerable <Claim> claims) { if (claims.FirstOrDefault(c => c.Type == "creation-date") != null) { DateTime dateTime = new DateTime(); if (DateTime.TryParse(claims.FirstOrDefault(c => c.Type == "creation-date").Value, out dateTime)) { CreationDate = dateTime; } } if (claims.FirstOrDefault(c => c.Type == "last-seen") != null) { DateTime dateTime = new DateTime(); if (DateTime.TryParse(claims.FirstOrDefault(c => c.Type == "last-seen").Value, out dateTime)) { CreationDate = dateTime; } } if (claims.FirstOrDefault(c => c.Type == "account-type") != null) { AccountType accountType = Utilities.AccountType.Basic; if (Enum.TryParse(claims.FirstOrDefault(c => c.Type == "account-type").Value, out accountType)) { AccountType = accountType; } } if (claims.FirstOrDefault(c => c.Type == "account-status") != null) { AccountStatus accountStatus = Utilities.AccountStatus.Active; if (Enum.TryParse(claims.FirstOrDefault(c => c.Type == "account-status").Value, out accountStatus)) { AccountStatus = accountStatus; } } if (claims.FirstOrDefault(c => c.Type == "recovery-email") != null) { RecoveryEmail = claims.FirstOrDefault(c => c.Type == "recovery-email").Value; } if (claims.FirstOrDefault(c => c.Type == "recovery-verified") != null) { bool verified = false; if (bool.TryParse(claims.FirstOrDefault(c => c.Type == "recovery-verified").Value, out verified)) { RecoveryVerified = verified; } } if (claims.FirstOrDefault(c => c.Type == "2fa-enabled") != null) { bool twoFactor = false; if (bool.TryParse(claims.FirstOrDefault(c => c.Type == "2fa-enabled").Value, out twoFactor)) { TwoFactorEnabled = twoFactor; } } if (claims.FirstOrDefault(c => c.Type == "pgp-public-key") != null) { PGPPublicKey = claims.FirstOrDefault(c => c.Type == "pgp-public-key").Value; } }
public IdentityUserInfo(JObject info) { if (info["creation-date"] != null) { DateTime dateTime = new DateTime(); if (DateTime.TryParse(info["creation-date"].ToString(), out dateTime)) { CreationDate = dateTime; } } if (info["last-seen"] != null) { DateTime dateTime = new DateTime(); if (DateTime.TryParse(info["last-seen"].ToString(), out dateTime)) { LastSeen = dateTime; } } if (info["account-type"] != null) { AccountType accountType = Utilities.AccountType.Basic; if (Enum.TryParse(info["account-type"].ToString(), out accountType)) { AccountType = accountType; } } if (info["account-status"] != null) { AccountStatus accountStatus = Utilities.AccountStatus.Active; if (Enum.TryParse(info["account-status"].ToString(), out accountStatus)) { AccountStatus = accountStatus; } } if (info["recovery-email"] != null) { RecoveryEmail = info["recovery-email"].ToString(); } if (info["recovery-verified"] != null) { bool verified = false; if (bool.TryParse(info["recovery-verified"].ToString(), out verified)) { RecoveryVerified = verified; } } if (info["2fa-enabled"] != null) { bool twoFactor = false; if (bool.TryParse(info["2fa-enabled"].ToString(), out twoFactor)) { TwoFactorEnabled = twoFactor; } } if (info["pgp-public-key"] != null) { PGPPublicKey = info["pgp-public-key"].ToString(); } }
public KeyShareDialog(Form parent, SharingListViewModel viewModel) : this() { if (viewModel == null) { throw new ArgumentNullException(nameof(viewModel)); } InitializeStyle(parent); _viewModel = viewModel; _viewModel.BindPropertyChanged <IEnumerable <UserPublicKey> >(nameof(SharingListViewModel.SharedWith), (aks) => { _sharedWith.Items.Clear(); _sharedWith.Items.AddRange(aks.Distinct(UserPublicKey.EmailComparer).ToArray()); SetNotSharedWithActionButtonsState(); }); _viewModel.BindPropertyChanged <IEnumerable <UserPublicKey> >(nameof(SharingListViewModel.NotSharedWith), (aks) => { _notSharedWith.Items.Clear(); aks = FilterNotSharedContactsByCapability(aks); _notSharedWith.Items.AddRange(aks.ToArray()); SetNotSharedWithActionButtonsState(); }); _viewModel.BindPropertyChanged <string>(nameof(SharingListViewModel.NewKeyShare), (email) => SetNotSharedWithActionButtonsState()); _viewModel.BindPropertyChanged <bool>(nameof(SharingListViewModel.IsOnline), (isOnline) => { SetNewContactState(isOnline); }); _sharedWith.SelectedIndexChanged += (sender, e) => SetUnshareButtonState(); _notSharedWith.SelectedIndexChanged += (sender, e) => SetNotSharedWithActionButtonsState(); _sharedWith.MouseDoubleClick += async(sender, e) => await Unshare(_sharedWith.IndexFromPoint(e.Location)); _notSharedWith.MouseDoubleClick += async(sender, e) => { await ShareSelectedIndices(new int[] { _notSharedWith.IndexFromPoint(e.Location) }); }; _newContact.TextChanged += (sender, e) => { _viewModel.NewKeyShare = _newContact.Text.Trim(); ClearErrorProviders(); }; _newContact.Enter += (sender, e) => { _sharedWith.ClearSelected(); _notSharedWith.ClearSelected(); }; _shareButton.Click += async(sender, e) => { await ShareSelectedIndices(_notSharedWith.SelectedIndices.Cast <int>()); AccountStatus accountStatus = await ShareNewContactAsync(); if (accountStatus == AccountStatus.Unverified) { await DisplayInviteMessageAsync(_viewModel.NewKeyShare); } if (accountStatus != AccountStatus.Unknown) { _newContact.Text = string.Empty; } }; _unshareButton.Click += async(sender, e) => { await Unshare(); SetUnshareButtonState(); }; _removeKnownContactButton.Click += async(sender, e) => { await RemoveKnownContact(); }; SetOkButtonState(); _notSharedWith.Focus(); }
public BankAccountDTO(int id, AccountStatus status, int bonus, int balance, AccountHolder holder) { Id = id; Status = status; BonusPoints = bonus; Balance = balance; Person = holder; }
public static ulong GetClanStatus(AccountStatus status, bool isOnline) { FriendState state; int serverId, channelId, roomId, clanFId; GetPlayerLocation(status, isOnline, out state, out roomId, out channelId, out serverId, out clanFId); return(GetPlayerStatus(clanFId, roomId, channelId, serverId, (int)state)); }
public decimal ApplyDiscount(decimal price, AccountStatus accountStatus, int timeOfHavingAccountInYears) { decimal priceAfterDiscount = 0; priceAfterDiscount = factory.getAccountDiscountCalculator(accountStatus).ApplyDiscount(price); priceAfterDiscount = loyaltyDiscountCalculator.applyDiscount(priceAfterDiscount, timeOfHavingAccountInYears); return(priceAfterDiscount); }
/// <summary> /// Initializes a new instance of the <see cref="BankAccount"/> class. /// </summary> /// <param name="id">The identifier.</param> /// <param name="user">The user.</param> /// <param name="accountType">The account type.</param> /// <param name="status">The status.</param> /// <param name="balance">The balance.</param> /// <param name="bonus">The bonus.</param> protected BankAccount(User user, AccountType accountType, AccountStatus status, decimal balance, int bonus) { this.user = user; this.AccountType = accountType; this.Status = status; this.balance = balance; this.bonusPoints = bonus; }
public AccountState WithStatus(AccountStatus newStatus) => new AccountState { Status = newStatus, Currency = this.Currency, AllowedOverdraft = this.AllowedOverdraft, TransactionHistory = this.TransactionHistory };
/// <summary> /// Gets all users with a given status in the provided role /// </summary> /// <param name="role">The users role within the company. Like Agent or Manager</param> /// <param name="status">The AccountStatus of the desired ApplicationUsers</param> /// <returns>An IQueryable of users with a given status in the provided role.</returns> private IQueryable <ApplicationUser> GetUsersByRole(string role, AccountStatus status) { return(from u in _context.Users join r in _context.UserRoles on u.Id equals r.UserId join ur in _context.Roles on r.RoleId equals ur.Id where ur.Name == role && u.AccountStatus == status select u); }
/* * public AccountModel(Guid userId, long number) * { * User_id = userId; * Number = number; * Amount = 0; * Status = AccountStatus.OPENED; * } * * public AccountModel(Guid userId, long number, decimal amount, AccountStatus status) * { * User_id = userId; * Number = number; * Amount = amount; * Status = status; * } */ public AccountModel(Guid id, Guid user_id, long number, decimal amount, AccountStatus status) { Id = id; User_id = user_id; Number = number; Amount = amount; Status = status; }
public void AccountStatus_Success() { AccountStatus status = new AccountStatus(AccountKey.Parse("/account/", "/asset/"), 1, ByteString.Parse("ab")); Assert.Equal("/account/", status.AccountKey.Account.FullPath); Assert.Equal("/asset/", status.AccountKey.Asset.FullPath); Assert.Equal(1, status.Balance); Assert.Equal(ByteString.Parse("ab"), status.Version); }
public virtual bool Equals(AccountStatus other) { if (null != other && other.GetType() == GetType()) { return other.Status == Status; } return false; }
/// <summary> /// Sends an authentication challenge error to the client. /// </summary> /// <param name="client">the client</param> /// <param name="error">the authentication challenge error to send</param> public static void SendAuthChallengeErrorReply(IAuthClient client, AccountStatus error) { using (var packet = new AuthPacketOut(AuthServerOpCode.AUTH_LOGON_CHALLENGE)) { packet.Write((byte)0x00); packet.Write((byte)error); client.Send(packet); } }
public static bool IsAllow(string area, string controller, string action, AccountStatus status) { /*var result = db.AccessRights.SingleOrDefault(i => ((controller == i.Controller) && (action == i.Action) && (status == i.Role) && ((area == i.Area) || ((area == null) && (i.Area == null))))); if (result != null) return result.IsAllowed; db.AccessRights.Add(new AccessRight() { Area = area, Controller = controller, Action = action, Role = status, IsAllowed = true }); db.SaveChanges(); */ return true; }
private bool IsAccountDtoMatchedByStatus(AccountStatus accountStatus, bool isDeleted) { switch (accountStatus) { case AccountStatus.Any: return true; case AccountStatus.Active: return !isDeleted; case AccountStatus.Deleted: return isDeleted; default: throw new NotSupportedException("The account status filter specified is not supported: " + accountStatus); } }
/// <summary> /// Initializes a new instance of the StorageAccountProperties class. /// </summary> /// <param name="provisioningState">Gets the status of the storage /// account at the time the operation was called. Possible values /// include: 'Creating', 'ResolvingDNS', 'Succeeded'</param> /// <param name="accountType">Gets the type of the storage account. /// Possible values include: 'Standard_LRS', 'Standard_ZRS', /// 'Standard_GRS', 'Standard_RAGRS', 'Premium_LRS'</param> /// <param name="primaryEndpoints">Gets the URLs that are used to /// perform a retrieval of a public blob, queue or table object.Note /// that StandardZRS and PremiumLRS accounts only return the blob /// endpoint.</param> /// <param name="primaryLocation">Gets the location of the primary for /// the storage account.</param> /// <param name="statusOfPrimary">Gets the status indicating whether /// the primary location of the storage account is available or /// unavailable. Possible values include: 'Available', /// 'Unavailable'</param> /// <param name="lastGeoFailoverTime">Gets the timestamp of the most /// recent instance of a failover to the secondary location. Only the /// most recent timestamp is retained. This element is not returned if /// there has never been a failover instance. Only available if the /// accountType is StandardGRS or StandardRAGRS.</param> /// <param name="secondaryLocation">Gets the location of the geo /// replicated secondary for the storage account. Only available if the /// accountType is StandardGRS or StandardRAGRS.</param> /// <param name="statusOfSecondary">Gets the status indicating whether /// the secondary location of the storage account is available or /// unavailable. Only available if the accountType is StandardGRS or /// StandardRAGRS. Possible values include: 'Available', /// 'Unavailable'</param> /// <param name="creationTime">Gets the creation date and time of the /// storage account in UTC.</param> /// <param name="customDomain">Gets the user assigned custom domain /// assigned to this storage account.</param> /// <param name="secondaryEndpoints">Gets the URLs that are used to /// perform a retrieval of a public blob, queue or table object from /// the secondary location of the storage account. Only available if /// the accountType is StandardRAGRS.</param> public StorageAccountProperties(ProvisioningState? provisioningState = default(ProvisioningState?), AccountType? accountType = default(AccountType?), Endpoints primaryEndpoints = default(Endpoints), string primaryLocation = default(string), AccountStatus? statusOfPrimary = default(AccountStatus?), System.DateTime? lastGeoFailoverTime = default(System.DateTime?), string secondaryLocation = default(string), AccountStatus? statusOfSecondary = default(AccountStatus?), System.DateTime? creationTime = default(System.DateTime?), CustomDomain customDomain = default(CustomDomain), Endpoints secondaryEndpoints = default(Endpoints)) { ProvisioningState = provisioningState; AccountType = accountType; PrimaryEndpoints = primaryEndpoints; PrimaryLocation = primaryLocation; StatusOfPrimary = statusOfPrimary; LastGeoFailoverTime = lastGeoFailoverTime; SecondaryLocation = secondaryLocation; StatusOfSecondary = statusOfSecondary; CreationTime = creationTime; CustomDomain = customDomain; SecondaryEndpoints = secondaryEndpoints; }
/// <summary> /// Changes the status of a subaccount. You must be authenticated as the master account to call this method on a subaccount. /// WARNING: When closing an account, Twilio will release all phone numbers assigned to it and shut it down completely. /// You can't ever use a closed account to make and receive phone calls or send and receive SMS messages. /// It's closed, gone, kaput. It will still appear in your accounts list, and you will still have access to historical /// data for that subaccount, but you cannot reopen a closed account. /// </summary> /// <param name="subAccountSid">The subaccount to change the status on</param> /// <param name="status">The status to change the subaccount to</param> public virtual Account ChangeSubAccountStatus(string subAccountSid, AccountStatus status) { if (subAccountSid == AccountSid) { throw new InvalidOperationException("Subaccount status can only be changed when authenticated from the master account."); } var request = new RestRequest(Method.POST); request.Resource = "Accounts/{AccountSid}.json"; request.AddParameter("Status", status.ToString().ToLower()); request.AddUrlSegment("AccountSid", subAccountSid); return Execute<Account>(request); }
public ProfileData( string id, string name = null, string iconImageUrl = null, AccountStatus? status = null, string firstName = null, string lastName = null, string introduction = null, string braggingRights = null, string occupation = null, string greetingText = null, string nickName = null, RelationType? relationship = null, GenderType? genderType = null, LookingFor lookingFor = null, EmploymentInfo[] employments = null, EducationInfo[] educations = null, ContactInfo[] contactsInHome = null, ContactInfo[] contactsInWork = null, UrlInfo[] otherProfileUrls = null, UrlInfo[] contributeUrls = null, UrlInfo[] recommendedUrls = null, string[] placesLived = null, string[] otherNames = null, ProfileUpdateApiFlag loadedApiTypes = ProfileUpdateApiFlag.Unloaded, DateTime? lastUpdateLookupProfile = null, DateTime? lastUpdateProfileGet = null) { if (id == null) throw new ArgumentNullException("ProfileDataの引数idをnullにする事はできません。"); //idが数字になるならばProfileIdとして正しい。違うならばG+を始めていないアカウントのEMailAddressと見なす //また、スタブモード時は先頭に"Id"の2文字が入るため、テストコード用に先頭2文字を省いてParse()する。 double tmp; if (status == AccountStatus.Active && double.TryParse(id.Substring(2), out tmp) == false) throw new ArgumentException("ProfileDataの引数idがメアド状態で引数statusをActiveにする事はできません。"); LoadedApiTypes = loadedApiTypes; Status = status; Id = id; Name = name; FirstName = firstName; LastName = lastName; Introduction = introduction; BraggingRights = braggingRights; Occupation = occupation; GreetingText = greetingText; NickName = nickName; IconImageUrl = iconImageUrl; Relationship = relationship; Gender = genderType; LookingFor = lookingFor; Employments = employments; Educations = educations; ContactsInHome = contactsInHome; ContactsInWork = contactsInWork; OtherProfileUrls = otherProfileUrls; ContributeUrls = contributeUrls; RecommendedUrls = recommendedUrls; PlacesLived = placesLived; OtherNames = otherNames; LastUpdateLookupProfile = lastUpdateLookupProfile ?? DateTime.MinValue; LastUpdateProfileGet = lastUpdateProfileGet ?? DateTime.MinValue; }
public SavingAccount(string accountID, AccountStatus status, string firstName, string lastName, string address, string phoneNo, double balance, string pinCode) : base(accountID, status, firstName, lastName, address, phoneNo, balance, pinCode) { }
public ABankAccount(string accountID, AccountStatus status, string firstName, string lastName, string address, string phoneNo, double balance, string pinCode) { AccountID = accountID; Status = status; FirstName = firstName; LastName = lastName; Address = address; PhoneNo = phoneNo; Balance = balance; PinCode = pinCode; }
internal async Task CheckForAccountUpdateAsync(AccountStatus? targetStatus = null) { if(_checkingForAccountUpdate) return; ProgressRing.IsActive = true; _checkingForAccountUpdate = true; for(var i = 0; i < 10; i++) { Log.Debug($"Checking account info... try #{i+1}"); await ApiWrapper.UpdateAccountStatus(); if(targetStatus == null || Account.Instance.Status == targetStatus) { Log.Debug("Found updated account status"); Update(); break; } await Task.Delay(5000 + (int)Math.Sqrt(i * 5000)); } ProgressRing.IsActive = false; _checkingForAccountUpdate = false; }
public virtual bool Exists(string username, AccountStatus status = AccountStatus.EXISTS) { AccountStatus astatus = Status(username); if (astatus == AccountStatus.NULL) return false; return ((astatus & status) == status); }
public ExpirableItem(AccountStatus status, double expire, int index) { this.status = status; this.timestamp = DateTime.UtcNow; this.timetolive = TimeSpan.FromSeconds(expire); this.index = index; }
public AccountDto[] GetAccountDtos(AccountStatus accountStatus = AccountStatus.Active) { return GetAllAccountIds().Select(GetAccountDto).Where(accountDto => IsAccountDtoMatchedByStatus(accountStatus, accountDto.IsDeleted)) .ToArray(); }
public void UpdateUserAccountStatusTest(string userId, AccountStatus status) { var returned = _repo.UpdateUserAccountStatus(userId, status); Assert.AreEqual(status, returned.AccountStatus); }
public PSAuthLoginProof(AccountStatus status) : base(LoginOpcodes.AUTH_LOGIN_PROOF) { Write((byte)status); }
public AccountResult(AccountStatus status) { Status = status; StatusMessage = Status.ToString(); }
public ApplicationUser UpdateUserAccountStatus(string userId, AccountStatus status) { ApplicationUser user = new ApplicationUser(); using (SqlConnection cn = new SqlConnection(Settings.ConnectionString)) { SqlCommand cmd = new SqlCommand(); cmd.CommandText = "UpdateUserAccountStatus"; cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@UserID", userId); cmd.Parameters.AddWithValue("@AccountStatus", (int)status); cmd.Connection = cn; cn.Open(); using (SqlDataReader dr = cmd.ExecuteReader()) { while (dr.Read()) { user = PopulateUserFromDataReader(dr); } } } return user; }
public Response UpdateUserAccountStatus(string userId, AccountStatus status) { _response = new Response(); var user = _repo.UpdateUserAccountStatus(userId, status); if (user != null && user.AccountStatus == status) { _response.Success = true; _response.User = user; } return _response; }
public UnixIdentity(string domain, string userName, LdapConnection connection = null) : base(GetUserIDAsToken(domain, userName), null, WindowsAccountType.Normal, true) { m_domain = domain; m_userName = userName; Connection = connection; if (UserInfo.IsLocalDomain(domain)) { // Cache shadow information for local user before possible reduction in privileges if (GetLocalUserPasswordInformation(userName, out m_userPasswordInformation, out m_accountStatus) == 0) m_loadedUserPasswordInformation = true; else m_accountStatus = AccountStatus.Disabled; } }
[DllImport(ImportFileName, EntryPoint = "GetLocalUserPasswordInformation")] // 32-bit version private static extern int GetLocalUserPasswordInformation32(string userName, ref UserPasswordInformation32 userPasswordInfo, out AccountStatus status);
// Bit-size/platform inter-mediator for getting user password information private static int GetLocalUserPasswordInformation(string userName, out UserPasswordInformation userPasswordInfo, out AccountStatus accountStatus) { userPasswordInfo = new UserPasswordInformation(); if (Common.GetOSPlatformID() == PlatformID.MacOSX) { int lastChangeDate, maxDaysForChange, accountExpirationDate; accountStatus = AccountStatus.Normal; // Mac OS X call if (GetLocalUserPasswordInformationMac(userName, out lastChangeDate, out maxDaysForChange, out accountExpirationDate) == 0) { userPasswordInfo.lastChangeDate = lastChangeDate; userPasswordInfo.maxDaysForChange = maxDaysForChange; userPasswordInfo.accountExpirationDate = accountExpirationDate; return 0; } } else { if (IntPtr.Size == 4) { // 32-bit OS call UserPasswordInformation32 userPasswordInfo32 = new UserPasswordInformation32(); if (GetLocalUserPasswordInformation32(userName, ref userPasswordInfo32, out accountStatus) == 0) { userPasswordInfo.lastChangeDate = userPasswordInfo32.lastChangeDate; userPasswordInfo.minDaysForChange = userPasswordInfo32.minDaysForChange; userPasswordInfo.maxDaysForChange = userPasswordInfo32.maxDaysForChange; userPasswordInfo.warningDays = userPasswordInfo32.warningDays; userPasswordInfo.inactivityDays = userPasswordInfo32.inactivityDays; userPasswordInfo.accountExpirationDate = userPasswordInfo32.accountExpirationDate; return 0; } } else { // 64-bit OS call return GetLocalUserPasswordInformation64(userName, ref userPasswordInfo, out accountStatus); } } return 1; }
public bool TryGet(string username, out AccountStatus status) { status = AccountStatus.NULL; ExpirableItem item; if (data.TryGetValue(username, out item)) { if (!item.IsExpired()) { status = item.Status; return true; } } return false; }
/// <summary> /// Called when the given client failed to login due to the given reason. /// Delays, fires the LoginFailed event and sends the reply. /// </summary> /// <param name="client"></param> /// <param name="error"></param> public static void OnLoginError(IAuthClient client, AccountStatus error, bool silent) { if (!silent) { s_log.Debug("Client {0} failed to login: {1}", client, error); } LoginFailInfo failInfo; if (!failedLogins.TryGetValue(client.ClientAddress, out failInfo)) { failedLogins.Add(client.ClientAddress, failInfo = new LoginFailInfo(DateTime.Now)); } else { failInfo.LastAttempt = DateTime.Now; failInfo.Count++; // TODO: Ban, if trying too often? } // delay the reply ThreadPool.RegisterWaitForSingleObject(failInfo.Handle, (state, timedOut) => { if (client.IsConnected) { var evt = LoginFailed; if (evt != null) { evt(client, error); } SendAuthProofErrorReply(client, error); } }, null, FailedLoginDelay, true); }
/// <summary> /// Called when the given client failed to login due to the given reason. /// Delays, fires the LoginFailed event and sends the reply. /// </summary> /// <param name="client"></param> /// <param name="error"></param> public static void OnLoginError(IAuthClient client, AccountStatus error) { OnLoginError(client, error, false); }
/// <summary> /// Called when the given client failed to login due to the given reason. /// Delays, fires the LoginFailed event and sends the reply. /// </summary> /// <param name="client"></param> /// <param name="error"></param> private static void OnLoginError(IAuthClient client, AccountStatus error) { TimeoutWaitHandle delayHandle; if (!failedLogins.TryGetValue(client.ClientAddress, out delayHandle)) { failedLogins.Add(client.ClientAddress, delayHandle = new TimeoutWaitHandle(DateTime.Now)); } else { delayHandle.LastAttempt = DateTime.Now; } ThreadPool.RegisterWaitForSingleObject(delayHandle.Handle, (state, timedOut) => { if (client.IsConnected) { var evt = LoginFailed; if (evt != null) { evt(client, error); } SendAuthProofErrorReply(client, error); } }, null, LoginFailedDelay, true); }
private static int GetCachedLocalUserPasswordInformation(string userName, out UserPasswordInformation userPasswordInfo, out AccountStatus accountStatus) { // Attempt to retrieve Unix user principal identity in case shadow information has already been parsed, in most // cases we will have already reduced rights needed to read this information so we pick up pre-parsed info WindowsPrincipal principal = Thread.CurrentPrincipal as WindowsPrincipal; if ((object)principal != null) { UnixIdentity identity = principal.Identity as UnixIdentity; // If user has already been authenticated, we can load pre-parsed shadow information if ((object)identity != null && identity.LoadedUserPasswordInformation && identity.UserName.Equals(userName, StringComparison.OrdinalIgnoreCase)) { userPasswordInfo = identity.UserPasswordInformation; accountStatus = identity.AccountStatus; return 0; } } return GetLocalUserPasswordInformation(userName, out userPasswordInfo, out accountStatus); }
public void Insert(string username, AccountStatus status) { double seconds; DateTime expire_curr_timestamp; // purge all invalid/expired records // check if we came from future(?!) or all data exceeds "expire" time while (true) { expire_curr_timestamp = DateTime.UtcNow; seconds = (expire_last_timestamp - expire_curr_timestamp).TotalSeconds; if (seconds >= 0 && seconds < expire) break; Clear(); } int index = (int) (expire_intervals * (seconds / expire)); // purge selected expired records if (expire_last_index != index) { for (int i = expire_last_index + 1; i < expire_last_index + expire_intervals; i++) { int curr_index = i % expire_intervals; foreach (string ausername in expire_sets[i]) { data.Remove(ausername); } expire_sets[i].Clear(); if (curr_index == index) break; } } // remove oldest cached data when we reach max_size quota if (data.Count > max_size) { for (int i = expire_intervals + index - 1; i > index; i--) { int curr_index = i % expire_intervals; foreach (string ausername in expire_sets[i]) { data.Remove(ausername); } expire_sets[i].Clear(); } // NOTE: now we should check if all data doesn't sit in expire_sets[index] // and remove oldest record (or some fraction of oldest records) } // remove old record for username ExpirableItem last; if (data.TryGetValue(username, out last)) { expire_sets[last.Index].Remove(username); data.Remove(username); } data[username] = new ExpirableItem(status, expire, index); expire_sets[index].Add(username); }