/// <summary>
 /// Actual execute a move by moving the securities.
 /// </summary>
 /// <param name="client">The trading support client to use.</param>
 /// <param name="records">The security records to move.</param>
 /// <param name="newParent">The new blotter.</param>
 /// <returns>The server response</returns>
 protected virtual MethodResponseErrorCode MoveSecurity(
     TradingSupportClient client,
     BaseRecord[] records,
     Blotter newParent)
 {
     throw new NotImplementedException("Only consumer debt securities are implemented");
 }
Example #2
0
        /// <summary>
        /// Delete the debt holder proper.
        /// </summary>
        protected override void DeleteDebtClass()
        {
            TradingSupportClient client = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            base.DeleteDebtClass();

            MethodResponseErrorCode response = client.DeleteDebtHolder(new TradingSupportReference.DebtHolder[] { new TradingSupportReference.DebtHolder
                                                                                                                  {
                                                                                                                      RowId      = this.EntityId,
                                                                                                                      RowVersion = this.RowVersion
                                                                                                                  } });

            if (!response.IsSuccessful)
            {
                if (response.Errors.Length > 0)
                {
                    Entity.ThrowErrorInfo(response.Errors[0]);
                }
                else
                {
                    Entity.ThrowErrorInfo(response.Result);
                }
            }

            client.Close();
        }
Example #3
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="consumers"></param>
        public static MethodResponseErrorCode UpdateConsumer(Consumer[] consumers)
        {
            MethodResponseErrorCode response = null;

            // Update the database.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                response = tradingSupportClient.UpdateConsumer(consumers);
            }
            catch (Exception exception)
            {
                // Any issues trying to communicate to the server are logged.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }
            return(response);
        }
Example #4
0
        /// <summary>
        /// Marks a set of record(s) as read.
        /// </summary>
        /// <param name="state">The list to delete.</param>
        private void ApproveSettlementThread(object state)
        {
            List <ConsumerDebtSettlementRow>        consumerDebtSettlementRows        = state as List <ConsumerDebtSettlementRow>;
            List <ConsumerDebtSettlementAcceptInfo> consumerDebtSettlementAcceptInfos = new List <ConsumerDebtSettlementAcceptInfo>();

            // Set up the list of accept records to send.
            try
            {
                lock (DataModel.SyncRoot)
                {
                    foreach (ConsumerDebtSettlementRow consumerDebtSettlementRow in consumerDebtSettlementRows)
                    {
                        // Construct a version of the negotiation record from the known information and update the 'IsRead' flag.
                        ConsumerDebtSettlementAcceptInfo consumerDebtSettlementAcceptInfo = new ConsumerDebtSettlementAcceptInfo();
                        consumerDebtSettlementAcceptInfo.ConsumerDebtSettlementId = consumerDebtSettlementRow.ConsumerDebtSettlementId;
                        consumerDebtSettlementAcceptInfo.RowVersion = consumerDebtSettlementRow.RowVersion;
                        consumerDebtSettlementAcceptInfos.Add(consumerDebtSettlementAcceptInfo);
                    }
                }
            }
            catch (Exception exception)
            {
                // Any issues trying to communicate to the server are logged or might not have a valid match row cell to bold or unbold.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);

                this.Dispatcher.BeginInvoke(new Action(() =>
                                                       MessageBox.Show(Application.Current.MainWindow, "Failed to perform Approve Settlement operation.", Application.Current.MainWindow.Title)));
                return;
            }

            // Send the accept records.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                tradingSupportClient.AcceptConsumerDebtSettlement(consumerDebtSettlementAcceptInfos.ToArray());
            }
            catch (FaultException faultException)
            {
                EventLog.Error("{0}, {1}", faultException.Message, faultException.StackTrace);

                this.Dispatcher.BeginInvoke(new Action(() =>
                                                       MessageBox.Show(Application.Current.MainWindow, faultException.Message, Application.Current.MainWindow.Title)));
            }
            catch (Exception exception)
            {
                // Any issues trying to communicate to the server are logged or might not have a valid match row cell to bold or unbold.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);

                this.Dispatcher.BeginInvoke(new Action(() =>
                                                       MessageBox.Show(Application.Current.MainWindow, "Failed to perform Approve Settlement operation.", Application.Current.MainWindow.Title)));
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }
        }
