/// <summary> /// Do actual delete. /// </summary> /// <param name="tradingSupport">The trading support client.</param> private void CommitDelete(TradingSupportClient tradingSupport) { if (this.DebtRuleId != null) { Boolean inUse = false; lock (DataModel.SyncRoot) inUse = DataModel.DebtClass.Any(row => !row.IsDebtRuleIdNull() && row.DebtRuleId == this.DebtRuleId); if (!inUse) { MethodResponseErrorCode response = tradingSupport.DeleteDebtRule(new TradingSupportReference.DebtRule[] { new TradingSupportReference.DebtRule() { RowId = this.DebtRuleId.Value, RowVersion = this.RowVersion } }); if (!response.IsSuccessful && (response.Errors.Length == 0 || response.Errors[0].ErrorCode != ErrorCode.Deadlock)) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } } else { throw new DebtRuleInUseException(this.Name, "Cannot delete a debt rule that is currently in use."); } } }
private void Create(String name, Guid typeId) { AdminSupportClient adminClient = new AdminSupportClient(Properties.Settings.Default.AdminSupportEndpoint); Guid organizationId = Guid.Empty; try { AdminSupportReference.MethodResponseguid response; String currentOrganization; lock (DataModel.SyncRoot) currentOrganization = DataModel.User.UserKey.Find(UserContext.Instance.UserId).TenantRow.ExternalId0; response = adminClient.AddOrganization(name, currentOrganization); adminClient.Close(); if (!response.IsSuccessful) { if (response.Errors.Length > 0) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } else { throw new Exception("Unknown error occured"); } } else { organizationId = response.Result; } } catch { MessageBox.Show(Properties.Resources.OperationFailed); return; } try { Guid parentId; lock (DataModel.SyncRoot) parentId = FindUserFolder(); Guid entityId = Entity.Create(typeId, parentId, organizationId); TradingSupportReference.TradingSupportClient client = new TradingSupportReference.TradingSupportClient(Properties.Settings.Default.TradingSupportEndpoint); client.UpdateEntity(new TradingSupportReference.Entity[] { new TradingSupportReference.Entity() { RowId = entityId, Name = name } }); } catch { MessageBox.Show(Properties.Resources.OperationFailed); return; } }
/// <summary> /// Commit any changes to the access control. /// </summary> public void Commit() { TradingSupportClient client = new TradingSupportClient(FluidTrade.Guardian.Properties.Settings.Default.TradingSupportEndpoint); try { if (this.Deleted) { // Could be the user added and then deleted a user to the list, so makes sure the row actually exists. if (!this.newRights) { MethodResponseErrorCode response; response = client.RevokeAccess(this.User.EntityId, this.Entity.EntityId); if (response.Result != ErrorCode.Success) { if (response.Errors.Length > 0) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } else { GuardianObject.ThrowErrorInfo(response.Result); } } } } else if (this.Dirty) { Guid accessRightId; MethodResponseguid response; lock (DataModel.SyncRoot) accessRightId = DataModel.AccessRight.AccessRightKeyAccessRightCode.Find(this.AccessRight).AccessRightId; response = client.GrantAccess(this.User.EntityId, this.Entity.EntityId, accessRightId); if (response.Errors.Length > 0) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } this.accessControlId = response.Result; this.newRights = false; this.dirty = false; } } finally { if (client != null && client.State == CommunicationState.Opened) { client.Close(); } } }
/// <summary> /// Move several working orders from one blotter to another. /// </summary> /// <param name="objects">The list of working orders to move.</param> /// <param name="newParent">The new location of the working orders.</param> /// <param name="errors">The list of errors and at what index.</param> public void Move(List <IMovableObject> objects, GuardianObject newParent, List <ErrorInfo> errors) { try { Int32 tries = 0; bool retry = false; BaseRecord[] records = this.PopulateSecurityRecords(objects); MethodResponseErrorCode response = null; do { TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint); response = this.MoveSecurity(tradingSupportClient, records, newParent as Blotter); if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened) { tradingSupportClient.Close(); } tries += 1; if (!response.IsSuccessful) { List <BaseRecord> retryRecords = new List <BaseRecord>(); foreach (ErrorInfo errorInfo in response.Errors) { // If the error's "just" a deadlock, add it to the retry list we can attempt it again. if (errorInfo.ErrorCode == ErrorCode.Deadlock) { retryRecords.Add(records[errorInfo.BulkIndex]); } //No need to retry if the client does not have permission to move. else if (errorInfo.ErrorCode == ErrorCode.AccessDenied) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } else { errors.Add(errorInfo); } } records = retryRecords.ToArray(); retry = retryRecords.Count > 0; } } while (retry && tries < WorkingOrder.TotalRetries); } catch (Exception exception) { // Any issues trying to communicate to the server are logged. EventLog.Error("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace); throw; } }
/// <summary> /// Commit any changes to this object to the server. /// </summary> public override void Commit() { TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint); try { TradingSupportReference.WorkingOrderRecord record = new TradingSupportReference.WorkingOrderRecord(); Int32 tries = 0; MethodResponseErrorCode response; this.PopulateRecord(record); do { if (this.Deleted) { response = tradingSupportClient.DeleteWorkingOrder(new TradingSupportReference.WorkingOrderRecord[] { record }); if (this.GetFirstErrorCode(response) == ErrorCode.RecordExists) { throw new IsSettledException(this.ToString() + " is settled"); } } else { response = tradingSupportClient.UpdateWorkingOrder(new TradingSupportReference.WorkingOrderRecord[] { record }); } tries += 1; if (!response.IsSuccessful && (response.Errors.Length == 0 || response.Errors[0].ErrorCode != ErrorCode.Deadlock)) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } } while (!response.IsSuccessful && tries < WorkingOrder.TotalRetries); this.Modified = false; } catch (Exception exception) { // Any issues trying to communicate to the server are logged. EventLog.Error("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace); if (this.Deleted) { throw new DeleteException(this, exception); } } finally { if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened) { tradingSupportClient.Close(); } } }
/// <summary> /// Commit the new link to the database. /// </summary> /// <param name="parent">The parent folder.</param> /// <param name="child">The child folder.</param> private void Commit(Entity parent, Entity child) { try { TradingSupportClient client = new TradingSupportClient(Properties.Settings.Default.TradingSupportEndpoint); MethodResponseArrayOfguid response = client.CreateEntityTree(new EntityTree[] { new EntityTree() { ChildId = child.EntityId, ParentId = parent.EntityId } }); if (!response.IsSuccessful) { if (response.Errors.Length > 0) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } else { Application.Current.Dispatcher.BeginInvoke(new WaitCallback(data => MessageBox.Show( Application.Current.MainWindow, String.Format(FluidTrade.Guardian.Properties.Resources.LinkFolderFailed, data), Application.Current.MainWindow.Title)), DispatcherPriority.Normal, child); } } client.Close(); } catch (FaultException <RecordExistsFault> exception) { EventLog.Warning("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace); Application.Current.Dispatcher.BeginInvoke(new WaitCallback(data => MessageBox.Show( Application.Current.MainWindow, String.Format(FluidTrade.Guardian.Properties.Resources.LinkFolderFailedRecordExists, data), Application.Current.MainWindow.Title)), DispatcherPriority.Normal, child); } catch (Exception exception) { EventLog.Error("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace); Application.Current.Dispatcher.BeginInvoke(new WaitCallback(data => MessageBox.Show( Application.Current.MainWindow, String.Format(FluidTrade.Guardian.Properties.Resources.LinkFolderFailed, data), Application.Current.MainWindow.Title)), DispatcherPriority.Normal, child); } }
/// <summary> /// Commit changes or create a new rule. /// </summary> /// <param name="tradingSupport">The trading support client.</param> /// <param name="owner">The debt class that owns the rule.</param> private void CommitModified(TradingSupportClient tradingSupport, Guid owner) { Guid[] paymentMethod = new Guid[this.PaymentMethod.Count]; this.PaymentMethod.CopyTo(paymentMethod, 0); if (this.DebtRuleId != null) { TradingSupportReference.MethodResponseErrorCode response = tradingSupport.UpdateDebtRule(new TradingSupportReference.DebtRule[] { new TradingSupportReference.DebtRule() { IsAutoSettled = this.IsAutoSettled, Name = this.Name, Owner = owner, PaymentLength = this.PaymentLength, PaymentMethod = paymentMethod, PaymentStartDateLength = this.PaymentStartDateLength, PaymentStartDateUnitId = this.PaymentStartDateUnitId, RowId = this.DebtRuleId.Value, RowVersion = this.RowVersion, SettlementUnitId = this.settlementUnitId, SettlementValue = this.SettlementValue } }); if (!response.IsSuccessful && (response.Errors.Length == 0 || response.Errors[0].ErrorCode != ErrorCode.Deadlock)) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } } else { MethodResponseArrayOfguid guids = tradingSupport.CreateDebtRule(new TradingSupportReference.DebtRule[] { new TradingSupportReference.DebtRule() { IsAutoSettled = this.isAutoSettled, Name = this.Name, Owner = owner, PaymentLength = this.PaymentLength, PaymentMethod = paymentMethod, PaymentStartDateLength = this.PaymentStartDateLength, PaymentStartDateUnitId = this.PaymentStartDateUnitId, SettlementUnitId = this.settlementUnitId, SettlementValue = this.SettlementValue } }); if (guids.IsSuccessful) { this.DebtRuleId = guids.Result[0]; } else { throw new Exception("Failed to create debt rule."); } } }
/// <summary> /// Commit the new link to the database. /// </summary> /// <param name="parent">The parent folder.</param> /// <param name="child">The child folder.</param> private void Commit(Entity parent, Entity child) { try { lock (DataModel.SyncRoot) { EntityTreeRow entityTreeRow = DataModel.EntityTree.EntityTreeKeyChildIdParentId.Find(child.EntityId, parent.EntityId); TradingSupportClient client = new TradingSupportClient(Properties.Settings.Default.TradingSupportEndpoint); MethodResponseErrorCode response = client.DeleteEntityTree( new EntityTree[] { new EntityTree() { RowId = entityTreeRow.EntityTreeId, RowVersion = entityTreeRow.RowVersion } }); if (!response.IsSuccessful) { if (response.Errors.Length > 0) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } else { GuardianObject.ThrowErrorInfo(response.Result); } } client.Close(); } } catch (FaultException <RecordNotFoundFault> exception) { EventLog.Warning("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace); } catch (Exception exception) { EventLog.Error("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace); Application.Current.Dispatcher.BeginInvoke(new WaitCallback(data => MessageBox.Show( Application.Current.MainWindow, String.Format(FluidTrade.Guardian.Properties.Resources.UnlinkFolderFailed, child, parent), Application.Current.MainWindow.Title)), DispatcherPriority.Normal); } }
/// <summary> /// Set the user's password to the new password. /// </summary> /// <param name="user">The user to change.</param> /// <param name="oldPassword">The current password.</param> /// <param name="password">The new password.</param> private void ResetPassword(User user, string oldPassword, string password) { try { AdminSupportClient adminSupportClient = new AdminSupportClient(Guardian.Properties.Settings.Default.AdminSupportEndpoint); AdminSupportReference.User userRecord = new AdminSupportReference.User(); MethodResponseErrorCode response = null; DataModel.IsReading = false; if (user.UserId == UserContext.Instance.UserId) { response = adminSupportClient.ChangePassword(oldPassword, password); if (response.IsSuccessful) { ChannelStatus.LoginEvent.Set(); ChannelStatus.IsPrompted = false; ChannelStatus.Secret = password; ChannelStatus.LogggedInEvent.Set(); } } else { response = adminSupportClient.ResetPassword(user.IdentityName, password); } if (!response.IsSuccessful) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } adminSupportClient.Close(); } catch (FaultException <ArgumentFault> ) { this.Dispatcher.BeginInvoke(new Action(() => MessageBox.Show(this, String.Format(Properties.Resources.ResetPasswordFailedPoorComplexity, user), this.Title))); } catch (SecurityAccessDeniedException) { this.Dispatcher.BeginInvoke(new Action(() => MessageBox.Show(this, String.Format(Properties.Resources.UserNotFound, user), this.Title))); } catch (FaultException <RecordNotFoundFault> ) { this.Dispatcher.BeginInvoke(new Action(() => MessageBox.Show(this, String.Format(Properties.Resources.ResetPasswordFailedPermissionDenied, user), this.Title))); } catch (Exception exception) { // Any issues trying to communicate to the server are logged. EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace); this.Dispatcher.BeginInvoke(new Action(() => MessageBox.Show(this, String.Format(Properties.Resources.ResetPasswordFailed, user.Name), this.Title))); } finally { DataModel.IsReading = true; } }
/// <summary> /// Delete an set of debt holders. /// </summary> /// <param name="debtHolders">The set of working orders.</param> /// <returns>The actual bulk size used.</returns> protected override Int32 Delete(List <GuardianObject> debtHolders) { Int32 attemptedBulkSize = debtHolders.Count; Int32 actualBulkSize = attemptedBulkSize; GuardianObject failedObject = null; TradingSupportReference.DebtHolder[] records = new TradingSupportReference.DebtHolder[debtHolders.Count]; Dictionary <TradingSupportReference.DebtHolder, DebtHolder> recordsToHolders = new Dictionary <TradingSupportReference.DebtHolder, DebtHolder>(); // Convert the GuardianObjects to records we can push up to the server. for (Int32 index = 0; index < records.Length; ++index) { DebtHolder debtHolder = debtHolders[0] as DebtHolder; records[index] = new TradingSupportReference.DebtHolder(); debtHolder.PopulateRecord(records[index]); recordsToHolders[records[index]] = debtHolder; debtHolders.RemoveAt(0); } try { Int32 sentSize; MethodResponseErrorCode response; response = NetworkHelper.Attempt <MethodResponseErrorCode>( (client, a) => client.DeleteDebtHolder(a as TradingSupportReference.DebtHolder[]), records, true, out sentSize); if (sentSize < attemptedBulkSize) { actualBulkSize = sentSize; } if (!response.IsSuccessful) { List <TradingSupportReference.DebtHolder> retryRecords = new List <TradingSupportReference.DebtHolder>(); foreach (ErrorInfo errorInfo in response.Errors) { // The bulk index is an index into the set we sent, which may be smaller than the set passed in. failedObject = recordsToHolders[records[errorInfo.BulkIndex]]; // If the error's "just" a deadlock, we should retry it. if (errorInfo.ErrorCode == ErrorCode.Deadlock) { retryRecords.Add(records[errorInfo.BulkIndex]); } else if (errorInfo.ErrorCode == ErrorCode.RecordExists) { throw new HasSettlementsException(this.ToString() + " has settled accounts"); } // We can safely ignore not-found errors (we are deleting after all), but if the error's more severe, forget the how // thing and throw up the error. else if (errorInfo.ErrorCode != ErrorCode.RecordNotFound) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } } records = retryRecords.ToArray(); } } catch (Exception exception) { // Any issues trying to communicate to the server are logged. EventLog.Error("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace); throw new DeleteException(failedObject, exception); } return(actualBulkSize); }
/// <summary> /// Commit any changes to this user to the server. /// </summary> public override void Commit() { AdminSupportClient client = new AdminSupportClient(Guardian.Properties.Settings.Default.AdminSupportEndpoint); AdminSupportReference.User user = new AdminSupportReference.User(); MethodResponseErrorCode response; this.PopulateRecord(user); if (this.Deleted) { response = client.DeleteUserAccount(user.LookupId); if (this.GetFirstErrorCode(response) == ErrorCode.RecordNotFound) { throw new UserNotFoundException(this, "User not found"); } } else { response = client.UpdateUser(new AdminSupportReference.User[] { user }); if (this.GetFirstErrorCode(response) == ErrorCode.RecordNotFound) { throw new UserNotFoundException(this, "User not found"); } if (response.IsSuccessful) { if (this.AccountDisabled) { response = client.DisableUserAccount(this.IdentityName); } } if (response.IsSuccessful) { lock (DataModel.SyncRoot) { List <Group> newGroups = this.Groups.ToList(); List <Guid> add = new List <Guid>(); List <Guid> del = new List <Guid>(); GroupUsersRow[] oldGroups = DataModel.User.UserKey.Find(this.UserId).GetGroupUsersRows(); ErrorCode firstError; foreach (GroupUsersRow groupUsersRow in oldGroups) { Group group = newGroups.FirstOrDefault(g => g.GroupId == groupUsersRow.GroupId); if (group == null) { del.Add(groupUsersRow.GroupId); } else { if (group.Deleted) { del.Add(group.GroupId); } newGroups.Remove(group); } } foreach (Group group in newGroups) { response = client.AddUserToGroup(this.IdentityName, group.GroupId, this.TenantId); firstError = this.GetFirstErrorCode(response); if (firstError == ErrorCode.RecordNotFound) { throw new GroupNotFoundException(this.DefaultGroup, "Group not found"); } else if (firstError != ErrorCode.Success) { break; } } foreach (Guid group in del) { response = client.RemoveUserFromGroup(this.IdentityName, group); firstError = this.GetFirstErrorCode(response); if (firstError != ErrorCode.RecordNotFound && firstError != ErrorCode.Success) { break; } } } } } if (!response.IsSuccessful) { GuardianObject.ThrowErrorInfo(response.Errors[0]); } client.Close(); this.Modified = false; }