public override WorkerResult Run(IDalSessionFactory factory, BackgroundWorker worker, DoWorkEventArgs e) { try { IDalSession session = factory.CreateSession(); if (session == null) throw new ApplicationException("The session cannot be null"); session.Close(); BatchExecutionResults results = new BatchExecutionResults(); if (NotaType == -1) PrintNotasAdapter.PrintNotas(results, ManagementCompanyID); else PrintNotasAdapter.PrintNotas(results, ManagementCompanyID, (NotaReturnClass)NotaType); string result = PrintNotasAdapter.FormatErrorsForPrintNotas(results, ManagementCompanyID.ToString()); e.Result = new WorkerResult(WorkerResult.STATE_NORMAL, WorkerResultStatus.Ok, result, result); } catch (Exception ex) { e.Result = new WorkerResult(WorkerResult.STATE_EXCEPTION, WorkerResultStatus.Exception, "An error occured in the print notas worker", "", ex); } finally { worker.ReportProgress(100); } return (WorkerResult)e.Result; }
public static bool CreateMgtFeeTransactions(BatchExecutionResults results, int[] mgtPeriodIds, int year, int quarter, ManagementTypes managementType, bool createCashInitiatedOrders) { IDalSession session = NHSessionFactory.CreateSession(); DateTime minDate, maxDate; Util.GetDatesFromQuarter(year, quarter, out minDate, out maxDate); int mgtPeriodId = 0; int journalID = int.Parse((string)(System.Configuration.ConfigurationManager.AppSettings.Get("DefaultManagementFeeJournal"))); IJournal journalMgmtFee = JournalMapper.GetJournal(session, journalID); IGLLookupRecords lookups = GlLookupRecordMapper.GetGLLookupRecords(session, BookingComponentParentTypes.ManagementFee); if (mgtPeriodIds != null && mgtPeriodIds.Length > 0) { FeeFactory feeFactory = FeeFactory.GetInstance(session, FeeFactoryInstanceTypes.Fee, true); decimal taxPercentage = feeFactory.GetHistoricalTaxRate(maxDate).StandardRate; for (int i = 0; i < mgtPeriodIds.Length; i++) { try { mgtPeriodId = mgtPeriodIds[i]; if (createMgtFeeTransactionForMP(journalMgmtFee, lookups, mgtPeriodId, year, quarter, managementType, feeFactory, minDate, maxDate, taxPercentage, createCashInitiatedOrders)) results.MarkSuccess(); } catch (Exception ex) { results.MarkError( new ApplicationException(string.Format("Error creating management fee transaction for management period {0}.", mgtPeriodId), ex)); } } } session.Close(); return true; }
public static void CreateNotaFromOrder(BatchExecutionResults results, int orderId) { IDalSession session = NHSessionFactory.CreateSession(); try { ISecurityOrder order = OrderMapper.GetOrder(session, orderId) as ISecurityOrder; if (order != null) { INota nota = order.CreateNota(); if (nota != null) { NotaMapper.Update(session, nota); results.MarkSuccess(); } } else results.MarkError(new ApplicationException(string.Format("Security Order {0} not found.", orderId))); } catch (Exception ex) { results.MarkError(new ApplicationException(string.Format("Error creating nota for order {0}.", orderId), ex)); } finally { session.Close(); } }
protected void btnCreateRebalanceInstructions_Click(object sender, EventArgs e) { try { lblError.Text = ""; int[] accountIds = gvAccounts.GetSelectedIds(); if (accountIds.Length > 0) { if (!EditMode) { EditMode = true; chkNoCharges.Checked = true; dtpExecDate.SelectedDate = DateTime.Today; } else { BatchExecutionResults results = new BatchExecutionResults(); InstructionEntryAdapter.CreateRebalanceInstructions(results, accountIds, OrderActionTypes.Rebalance, chkNoCharges.Checked, dtpExecDate.SelectedDate, null); lblError.Text = InstructionEntryAdapter.FormatErrorsForCreateInstructions(results, "rebalance"); EditMode = false; gvAccounts.ClearSelection(); } } gvAccounts.DataBind(); } catch (Exception ex) { lblError.Text = string.Format("<br/>{0}<br/>", Utility.GetCompleteExceptionMessage(ex)); } }
public static string FormatErrorsForCreatePeriodicWithdrawals(BatchExecutionResults results) { const int MAX_ERRORS_DISPLAYED = 25; string message = "<br/>"; if (results.SuccessCount == 0 && results.ErrorCount == 0) message += "No new periodic withdrawal instructions need to be created"; else { if (results.SuccessCount > 0) message += string.Format("{0} periodic withdrawal instructions were successfully created.<br/><br/><br/>", results.SuccessCount); if (results.ErrorCount > 0) { string tooManyErrorsMessage = (results.ErrorCount > MAX_ERRORS_DISPLAYED ? string.Format(" (only the first {0} are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} errors occured while creating periodic withdrawal instructions{1}:<br/><br/><br/>", results.ErrorCount, tooManyErrorsMessage); int errors = 0; foreach (Exception ex in results.Errors) { if (++errors > MAX_ERRORS_DISPLAYED) break; message += Utility.GetCompleteExceptionMessage(ex) + "<br/>"; } } } return message; }
public static string FormatErrorsForSkipAverageHoldingCorrections(BatchExecutionResults results) { const int MAX_ERRORS_DISPLAYED = 25; string message = "<br/>"; if (results.SuccessCount == 0 && results.ErrorCount == 0) message += "No new average holding corrections need to be skipped"; else { if (results.SuccessCount > 0) message += string.Format("{0} average holding corrections were successfully skipped.<br/><br/><br/>", results.SuccessCount); if (results.ErrorCount > 0) { string tooManyErrorsMessage = (results.ErrorCount > MAX_ERRORS_DISPLAYED ? string.Format(" (only the first {0} are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} errors occured while skipping average holding corrections{1}:<br/><br/><br/>", results.ErrorCount, tooManyErrorsMessage); int errors = 0; foreach (Exception ex in results.Errors) { if (++errors > MAX_ERRORS_DISPLAYED) break; message += Utility.GetCompleteExceptionMessage(ex) + "<br/>"; } } } return message; }
private string createResultsMessage(BatchExecutionResults results) { const int MAX_ERRORS_DISPLAYED = 25; string message = "<br/>"; if (results.SuccessCount == 0 && results.ErrorCount == 0) message += "No ledger entries need to be exported up to the selected date."; else { if (results.SuccessCount > 0) message += string.Format("{0} ledger {1} exported successfully.<br/><br/><br/>", results.SuccessCount, (results.SuccessCount != 1 ? "entries were" : "entry was")); if (results.ErrorCount > 0) { string tooManyErrorsMessage = (results.ErrorCount > MAX_ERRORS_DISPLAYED ? string.Format(" (only the first {0} errors are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} error{1} occured while exporting{2}:<br/><br/><br/>", results.ErrorCount, (results.ErrorCount != 1 ? "s" : ""), tooManyErrorsMessage); int errors = 0; foreach (Exception ex in results.Errors) { if (++errors > MAX_ERRORS_DISPLAYED) break; message += Utility.GetCompleteExceptionMessage(ex) + "<br/>"; } } } return message; }
public static bool CreateRebalanceInstructions(BatchExecutionResults results, int[] accountIds, OrderActionTypes orderActionType, bool noCharges, DateTime execDate, List<RebalanceExclusionDetails> exclusions) { bool retVal = false; if (accountIds == null || accountIds.Count() == 0) throw new B4F.TotalGiro.ApplicationLayer.Common.GridviewNoSelectionException(); using (IDalSession session = NHSessionFactory.CreateSession()) { IList<IAccountTypeCustomer> accounts = AccountMapper.GetAccounts<IAccountTypeCustomer>(session, accountIds); if (accounts != null && accounts.Count > 0) { IList saveAccounts = new ArrayList(); foreach (IAccountTypeCustomer account in accounts) { try { IRebalanceInstruction instruction = (IRebalanceInstruction)account.CreateInstruction(InstructionTypes.Rebalance, orderActionType, execDate, noCharges); if (instruction != null) { if (exclusions != null && exclusions.Count > 0) { foreach (RebalanceExclusionDetails exclusion in exclusions) { switch (exclusion.ComponentType) { case ModelComponentType.Model: if (exclusion.Model == null) exclusion.Model = ModelMapper.GetModel(session, exclusion.ComponentKey); instruction.ExcludedComponents.AddExclusion(exclusion.Model); break; case ModelComponentType.Instrument: if (exclusion.Instrument == null) exclusion.Instrument = InstrumentMapper.GetTradeableInstrument(session, exclusion.ComponentKey); instruction.ExcludedComponents.AddExclusion(exclusion.Instrument); break; } } } saveAccounts.Add(account); results.MarkSuccess(); } } catch (Exception ex) { results.MarkError( new ApplicationException(string.Format("Error creating rebalance instruction for {0}.", account.DisplayNumberWithName), ex)); } } retVal = AccountMapper.UpDateList(session, saveAccounts); } } return retVal; }
protected void btnExportToExact_Click(object sender, EventArgs e) { try { dpDateUntil.IsExpanded = false; BatchExecutionResults results = new BatchExecutionResults(); ExportExactAdapter.ExportToExact(results, dpDateUntil.SelectedDate); lblErrorMessage.Text = createResultsMessage(results); } catch (Exception ex) { lblErrorMessage.Text = "<br/ >" + Utility.GetCompleteExceptionMessage(ex); } }
protected void btnCreatePeriodicWithdrawals_Click(object sender, EventArgs e) { try { lblMessage2.Text = ""; BatchExecutionResults results = new BatchExecutionResults(); CreatePeriodicWithdrawalInstructionsAdapter.CreatePeriodicWithdrawals(results); lblMessage2.Text = CreatePeriodicWithdrawalInstructionsAdapter.FormatErrorsForCreatePeriodicWithdrawals(results); } catch (Exception ex) { lblMessage2.ForeColor = Color.Red; lblMessage2.Text = "<br/>ERROR: " + Utility.GetCompleteExceptionMessage(ex); } }
public static string FormatErrorsForUpdateLifecycleModelToAge(BatchExecutionResults results) { const int MAX_ERRORS_DISPLAYED = 25; string message = "<br/>"; if (results.SuccessCount == 0 && results.ErrorCount == 0) message += "No accounts needed to be updated.<br/><br/>"; else message += string.Format("{0} accounts have been updated to a new model according with their age.<br/><br/><br/>", results.SuccessCount); if (results.WarningCount > 0) { string tooManyWarningsMessage = (results.WarningCount > MAX_ERRORS_DISPLAYED ? string.Format(" (only the first {0} are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} warnings occured while updating Lifecycle Models to the account's age{1}:<br/><br/><br/>", results.WarningCount, tooManyWarningsMessage); int warnings = 0; foreach (string wr in results.Warnings) { if (++warnings > MAX_ERRORS_DISPLAYED) break; message += string.Format("{0}<br/>", wr); } } if (results.ErrorCount > 0) { string tooManyErrorsMessage = (results.ErrorCount > MAX_ERRORS_DISPLAYED ? string.Format(" (only the first {0} are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} errors occured while updating Lifecycle Models to the account's age{1}:<br/><br/><br/>", results.ErrorCount, tooManyErrorsMessage); int errors = 0; foreach (Exception ex in results.Errors) { if (++errors > MAX_ERRORS_DISPLAYED) break; message += Utility.GetCompleteExceptionMessage(ex) + "<br/>"; } } return message; }
protected void btnCreateNotas_Click(object sender, EventArgs e) { try { int currentManagmentCompanyId; string currentManagmentCompanyName; PrintNotasAdapter.GetCurrentManagmentCompany(out currentManagmentCompanyId, out currentManagmentCompanyName); BatchExecutionResults results = new BatchExecutionResults(); PrintNotasAdapter.CreateNotas(results, currentManagmentCompanyId); lblErrorMessage.Text = PrintNotasAdapter.FormatErrorsForCreateNotas(results, currentManagmentCompanyName); } catch (Exception ex) { lblErrorMessage.Text = "<br/>ERROR: " + Utility.GetCompleteExceptionMessage(ex); } }
public static bool CreateDepartureInstructions(BatchExecutionResults results, int[] accountIds, DateTime executionDate, int? counterAccountID, string transferDescription, bool noCharges) { bool retVal = false; if (accountIds == null || accountIds.Count() == 0) throw new B4F.TotalGiro.ApplicationLayer.Common.GridviewNoSelectionException(); using (IDalSession session = NHSessionFactory.CreateSession()) { ICounterAccount counterAcc = null; if (counterAccountID.HasValue && counterAccountID.Value != 0) counterAcc = CounterAccountMapper.GetCounterAccount(session, counterAccountID.Value); IList<IAccountTypeCustomer> accounts = AccountMapper.GetAccounts<IAccountTypeCustomer>(session, accountIds); if (accounts != null && accounts.Count > 0) { IList saveAccounts = new ArrayList(); foreach (IAccountTypeCustomer account in accounts) { try { int? withdrawalCount = account.ActiveWithdrawalInstructions.GetV(e => e.Count); if (withdrawalCount.HasValue && withdrawalCount.Value > 0) throw new ApplicationException(string.Format("{0} withdrawal instructions exist and need to be cancelled before the clients portfolio can be liquidated.", withdrawalCount.Value)); IClientDepartureInstruction instruction = account.CreateDepartureInstruction(executionDate, counterAcc, transferDescription, noCharges); if (instruction != null) { saveAccounts.Add(account); results.MarkSuccess(); if (instruction.CounterAccount == null) results.MarkWarning(string.Format("Account {0} does not have a default counter account. Please look up it's counter account otherwise the client can not be paid.", instruction.Account.DisplayNumberWithName)); } } catch (Exception ex) { results.MarkError( new ApplicationException(string.Format("Error creating departure instruction for {0}.", account.DisplayNumberWithName), ex)); } } retVal = AccountMapper.UpDateList(session, saveAccounts); } } return retVal; }
public static void ExportToExact(BatchExecutionResults results, DateTime dateUntil) { createExportEntries(dateUntil); IDalSession session = NHSessionFactory.CreateSession(); try { string exportFilePath = Utility.GetPathFromConfigFile("ExactExportFilePath"); IList<ILedgerType> ledgerGroups = LedgerEntryMapper.GetLedgerEntryGroupings(session, dateUntil); foreach (ILedgerType grouping in ledgerGroups) { //ILedgerType ledgerType = (ILedgerType)grouping; exportGrouping(results, session, grouping, dateUntil, exportFilePath); } } finally { session.Close(); } }
public static bool CreatePeriodicWithdrawals(BatchExecutionResults results) { using (IDalSession session = NHSessionFactory.CreateSession()) { Hashtable parameters = new Hashtable(); IManagementCompany company = LoginMapper.GetCurrentManagmentCompany(session); if (company != null && !company.IsStichting) parameters.Add("assetManagerId", company.Key); int[] keys = session.GetTypedListByNamedQuery<int>( "B4F.TotalGiro.Accounts.Withdrawals.GetWithdrawalRuleKeys", parameters) .ToArray(); if (keys.Count() > 0) return CreatePeriodicWithdrawals(results, keys, DateTime.MinValue); else return false; } }
protected void btnCreatePeriodicWithdrawals2_Click(object sender, EventArgs e) { try { lblMessage2.Text = ""; int key = 0; if (int.TryParse(gvWithDrawals.SelectedValue.ToString(), out key)) { BatchExecutionResults results = new BatchExecutionResults(); CreatePeriodicWithdrawalInstructionsAdapter.CreatePeriodicWithdrawals(results, key, dtpEndDate.SelectedDate); lblMessage2.Text = CreatePeriodicWithdrawalInstructionsAdapter.FormatErrorsForCreatePeriodicWithdrawals(results); setEditMode(false); } else throw new ApplicationException("Please select a withdrawal rule first."); } catch (Exception ex) { lblMessage2.ForeColor = Color.Red; lblMessage2.Text = "<br/>ERROR: " + Utility.GetCompleteExceptionMessage(ex); } }
private static int[] getAccountIdsWithFreshDocuments(BatchExecutionResults results, DocumentSubtypes documentSubtype, int managementCompanyId, int accountId) { IDalSession session = NHSessionFactory.CreateSession(); try { return DocumentMapper.GetAccountIdsWithFreshDocuments(session, documentSubtype, managementCompanyId, accountId); } catch (Exception ex) { results.MarkError(new ApplicationException( string.Format("Error retrieving list of accounts needing email notifications ({0}).", Util.SplitCamelCase(documentSubtype.ToString())), ex)); return new int[] { }; } finally { session.Close(); } }
private static void sendEmailNotificationsForAccount(BatchExecutionResults results, DocumentSubtypes documentSubtype, int accountId) { IDalSession session = NHSessionFactory.CreateSession(); try { List<IDocument> documents = DocumentMapper.GetFreshDocuments(session, documentSubtype, accountId); if (documents.Count > 0) { ICustomerAccount account = documents[0].Account; if (account.Status == AccountStati.Active) { List<IContact> contacts = (from ah in account.AccountHolders where ah.IsPrimaryAccountHolder || account.AccountHolders.Count == 1 select ah.Contact into c where c.IsActive && c.Email != "" && c.ContactSendingOptions.GetValueOrDefault( SendableDocumentCategories.NotasAndQuarterlyReports, SendingOptions.ByEmail) select c).ToList(); sendEmailNotificationsToContacts(results, contacts, documents, documentSubtype); } foreach (IDocument document in documents) document.EmailNotificationHandled = true; session.Update(documents); } } catch (Exception ex) { results.MarkError(new ApplicationException( string.Format("Error sending email notifications for account {0}.", accountId), ex)); } finally { session.Close(); } }
public static void UpdateLifecycleModelToAge(BatchExecutionResults results) { using (IDalSession session = NHSessionFactory.CreateSession()) { try { IManagementCompany comp = LoginMapper.GetCurrentManagmentCompany(session); IInternalEmployeeLogin employee = (IInternalEmployeeLogin)LoginMapper.GetCurrentLogin(session); Hashtable parameters = new Hashtable(); if (!comp.IsStichting) { IAssetManager am = (IAssetManager)comp; if (!am.SupportLifecycles) throw new ApplicationException("This asset manager does not support lifecycles."); else parameters.Add("managementCompanyID", am.Key); } List<ILifecycle> cycles = session.GetTypedListByNamedQuery<ILifecycle>( "B4F.TotalGiro.Instruments.ActiveLifecycles", parameters); List<ILifecycleLine> lines = cycles.SelectMany(x => x.Lines).ToList(); List<Object> accountWithLifecycleData = session.GetTypedListByNamedQuery<Object>( "B4F.TotalGiro.Instruments.AccountWithLifecycleData", parameters); var acctData = from a in accountWithLifecycleData.Cast<object[]>() where (DateTime)(a[4] ?? a[5] ?? DateTime.MinValue) != DateTime.MinValue select new { AccountID = (int)a[0], ModelID = (int)(a[2] ?? 0), LifecycleID = (int)a[3], Age = Util.CalculateCurrentAge((DateTime)(a[4] ?? a[5])) }; var acctNoBirthDate = from a in accountWithLifecycleData.Cast<object[]>() where (DateTime)(a[4] ?? a[5] ?? DateTime.MinValue) == DateTime.MinValue select (string)a[1]; if (acctNoBirthDate.Count() > 0) results.MarkWarning(string.Format("{0} accounts have a primary account holder without a proper birth date: {1}", acctNoBirthDate.Count(), acctNoBirthDate.Take(25).JoinStrings(","))); var acctIds = from x in acctData join y in lines on x.LifecycleID equals y.Parent.Key where x.Age >= y.AgeFrom && x.Age < y.AgeTo && x.ModelID != y.Model.Key select new { x.AccountID, x.Age }; //, x.Age, x.ModelID, y.AgeFrom, y.AgeTo, y.Model.ModelName }; foreach (var acctId in acctIds) { ICustomerAccount acc = (ICustomerAccount)AccountMapper.GetAccount(session, acctId.AccountID); if (acc.IsDeparting) results.MarkWarning(string.Format("Account {0} is departing so the model will not be updated", acc.DisplayNumberWithName)); else if (acc.IsUnderRebalance) results.MarkWarning(string.Format("Account {0} is under rebalance so the model will not be updated", acc.DisplayNumberWithName)); else { ILifecycle lc = acc.Lifecycle; IPortfolioModel model = null; if (lc != null) { model = lc.GetRelevantModel(acctId.Age); if (!acc.ModelPortfolio.Equals(model)) acc.SetModelPortfolio(acc.Lifecycle, model, acc.IsExecOnlyCustomer, acc.EmployerRelationship, employee, DateTime.Now); if (AccountMapper.Update(session, acc)) results.MarkSuccess(); } else results.MarkError( new ApplicationException(string.Format("Account {0} did not have a lifecycle.", acc.DisplayNumberWithName))); } } } catch (Exception ex) { results.MarkError( new ApplicationException("Error in UpdateLifecycleModelToAge.", ex)); } } }
//Process instructions protected void btnSkip_Click(object sender, EventArgs e) { try { int[] avgHoldingIds = gvMgtFeeCorrections.GetSelectedIds(); if (avgHoldingIds.Length > 0) { lblResult.Text = ""; BatchExecutionResults results = new BatchExecutionResults(); bool success = ManagementFeeCorrectionsAdapter.SkipAverageHoldingCorrections(results, avgHoldingIds, ManagementTypes.ManagementFee); lblResult.Text = ManagementFeeCorrectionsAdapter.FormatErrorsForSkipAverageHoldingCorrections(results); if (success) { gvMgtFeeCorrections.ClearSelection(); gvMgtFeeCorrections.DataBind(); } } } catch (Exception ex) { lblError.Text = getErrorMessage(ex); } }
private static void sendEmailNotificationsToContacts(BatchExecutionResults results, List<IContact> contacts, List<IDocument> documents, DocumentSubtypes documentSubtype) { if (contacts.Count > 0) { ICustomerAccount account = documents[0].Account; string body = documentsCreatedEmailTemplate; body = Utility.ShowOptionalTag(body, "option-notas", documentSubtype == DocumentSubtypes.Notas); body = Utility.ShowOptionalTag(body, "option-reports", documentSubtype == DocumentSubtypes.QuarterlyReports || documentSubtype == DocumentSubtypes.YearlyReports); string clientWebsiteUrl = (account.AccountOwner.StichtingDetails.ClientWebsiteUrl ?? "").TrimEnd('/'); if (string.IsNullOrEmpty(clientWebsiteUrl)) throw new ApplicationException("Client Website URL not known."); body = body.Replace("<%AccountNumber%>", account.Number) .Replace("<%ClientWebsiteUrl%>", clientWebsiteUrl); MailMessage message = new MailMessage(); message.Subject = string.Format("Nieuwe {0} portefeuille {1}", documentSubtype == DocumentSubtypes.Notas ? "transactienota’s" : "rapportage", account.Number); message.IsBodyHtml = true; SmtpClient client = new SmtpClient(); foreach (IContact contact in contacts) { message.To.Clear(); message.To.Add(testEmailRecipients != "" ? testEmailRecipients : contact.Email); message.Body = body.Replace("<%DearSirForm%>", contact.CurrentNAW.Formatter.DearSirForm); client.Send(message); results.MarkSuccess(); } } }
private static bool CreatePeriodicWithdrawals(BatchExecutionResults results, int[] keys, DateTime endDate) { ICustomerAccount account = null; IDalSession session = null; if (keys != null && keys.Length > 0) { for (int j = 0; j < keys.Length; j++) { int ruleKey = keys[j]; int itemsCreated = 0; try { session = NHSessionFactory.CreateSession(); Hashtable parameters = new Hashtable(1); parameters.Add("withdrawalRuleId", ruleKey); IList<IWithdrawalRule> rules = session.GetTypedListByNamedQuery<IWithdrawalRule>( "B4F.TotalGiro.Accounts.Withdrawals.GetWithdrawalRule", parameters); if (rules != null && rules.Count == 1) { IWithdrawalRule rule = rules[0]; account = rule.Account; if (!account.IsDeparting) { DateTime maxDate; // if not passed in -> get the max date if (endDate == DateTime.MinValue) maxDate = rule.GetMaxWithdrawalDate(); else { if (Util.IsNotNullDate(rule.EndDateWithdrawal) && endDate > rule.EndDateWithdrawal) maxDate = rule.EndDateWithdrawal; else maxDate = endDate; } bool isDirty = false; int start = (rule.LastWithdrawalDate >= DateTime.Today ? 0 : 1); // hardcoded: Never look further then 12 months for (int i = start; i < (12 + start); i++) { DateTime nextDate = rule.GetSpecificDate(i); if (Util.IsNullDate(nextDate) || nextDate > maxDate) break; if (!rule.WithdrawalInstructions.Contains(nextDate)) { // periodic withdrawal is always without commission account.CreateWithdrawalInstruction(DateTime.Today, nextDate, rule.Amount.Negate(), null, rule, null, rule.DoNotChargeCommission); isDirty = true; itemsCreated++; } } if (isDirty) { AccountMapper.Update(session, account); results.MarkSuccess(itemsCreated); } } else results.MarkError( new ApplicationException(string.Format("Did not create periodic Withdrawal Instruction for {0} since the account is departing.", (account != null ? account.DisplayNumberWithName : ruleKey.ToString())))); } } catch (Exception ex) { results.MarkError( new ApplicationException(string.Format("Error creating periodic Withdrawal Instruction for {0}.", (account != null ? account.DisplayNumberWithName : ruleKey.ToString())), ex)); } } } if (session != null) session.Close(); return true; }
public static void CreateNotaFromTransaction(BatchExecutionResults results, int transactionId) { createNotaFromTransaction(results, transactionId, TransactionTypes.Transaction); }
public static string FormatErrorsForCreateInstructions(BatchExecutionResults results, string instructionType) { const int MAX_ERRORS_DISPLAYED = 25; const int MAX_WARNINGS_DISPLAYED = 25; string message = "<br/>"; if (results.SuccessCount == 0 && results.ErrorCount == 0) message += string.Format("No new {0} instructions were created", instructionType); else { if (results.SuccessCount > 0) message += string.Format("{0} {1} instructions were successfully created.<br/><br/><br/>", results.SuccessCount, instructionType); if (results.ErrorCount > 0) { string tooManyErrorsMessage = (results.ErrorCount > MAX_ERRORS_DISPLAYED ? string.Format(" (only the first {0} are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} errors occured while creating {1} instructions{2}:<br/><br/><br/>", results.ErrorCount, instructionType, tooManyErrorsMessage); int errors = 0; foreach (Exception ex in results.Errors) { if (++errors > MAX_ERRORS_DISPLAYED) break; message += Utility.GetCompleteExceptionMessage(ex) + "<br/>"; } } if (results.WarningCount > 0) { string tooManyWarningsMessage = (results.WarningCount > MAX_WARNINGS_DISPLAYED ? string.Format(" (only the first {0} warnings are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} warnings occured while creating {1} instructions{2}:<br/><br/><br/>", results.WarningCount, instructionType, tooManyWarningsMessage); int warnings = 0; foreach (string warning in results.Warnings) { if (++warnings > MAX_WARNINGS_DISPLAYED) break; message += warning + "<br/>"; } } } return message; }
private static void exportGrouping(BatchExecutionResults results, IDalSession session, ILedgerType ledgerType, DateTime dateUntil, string exportFilePath) { try { string fileName = string.Format("{0}_{1:yyyyMMdd}", ledgerType.Type, dateUntil); string fileExt = "csv"; IList ledgerEntries = LedgerEntryMapper.GetLedgerEntries(session, ledgerType, dateUntil); int fileOrdinal = ExportedLedgerFileMapper.GetNextOrdinal(session, fileName); if ((ledgerEntries != null) && (ledgerEntries.Count > 0)) { ExportedLedgerFile exportedLedgerFile = new ExportedLedgerFile(fileName, fileExt, exportFilePath, fileOrdinal++); FileStream fs = new FileStream(exportedLedgerFile.FullPathName, FileMode.Create); StreamWriter sw = new StreamWriter(fs); foreach (ILedgerEntry ledgerEntry in ledgerEntries) { string formattedEntry = formatLedgerEntry(results, ledgerEntry); if (formattedEntry.Length > 0) { sw.Write(formattedEntry); ledgerEntry.ExportedLedgerFile = exportedLedgerFile; exportedLedgerFile.LedgerEntries.AddLedgerEntry(ledgerEntry); } } sw.Close(); fs.Close(); ExportedLedgerFileMapper.Update(session, exportedLedgerFile); results.MarkSuccess(); } } catch (Exception ex) { results.MarkError( new ApplicationException(string.Format("Error exporting for ledger type '{0}', currency '{1}' and transaction date {2:d}.", ledgerType.Type, dateUntil), ex)); } }
private static string formatLedgerEntry(BatchExecutionResults results, ILedgerEntry ledgerEntry) { try { string formatted = ""; formatted += ledgerEntry.FormatLine() + Environment.NewLine; foreach (var subledgerEntry in ledgerEntry.SubledgerEntries .Where(x => ((x.LineNumber > 0) && (x.Amount != 0m))) .OrderBy(y => y.LineNumber)) { formatted += subledgerEntry.FormatLine() + Environment.NewLine; } return formatted; } catch (Exception ex) { results.MarkError( new ApplicationException(string.Format("Error exporting ledger entry {0} or one of its sub-ledger entries.", ledgerEntry.Key), ex)); return ""; } }
private static string formatErrors(BatchExecutionResults results, string entities, string verbThirdForm, string verbContinuousForm, string noNeedMessage, string currentManagmentCompanyName) { const int MAX_ERRORS_DISPLAYED = 25; string message = "<br/>"; if (results.SuccessCount == 0 && results.ErrorCount == 0) message += string.Format("{0} for company '{1}'.", noNeedMessage, currentManagmentCompanyName); else { if (results.SuccessCount > 0) message += string.Format("{0} {1} were successfully {2} for company '{3}'.<br/><br/><br/>", results.SuccessCount, entities, verbThirdForm, currentManagmentCompanyName); if (results.ErrorCount > 0) { string tooManyErrorsMessage = (results.ErrorCount > MAX_ERRORS_DISPLAYED ? string.Format(" (only the first {0} are shown)", MAX_ERRORS_DISPLAYED) : ""); message += string.Format("{0} errors occured while {1} {2} for company '{3}'{4}:<br/><br/><br/>", results.ErrorCount, verbContinuousForm, entities, currentManagmentCompanyName, tooManyErrorsMessage); int errors = 0; foreach (Exception ex in results.Errors) { if (++errors > MAX_ERRORS_DISPLAYED) break; message += Utility.GetCompleteExceptionMessage(ex) + "<br/>"; } } } return message; }
public static bool CreatePeriodicWithdrawals(BatchExecutionResults results, int key, DateTime endDate) { int[] keys = { key }; return CreatePeriodicWithdrawals(results, keys, endDate); }
public static bool CreateWithdrawalInstructions(BatchExecutionResults results, int[] accountIds, DateTime executionDate, DateTime withdrawalDate, decimal withdrawalAmount, int? counterAccountID, string transferDescription, bool noCharges) { bool retVal = false; if (accountIds == null || accountIds.Count() == 0) throw new B4F.TotalGiro.ApplicationLayer.Common.GridviewNoSelectionException(); using (IDalSession session = NHSessionFactory.CreateSession()) { if (withdrawalAmount == 0) throw new ApplicationException("The amount can not be zero"); ICounterAccount counterAcc = null; if (counterAccountID.HasValue && counterAccountID.Value != 0) { counterAcc = CounterAccountMapper.GetCounterAccount(session, counterAccountID.Value); if (counterAcc == null) throw new ApplicationException("Counter Account can not be found."); } ICurrency baseCurrency = LoginMapper.GetCurrentManagmentCompany(session).BaseCurrency; Money amount = new Money(withdrawalAmount, baseCurrency).Negate(); IList<IAccountTypeCustomer> accounts = AccountMapper.GetAccounts<IAccountTypeCustomer>(session, accountIds); if (accounts != null && accounts.Count > 0) { IList saveAccounts = new ArrayList(); foreach (IAccountTypeCustomer account in accounts) { try { if (account.CreateWithdrawalInstruction(executionDate, withdrawalDate, amount, counterAcc, null, transferDescription, noCharges) != null) { saveAccounts.Add(account); results.MarkSuccess(); } } catch (Exception ex) { results.MarkError( new ApplicationException(string.Format("Error creating withdrawal instruction for {0}.", account.DisplayNumberWithName), ex)); } } retVal = AccountMapper.UpDateList(session, saveAccounts); } } return retVal; }
public static bool SkipAverageHoldingCorrections(BatchExecutionResults results, int[] avgHoldingIds, ManagementTypes managementType) { IDalSession session = NHSessionFactory.CreateSession(); if (avgHoldingIds != null && avgHoldingIds.Length > 0) { try { IList list = ManagementPeriodUnitMapper.GetManagementPeriodUnitCorrections(session, avgHoldingIds, managementType); if (list != null) { int counter = 0; foreach (IManagementPeriodUnitCorrection correction in list) { correction.Skip = true; counter++; } if (session.Update(list)) results.MarkSuccess(counter); } } catch (Exception ex) { results.MarkError( new ApplicationException("Error skipping average holding corrections.", ex)); } } session.Close(); return true; }