Example #5
0
        /// <summary>
        /// Commit any changes to the debt class to the server.
        /// </summary>
        protected override void CommitDebtClass()
        {
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            TradingSupportReference.DebtHolder record = new TradingSupportReference.DebtHolder();

            this.PopulateRecord(record);

            if (this.EntityId == Guid.Empty)
            {
                MethodResponseArrayOfguid response = tradingSupportClient.CreateDebtHolder(new TradingSupportReference.DebtHolder[] { record });

                if (!response.IsSuccessful)
                {
                    Entity.ThrowErrorInfo(response.Errors[0]);
                }
            }
            else
            {
                MethodResponseErrorCode response = tradingSupportClient.UpdateDebtHolder(new TradingSupportReference.DebtHolder[] { record });

                if (!response.IsSuccessful)
                {
                    Entity.ThrowErrorInfo(response.Errors[0]);
                }
            }

            tradingSupportClient.Close();
        }
Example #6
0
        /// <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.");
                }
            }
        }
Example #7
0
        /// <summary>
        /// Create, update, or destroy the debt rule in the datamodel that corresponds to this DebtRule object.
        /// </summary>
        /// <param name="owner">The debt class that owns the debt rule.</param>
        public void Commit(Guid owner)
        {
            TradingSupportClient tradingSupport = new TradingSupportClient(Properties.Settings.Default.TradingSupportEndpoint);
            Int32 tries = 0;

            do
            {
                try
                {
                    if (this.Delete)
                    {
                        this.CommitDelete(tradingSupport);
                    }
                    else if (this.Modified)
                    {
                        this.CommitModified(tradingSupport, owner);
                        this.modified = false;
                    }

                    break;
                }
                catch (FaultException <DeadlockFault> )
                {
                    if (tries > 3)
                    {
                        throw;
                    }
                }

                tries += 1;
            } while (tries < 3);

            tradingSupport.Close();
        }
Example #8
0
        private static void GetUserId(string serverName, string userName, string password, bool verbose)
        {
            Uri tcpUri = new Uri(serverName);

            NetTcpBinding binding = new NetTcpBinding(SecurityMode.TransportWithMessageCredential);

            binding.Security.Message.ClientCredentialType = MessageCredentialType.UserName;

            if (verbose)
            {
                Console.WriteLine("Connecting to: " + serverName);
            }

            EndpointAddress address = new EndpointAddress(tcpUri);

            TradingSupportClient client = new TradingSupportClient(binding, address);

            client.ClientCredentials.UserName.UserName = userName;
            client.ClientCredentials.UserName.Password = password;

            Guid result = client.GetUserId();

            if (verbose)
            {
                Console.WriteLine("UserId: " + result.ToString());
            }
        }
