private void NewRowManual(ref PDataLabelLookupRow ARow) { // Deal with the primary key - we need a unique Category code and value code // We use the first category code from our category list Type DataTableType; // Load Data PDataLabelLookupCategoryTable allCategories = new PDataLabelLookupCategoryTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("DataLabelLookupCategoryList", String.Empty, null, out DataTableType); allCategories.Merge(CacheDT); ARow.CategoryCode = allCategories.Rows[0][0].ToString(); // We need a simple string for the value code string newName = Catalog.GetString("NEWVALUE"); Int32 countNewDetail = 0; if (FMainDS.PDataLabelLookup.Rows.Find(new object[] { ARow.CategoryCode, newName }) != null) { while (FMainDS.PDataLabelLookup.Rows.Find(new object[] { ARow.CategoryCode, newName + countNewDetail.ToString() }) != null) { countNewDetail++; } newName += countNewDetail.ToString(); } ARow.ValueCode = newName; }
private void InitializeManualCode() { // Set up the appearance of the combo boxes cmbDetailAddressLayoutCode.AppearanceSetup(new int[] { -1, 150 }, -1); cmbAddressBlockElement.AppearanceSetup(new int[] { 190, 390 }, -1); cmbAddressBlockElement.AttachedLabel.Left += 100; // set up the appearance of the text box txtDetailAddressBlockText.HideSelection = false; // set up the properties of the additional button btnInsert.Name = "btnInsert"; btnInsert.Text = "&Insert"; btnInsert.Size = new System.Drawing.Size(80, 23); btnInsert.Left = 10; btnInsert.Top = txtDetailAddressBlockText.Bottom - btnInsert.Height; btnInsert.TabIndex = txtDetailAddressBlockText.TabIndex + 3; btnInsert.Click += new System.EventHandler(InsertElement); pnlDetails.Controls.Add(btnInsert); FPetraUtilsObject.SetStatusBarText(btnInsert, Catalog.GetString("Click to enter the selected placeholder at the cursor position in the Address Layout")); FAddressBlockElements = (PAddressBlockElementTable)TDataCache.GetCacheableDataTableFromCache("AddressBlockElementList"); if (FPetraUtilsObject.SecurityReadOnly) { btnCopy.Enabled = false; btnInsert.Enabled = false; btnInsertLine.Enabled = false; } }
/// <summary> /// Will be called by TFormsList to inform any Form that is registered in TFormsList /// about any 'Forms Messages' that are broadcasted. /// </summary> /// <remarks>This screen 'listens' to such 'Forms Message' broadcasts by /// implementing this virtual Method. This Method will be called each time a /// 'Forms Message' broadcast occurs. /// </remarks> /// <param name="AFormsMessage">An instance of a 'Forms Message'. This can be /// inspected for parameters in the Method Body and the Form can use those to choose /// to react on the Message, or not.</param> /// <returns>Returns True if the Form reacted on the specific Forms Message, /// otherwise false.</returns> public bool ProcessFormsMessage(TFormsMessage AFormsMessage) { bool MessageProcessed = false; if (AFormsMessage.MessageClass == TFormsMessageClassEnum.mcAccountsChanged) { string CurrentlySelectedAccountCode = FPreviouslySelectedDetailRow.AccountCode; Type DataTableType; // Load Data DataTable CacheDT = TDataCache.GetSpecificallyFilteredCacheableDataTableFromCache("AccountList", "Ledger", FFilter, out DataTableType); FMainDS.AAccount.Merge(CacheDT); GetData(); // reapply filter FFilterAndFindObject.ApplyFilter(); // reselect the last selected account code if (FPreviouslySelectedDetailRow != null) { SelectAccountInGrid(CurrentlySelectedAccountCode); } UpdateRecordNumberDisplay(); MessageProcessed = true; } return(MessageProcessed); }
private void InitializeManualCode() { Type DataTableType; DataTable CacheRegionDT = TDataCache.GetCacheableDataTableFromCache("PostcodeRegionList", String.Empty, null, out DataTableType); DataTable CacheRegionRangeDT = TDataCache.GetCacheableDataTableFromCache("PostcodeRegionRangeList", String.Empty, null, out DataTableType); PPostcodeRangeTable RangeTable = (PPostcodeRangeTable)TDataCache.GetCacheableDataTableFromCache("PostcodeRangeList", String.Empty, null, out DataTableType); FMainDS.PPostcodeRegion.Merge(CacheRegionDT); FMainDS.PPostcodeRegionRange.Merge(CacheRegionRangeDT); foreach (PostcodeRegionsTDSPPostcodeRegionRangeRow Row in FMainDS.PPostcodeRegionRange.Rows) { PPostcodeRangeRow RangeRow = (PPostcodeRangeRow)RangeTable.Rows.Find(new object[] { Row.Range }); Row.From = RangeRow.From; Row.To = RangeRow.To; } FMainDS.AcceptChanges(); FPetraUtilsObject.ApplySecurity(TSecurityChecks.SecurityPermissionsSetupScreensEditingAndSaving); }
private void NewRecord(Object sender, EventArgs e) { // We need to check that we do have a language that we do not yet have a calendar definition for Type DataTableType; // Load Data PLanguageTable allLanguages = new PLanguageTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("LanguageCodeList", String.Empty, null, out DataTableType); allLanguages.Merge(CacheDT); Int32 languageCount = allLanguages.Rows.Count - 1; // exclude the '99' row languageCount = 3; if (grdDetails.Rows.Count <= languageCount) { CreateNewSLanguageSpecific(); } else { MessageBox.Show(Catalog.GetString("You already have a row for every specified language in the database."), Catalog.GetString("Add new Month Names")); } }
private void ValidateDataManual(PChurchRow ARow) { TVerificationResultCollection VerificationResultCollection = FPetraUtilsObject.VerificationResultCollection; TSharedPartnerValidation_Partner.ValidatePartnerChurchManual(this, ARow, TDataCache.GetCacheableDataTableFromCache("DenominationList"), ref VerificationResultCollection, FValidationControlsDict); }
/// <summary> /// Opens a Modal instance of the Partner Find screen. /// </summary> /// <param name="ARegionName">Pass in the selected Region's name.</param> /// <param name="ARangeName">Name of the found Range.</param> /// <param name="AFrom">'From' field of the found Partner.</param> /// <param name="ATo">'To' field of the found Partner.</param> /// <param name="AParentForm"></param> /// <returns>True if a Partner was found and accepted by the user, /// otherwise false.</returns> public static bool OpenModalForm(String ARegionName, out String[] ARangeName, out String[] AFrom, out String[] ATo, Form AParentForm) { DialogResult dlgResult; ARangeName = null; AFrom = null; ATo = null; TFrmPostcodeRangeSetup SelectRange = new TFrmPostcodeRangeSetup(AParentForm); SelectRange.SetParameters(ARegionName); dlgResult = SelectRange.ShowDialog(); if (dlgResult == DialogResult.OK) { DataRowView[] HighlightedRows = SelectRange.GetSelectedRows(); int NumberOfRows = HighlightedRows.Length; PPostcodeRangeTable CachedRangeTable = (PPostcodeRangeTable)TDataCache.GetCacheableDataTableFromCache("PostcodeRangeList"); bool NoRangesSelected = true; ARangeName = new string[NumberOfRows]; AFrom = new string[NumberOfRows]; ATo = new string[NumberOfRows]; for (int i = 0; i < NumberOfRows; i++) { if (CachedRangeTable.Rows.Find(new object[] { ((PPostcodeRangeRow)HighlightedRows[i].Row).Range }) != null) { ARangeName[i] = ((PPostcodeRangeRow)HighlightedRows[i].Row).Range; AFrom[i] = ((PPostcodeRangeRow)HighlightedRows[i].Row).From; ATo[i] = ((PPostcodeRangeRow)HighlightedRows[i].Row).To; NoRangesSelected = false; } else { ARangeName[i] = null; AFrom[i] = null; ATo[i] = null; } } if (NoRangesSelected) { MessageBox.Show(String.Format("No valid ranges have been selected."), String.Format("Add Range"), MessageBoxButtons.OK, MessageBoxIcon.Information); } return(true); } return(false); }
/// <summary> /// /// </summary> /// <param name="AParameters"></param> public void SetControls(TParameterList AParameters) { // // If LedgerNumber hasn't been set yet, do nothing: if (FLedgerNumber < 0) { return; } lstDontPrint.BeginUpdate(); lstDontPrint.Items.Clear(); AFeesReceivableTable FeesReceivable = new AFeesReceivableTable(); Type DataTableType; DataTable CacheDT = TDataCache.GetCacheableDataTableFromPetraServer("FeesReceivableList", String.Empty, FLedgerNumber, out DataTableType); FeesReceivable.Merge(CacheDT); foreach (AFeesReceivableRow Row in FeesReceivable.Rows) { lstDontPrint.Items.Add(Row.FeeCode); } AFeesPayableTable FeesPayable = new AFeesPayableTable(); CacheDT = TDataCache.GetCacheableDataTableFromPetraServer("FeesPayableList", String.Empty, FLedgerNumber, out DataTableType); FeesPayable.Merge(CacheDT); foreach (AFeesPayableRow Row in FeesPayable.Rows) { lstDontPrint.Items.Add(Row.FeeCode); } lstDontPrint.EndUpdate(); String FeeStr = AParameters.Get("param_fee_codes").ToString(); // // If there's no fees selected, it's perhaps because the installation is new. // Add all the fees from the "Don't Print" box, up to the maximum number allowed. if (FeeStr == "") { Array.Resize(ref FSelectedFees, lstDontPrint.Items.Count); lstDontPrint.Items.CopyTo(FSelectedFees, 0); if (lstDontPrint.Items.Count > MAX_FEE_COUNT) { Array.Resize(ref FSelectedFees, MAX_FEE_COUNT); } } else { FSelectedFees = FeeStr.Split(','); } RefreshDoList(); }
private void NewRowManual(ref PPublicationCostRow ARow) { // Deal with primary key. It is combination of a code and a effective date // Start by finding a code that does not have today's date Type DataTableType; // Load Data PPublicationTable allPublications = new PPublicationTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("PublicationList", String.Empty, null, out DataTableType); allPublications.Merge(CacheDT); bool bFound = false; for (int i = 0; i < allPublications.Rows.Count; i++) { string tryCode = allPublications.Rows[i][0].ToString(); if (FMainDS.PPublicationCost.Rows.Find(new object[] { tryCode, DateTime.Today }) == null) { ARow.PublicationCode = tryCode; bFound = true; break; } } if (!bFound) { // use the first Publication and the first unused date string tryCode = allPublications.Rows[0][0].ToString(); for (int i = 1;; i++) { DateTime tryDate = DateTime.Today.AddDays(i); if (FMainDS.PPublicationCost.Rows.Find(new object[] { tryCode, tryDate }) == null) { ARow.PublicationCode = tryCode; ARow.DateEffective = tryDate; break; } } } if (FPreviouslySelectedDetailRow == null) { ARow.CurrencyCode = FLedgerBaseCurrency; } else { ARow.CurrencyCode = FPreviouslySelectedDetailRow.CurrencyCode; } }
private void RunOnceOnActivationManual() { FPetraUtilsObject.DataSaved += new TDataSavedHandler(FPetraUtilsObject_DataSaved); // Load the data from the Fees Payable cached table Type DataTableType; DataTable CacheDT = TDataCache.GetCacheableDataTableFromPetraServer("FeesPayableList", String.Empty, FFilter, out DataTableType); FExtraDS.AFeesPayable.Merge(CacheDT); FExtraDS.AFeesPayable.DefaultView.Sort = String.Format("{0}, {1} ASC", AFeesPayableTable.GetLedgerNumberDBName(), AFeesPayableTable.GetFeeCodeDBName()); SelectRowInGrid(1); UpdateRecordNumberDisplay(); }
private void NewRowManual(ref SLanguageSpecificRow ARow) { // Deal with primary key. LanguageCode is unique and is 10 characters. // We use the first unused language code from our language code list Type DataTableType; // Load Data PLanguageTable allLanguages = new PLanguageTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("LanguageCodeList", String.Empty, null, out DataTableType); allLanguages.Merge(CacheDT); // Because of the checking code in NewRecord, we know there is at least one spare language we can use int rowIndex = 1; // first row is invalid 99 code while (FMainDS.SLanguageSpecific.Rows.Find(new object[] { allLanguages.Rows[rowIndex][0].ToString() }) != null) { rowIndex++; } ARow.LanguageCode = allLanguages.Rows[rowIndex][0].ToString(); ARow.MonthName1 = Catalog.GetString("January"); ARow.MonthName2 = Catalog.GetString("February"); ARow.MonthName3 = Catalog.GetString("March"); ARow.MonthName4 = Catalog.GetString("April"); ARow.MonthName5 = Catalog.GetString("May"); ARow.MonthName6 = Catalog.GetString("June"); ARow.MonthName7 = Catalog.GetString("July"); ARow.MonthName8 = Catalog.GetString("August"); ARow.MonthName9 = Catalog.GetString("September"); ARow.MonthName10 = Catalog.GetString("October"); ARow.MonthName11 = Catalog.GetString("November"); ARow.MonthName12 = Catalog.GetString("December"); ARow.MonthNameShort1 = Catalog.GetString("Jan"); ARow.MonthNameShort2 = Catalog.GetString("Feb"); ARow.MonthNameShort3 = Catalog.GetString("Mar"); ARow.MonthNameShort4 = Catalog.GetString("Apr"); ARow.MonthNameShort5 = Catalog.GetString("May"); ARow.MonthNameShort6 = Catalog.GetString("Jun"); ARow.MonthNameShort7 = Catalog.GetString("Jul"); ARow.MonthNameShort8 = Catalog.GetString("Aug"); ARow.MonthNameShort9 = Catalog.GetString("Sep"); ARow.MonthNameShort10 = Catalog.GetString("Oct"); ARow.MonthNameShort11 = Catalog.GetString("Nov"); ARow.MonthNameShort12 = Catalog.GetString("Dec"); }
private void RunOnceOnActivationManual() { FPetraUtilsObject.DataSaved += new TDataSavedHandler(FPetraUtilsObject_DataSaved); // Load the data from the Fees Payable cached table Type DataTableType; DataTable CacheDT = TDataCache.GetCacheableDataTableFromPetraServer("FeesPayableList", String.Empty, FFilter, out DataTableType); FExtraDS.AFeesPayable.Merge(CacheDT); FExtraDS.AFeesPayable.DefaultView.Sort = String.Format("{0}, {1} ASC", AFeesPayableTable.GetLedgerNumberDBName(), AFeesPayableTable.GetFeeCodeDBName()); ALedgerRow LedgerRow = ((ALedgerTable)TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.LedgerDetails, FLedgerNumber))[0]; txtDetailChargeAmount.CurrencyCode = LedgerRow.BaseCurrency; SelectRowInGrid(1); UpdateRecordNumberDisplay(); }
private void NewRecord(Object sender, EventArgs e) { // Deal with the possibility that we have no categories set up for the comboBox Type DataTableType; // Load Data PmDocumentCategoryTable allCategories = new PmDocumentCategoryTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("DocumentTypeCategoryList", String.Empty, null, out DataTableType); allCategories.Merge(CacheDT); if (allCategories.Rows.Count == 0) { string Msg = "Before you attempt to create a New Document Type you should return to the Personnel Setup screen and create a new 'Document Type Category'."; MessageBox.Show(Msg, "Open Petra Client", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } CreateNewPmDocumentType(); }
private void NewRecord(Object sender, EventArgs e) { // Deal with the possibility that we have no categories set up for the primary key for this table Type DataTableType; // Load Data PDataLabelLookupCategoryTable allCategories = new PDataLabelLookupCategoryTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("DataLabelLookupCategoryList", String.Empty, null, out DataTableType); allCategories.Merge(CacheDT); if (allCategories.Rows.Count == 0) { string Msg = "Before you attempt to save a New Local Data Option you should return to the Partner Setup screen and create a new 'Local Data Option List Name'."; MessageBox.Show(Msg, "Open Petra Client", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } CreateNewPDataLabelLookup(); }
private void InitializeManualCode() { Type DataTableType; DataTable CacheRegionDT = TDataCache.GetCacheableDataTableFromCache("PostcodeRegionList", String.Empty, null, out DataTableType); DataTable CacheRegionRangeDT = TDataCache.GetCacheableDataTableFromCache("PostcodeRegionRangeList", String.Empty, null, out DataTableType); PPostcodeRangeTable RangeTable = (PPostcodeRangeTable)TDataCache.GetCacheableDataTableFromCache("PostcodeRangeList", String.Empty, null, out DataTableType); FMainDS.PPostcodeRegion.Merge(CacheRegionDT); FMainDS.PPostcodeRegionRange.Merge(CacheRegionRangeDT); foreach (PostcodeRegionsTDSPPostcodeRegionRangeRow Row in FMainDS.PPostcodeRegionRange.Rows) { PPostcodeRangeRow RangeRow = (PPostcodeRangeRow)RangeTable.Rows.Find(new object[] { Row.Range }); Row.From = RangeRow.From; Row.To = RangeRow.To; } FMainDS.AcceptChanges(); }
/// <summary> /// this is usually only used for remote clients; standalone clients are patched with a windows installer program /// </summary> private static void CheckForPatches() { FSplashScreen.ProgressText = "Running checks that are specific to Remote Installation..."; // todo: check whether the user has SYSADMIN rights; should not be required // todo: check whether the user has write access to the bin directory // check whether the user has access to the server and the Petra patches directory if ((TClientSettings.Petra_Path_RemotePatches.Length > 0) && !(TClientSettings.Petra_Path_RemotePatches.ToLower().StartsWith("http://") || TClientSettings.Petra_Path_RemotePatches.ToLower().StartsWith("https://")) && !System.IO.Directory.Exists(TClientSettings.Petra_Path_RemotePatches)) { FSplashScreen.ShowMessageBox( String.Format( Catalog.GetString( "Please make sure that you have logged in to your network drive\nand can access the directory\n{0}\nIf this is the case and you still get this message,\nyou might use an IP address rather than a hostname for the server.\nPlease ask your local System Administrator for help."), TClientSettings.Petra_Path_RemotePatches), Catalog.GetString("Cannot check for patches")); } // check whether there is a patch available; if this is a remote version, try to download a patch from the server TPatchTools patchTools = new TPatchTools(Path.GetFullPath(TClientSettings.Petra_Path_Bin + Path.DirectorySeparatorChar + ".."), TClientSettings.Petra_Path_Bin, TPatchTools.OPENPETRA_VERSIONPREFIX, TClientSettings.PathTemp, "", TClientSettings.Petra_Path_Patches, TClientSettings.Petra_Path_RemotePatches); string PatchStatusMessage; // TODO: run this only if necessary. seem adding cost centre does not update the cache? TDataCache.ClearAllCaches(); if (patchTools.CheckForRecentPatch(false, out PatchStatusMessage)) { // todo: display a list of all patches that will be installed? or confusing with different builds? if (FSplashScreen.ShowMessageBox(String.Format(Catalog.GetString("There is a new patch available: {0}" + ".\r\nThe currently installed version is {1}" + ".\r\nThe patch will be installed to directory '{2}'.\r\nDo you want to install now?"), patchTools.GetLatestPatchVersion(), patchTools.GetCurrentPatchVersion(), TClientSettings.Petra_Path_Bin), String.Format(Catalog.GetString("Install new OpenPetra patch")), MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) == DialogResult.Yes) { // reset the caches in IsolatedStorage. This can help if things have changed drastically in the database // TODO: run this also after the software has been reinstalled with the InnoSetup installer? Remember the current patch number in the IsolatedStorage? TDataCache.ClearAllCaches(); // create the temp directory; using the Petra tmp directory, so that we don't need to change the drive in the batch file string TempPath = TClientSettings.PathTemp + Path.DirectorySeparatorChar + "petrapatch"; Directory.CreateDirectory(TempPath); // check for newer patchtool patchTools.CopyLatestPatchProgram(TempPath); string PatchToolExe = TempPath + Path.DirectorySeparatorChar + "Ict.Tools.PatchTool.exe"; if (!File.Exists(PatchToolExe)) { TLogging.Log("cannot find file " + PatchToolExe); } // need to stop petra client, start the patch in temppath, restart Petra client Process PatchProcess = new System.Diagnostics.Process(); PatchProcess.EnableRaisingEvents = false; PatchProcess.StartInfo.FileName = PatchToolExe; PatchProcess.StartInfo.Arguments = "-action:patchRemote " + "-ClientConfig:\"" + Path.GetFullPath( TAppSettingsManager.ConfigFileName) + "\" " + "-OpenPetra.Path.Patches:\"" + Path.GetFullPath( TClientSettings.Petra_Path_Bin + "/../patches30") + "\" " + "-OpenPetra.PathTemp:\"" + Path.GetFullPath( TClientSettings.Petra_Path_Bin + "/../tmp30") + "\" " + "-OpenPetra.Path:\"" + Path.GetFullPath( TClientSettings.Petra_Path_Bin + Path.DirectorySeparatorChar + "..") + "\" " + "-OpenPetra.Path.Bin:\"" + Path.GetFullPath( TClientSettings.Petra_Path_Bin) + "\""; PatchProcess.Start(); // Application stops here !!! Environment.Exit(0); } } else { if (PatchStatusMessage != String.Empty) { FSplashScreen.ShowMessageBox(PatchStatusMessage, ""); } } }
/// <summary> /// Imports currency exchange rates, daily and corporate, /// from a one-of-two-styles formatted CSV file /// </summary> /// <param name="AExchangeRDT">Daily or Corporate exchange rate table</param> /// <param name="ADataFilename">The .CSV file to process</param> /// <param name="ACSVSeparator"></param> /// <param name="ANumberFormat"></param> /// <param name="ADateFormat"></param> /// <param name="AImportMode">Daily or Corporate</param> /// <param name="AResultCollection">A validation collection to which errors will be added</param> /// <returns>The number of rows that were actually imported. Rows that duplicate existing rows do not count. /// This is usually because this is an attempt to import again after a failed previous attempt.</returns> private static int ImportCurrencyExRatesFromCSV(TTypedDataTable AExchangeRDT, string ADataFilename, string ACSVSeparator, string ANumberFormat, string ADateFormat, string AImportMode, TVerificationResultCollection AResultCollection) { if ((AImportMode != "Corporate") && (AImportMode != "Daily")) { throw new ArgumentException("Invalid value '" + AImportMode + "' for mode argument: Valid values are Corporate and Daily"); } else if ((AImportMode == "Corporate") && (AExchangeRDT.GetType() != typeof(ACorporateExchangeRateTable))) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Corporate'. Needs to be: ACorporateExchangeRateTable"); } else if ((AImportMode == "Daily") && (AExchangeRDT.GetType() != typeof(ADailyExchangeRateTable))) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Daily'. Needs to be: ADailyExchangeRateTable"); } bool IsShortFileFormat; int x, y; // To store the From and To currencies // Use an array to store these to make for easy // inverting of the two currencies when calculating // the inverse value. string[] Currencies = new string[2]; Type DataTableType; int RowsImported = 0; ACurrencyTable allCurrencies = new ACurrencyTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("CurrencyCodeList", String.Empty, null, out DataTableType); allCurrencies.Merge(CacheDT); using (StreamReader DataFile = new StreamReader(ADataFilename, System.Text.Encoding.Default)) { string ThousandsSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "," : "."); string DecimalSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "." : ","); CultureInfo MyCultureInfoDate = new CultureInfo("en-GB"); MyCultureInfoDate.DateTimeFormat.ShortDatePattern = ADateFormat; // TODO: disconnect the grid from the datasource to avoid flickering? string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(ADataFilename); if ((FileNameWithoutExtension.IndexOf("_") == 3) && (FileNameWithoutExtension.LastIndexOf("_") == 3) && (FileNameWithoutExtension.Length == 7)) { // File name format assumed to be like this: USD_HKD.csv IsShortFileFormat = true; Currencies = FileNameWithoutExtension.Split(new char[] { '_' }); } else { IsShortFileFormat = false; } int LineNumber = 0; while (!DataFile.EndOfStream) { string Line = DataFile.ReadLine(); LineNumber++; // See if the first line is a special case?? if (LineNumber == 1) { // see if the first line is a text header - look for digits // A valid header would look like: From,To,Date,Rate bool bFoundDigit = false; for (int i = 0; i < Line.Length; i++) { char c = Line[i]; if ((c >= '0') && (c <= '9')) { bFoundDigit = true; break; } } if (!bFoundDigit) { // No digits so we will assume the line is a header continue; } } //Convert separator to a char char Sep = ACSVSeparator[0]; //Turn current line into string array of column values string[] CsvColumns = Line.Split(Sep); int NumCols = CsvColumns.Length; //If number of columns is not 4 then import csv file is wrongly formed. if (IsShortFileFormat && (NumCols < 2)) { // raise an error string resultText = String.Format(Catalog.GetString("Failed to import the CSV currency file:{0} {1}{0}{0}"), Environment.NewLine, ADataFilename); resultText += String.Format(Catalog.GetString( "Line #{1} contains {2} column(s). Import files with names like 'USD_HKD.csv', where the From and To currencies are given in the name, should contain 2 or 3 columns:{0}{0}"), Environment.NewLine, LineNumber, NumCols.ToString()); resultText += String.Format(Catalog.GetString( " 1. Effective Date{0} 2. Exchange Rate{0} 3. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INFORMATIONMISSING, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return(RowsImported); } else if (!IsShortFileFormat && (NumCols < 4)) { string resultText = String.Format(Catalog.GetString("Failed to import the CSV currency file:{0} {1}{0}{0}"), Environment.NewLine, ADataFilename); resultText += String.Format(Catalog.GetString("Line #{1} contains {2} column(s). It should have 4 or 5 as follows:{0}{0}"), Environment.NewLine, LineNumber, NumCols.ToString()); resultText += String.Format(Catalog.GetString( " 1. From Currency{0} 2. To Currency{0} 3. Effective Date{0} 4. Exchange Rate{0} 5. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INFORMATIONMISSING, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return(RowsImported); } if (!IsShortFileFormat) { //Read the values for the current line //From currency Currencies[0] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString(); //To currency Currencies[1] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString(); } // Perform validation on the From and To currencies at this point!! if ((allCurrencies.Rows.Find(Currencies[0]) == null) || (allCurrencies.Rows.Find(Currencies[1]) == null)) { // raise an error string resultText = String.Format(Catalog.GetString("Invalid currency in import file in line #{0}"), LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INCONGRUOUSSTRINGS, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return(RowsImported); } // Date parsing as in Petra 2.x instead of using XML date format!!! string DateEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace("\"", String.Empty); DateTime DateEffective; if (!DateTime.TryParse(DateEffectiveStr, MyCultureInfoDate, DateTimeStyles.None, out DateEffective)) { // raise an error string resultText = String.Format(Catalog.GetString( "Invalid date ({0}) in import file in line #{1}"), DateEffectiveStr, LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INVALIDDATE, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return(RowsImported); } decimal ExchangeRate = 0.0m; try { string ExchangeRateString = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace(ThousandsSeparator, "").Replace( DecimalSeparator, ".").Replace("\"", String.Empty); ExchangeRate = Convert.ToDecimal(ExchangeRateString, System.Globalization.CultureInfo.InvariantCulture); } catch (Exception) { // raise an error string resultText = String.Format(Catalog.GetString( "Invalid rate of exchange in import file in line #{0}"), LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INVALIDNUMBER, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return(RowsImported); } int TimeEffective = 7200; if (AImportMode == "Daily") { // Daily rate imports can have an optional final column which is the time // Otherwise we assume the time is a default of 7200 (02:00am) if ((IsShortFileFormat && (NumCols == 3)) || (!IsShortFileFormat && (NumCols == 5))) { string timeEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true); int t = (int)new Ict.Common.TypeConverter.TShortTimeConverter().ConvertTo(timeEffectiveStr, typeof(int)); if (t < 0) { // it wasn't in the format 02:00 if (!Int32.TryParse(timeEffectiveStr, out t)) { // Not a regular Int32 either t = -1; } } if ((t >= 0) && (t < 86400)) { TimeEffective = t; } else { // raise an error string resultText = String.Format(Catalog.GetString( "Invalid effective time in import file in line #{0}"), LineNumber.ToString()); TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INVALIDINTEGERTIME, TResultSeverity.Resv_Critical); AResultCollection.Add(result); return(RowsImported); } } } if ((AImportMode == "Corporate") && AExchangeRDT is ACorporateExchangeRateTable) { ACorporateExchangeRateTable ExchangeRateDT = (ACorporateExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ACorporateExchangeRateRow ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = 1 / ExchangeRate; } } } else if ((AImportMode == "Daily") && AExchangeRDT is ADailyExchangeRateTable) { ADailyExchangeRateTable ExchangeRateDT = (ADailyExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ADailyExchangeRateRow ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective, TimeEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRow.TimeEffectiveFrom = TimeEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = 1 / ExchangeRate; } } } } DataFile.Close(); return(RowsImported); } }
private void SaveDataLabelUseChanges(TTypedDataTable ASubmitChanges) { // Submit changes to the PETRAServer for the DataLabelUse table // This code is basically lifted from a typical auto-generated equivalent // TODO: If the standard code changes because TODO's get done, we will need to change this manual code TSubmitChangesResult SubmissionResult; TVerificationResultCollection VerificationResult; try { SubmissionResult = TDataCache.SaveChangedCacheableDataTableToPetraServer("DataLabelUseList", ref ASubmitChanges, out VerificationResult); } catch (ESecurityDBTableAccessDeniedException Exp) { FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException); this.Cursor = Cursors.Default; TMessages.MsgSecurityException(Exp, this.GetType()); return; } catch (EDBConcurrencyException Exp) { FPetraUtilsObject.WriteToStatusBar(MCommonResourcestrings.StrSavingDataException); this.Cursor = Cursors.Default; TMessages.MsgDBConcurrencyException(Exp, this.GetType()); return; } catch (Exception exp) { TLogging.Log( "An error occured while saving the 'used by' data" + Environment.NewLine + exp.ToString(), TLoggingType.ToLogfile); MessageBox.Show( Catalog.GetString("An error occured while saving the 'used by' data") + Environment.NewLine + Catalog.GetString("For details see the log file: ") + TLogging.GetLogFileName(), Catalog.GetString("Failed to Save 'Used By' Data"), MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } switch (SubmissionResult) { case TSubmitChangesResult.scrOK: // Call AcceptChanges to get rid now of any deleted columns before we Merge with the result from the Server FExtraDS.PDataLabelUse.AcceptChanges(); // Merge back with data from the Server (eg. for getting Sequence values) ASubmitChanges.AcceptChanges(); FExtraDS.PDataLabelUse.Merge(ASubmitChanges, false); // need to accept the new modification ID FExtraDS.PDataLabelUse.AcceptChanges(); // need to refresh the cacheable DataTable 'DataLabelsForPartnerClassesList' (used by Partner Find's Maintain Menu) TDataCache.TMPartner.RefreshCacheablePartnerTable(TCacheablePartnerTablesEnum.DataLabelsForPartnerClassesList); return; case TSubmitChangesResult.scrNothingToBeSaved: return; case TSubmitChangesResult.scrError: MessageBox.Show(Catalog.GetString( "The 'UsedBy' part of the data could not be saved! There has been an error while making changes to the table."), Catalog.GetString("Submit Changes to Table Error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); break; case TSubmitChangesResult.scrInfoNeeded: MessageBox.Show(Catalog.GetString( "The 'UsedBy' part of the data could not be saved! Insufficient information was provided when making changes to the table."), Catalog.GetString("Submit Changes to Table Error"), MessageBoxButtons.OK, MessageBoxIcon.Warning); break; } }
// This is the main area where we set up to use the additional information from the extra table private void InitializeManualCode() { // Get our screenClassName string ScreenName = this.GetType().Name; // Initialise the list box column headings in the working DataTable and the GUI string DBCol1 = DBUsedBy; string DBCol2 = String.Empty; string GUICol2 = String.Empty; string DBCol3 = "Label"; if (String.Compare(ScreenName, "TFrmLocalPartnerDataFieldSetup", true) == 0) { CurrentContext = Context.Partner; DBCol2 = "PartnerClass"; GUICol2 = Catalog.GetString("Partner Class"); } else if (String.Compare(ScreenName, "TFrmLocalApplicationDataFieldSetup", true) == 0) { CurrentContext = Context.Application; DBCol2 = "Application"; GUICol2 = Catalog.GetString("Application"); } else if (String.Compare(ScreenName, "TFrmLocalPersonnelDataFieldSetup", true) == 0) { CurrentContext = Context.Personnel; DBCol2 = "Personnel"; GUICol2 = Catalog.GetString("Personnel"); } // Now we can initialise our little data table that backs the checkbox list view DTUsedBy.Columns.Add(DBCol1).DataType = typeof(Boolean); DTUsedBy.Columns.Add(DBCol2).DataType = typeof(String); DTUsedBy.Columns.Add(DBCol3).DataType = typeof(String); // Add a 'Context' column so we can filter the data ContextColumnOrdinal = FMainDS.PDataLabel.Columns.Add("Context", typeof(int)).Ordinal; // Add a 'Used By' column to our main dataset (Do it twice so we track changes) FMainDS.PDataLabel.Columns.Add("UsedByInit", typeof(String)); UsedByColumnOrdinal = FMainDS.PDataLabel.Columns.Add(DBUsedBy, typeof(String)).Ordinal; // Add a 'Converted Data Type' column to the dataset because we want to 'translate' from geeky database entries to friendly user ones // This column data is derived from an expression string expression = String.Format("IIF(p_data_type_c='char','{0}',", Catalog.GetString("Text")); expression += String.Format("IIF(p_data_type_c='float','{0}',", Catalog.GetString("Number")); expression += String.Format("IIF(p_data_type_c='currency','{0}',", Catalog.GetString("Currency")); expression += String.Format("IIF(p_data_type_c='boolean','{0}',", Catalog.GetString("Yes/No")); expression += String.Format("IIF(p_data_type_c='date','{0}',", Catalog.GetString("Date")); expression += String.Format("IIF(p_data_type_c='time','{0}',", Catalog.GetString("Time")); expression += String.Format("IIF(p_data_type_c='lookup','{0}',", Catalog.GetString("Option List")); expression += String.Format("IIF(p_data_type_c='partnerkey','{0}',", Catalog.GetString("Partner Key")); expression += String.Format("'{0}'))))))))", Catalog.GetString("Unknown")); DataTypeColumnOrdinal = FMainDS.PDataLabel.Columns.Add("DataTypeEx", typeof(System.String), expression).Ordinal; // Load the Extra Data from DataLabelUse table Type DataTableType; FExtraDS.PDataLabelUse = new PDataLabelUseTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("DataLabelUseList", String.Empty, null, out DataTableType); FExtraDS.PDataLabelUse.Merge(CacheDT); // Take each row of our main dataset and populate the new column with relevant data // from the DataLabelUse table foreach (PDataLabelRow labelRow in FMainDS.PDataLabel.Rows) { string usedBy = String.Empty; int key = labelRow.Key; DataRow[] rows = FExtraDS.PDataLabelUse.Select("p_data_label_key_i=" + key.ToString()); foreach (PDataLabelUseRow useRow in rows) { if (usedBy != String.Empty) { usedBy += ","; } usedBy += useRow.Use; // Update the value of our MaxIdx1Value variable if (useRow.Idx1 > MaxIdx1Value) { MaxIdx1Value = useRow.Idx1; } } // Initially our two new columns hold the same values, but if we make a change we modify the second one. labelRow[UsedByColumnOrdinal - 1] = usedBy; // since we added this column manually, it does not have a handy property labelRow[UsedByColumnOrdinal] = usedBy; // since we added this column manually, it does not have a handy property if (usedBy.IndexOf("personnel", StringComparison.InvariantCultureIgnoreCase) >= 0) { labelRow[ContextColumnOrdinal] = (int)Context.Personnel; } else if (usedBy.IndexOf("termapp", StringComparison.InvariantCultureIgnoreCase) >= 0) { labelRow[ContextColumnOrdinal] = (int)Context.Application; } else { labelRow[ContextColumnOrdinal] = (int)Context.Partner; } } // So now our main data set has everything we need // But the grid doesn't know about our new column yet // We do that in 'RunOnceOnActivationManual()' // Set the form title and list box content depending on our context if (CurrentContext == Context.Partner) { this.Text = "Maintain Local Partner Data Fields"; AddRowToUsedByList("Person", Catalog.GetString("Person")); AddRowToUsedByList("Family", Catalog.GetString("Family")); AddRowToUsedByList("Church", Catalog.GetString("Church")); AddRowToUsedByList("Organisation", Catalog.GetString("Organisation")); AddRowToUsedByList("Bank", Catalog.GetString("Bank")); AddRowToUsedByList("Unit", Catalog.GetString("Unit")); AddRowToUsedByList("Venue", Catalog.GetString("Venue")); } else if (CurrentContext == Context.Application) { this.Text = "Maintain Local Application Data Fields"; AddRowToUsedByList("LongTermApp", Catalog.GetString("Long Term")); AddRowToUsedByList("ShortTermApp", Catalog.GetString("Short Term")); } else if (CurrentContext == Context.Personnel) { this.Text = "Maintain Local Personnel Data Fields"; AddRowToUsedByList("Personnel", Catalog.GetString("Personnel")); clbUsedBy.Visible = false; } //Set up our checked list box columns and bind to our DTUsedBy table clbUsedBy.AddCheckBoxColumn(GUIUsedBy, DTUsedBy.Columns[0], 17, false); clbUsedBy.AddTextColumn(GUICol2, DTUsedBy.Columns[2], 169); clbUsedBy.DataBindGrid(DTUsedBy, DBCol3, DBCol1, DBCol2, false, false, false); FPetraUtilsObject.SetStatusBarText(clbUsedBy, Catalog.GetString("Choose the screens when this label will be used")); // Now we have to deal with the form controls that depend on the selection of DataType // and we only want one visible at a time - so hide these three pnlCurrencyCode.Visible = false; pnlLookupCategoryCode.Visible = false; pnlNumDecimalPlaces.Visible = false; // We can prevent screen 'flicker' by setting the DefaultView RowFilter to some stupid setting that finds no rows // This stops the auto-genertaed code populating the list with incorrect data before we get it right in our code // that runs later (RunOnceOnActivationManual) // Actually this line was added after completing the rest of the code. Having added it I could probably // remove a few lines elsewhere, but I am not going to because I don't want to break anything! FMainDS.PDataLabel.DefaultView.RowFilter = "Context=0"; // We need to capture the 'DataSaved' event, so we can save our Extra DataSet FPetraUtilsObject.DataSaved += new TDataSavedHandler(FPetraUtilsObject_DataSaved); FPetraUtilsObject.DataSavingStarted += new TDataSavingStartHandler(FPetraUtilsObject_DataSavingStarted); }
/// <summary> /// Executes the Client Task. /// </summary> public override void Execute() { try { switch (FClientTaskDataRow["TaskGroup"].ToString()) { // MessageBox.Show('Executing Client Task #' + FClientTaskDataRow['TaskID'].ToString + ' in Thread.'); case SharedConstants.CLIENTTASKGROUP_USERMESSAGE: { // MessageBox.Show(CLIENTTASKGROUP_USERMESSAGE + ' (Client Task #' + FClientTaskDataRow['TaskID'].ToString + '): ' + FClientTaskDataRow['TaskCode'].ToString, 'Client #' + UClientID.ToString + ' received a ClientTask.'); MessageBox.Show(FClientTaskDataRow["TaskCode"].ToString(), "OpenPetra Message"); break; } case SharedConstants.CLIENTTASKGROUP_CACHEREFRESH: { if (FClientTaskDataRow["TaskParameter1"].ToString() == "") { TDataCache.ReloadCacheTable(FClientTaskDataRow["TaskCode"].ToString()); } else { TDataCache.ReloadCacheTable(FClientTaskDataRow["TaskCode"].ToString(), FClientTaskDataRow["TaskParameter1"]); } break; } case SharedConstants.CLIENTTASKGROUP_USERDEFAULTSREFRESH: { if (FClientTaskDataRow["TaskCode"].ToString() == "All") { // MessageBox.Show('FClientTaskDataRow[''TaskCode''] = All!'); TUserDefaults.ReloadCachedUserDefaults(); TUserDefaults.SaveChangedUserDefaults(); } else { // MessageBox.Show('FClientTaskDataRow[''TaskCode''] <> All, but ''' + FClientTaskDataRow['TaskCode'].ToString + ''''); // MessageBox.Show('FClientTaskDataRow[''TaskParameter1'']: ' + FClientTaskDataRow['TaskParameter1'].ToString + "\r\n" + // 'FClientTaskDataRow[''TaskParameter2'']: ' + FClientTaskDataRow['TaskParameter2'].ToString + "\r\n" + // 'FClientTaskDataRow[''TaskParameter3'']: ' + FClientTaskDataRow['TaskParameter3'].ToString); TUserDefaults.RefreshCachedUserDefault( FClientTaskDataRow["TaskParameter1"].ToString(), FClientTaskDataRow["TaskParameter2"].ToString(), FClientTaskDataRow["TaskParameter3"].ToString()); } break; } case SharedConstants.CLIENTTASKGROUP_USERINFOREFRESH: { TUserInfo.ReloadCachedUserInfo(); break; } case RemotingConstants.CLIENTTASKGROUP_DISCONNECT: { if (FClientTaskDataRow["TaskCode"].ToString() == "IMMEDIATE") { TLogging.Log("Client disconnected due to server disconnection request."); PetraClientShutdown.Shutdown.SaveUserDefaultsAndDisconnectAndStop(); } if (FClientTaskDataRow["TaskCode"].ToString() == "IMMEDIATE-HARDEXIT") { TLogging.Log( "Application stopped due to server disconnection request (without saving of User Defaults or disconnection)."); // APPLICATION STOPS HERE !!! Environment.Exit(0); } break; } case SharedConstants.CLIENTTASKGROUP_REPORT: { FastReportsPrintReportNoUiDelegate(FClientTaskDataRow["TaskCode"].ToString(), FClientTaskDataRow["TaskParameter1"].ToString()); break; } } } catch (Exception Exp) { // MessageBox.Show("Exception occured in TClientTaskInstance.Execute: \r\n" + Exp.ToString()); TLogging.Log("Exception occured in TClientTaskInstance.Execute: \r\n" + Exp.ToString()); } }
/// <summary> /// Executes the Client Task. /// </summary> public override void Execute() { try { switch (FClientTaskDataRow["TaskGroup"].ToString()) { // MessageBox.Show('Executing Client Task #' + FClientTaskDataRow['TaskID'].ToString + ' in Thread.'); case SharedConstants.CLIENTTASKGROUP_USERMESSAGE: { //MessageBox.Show(SharedConstants.CLIENTTASKGROUP_USERMESSAGE + " (Client Task #" + // FClientTaskDataRow["TaskID"].ToString() + "): " + FClientTaskDataRow["TaskCode"].ToString(), // "Client #" + UserInfo.GUserInfo.ProcessID.ToString() + " received a ClientTask."); ShowMessageBoxOnTopOfAllFormsAutoParsed(); break; } case SharedConstants.CLIENTTASKGROUP_CACHEREFRESH: { if (FClientTaskDataRow["TaskParameter1"].ToString() == "") { TDataCache.ReloadCacheTable(FClientTaskDataRow["TaskCode"].ToString()); } else { TDataCache.ReloadCacheTable(FClientTaskDataRow["TaskCode"].ToString(), FClientTaskDataRow["TaskParameter1"]); } break; } case SharedConstants.CLIENTTASKGROUP_USERDEFAULTSREFRESH: { if (FClientTaskDataRow["TaskCode"].ToString() == "All") { // TLogging.Log("FClientTaskDataRow[TaskCode] = All!"); TUserDefaults.ReloadCachedUserDefaults(); TUserDefaults.SaveChangedUserDefaults(); } else { // TLogging.Log("FClientTaskDataRow[TaskCode] <> All, but '" + FClientTaskDataRow["TaskCode"].ToString() + "'" + // "FClientTaskDataRow[TaskParameter1]: '" + FClientTaskDataRow["TaskParameter1"].ToString() + "'\r\n" + // "FClientTaskDataRow[TaskParameter2]: '" + FClientTaskDataRow["TaskParameter2"].ToString() + "'\r\n" + // "FClientTaskDataRow[TaskParameter3]: '" + FClientTaskDataRow["TaskParameter3"].ToString() + "'" + // ((FClientTaskDataRow["TaskParameter4"] != System.DBNull.Value) ? "\r\nFClientTaskDataRow[TaskParameter4]: '" + // FClientTaskDataRow["TaskParameter4"].ToString() + "'" : "\r\nFClientTaskDataRow[TaskParameter4]: DBNull")); TUserDefaults.RefreshCachedUserDefault( FClientTaskDataRow["TaskParameter1"].ToString(), FClientTaskDataRow["TaskParameter2"].ToString(), FClientTaskDataRow["TaskParameter3"].ToString(), ((FClientTaskDataRow["TaskParameter4"] != System.DBNull.Value) ? Convert.ToInt32(FClientTaskDataRow["TaskParameter4"]) : -1)); } break; } case SharedConstants.CLIENTTASKGROUP_USERINFOREFRESH: { TUserInfo.ReloadCachedUserInfo(); break; } case RemotingConstants.CLIENTTASKGROUP_DISCONNECT: { if (FClientTaskDataRow["TaskCode"].ToString() == "IMMEDIATE") { TLogging.Log("Client disconnected due to server disconnection request."); PetraClientShutdown.Shutdown.SaveUserDefaultsAndDisconnectAndStop(); } if (FClientTaskDataRow["TaskCode"].ToString() == "IMMEDIATE-HARDEXIT") { TLogging.Log( "Application stopped due to server disconnection request (without saving of User Defaults or disconnection)."); // APPLICATION STOPS HERE !!! Environment.Exit(0); } break; } case SharedConstants.CLIENTTASKGROUP_REPORT: { FastReportsPrintReportNoUiDelegate(FClientTaskDataRow["TaskCode"].ToString(), FClientTaskDataRow["TaskParameter1"].ToString()); break; } case SharedConstants.CLIENTTASKGROUP_DBCONNECTIONBROKEN: { //MessageBox.Show(SharedConstants.CLIENTTASKGROUP_DBCONNECTIONBROKEN + " (Client Task #" + // FClientTaskDataRow["TaskID"].ToString() + "): " + FClientTaskDataRow["TaskCode"].ToString(), // "Client #" + UserInfo.GUserInfo.ProcessID.ToString() + " received a ClientTask."); ShowMessageBoxOnTopOfAllFormsDBConnectionBroken(); break; } } } catch (Exception Exp) { // MessageBox.Show("Exception occured in TClientTaskInstance.Execute: \r\n" + Exp.ToString()); TLogging.Log("Exception occured in TClientTaskInstance.Execute: \r\n" + Exp.ToString()); } }
/// <summary> /// /// </summary> /// <param name="AParameters"></param> public void SetControls(TParameterList AParameters) { // // If LedgerNumber hasn't been set yet, do nothing: if (FLedgerNumber < 0) { return; } AFeesReceivableTable FeesReceivable = new AFeesReceivableTable(); Type DataTableType; DataTable CacheDT = TDataCache.GetSpecificallyFilteredCacheableDataTableFromCache("FeesReceivableList", "Ledger", FLedgerNumber, out DataTableType); FeesReceivable.Merge(CacheDT); Array.Resize(ref FUnselectedFees, FeesReceivable.Rows.Count); for (Int32 Idx = 0; Idx < FeesReceivable.Rows.Count; Idx++) { AFeesReceivableRow Row = FeesReceivable[Idx]; FUnselectedFees[Idx] = Row.FeeCode; } AFeesPayableTable FeesPayable = new AFeesPayableTable(); CacheDT = TDataCache.GetSpecificallyFilteredCacheableDataTableFromCache("FeesPayableList", "Ledger", FLedgerNumber, out DataTableType); FeesPayable.Merge(CacheDT); Array.Resize(ref FUnselectedFees, FUnselectedFees.Length + FeesPayable.Rows.Count); for (Int32 Idx = 0; Idx < FeesPayable.Rows.Count; Idx++) { AFeesPayableRow Row = FeesPayable[Idx]; FUnselectedFees[FeesReceivable.Rows.Count + Idx] = Row.FeeCode; } String FeeStr = AParameters.Get("param_fee_codes").ToString(); // // If there's no fees selected, it's perhaps because the installation is new. // Add all the fees from the "Don't Print" box, up to the maximum number allowed. if (FeeStr == "") { Array.Resize(ref FSelectedFees, lstDontPrint.Items.Count); lstDontPrint.Items.CopyTo(FSelectedFees, 0); if (lstDontPrint.Items.Count > MAX_FEE_COUNT) { Array.Resize(ref FSelectedFees, MAX_FEE_COUNT); } } else { FSelectedFees = FeeStr.Split(','); } // Now I want to remove the selected items from the FSelectedFees list: for (Int32 Idx = 0; Idx < FSelectedFees.Length; Idx++) { Int32 pos = ((IList)FUnselectedFees).IndexOf(FSelectedFees[Idx]); if (pos >= 0) { Int32 NewLength = FUnselectedFees.Length - 1; for (Int32 i = pos; i < NewLength; i++) { FUnselectedFees[i] = FUnselectedFees[i + 1]; } Array.Resize(ref FUnselectedFees, NewLength); } } RefreshLists(); }
private void NewRowManual(ref ACurrencyLanguageRow ARow) { // Deal with primary key. CurrencyCode (varchar(16)) and LanguageCode (varchar(20)) are unique. if (FMainDS.ACurrencyLanguage.Rows.Count == 0) { // Our first row is always USD/EN ARow.CurrencyCode = "USD"; ARow.LanguageCode = "EN"; return; } else { // We already have some rows, so we use the currently selected language in the comboBox as a starter // This may or may not be the most recently added language depending on how the main data set has been sorted // But once we have started adding rows it should remain the 'active' row string prevLanguage = cmbDetailLanguageCode.cmbCombobox.Text; // Try and find some popular or at least likely currencies // Remember that we will almost certainly select a currency that the user does NOT want in their language // So this will be the one we always propose!!!! string[] tryCurrencies = { "USD", "GBP", "EUR", "INR", "AUD", "CAD", "CHF", "CNY", "JPY", "NZD", "PHP", "PKR", "ZAR" }; int nTryCurrency = 0; bool bFoundCurrency = true; while (FMainDS.ACurrencyLanguage.Rows.Find(new object[] { tryCurrencies[nTryCurrency], prevLanguage }) != null) { if (++nTryCurrency == tryCurrencies.Length) { // We have exhausted our popular choices bFoundCurrency = false; break; } } if (bFoundCurrency) { ARow.CurrencyCode = tryCurrencies[nTryCurrency]; ARow.LanguageCode = prevLanguage; return; } // So we have tried all the popular currencies in the current language // Now we fall back to trying all currencies in the current languages. // Remember that we will almost certainly select a currency that the user does NOT want in their language // So this will be the one we always propose!!!! Type DataTableType; ACurrencyTable allCurrencies = new ACurrencyTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("CurrencyCodeList", String.Empty, null, out DataTableType); allCurrencies.Merge(CacheDT); nTryCurrency = 0; bFoundCurrency = true; while (FMainDS.ACurrencyLanguage.Rows.Find(new object[] { allCurrencies.Rows[nTryCurrency][0].ToString(), prevLanguage }) != null) { if (++nTryCurrency == tryCurrencies.Length) { bFoundCurrency = false; break; } } if (bFoundCurrency) { ARow.CurrencyCode = allCurrencies.Rows[nTryCurrency][0].ToString(); ARow.LanguageCode = prevLanguage; } // We could at this point start trying other languages - but there seems little point since the currency list contains // currencies that will never be used since they no longer exist!! It is therefore assumed that by this time // the user has gone on to a different langauge where we will have started again with USD .... } }
/// <summary> /// Imports currency exchange rates, daily and corporate, /// from a one-of-two-styles formatted CSV file /// </summary> /// <param name="AExchangeRDT">Daily or Corporate exchange rate table</param> /// <param name="ADataFilename">The .CSV file to process</param> /// <param name="ACSVSeparator"></param> /// <param name="ANumberFormat"></param> /// <param name="ADateFormat"></param> /// <param name="AImportMode">Daily or Corporate</param> /// <param name="AResultCollection">A validation collection to which errors will be added</param> /// <returns>The number of rows that were actually imported. Rows that duplicate existing rows do not count. /// This is usually because this is an attempt to import again after a failed previous attempt.</returns> private static int ImportCurrencyExRatesFromCSV(TTypedDataTable AExchangeRDT, string ADataFilename, string ACSVSeparator, string ANumberFormat, string ADateFormat, string AImportMode, TVerificationResultCollection AResultCollection) { // Keep a list of errors/warnings and severity List <Tuple <string, TResultSeverity> > InvalidRows = new List <Tuple <string, TResultSeverity> >(); // keep a variable that becomes true if any row has an invalid column count, so we can show a helpful message bool InvalidColumnCount = false; // Check our method parameters if ((AImportMode != "Corporate") && (AImportMode != "Daily")) { throw new ArgumentException("Invalid value '" + AImportMode + "' for mode argument: Valid values are Corporate and Daily"); } else if ((AImportMode == "Corporate") && !(AExchangeRDT is ACorporateExchangeRateTable)) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Corporate'. Needs to be: ACorporateExchangeRateTable"); } else if ((AImportMode == "Daily") && !(AExchangeRDT is ADailyExchangeRateTable)) { throw new ArgumentException("Invalid type of exchangeRateDT argument for mode: 'Daily'. Needs to be: ADailyExchangeRateTable"); } bool IsShortFileFormat; int x, y; // To store the From and To currencies // Use an array to store these to make for easy // inverting of the two currencies when calculating // the inverse value. string[] Currencies = new string[2]; Type DataTableType; int RowsImported = 0; // This table will tell us the base currencies used by the current set of ledgers ALedgerTable ledgers = TRemote.MFinance.Setup.WebConnectors.GetAvailableLedgers(); List <string> allBaseCurrencies = new List <string>(); DateTime maxRecommendedEffectiveDate = DateTime.MaxValue; DateTime minRecommendedEffectiveDate = DateTime.MinValue; int preferredPeriodStartDay = 0; // Use the ledger table rows to get a list of base currencies and current period end dates for (int i = 0; i < ledgers.Rows.Count; i++) { ALedgerRow ledger = (ALedgerRow)ledgers.Rows[i]; string code = ledger.BaseCurrency; if (ledger.LedgerStatus == true) { if (allBaseCurrencies.Contains(code) == false) { allBaseCurrencies.Add(code); } DataTable AccountingPeriods = TDataCache.TMFinance.GetCacheableFinanceTable(TCacheableFinanceTablesEnum.AccountingPeriodList, ledger.LedgerNumber); AAccountingPeriodRow currentPeriodRow = (AAccountingPeriodRow)AccountingPeriods.Rows.Find(new object[] { ledger.LedgerNumber, ledger.CurrentPeriod }); AAccountingPeriodRow forwardPeriodRow = (AAccountingPeriodRow)AccountingPeriods.Rows.Find( new object[] { ledger.LedgerNumber, ledger.CurrentPeriod + ledger.NumberFwdPostingPeriods }); if ((forwardPeriodRow != null) && ((maxRecommendedEffectiveDate == DateTime.MaxValue) || (forwardPeriodRow.PeriodEndDate > maxRecommendedEffectiveDate))) { maxRecommendedEffectiveDate = forwardPeriodRow.PeriodEndDate; } if ((currentPeriodRow != null) && ((minRecommendedEffectiveDate == DateTime.MinValue) || (currentPeriodRow.PeriodStartDate > minRecommendedEffectiveDate))) { minRecommendedEffectiveDate = currentPeriodRow.PeriodStartDate; } if ((currentPeriodRow != null) && (preferredPeriodStartDay == 0)) { preferredPeriodStartDay = currentPeriodRow.PeriodStartDate.Day; } else if ((currentPeriodRow != null) && (currentPeriodRow.PeriodStartDate.Day != preferredPeriodStartDay)) { preferredPeriodStartDay = -1; } } } // This will tell us the complete list of all available currencies ACurrencyTable allCurrencies = new ACurrencyTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("CurrencyCodeList", String.Empty, null, out DataTableType); allCurrencies.Merge(CacheDT); allCurrencies.CaseSensitive = true; // Start reading the file using (StreamReader DataFile = new StreamReader(ADataFilename, System.Text.Encoding.Default)) { string ThousandsSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "," : "."); string DecimalSeparator = (ANumberFormat == TDlgSelectCSVSeparator.NUMBERFORMAT_AMERICAN ? "." : ","); CultureInfo MyCultureInfoDate = new CultureInfo("en-GB"); MyCultureInfoDate.DateTimeFormat.ShortDatePattern = ADateFormat; // TODO: disconnect the grid from the datasource to avoid flickering? string FileNameWithoutExtension = Path.GetFileNameWithoutExtension(ADataFilename).ToUpper(); if ((FileNameWithoutExtension.IndexOf("_") == 3) && (FileNameWithoutExtension.LastIndexOf("_") == 3) && (FileNameWithoutExtension.Length == 7)) { // File name format assumed to be like this: USD_HKD.csv IsShortFileFormat = true; Currencies = FileNameWithoutExtension.Split(new char[] { '_' }); } else { IsShortFileFormat = false; } int LineNumber = 0; while (!DataFile.EndOfStream) { string Line = DataFile.ReadLine(); LineNumber++; // See if the first line is a special case?? if (LineNumber == 1) { // see if the first line is a text header - look for digits // A valid header would look like: From,To,Date,Rate bool bFoundDigit = false; for (int i = 0; i < Line.Length; i++) { char c = Line[i]; if ((c >= '0') && (c <= '9')) { bFoundDigit = true; break; } } if (!bFoundDigit) { // No digits so we will assume the line is a header continue; } } //Convert separator to a char char Sep = ACSVSeparator[0]; //Turn current line into string array of column values string[] CsvColumns = Line.Split(Sep); int NumCols = CsvColumns.Length; // Do we have the correct number of columns? int minColCount = IsShortFileFormat ? 2 : 4; int maxColCount = (AImportMode == "Daily") ? minColCount + 1 : minColCount; if ((NumCols < minColCount) || (NumCols > maxColCount)) { // raise an error string resultText = String.Format(Catalog.GetPluralString( "Line {0}: contains 1 column", "Line {0}: contains {1} columns", NumCols, true), LineNumber, NumCols.ToString()); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); InvalidColumnCount = true; continue; } if (!IsShortFileFormat) { //Read the values for the current line //From currency Currencies[0] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString().ToUpper(); //To currency Currencies[1] = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).ToString().ToUpper(); } // Perform validation on the From and To currencies at this point!! if ((allCurrencies.Rows.Find(Currencies[0]) == null) && (allCurrencies.Rows.Find(Currencies[1]) == null)) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid currency codes ({1} and {2})"), LineNumber.ToString(), Currencies[0], Currencies[1]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } else if (allCurrencies.Rows.Find(Currencies[0]) == null) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid currency code ({1})"), LineNumber.ToString(), Currencies[0]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } else if (allCurrencies.Rows.Find(Currencies[1]) == null) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid currency code ({1})"), LineNumber.ToString(), Currencies[1]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } if ((allBaseCurrencies.Contains(Currencies[0]) == false) && (allBaseCurrencies.Contains(Currencies[1]) == false)) { //raise a non-critical error string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: One of '{1}' and '{2}' should be a base currency in one of the active ledgers."), LineNumber.ToString(), Currencies[0], Currencies[1]); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } // Date parsing as in Petra 2.x instead of using XML date format!!! string DateEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace("\"", String.Empty); DateTime DateEffective; if (!DateTime.TryParse(DateEffectiveStr, MyCultureInfoDate, DateTimeStyles.None, out DateEffective)) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid date ({1})"), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } if (DateEffective > maxRecommendedEffectiveDate) { // raise a warning string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: The date '{1}' is after the latest forwarding period of any active ledger"), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } else if (DateEffective < minRecommendedEffectiveDate) { // raise a warning string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: The date '{1}' is before the current accounting period of any active ledger"), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } if (AImportMode == "Corporate") { if ((preferredPeriodStartDay >= 1) && (DateEffective.Day != preferredPeriodStartDay)) { // raise a warning string resultText = String.Format(Catalog.GetString( "Line {0}: Warning: The date '{1}' should be the first day of an accounting period used by all the active ledgers."), LineNumber.ToString(), DateEffectiveStr); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Noncritical)); } } decimal ExchangeRate = 0.0m; try { string ExchangeRateString = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true).Replace(ThousandsSeparator, "").Replace( DecimalSeparator, ".").Replace("\"", String.Empty); ExchangeRate = Convert.ToDecimal(ExchangeRateString, System.Globalization.CultureInfo.InvariantCulture); if (ExchangeRate == 0) { throw new Exception(); } } catch (Exception) { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid rate of exchange ({1})"), LineNumber.ToString(), ExchangeRate); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } int TimeEffective = 7200; if (AImportMode == "Daily") { // Daily rate imports can have an optional final column which is the time // Otherwise we assume the time is a default of 7200 (02:00am) if ((IsShortFileFormat && (NumCols == 3)) || (!IsShortFileFormat && (NumCols == 5))) { string timeEffectiveStr = StringHelper.GetNextCSV(ref Line, ACSVSeparator, false, true); int t = (int)new Ict.Common.TypeConverter.TShortTimeConverter().ConvertTo(timeEffectiveStr, typeof(int)); if (t < 0) { // it wasn't in the format 02:00 if (!Int32.TryParse(timeEffectiveStr, out t)) { // Not a regular Int32 either t = -1; } } if ((t >= 0) && (t < 86400)) { TimeEffective = t; } else { // raise an error string resultText = String.Format(Catalog.GetString( "Line {0}: invalid effective time ({1})"), LineNumber.ToString(), t); InvalidRows.Add(new Tuple <string, TResultSeverity>(resultText, TResultSeverity.Resv_Critical)); continue; } } } if ((AImportMode == "Corporate") && AExchangeRDT is ACorporateExchangeRateTable) { ACorporateExchangeRateTable ExchangeRateDT = (ACorporateExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ACorporateExchangeRateRow ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ACorporateExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = Math.Round(1 / ExchangeRate, 10); } } } else if ((AImportMode == "Daily") && AExchangeRDT is ADailyExchangeRateTable) { ADailyExchangeRateTable ExchangeRateDT = (ADailyExchangeRateTable)AExchangeRDT; // run this code in the loop twice to get ExchangeRate value and its inverse for (int i = 0; i <= 1; i++) { //this will cause x and y to go from 0 to 1 and 1 to 0 respectively x = i; y = Math.Abs(i - 1); ADailyExchangeRateRow ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.Rows. Find(new object[] { Currencies[x], Currencies[y], DateEffective, TimeEffective }); if (ExchangeRow == null) // remove 0 for Corporate { ExchangeRow = (ADailyExchangeRateRow)ExchangeRateDT.NewRowTyped(); ExchangeRow.FromCurrencyCode = Currencies[x]; ExchangeRow.ToCurrencyCode = Currencies[y]; ExchangeRow.DateEffectiveFrom = DateEffective; ExchangeRow.TimeEffectiveFrom = TimeEffective; ExchangeRateDT.Rows.Add(ExchangeRow); RowsImported++; } if (i == 0) { ExchangeRow.RateOfExchange = ExchangeRate; } else { ExchangeRow.RateOfExchange = Math.Round(1 / ExchangeRate, 10); } } } } // if there are rows that could not be imported if ((InvalidRows != null) && (InvalidRows.Count > 0)) { int errorCount = 0; int warningCount = 0; // Go through once just to count the errors and warnings foreach (Tuple <string, TResultSeverity> Row in InvalidRows) { if (Row.Item2 == TResultSeverity.Resv_Noncritical) { warningCount++; } else { errorCount++; } } string resultText = String.Empty; bool messageListIsFull = false; int counter = 0; if (errorCount > 0) { resultText = string.Format(Catalog.GetPluralString("1 row was not imported due to invalid data:", "{0} rows were not imported due to invalid data:", errorCount, true), errorCount) + Environment.NewLine; } if (warningCount > 0) { resultText = string.Format(Catalog.GetPluralString("There was 1 warning associated with the imported rows:", "There were {0} warnings associated with the imported rows:", warningCount, true), warningCount) + Environment.NewLine; } // Now go through again itemising each one foreach (Tuple <string, TResultSeverity> Row in InvalidRows) { counter++; if (counter <= MAX_MESSAGE_COUNT) { resultText += Environment.NewLine + Row.Item1; } else if (!messageListIsFull) { resultText += String.Format(Catalog.GetString( "{0}{0}{1} errors/warnings were reported in total. This message contains the first {2}."), Environment.NewLine, InvalidRows.Count, MAX_MESSAGE_COUNT); messageListIsFull = true; } } // additional message if one or more rows has an invalid number of columns if (InvalidColumnCount && IsShortFileFormat) { resultText += String.Format("{0}{0}" + Catalog.GetString("Each row should contain 2 or 3 columns as follows:") + "{0}" + Catalog.GetString( " 1. Effective Date{0} 2. Exchange Rate{0} 3. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); } else if (InvalidColumnCount && !IsShortFileFormat) { resultText += String.Format("{0}{0}" + Catalog.GetString("Each row should contain 4 or 5 columns as follows:") + "{0}" + Catalog.GetString( " 1. From Currency{0} 2. To Currency{0} 3. Effective Date{0} 4. Exchange Rate{0} 5. Effective time in seconds (Optional for Daily Rate only)"), Environment.NewLine); } TVerificationResult result = new TVerificationResult(AImportMode, resultText, CommonErrorCodes.ERR_INCONGRUOUSSTRINGS, (errorCount > 0) ? TResultSeverity.Resv_Critical : TResultSeverity.Resv_Noncritical); AResultCollection.Add(result); } DataFile.Close(); return(RowsImported); } }
private void RunOnceOnActivationManual() { // Set up the window title if (String.Compare(Context, "Bank", true) == 0) { this.Text += Catalog.GetString(" For Bank"); } else if (String.Compare(Context, "Church", true) == 0) { this.Text += Catalog.GetString(" For Church"); } else if (String.Compare(Context, "Family", true) == 0) { this.Text += Catalog.GetString(" For Family"); } else if (String.Compare(Context, "Organisation", true) == 0) { this.Text += Catalog.GetString(" For Organisation"); } else if (String.Compare(Context, "Person", true) == 0) { this.Text += Catalog.GetString(" For Person"); } else if (String.Compare(Context, "Unit", true) == 0) { this.Text += Catalog.GetString(" For Unit"); } else if (String.Compare(Context, "Venue", true) == 0) { this.Text += Catalog.GetString(" For Venue"); } else if (String.Compare(Context, "LongTermApp", true) == 0) { this.Text += Catalog.GetString(" For Long Term Applications"); } else if (String.Compare(Context, "ShortTermApp", true) == 0) { this.Text += Catalog.GetString(" For Short Term Applications"); } else if (String.Compare(Context, "Personnel", true) == 0) { this.Text += Catalog.GetString(" For Personnel"); } // Initialize 'Helper Class' for handling the Indexes of the DataRows. FIndexedGridRowsHelper = new TSgrdDataGrid.IndexedGridRowsHelper( grdDetails, PDataLabelUseTable.ColumnIdx1Id, btnDemote, btnPromote, delegate { FPetraUtilsObject.SetChangedFlag(); }); // Load the Extra Data from DataLabel table Type DataTableType; FExtraDS.PDataLabel = new PDataLabelTable(); DataTable CacheDT = TDataCache.GetCacheableDataTableFromCache("DataLabelList", String.Empty, null, out DataTableType); FExtraDS.PDataLabel.Merge(CacheDT); // Extend our main DataLabelUse table int NameOrdinal = FMainDS.PDataLabelUse.Columns.Add("Name", typeof(String)).Ordinal; int GroupOrdinal = FMainDS.PDataLabelUse.Columns.Add("GroupHeading", typeof(String)).Ordinal; int DescriptionOrdinal = FMainDS.PDataLabelUse.Columns.Add("Description", typeof(String)).Ordinal; // Take each row of our main dataset and populate the new columns with relevant data // from the DataLabelUse table foreach (PDataLabelUseRow useRow in FMainDS.PDataLabelUse.Rows) { PDataLabelRow labelRow = (PDataLabelRow)FExtraDS.PDataLabel.Rows.Find(new object[] { useRow.DataLabelKey }); useRow[NameOrdinal] = labelRow.Text; useRow[GroupOrdinal] = labelRow.Group; useRow[DescriptionOrdinal] = labelRow.Description; } // Add columns to the grid for the label details grdDetails.AddTextColumn(Catalog.GetString("Name"), FMainDS.PDataLabelUse.Columns[NameOrdinal]); grdDetails.AddTextColumn(Catalog.GetString("Group Heading"), FMainDS.PDataLabelUse.Columns[GroupOrdinal]); grdDetails.AddTextColumn(Catalog.GetString("Description"), FMainDS.PDataLabelUse.Columns[DescriptionOrdinal]); grdDetails.Selection.SelectionChanged += HandleSelectionChanged; // Remove the first column. We added this in the YAML so that the auto-generator had something to do grdDetails.Columns.Remove(0); grdDetails.SetHeaderTooltip(0, Catalog.GetString("Name")); grdDetails.SetHeaderTooltip(1, Catalog.GetString("Group Heading")); grdDetails.SetHeaderTooltip(2, Catalog.GetString("Description")); // Create a view that will only show the rows applicable to our currentContext DataView contextView = new DataView(FMainDS.PDataLabelUse, "p_use_c='" + Context + "'", "p_idx1_i", DataViewRowState.CurrentRows); contextView.AllowNew = false; // Bind the view to our grid grdDetails.DataSource = new DevAge.ComponentModel.BoundDataView(contextView); grdDetails.Refresh(); SelectRowInGrid(1); }