Example #9
0
        /// <summary>
        /// Create a new DebtHolder in the data model.
        /// </summary>
        /// <param name="dataModel">The data model client to create the debt holder with.</param>
        /// <param name="typeId">The type-id of the DebtHolder type.</param>
        /// <param name="parentId">The entityId of the parent entity.</param>
        /// <param name="tenantId"></param>
        /// <returns>The entity-id of the new debt holder.</returns>
        public static new Guid Create(DataModelClient dataModel, Guid typeId, Guid parentId, Guid tenantId)
        {
            Guid entityId = Guid.Empty;
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                TradingSupportReference.DebtHolder record = new TradingSupportReference.DebtHolder();

                lock (DataModel.SyncRoot)
                {
                    DebtClassRow parent = DataModel.DebtClass.DebtClassKey.Find(parentId);

                    record.ConfigurationId   = "Default";
                    record.Name              = "New Debt Holder";
                    record.Address1          = parent.IsAddress1Null()? null : parent.Address1;
                    record.Address2          = parent.IsAddress2Null()? null : parent.Address2;
                    record.BankAccountNumber = parent.IsBankAccountNumberNull()? null : parent.BankAccountNumber;
                    record.BankRoutingNumber = parent.IsBankRoutingNumberNull()? null : parent.BankRoutingNumber;
                    record.City              = parent.IsCityNull()? null : parent.City;
                    record.CompanyName       = parent.IsCompanyNameNull()? null : parent.CompanyName;
                    record.ContactName       = parent.IsContactNameNull()? null : parent.ContactName;
                    record.Department        = parent.IsDepartmentNull()? null : parent.Department;
                    record.Email             = parent.IsEmailNull()? null : parent.Email;
                    record.Fax          = parent.IsFaxNull()? null : parent.Fax;
                    record.ForBenefitOf = parent.IsForBenefitOfNull()? null : parent.ForBenefitOf;
                    record.ParentId     = parent.DebtClassId;
                    record.Phone        = parent.IsPhoneNull()? null : parent.Phone;
                    record.PostalCode   = parent.IsPostalCodeNull()? null : parent.PostalCode;
                    record.Province     = parent.IsProvinceIdNull() ? null : (Guid?)parent.ProvinceId;
                }
                record.TenantId = tenantId;
                MethodResponseArrayOfguid response = tradingSupportClient.CreateDebtHolder(new TradingSupportReference.DebtHolder[] { record });
                if (response.IsSuccessful)
                {
                    entityId = response.Result[0];
                }
                else
                {
                    throw new Exception(String.Format("Server error: {0}, {1}", response.Errors[0].ErrorCode, response.Errors[0].Message));
                }
            }
            catch (Exception exception)
            {
                // Any issues trying to communicate to the server are logged.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
                throw;
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }

            return(entityId);
        }
Example #10
0
        /// <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>
        /// Actual execute a move by moving the securities.
        /// </summary>
        /// <param name="client">The trading support client to use.</param>
        /// <param name="records">The security records to move.</param>
        /// <param name="newParent">The new blotter.</param>
        /// <returns>The server response</returns>
        protected override MethodResponseErrorCode MoveSecurity(
            TradingSupportClient client,
            BaseRecord[] records,
            Blotter newParent)
        {
            MethodResponseErrorCode response = null;

            response = client.MoveConsumerDebtToBlotter(newParent.BlotterId, records);

            return(response);
        }
Example #14
0
        /// <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.");
                }
            }
        }
Example #15
0
        private void InitializeData(object state)
        {
            // This creates a client to communicate with the server.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Properties.Settings.Default.TradingSupportEndpoint);

            SimulationParameters simulationParameters = tradingSupportClient.GetSimulationParameters();

            // Release the resources used to communicate with the server.
            tradingSupportClient.Close();

            this.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new SetSimulationParametersHandler(OnSetSimulationParameters), simulationParameters);
        }
Example #16
0
        /// <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);
            }
        }
Example #17
0
        /// <summary>
        /// Adjusts the parameters of the market simulation.
        /// </summary>
        /// <param name="state">The generic thread initialization parameter.</param>
        public static void Simulate(object state)
        {
            // Extract the strongly typed parameter from the generic thread parameter.
            SimulationParameters simulationParameters = state as SimulationParameters;

            // This creates a client to communicate with the server.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Properties.Settings.Default.TradingSupportEndpoint);

            tradingSupportClient.SetSimulationParameters(simulationParameters);

            // Release the resources used to communicate with the server.
            tradingSupportClient.Close();
        }
Example #18
0
        /// <summary>
        /// Marks a set of record(s) as read.
        /// </summary>
        /// <param name="state">The list to delete.</param>
        private void RegenerateSettlementThread(object state)
        {
            List <BaseRecord>       consumerDebtSettlementRows = state as List <BaseRecord>;
            MethodResponseErrorCode response;

            // Send the regenerate records.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                response = tradingSupportClient.ResetConsumerDebtSettlement(consumerDebtSettlementRows.ToArray());

                if (!response.IsSuccessful)
                {
                    List <BaseRecord> retryRecords = new List <BaseRecord>();

                    foreach (ErrorInfo errorInfo in response.Errors)
                    {
                        EventLog.Error("ResetConsumerDebtSettlement {0} failed with following message: {1}", errorInfo.BulkIndex, errorInfo.Message);
                    }

                    throw new FaultException("Not all the records were reset.  Please see Event Viewer for detailed information about the errors.");
                }
            }
            catch (FaultException faultException)
            {
                EventLog.Error("{0}, {1}", faultException.Message, faultException.StackTrace);

                this.Dispatcher.BeginInvoke(new Action(() =>
                                                       MessageBox.Show(Application.Current.MainWindow, faultException.Message, Application.Current.MainWindow.Title, MessageBoxButton.OK,
                                                                       MessageBoxImage.Error)));
            }
            catch (Exception exception)
            {
                // Any issues trying to communicate to the server are logged or might not have a valid match row cell to bold or unbold.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);

                this.Dispatcher.BeginInvoke(new Action(() =>
                                                       MessageBox.Show(Application.Current.MainWindow, "Failed to perform Regenerate Settlement operation.", Application.Current.MainWindow.Title)));
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }
        }
Example #19
0
        /// <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);
            }
        }
Example #20
0
        /// <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.Entity record = new TradingSupportReference.Entity();
                MethodResponseErrorCode        response;

                this.PopulateRecord(record);

                if (this.Deleted)
                {
                    throw new NotImplementedException("Cannot delete from Entity.Commit. You must override Commit in a derived class");
                }
                else
                {
                    response = tradingSupportClient.UpdateEntity(new TradingSupportReference.Entity[] { record });
                }

                if (!response.IsSuccessful)
                {
                    Entity.ThrowErrorInfo(response.Errors[0]);
                }

                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);
                throw;
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }
        }
Example #21
0
        /// <summary>
        /// Accept a settlement.
        /// </summary>
        /// <param name="negotiationId"></param>
        private void AcceptSettlement(Guid negotiationId)
        {
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                tradingSupportClient.CreateConsumerTrustSettlement(negotiationId);

            }
            catch (FaultException<ArgumentFault> exception)
            {

                EventLog.Information(
                    "Server rejected auto-accept of consumer trust negotiation {0}: {1}: {2}\n {3}",
                    negotiationId,
                    exception.GetType(),
                    exception.Detail.Message,
                    exception.StackTrace);

            }
            catch (Exception exception)
            {

                System.Diagnostics.Debug.WriteLine(String.Format("Accepting negotiation {0} failed from trust side inexplicably.", negotiationId));
                EventLog.Error(
                    "Failed to auto-settle consumer trust negotiation {0}: {1}: {2}\n {3}",
                    negotiationId,
                    exception.GetType(),
                    exception.Message,
                    exception.StackTrace);

            }
            finally
            {

                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                    tradingSupportClient.Close();
            }

            Thread.Sleep(5000);
        }
Example #22
0
        public static void MoveConsumerDebtToBlotter(Guid blotterId, BaseRecord[] consumerDebt)
        {
            // Update the database.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                MethodResponseErrorCode response = tradingSupportClient.MoveConsumerDebtToBlotter(blotterId, consumerDebt);
            }
            catch (Exception exception)
            {
                // Any issues trying to communicate to the server are logged.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }
        }
Example #23
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="workingOders"></param>
        public static MethodResponseErrorCode UpdateWorkingOrder(WorkingOrderRecord workingOrder)
        {
            MethodResponseErrorCode response = null;
            // Update the database.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                lock (DataModel.SyncRoot)
                {
                    WorkingOrderRow row = DataModel.WorkingOrder.WorkingOrderKey.Find(workingOrder.RowId);

                    if (TradingSupportWebService.ColumnChanged(row, workingOrder))
                    {
                        response = tradingSupportClient.UpdateWorkingOrder(new WorkingOrderRecord[] { workingOrder });
                    }
                    else
                    {
                        response = null;
                    }
                }
            }
            catch (Exception exception)
            {
                // Any issues trying to communicate to the server are logged.
                EventLog.Error("{0}, {1}", exception.Message, exception.StackTrace);
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }
            return(response);
        }
Example #24
0
        /// <summary>
        /// Destroy the executions and destination orders on the shared data model.
        /// </summary>
        /// <param name="sender">The generic thread initialization parameter.</param>
        public static void DestroyOrders(object sender)
        {
            // This will establish an endpoint to the web services that support trading functions.
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Properties.Settings.Default.TradingSupportEndpoint);

            lock (DataModel.SyncRoot)
            {
                // To prevent a buffer of an arbitrary size, the commands to delete orders are batched up and sent in chunks.
                int batchCounter = 0;

                // This will construct a list of references to the orders.  This list will be transmitted to the server where a web service will
                // pull it apart and
                List <DestinationOrderReference> destinationOrderReferences = new List <DestinationOrderReference>();
                foreach (DestinationOrderRow destinationOrderRow in DataModel.DestinationOrder)
                {
                    DestinationOrderReference destinationOrderReference = new DestinationOrderReference();
                    destinationOrderReference.DestinationId = destinationOrderRow.DestinationOrderId;
                    destinationOrderReference.RowVersion    = destinationOrderRow.RowVersion;
                    destinationOrderReferences.Add(destinationOrderReference);

                    if (batchCounter++ == batchSize)
                    {
                        batchCounter = 0;
                        tradingSupportClient.DestroyDestinationOrders(destinationOrderReferences.ToArray());
                        destinationOrderReferences = new List <DestinationOrderReference>();
                    }
                }

                if (destinationOrderReferences.Count != 0)
                {
                    tradingSupportClient.DestroyDestinationOrders(destinationOrderReferences.ToArray());
                }
            }

            tradingSupportClient.Close();
        }
        /// <summary>
        /// Delete a list of credit card rows.
        /// </summary>
        /// <param name="state">The list to delete.</param>
        public void DestroyRecords(object state)
        {
            List <CreditCardRow> toDeleteRows         = state as List <CreditCardRow>;
            TradingSupportClient tradingSupportClient = new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

            try
            {
                int recordsPerCall = 100;
                TradingSupportReference.CreditCard[] orders = null;
                int recordTotal = 0;
                int recordIndex = 0;

                foreach (CreditCardRow workingOrderRow in toDeleteRows)
                {
                    if (recordIndex == 0)
                    {
                        orders = new TradingSupportReference.CreditCard[
                            toDeleteRows.Count - recordTotal < recordsPerCall ?
                            toDeleteRows.Count - recordTotal :
                            recordsPerCall];
                    }

                    orders[recordIndex++] = new TradingSupportReference.CreditCard()
                    {
                        RowId      = workingOrderRow.CreditCardId,
                        RowVersion = workingOrderRow.RowVersion
                    };

                    if (recordIndex == orders.Length)
                    {
                        MethodResponseErrorCode response = tradingSupportClient.DeleteCreditCard(orders);
                        if (!response.IsSuccessful)
                        {
                            ErrorCode error = response.Result;
                            if (response.Errors.Length > 0)
                            {
                                error = response.Errors[0].ErrorCode;
                            }
                            if (error == ErrorCode.RecordExists)
                            {
                                throw new IsSettledException(string.Format("{0} is settled", workingOrderRow.OriginalAccountNumber));
                            }
                            else
                            {
                                throw new Exception(String.Format("Server error {0}", response.Result));
                            }
                        }
                        recordTotal += recordIndex;
                        recordIndex  = 0;
                    }
                }
            }
            catch (IsSettledException exception)
            {
                EventLog.Information("{0}: {1}\n{2}", exception.GetType(), exception.Message, exception.StackTrace);

                this.Dispatcher.BeginInvoke(new Action(() =>
                                                       MessageBox.Show(Application.Current.MainWindow, "Cannot delete Credit Card: " + exception.Message, Application.Current.MainWindow.Title)));
            }
            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);

                this.Dispatcher.BeginInvoke(new Action(() =>
                                                       MessageBox.Show(Application.Current.MainWindow, "Cannot delete Credit Card", Application.Current.MainWindow.Title)));
            }
            finally
            {
                if (tradingSupportClient != null && tradingSupportClient.State == CommunicationState.Opened)
                {
                    tradingSupportClient.Close();
                }
            }
        }
Example #26
0
        /// <summary>
        /// Attempt to make a call until it either succeeds, or a maximum number of probably innocuous errors occur.
        /// </summary>
        /// <typeParam name="T">The typeof the response. This must have an Errors property of type TradingSupportReference.ErrorInfo[].</typeParam>
        /// <param name="func">The call ot make.</param>
        /// <param name="records">The records to pass to func.</param>
        /// <param name="stopsOnError">If true, dead lock errors will continue from the point of failure, rather than simply retrying the failed
        /// records.</param>
        /// <param name="sentSize">The number of records per call.</param>
        public static T Attempt <T>(Func <TradingSupportClient, Array, T> func, Array records, Boolean stopsOnError, out Int32 sentSize)
        {
            ConstructorInfo recordsConstructor = records.GetType().GetConstructor(new Type[] { typeof(Int32) });
            T       response;
            Int32   calls     = 0;
            Boolean succeeded = false;
            Random  rand      = new Random((Int32)DateTime.Now.Ticks);

            sentSize = records.Length;

            do
            {
                Thread.Sleep(calls * (NetworkHelper.WaitTimeScale + rand.Next(NetworkHelper.WaitTimeScale)));

                try
                {
                    try
                    {
                        List <object>        retryRecords = new List <object>();
                        ErrorInfo[]          errors;
                        TradingSupportClient tradingSupportClient =
                            new TradingSupportClient(Guardian.Properties.Settings.Default.TradingSupportEndpoint);

                        calls   += 1;
                        response = func(tradingSupportClient, records);
                        errors   = response.GetErrors();

                        succeeded = true;

                        foreach (ErrorInfo error in errors)
                        {
                            if (error.ErrorCode == ErrorCode.Deadlock)
                            {
                                succeeded = false;

                                if (stopsOnError)
                                {
                                    Array newArray = recordsConstructor.Invoke(new object[] { records.Length - error.BulkIndex }) as Array;

                                    Array.Copy(records, error.BulkIndex, newArray, 0, newArray.Length);
                                    records = newArray;
                                    System.Diagnostics.Debug.WriteLine("Retrying because of SQL deadlock");

                                    break;
                                }
                                else
                                {
                                    retryRecords.Add(records.GetValue(error.BulkIndex));
                                }
                            }
                        }

                        if (retryRecords.Count > 0 && stopsOnError)
                        {
                            records = retryRecords.ToArray();
                            System.Diagnostics.Debug.WriteLine("Retrying because of SQL deadlock");
                        }

                        try
                        {
                            tradingSupportClient.Close();
                        }
                        catch (Exception exception)
                        {
                            EventLog.Information(String.Format(
                                                     "Unable to close client after successful transaction: {0}: {1}\n{2}",
                                                     exception.GetType(), exception.Message,
                                                     exception.StackTrace));
                        }
                    }
                    catch (TargetInvocationException exception)
                    {
                        throw exception.InnerException;
                    }
                }
                catch (CommunicationObjectFaultedException)
                {
                    if (records.Length == 1)
                    {
                        throw;
                    }

                    Thread.Sleep(NetworkHelper.WaitTimeScale);

                    response = NetworkHelper.Reattempt(func, records, stopsOnError, out sentSize);
                }
            } while (calls < NetworkHelper.MaxCalls && !succeeded);

            return(response);
        }