/// <summary> /// open template.pot again and remove source code lines of not translated msgids /// </summary> private static void ReviewTemplateFile(string ATranslationFile) { StreamReader sr = new StreamReader(ATranslationFile); Encoding enc = new UTF8Encoding(false); StreamWriter sw = new StreamWriter(ATranslationFile + ".new", false, enc); string line = sr.ReadLine(); while (line != null) { if (line.StartsWith("#:")) { string currentLine; if (line.Contains("csharp")) { //cut away first part of source location currentLine = line.Remove(3, line.IndexOf("csharp") - 3); } else { currentLine = line; } //write line only to new template file if the following line is not empty line = sr.ReadLine(); if (line != "") { sw.WriteLine(currentLine); } } else if (line == "") { //add empty line only if the next line is not aswell an empty line string currentLine = line; line = sr.ReadLine(); if (line != "") { sw.WriteLine(currentLine); } } else { sw.WriteLine(line); line = sr.ReadLine(); } /*if(line.Contains("txtAutoPopulatedButtonLabel")) * { * Console.WriteLine("here"); * }*/ } sr.Close(); sw.Close(); TTextFile.UpdateFile(ATranslationFile); }
/// <summary> /// compare the written result and parameter files with the files approved by a domain expert /// </summary> public static void TestResult(string AResultsFile, int ALedgerNumber = -1) { if (AResultsFile.IndexOf(".Results.html") == -1) { throw new Exception("invalid file name, should end with .Results.html"); } string resultFile = AResultsFile; string resultExpectedFile = AResultsFile.Replace(".Results.html", ".Results.Expected.html"); SortedList <string, string> ToReplace = new SortedList <string, string>(); ToReplace.Add("{ledgernumber}", ALedgerNumber.ToString()); ToReplace.Add("{Today}", DateTime.Today.ToString("yyyy-MM-dd")); int currentYear = DateTime.Today.Year; ToReplace.Add("{ThisYear}", currentYear.ToString()); ToReplace.Add("{PreviousYear}", (currentYear - 1).ToString()); if (ALedgerNumber != -1) { TLedgerInfo ledger = new TLedgerInfo(ALedgerNumber); ToReplace.Add("{CurrentPeriod}", ledger.CurrentPeriod.ToString()); } Assert.True(TTextFile.SameContent(resultFile, resultExpectedFile, true, ToReplace, true), "the file " + resultFile + " should have the same content as " + resultExpectedFile); File.Delete(resultFile); }
public void TestAnnualReceipt() { CommonNUnitFunctions.ResetDatabase(); // import a test gift batch TVerificationResultCollection VerificationResult; if (!ImportAndPostGiftBatch(FLedgerNumber, out VerificationResult)) { Assert.Fail("ImportAndPostGiftBatch failed: " + VerificationResult.BuildVerificationResultString()); } // TODO test reversed gifts string formletterTemplateFile = TAppSettingsManager.GetValue("ReceiptTemplate.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/AnnualReceiptTemplate.html"); Encoding encodingOfHTMLfile = TTextFile.GetFileEncoding(formletterTemplateFile); StreamReader sr = new StreamReader(formletterTemplateFile, encodingOfHTMLfile, false); string FileContent = sr.ReadToEnd(); sr.Close(); string formletterExpectedFile = TAppSettingsManager.GetValue("ReceiptExptected.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/AnnualReceiptExpected.html"); Catalog.Init("de-DE", "de-DE"); sr = new StreamReader(formletterExpectedFile, encodingOfHTMLfile, false); string ExpectedFormletterContent = sr.ReadToEnd(). Replace("#TODAY#", DateTime.Now.ToString("d. MMMM yyyy")). Replace("#THISYEAR#", DateTime.Today.Year.ToString()); sr.Close(); StreamWriter sw = new StreamWriter(formletterExpectedFile + ".updated", false, encodingOfHTMLfile); sw.WriteLine(ExpectedFormletterContent); sw.Close(); TLanguageCulture.SetLanguageAndCulture("de-DE", "de-DE"); //TODO: Calendar vs Financial Date Handling - Check if this should use financial year start/end and not assume calendar string receipts = TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber, new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent); sw = new StreamWriter(formletterExpectedFile + ".new", false, encodingOfHTMLfile); sw.WriteLine(receipts); sw.WriteLine(); sw.Close(); Assert.IsTrue( TTextFile.SameContent(formletterExpectedFile + ".updated", formletterExpectedFile + ".new"), "receipt was not printed as expected, check " + formletterExpectedFile + ".new"); File.Delete(formletterExpectedFile + ".new"); File.Delete(formletterExpectedFile + ".updated"); }
public void TestYmlWriter() { XmlDocument doc = CreateTestDoc(); // now test the yml file string filename = PathToTestData + "test.yml"; TYml2Xml.Xml2Yml(doc, filename + ".new"); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
/// <summary> /// print single gift receipt /// </summary> //[Test] public void TestSingleReceipt() { CommonNUnitFunctions.ResetDatabase(); TPetraServerConnector.Connect("../../etc/TestServer.config"); // import a test gift batch TVerificationResultCollection VerificationResult; if (!TGiftAnnualReceiptTest.ImportAndPostGiftBatch(FLedgerNumber, out VerificationResult)) { Assert.Fail("ImportAndPostGiftBatch failed: " + VerificationResult.BuildVerificationResultString()); } string formletterTemplateFile = TAppSettingsManager.GetValue("ReceiptTemplate.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/SingleGiftReceiptTemplate.html"); Encoding encodingOfHTMLfile = TTextFile.GetFileEncoding(formletterTemplateFile); StreamReader sr = new StreamReader(formletterTemplateFile, encodingOfHTMLfile, false); string FileContent = sr.ReadToEnd(); sr.Close(); string formletterExpectedFile = TAppSettingsManager.GetValue("ReceiptExpected.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/SingleGiftReceiptExpected.html"); //TODO: Calendar vs Financial Date Handling - Check if this should use financial year start/end and not assume calendar string receipts; string receiptsPDF; bool result = TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber, "Annual", new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent, null, String.Empty, null, String.Empty, "de-DE", out receiptsPDF, out receipts); Assert.AreEqual(true, result, "receipt was empty"); StreamWriter sw = new StreamWriter(formletterExpectedFile + ".new", false, encodingOfHTMLfile); sw.WriteLine(receipts); sw.WriteLine(); sw.Close(); SortedList <string, string> ToReplace = new SortedList <string, string>(); ToReplace.Add("#TODAY#", DateTime.Now.ToString("d. MMMM yyyy")); ToReplace.Add("#THISYEAR#", DateTime.Today.Year.ToString()); Assert.IsTrue( TTextFile.SameContent(formletterExpectedFile, formletterExpectedFile + ".new", true, ToReplace, true), "receipt was not printed as expected, check " + formletterExpectedFile + ".new"); File.Delete(formletterExpectedFile + ".new"); }
public void TestReadAndWriteYaml() { // parse a winforms yaml file, write it again, check if the same string filename = PathToTestData + "testReadWrite.yml"; TYml2Xml converterYml = new TYml2Xml(filename); XmlDocument docFromYML = converterYml.ParseYML2XML(); TYml2Xml.Xml2Yml(docFromYML, filename + ".new"); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
public void TestCSVWriter() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; XmlDocument doc = CreateTestDoc(); // now test the csv file string filename = PathToTestData + "test.csv"; TCsv2Xml.Xml2Csv(doc, filename + ".new"); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
public void TestXmlWriter() { XmlDocument doc = CreateTestDoc(); // first see if the xml file is still the same string filename = PathToTestData + "test.xml"; StreamWriter sw = new StreamWriter(filename + ".new"); sw.Write(TXMLParser.XmlToString(doc)); sw.Close(); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
public void TestSingleReceipt() { CommonNUnitFunctions.ResetDatabase(); // import a test gift batch TVerificationResultCollection VerificationResult; if (!TGiftAnnualReceiptTest.ImportAndPostGiftBatch(FLedgerNumber, out VerificationResult)) { Assert.Fail("ImportAndPostGiftBatch failed: " + VerificationResult.BuildVerificationResultString()); } string formletterTemplateFile = TAppSettingsManager.GetValue("ReceiptTemplate.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/SingleGiftReceiptTemplate.html"); Encoding encodingOfHTMLfile = TTextFile.GetFileEncoding(formletterTemplateFile); StreamReader sr = new StreamReader(formletterTemplateFile, encodingOfHTMLfile, false); string FileContent = sr.ReadToEnd(); sr.Close(); string formletterExpectedFile = TAppSettingsManager.GetValue("ReceiptExptected.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/SingleGiftReceiptExpected.html"); Catalog.Init("de-DE", "de-DE"); TLanguageCulture.SetLanguageAndCulture("de-DE", "de-DE"); string receipts = TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber, new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent); StreamWriter sw = new StreamWriter(formletterExpectedFile + ".new", false, encodingOfHTMLfile); sw.WriteLine(receipts); sw.WriteLine(); sw.Close(); SortedList <string, string> ToReplace = new SortedList <string, string>(); ToReplace.Add("#TODAY#", DateTime.Now.ToString("d. MMMM yyyy")); ToReplace.Add("#THISYEAR#", DateTime.Today.Year.ToString()); Assert.IsTrue( TTextFile.SameContent(formletterExpectedFile, formletterExpectedFile + ".new", true, ToReplace, true), "receipt was not printed as expected, check " + formletterExpectedFile + ".new"); File.Delete(formletterExpectedFile + ".new"); }
public void TestYMLParser() { CreateTestDoc(); // load from yml, is it the same xml code? string filename = PathToTestData + "test.yml"; TYml2Xml converterYml = new TYml2Xml(filename); XmlDocument docFromYML = converterYml.ParseYML2XML(); filename = PathToTestData + "testWithInheritedAttributes.xml"; StreamWriter sw = new StreamWriter(filename + ".new"); sw.Write(TXMLParser.XmlToString2(docFromYML)); sw.Close(); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "after importing from yml: the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
public void TestCSVParser() { CreateTestDoc(); // load from csv, is it the same xml code? string filename = PathToTestData + "test.csv"; XmlDocument docFromCSV = TCsv2Xml.ParseCSV2Xml(filename); filename = PathToTestData + "test.xml"; StreamWriter sw = new StreamWriter(filename + ".new"); sw.Write(TXMLParser.XmlToString2(docFromCSV)); sw.Close(); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "after importing from csv: the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
/// <summary> /// write the file clean.sql that removes all data from the database, for easy resetting of the database with clean test data /// </summary> /// <param name="AStore"></param> /// <param name="AFilename"></param> public static void WriteDBClean(TDataDefinitionStore AStore, string AFilename) { StreamWriter sw = new StreamWriter(AFilename + ".new"); sw.WriteLine("-- Generated with nant generateORMTables"); List <TTable> tables = AStore.GetTables(); tables = TTableSort.TopologicalSort(AStore, tables); tables.Reverse(); foreach (TTable t in tables) { sw.WriteLine("DELETE FROM " + t.strName + ";"); } sw.Close(); TTextFile.UpdateFile(AFilename); }
public void TestYMLBackSlashValue() { string filename = PathToTestData + "testBackslash.yml"; string backslashValue = "data\\Kontoauszuege\\test.csv"; TYml2Xml converterYml = new TYml2Xml(filename); XmlDocument docFromYML = converterYml.ParseYML2XML(); XmlNode node = TXMLParser.FindNodeRecursive(docFromYML.DocumentElement, "testname"); Assert.AreEqual(backslashValue, TXMLParser.GetAttribute(node, "Filename")); // does writing of the backslash value work as well? TXMLParser.SetAttribute(node, "Filename", backslashValue); TYml2Xml.Xml2Yml(docFromYML, filename + ".new"); Assert.AreEqual(true, TTextFile.SameContent(filename, filename + ".new"), "the files should be the same: " + filename); System.IO.File.Delete(filename + ".new"); }
/// <summary> /// write the file clean.sql that removes all data from the database, for easy resetting of the database with clean test data /// </summary> /// <param name="AStore"></param> /// <param name="AFilename"></param> private static void WriteDBClean(TDataDefinitionStore AStore, string AFilename) { StreamWriter sw = new StreamWriter(AFilename + ".new"); sw.WriteLine("-- Generated with nant createSQLStatements"); List <TTable> tables = AStore.GetTables(); tables = TTableSort.TopologicalSort(AStore, tables); tables.Reverse(); foreach (TTable t in tables) { sw.WriteLine("DELETE FROM " + t.strName + ";"); } sw.Close(); TTextFile.UpdateFile(AFilename); System.Console.WriteLine("Success: file written: {0}", AFilename); }
/// <summary> /// write the file clean.sql that removes all data from the database, for easy resetting of the database with clean test data /// </summary> /// <param name="AStore"></param> /// <param name="AFilename"></param> private static void WriteDBClean(TDataDefinitionStore AStore, string AFilename) { StreamWriter sw = new StreamWriter(AFilename + ".new"); sw.WriteLine("-- Generated with nant createSQLStatements"); List <TTable> tables = AStore.GetTables(); tables = TTableSort.TopologicalSort(AStore, tables); tables.Reverse(); // drop link between s_user and p_partner, for example used for self-service sw.WriteLine("UPDATE s_user SET p_partner_key_n = NULL;"); foreach (TTable t in tables) { sw.WriteLine("DELETE FROM " + t.strName + ";"); } sw.Close(); TTextFile.UpdateFile(AFilename); System.Console.WriteLine("Success: file written: {0}", AFilename); }
/// <summary> /// modify the given file, and replace the content of the region with the new content /// </summary> /// <param name="AFilename"></param> /// <param name="ARegionName"></param> /// <param name="AInsertCode"></param> /// <returns></returns> public static bool InsertIntoRegion(string AFilename, string ARegionName, string AInsertCode) { try { StreamReader sr = new StreamReader(AFilename); StreamWriter sw = new StreamWriter(AFilename + ".new"); while (!sr.EndOfStream) { string line = sr.ReadLine(); if (line.ToLower().Contains("#region " + ARegionName.ToLower())) { sw.WriteLine(line); sw.WriteLine(AInsertCode.Replace("INDENT", "".PadLeft(line.IndexOf("#")))); while (!sr.EndOfStream && !line.ToLower().Contains("#endregion")) { line = sr.ReadLine(); } } sw.WriteLine(line); } sr.Close(); sw.Close(); TTextFile.UpdateFile(AFilename); } catch (Exception e) { Console.WriteLine("Error InsertIntoRegion: " + e.Message); return(false); } return(true); }
/// <summary> /// compare the written result and parameter files with the files approved by a domain expert /// </summary> public static void TestResult(string AReportParameterXmlFile, int ALedgerNumber = -1) { string resultFile = AReportParameterXmlFile.Replace(".xml", ".Results.xml"); string parameterFile = AReportParameterXmlFile.Replace(".xml", ".Parameters.xml"); string resultExpectedFile = AReportParameterXmlFile.Replace(".xml", ".Results.Expected.xml"); string parameterExpectedFile = AReportParameterXmlFile.Replace(".xml", ".Parameters.Expected.xml"); SortedList <string, string> ToReplace = new SortedList <string, string>(); ToReplace.Add("{ledgernumber}", ALedgerNumber.ToString()); int currentYear = DateTime.Today.Year; ToReplace.Add("{ThisYear}", currentYear.ToString()); ToReplace.Add("{PreviousYear}", (currentYear - 1).ToString()); Assert.True(TTextFile.SameContent(resultFile, resultExpectedFile, true, ToReplace, true), "the file " + resultFile + " should have the same content as " + resultExpectedFile); Assert.True(TTextFile.SameContent(parameterFile, parameterExpectedFile, true, ToReplace, true), "the file " + parameterFile + " should have the same content as " + parameterExpectedFile); File.Delete(parameterFile); File.Delete(resultFile); }
/// <summary> /// for testing csv files and printouts /// </summary> public void RunLocalizedReport(String OutputCSVFile) { if (!System.IO.File.Exists(OutputCSVFile + ".csv")) { /* create a new reference file */ FCalculator.GetResults().WriteCSV(FCalculator.GetParameters(), OutputCSVFile + ".csv"); } else { FCalculator.GetResults().WriteCSV(FCalculator.GetParameters(), OutputCSVFile + ".csv.new"); } if (!System.IO.File.Exists(OutputCSVFile + ".txt")) { /* create a new reference file */ PrintTxt(FCalculator.GetResults(), FCalculator.GetParameters(), OutputCSVFile + ".txt"); } else { PrintTxt(FCalculator.GetResults(), FCalculator.GetParameters(), OutputCSVFile + ".txt.new"); } if (System.IO.File.Exists(OutputCSVFile + ".csv.new")) { Assert.AreEqual(true, TTextFile.SameContent(OutputCSVFile + ".csv", OutputCSVFile + ".csv.new"), "the csv files should be the same: " + OutputCSVFile); System.IO.File.Delete(OutputCSVFile + ".csv.new"); } if (System.IO.File.Exists(OutputCSVFile + ".txt.new")) { Assert.AreEqual(true, TTextFile.SameContent(OutputCSVFile + ".txt", OutputCSVFile + ".txt.new"), "the txt files should be the same: " + OutputCSVFile); System.IO.File.Delete(OutputCSVFile + ".txt.new"); } }
public void TestImportExportGLBatch() { // create two test batches, with some strange figures, to test problem with double values // export the 2 test batches, with summarize option // compare the exported text file string TestFile = TAppSettingsManager.GetValue("Testing.Path") + "/lib/MFinance/GLForm/TestData/BatchImportFloatTest.csv"; TestFile = Path.GetFullPath(TestFile); Assert.IsTrue(File.Exists(TestFile), "File does not exist: " + TestFile); TFrmGLBatch frmBatch = new TFrmGLBatch(null); frmBatch.LedgerNumber = FLedgerNumber; frmBatch.Show(); ModalFormHandler = delegate(string name, IntPtr hWnd, Form form) { OpenFileDialogTester tester = new OpenFileDialogTester(hWnd); ModalFormHandler = delegate(string name2, IntPtr hWnd2, Form form2) { TDlgSelectCSVSeparatorTester tester2 = new TDlgSelectCSVSeparatorTester(hWnd2); TextBoxTester txtDateFormat = new TextBoxTester("txtDateFormat"); txtDateFormat.Properties.Text = "MM/dd/yyyy"; RadioButtonTester rbtSemicolon = new RadioButtonTester("rbtSemicolon"); rbtSemicolon.Properties.Checked = true; ButtonTester btnOK = new ButtonTester("btnOK", tester2.Properties.Name); btnOK.Click(); }; tester.OpenFile(TestFile); }; ToolStripButtonTester btnImport = new ToolStripButtonTester("tbbImportBatches"); btnImport.Click(); ToolStripButtonTester btnSave = new ToolStripButtonTester("tbbSave"); Assert.IsTrue(btnSave.Properties.Enabled, "Save button has not been activated"); btnSave.Click(); // go to Journal tab TabControlTester tabGLBatch = new TabControlTester("tabGLBatch"); tabGLBatch.SelectTab(1); TextBoxTester txtBatchNumber = new TextBoxTester("ucoJournals.txtBatchNumber"); // get the batch number from the journal tab int ImportedBatchNumber = Convert.ToInt32(txtBatchNumber.Properties.Text); TFrmGLBatchExport frmBatchExport = new TFrmGLBatchExport(null); frmBatch.Close(); // export that batch, summarize the transactions // compare the result with the expected file frmBatchExport.LedgerNumber = FLedgerNumber; frmBatchExport.Show(); CheckBoxTester chkIncludeUnposted = new CheckBoxTester("chkIncludeUnposted"); chkIncludeUnposted.Properties.Checked = true; RadioButtonTester rbtSummary = new RadioButtonTester("rbtSummary"); rbtSummary.Properties.Checked = false; RadioButtonTester rbtBatchNumberSelection = new RadioButtonTester("rbtBatchNumberSelection"); rbtBatchNumberSelection.Properties.Checked = true; TextBoxTester txtFilename = new TextBoxTester("txtFilename"); TTxtNumericTextBoxTester txtBatchNumberStart = new TTxtNumericTextBoxTester("txtBatchNumberStart"); txtBatchNumberStart.Properties.NumberValueInt = ImportedBatchNumber; TTxtNumericTextBoxTester txtBatchNumberEnd = new TTxtNumericTextBoxTester("txtBatchNumberEnd"); txtBatchNumberEnd.Properties.NumberValueInt = ImportedBatchNumber; // Test simple export of batches, no summary TestFile = TAppSettingsManager.GetValue("Testing.Path") + "/MFinance/GLForm/TestData/BatchExportFloatTest.csv"; TestFile = Path.GetFullPath(TestFile); Assert.IsTrue(File.Exists(TestFile), "File does not exist: " + TestFile); txtFilename.Properties.Text = TestFile + ".new"; ModalFormHandler = delegate(string name2, IntPtr hWnd2, Form form2) { MessageBoxTester tester2 = new MessageBoxTester(hWnd2); // Assert.AreEqual("Success", tester.Title); tester2.SendCommand(MessageBoxTester.Command.OK); }; frmBatchExport.ExportBatches(false); Assert.AreEqual(true, TTextFile.SameContent(TestFile, TestFile + ".new"), "the files should be the same: " + TestFile); System.IO.File.Delete(TestFile + ".new"); // Test export of batches, summarizing the transactions TestFile = TAppSettingsManager.GetValue("Testing.Path") + "/MFinance/GLForm/TestData/BatchExportFloatTestSummary.csv"; TestFile = Path.GetFullPath(TestFile); Assert.IsTrue(File.Exists(TestFile), "File does not exist: " + TestFile); txtFilename.Properties.Text = TestFile + ".new"; rbtSummary.Properties.Checked = true; ModalFormHandler = delegate(string name2, IntPtr hWnd2, Form form2) { MessageBoxTester tester2 = new MessageBoxTester(hWnd2); // Assert.AreEqual("Success", tester.Title); tester2.SendCommand(MessageBoxTester.Command.OK); }; frmBatchExport.ExportBatches(false); Assert.AreEqual(true, TTextFile.SameContent(TestFile, TestFile + ".new"), "the files should be the same: " + TestFile); System.IO.File.Delete(TestFile + ".new"); frmBatchExport.Close(); }
/// <summary> /// remove all strings from po file that are listed in the "Do Not Translate" file /// </summary> /// <param name="ADoNotTranslatePath"></param> /// <param name="ATranslationFile"></param> public static void RemoveUnwantedStringsFromTranslation(string ADoNotTranslatePath, string ATranslationFile) { StringCollection DoNotTranslate = GetDoNotTranslateStrings(ADoNotTranslatePath); StreamReader sr = new StreamReader(ATranslationFile); Encoding enc = new UTF8Encoding(false); StreamWriter sw = new StreamWriter(ATranslationFile + ".new", false, enc); //create a template in which all the source links are contained StreamWriter sw_all = new StreamWriter(ATranslationFile + ".withallsources", false, enc); string line = sr.ReadLine(); int counter = 0; while (line != null) { counter++; if (!line.StartsWith("msgid")) { sw_all.WriteLine(line); sw.WriteLine(line); line = sr.ReadLine(); //get the empty line if (line != null) { if (line.Contains("todoComment")) { //Console.WriteLine("here"); } while (line.StartsWith("#.") && !line.Contains("todoComment")) //take over the comments(if they exist) { string line_part1 = AdaptString(line, "_ "); string line_part2 = AdaptString(line_part1, "<summary>"); string line_part3 = AdaptString(line_part2, "</summary>"); sw_all.WriteLine(line_part3); sw.WriteLine(line_part3); line = sr.ReadLine(); } if (line.StartsWith("#:")) //take over the first source code line (if it exists) { sw_all.WriteLine(line); if (line.Contains("GenerateI18N.CollectedGettext.cs")) { sw.WriteLine("#: - This item was created automatically from a designer file"); line = sr.ReadLine(); } else { string currentLine = line; line = sr.ReadLine(); if (line.StartsWith("#:")) { sw.WriteLine( currentLine + " (first of several occurrences - the whole list can be found in i8n/template.pot.withallsources)"); } else { sw.WriteLine(currentLine); } } } while (line.StartsWith("#:") || line.StartsWith("#,")) //ignore all other source code lines { sw_all.WriteLine(line); line = sr.ReadLine(); } if (line.Contains("todoComment")) { line = sr.ReadLine(); //ignore todoComment } } } else if ((line != null) && line.StartsWith("msgid")) { if (line.Contains("Maintain Month Names for Different Languages")) { // Console.WriteLine("here"); } StringCollection OriginalLines; string messageId = TPoFileParser.ParsePoLine(sr, ref line, out OriginalLines); if (DoNotTranslate.Contains(messageId)) { if (!line.StartsWith("msgstr")) { throw new Exception("did expect msgstr in the line"); } TPoFileParser.ParsePoLine(sr, ref line, out OriginalLines); } else { foreach (string s in OriginalLines) { sw_all.WriteLine(s); sw.WriteLine(s); } } } } sr.Close(); sw_all.Close(); sw.Close(); TTextFile.UpdateFile(ATranslationFile); ReviewTemplateFile(ATranslationFile); }
/// <summary> /// This is the main routine that does the work /// </summary> private void BtnOK_Click(object sender, EventArgs e) { // Enforce some validation rules if (txtExtractName.Text.Trim().Length == 0) { MessageBox.Show(Catalog.GetString("Please enter a name for the extract."), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (TRemote.MPartner.Partner.WebConnectors.ExtractExists(txtExtractName.Text)) { MessageBox.Show(Catalog.GetString("An extract with this name already exists. Please enter a new name."), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Stop); return; } // Import the text string importString = null; if (rbtClipboard.Checked) { // Import from the clipboard importString = Clipboard.GetText(TextDataFormat.UnicodeText); if ((importString == null) || (importString.Length == 0)) { MessageBox.Show(Catalog.GetString("Please first copy data from your spreadsheet application!"), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } else { // Import from the specified file string pathToFile = txtFileName.Text; if (!File.Exists(pathToFile)) { MessageBox.Show(Catalog.GetString( "Cannot find the file to import from."), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } string extension = Path.GetExtension(pathToFile); if (".txt.csv.".Contains(extension + ".") == false) { MessageBox.Show(Catalog.GetString("You must choose either a text or CSV file with a file extension of .txt or .csv"), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } System.Text.Encoding FileEncoding = TTextFile.GetFileEncoding(pathToFile); // // If it failed to open the file, GetFileEncoding returned null. if (FileEncoding == null) { MessageBox.Show(Catalog.GetString("Could not open the file."), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } StreamReader reader = new StreamReader(pathToFile, FileEncoding, false); while (!reader.EndOfStream) { importString = reader.ReadToEnd(); } reader.Close(); if (importString.Length == 0) { MessageBox.Show(Catalog.GetString("The file was empty!"), this.Text, MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } // So we know we have some text rather than an empty string // The partner keys must be the first column of a row List <Int64> partnerKeyList = new List <Int64>(); string[] rows = importString.Split('\n'); for (int i = 0; i < rows.Length; i++) { string row = rows[i].TrimEnd('\r'); if ((row.Length == 0) || row.StartsWith("#") || row.StartsWith("/*") || row.StartsWith(";")) { // Empty line or a comment continue; } // The row has some length. Columns can be separated by tab, comma or semicolon // Partner key must be in the first column string[] cols = row.Split(new char[] { '\t', ',', ';' }); Int64 partnerKey; // See if it is a number (remove any quotes around the string first) if (Int64.TryParse(cols[0].Replace("\"", ""), out partnerKey) && (partnerKey != 0)) { partnerKeyList.Add(partnerKey); } } if (MessageBox.Show(string.Format(Catalog.GetString("Found {0} partners to import. Continue?"), partnerKeyList.Count), this.Text, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.No) { return; } // Convert our list to a datatable DataTable table = new DataTable(); table.Columns.Add("Key", typeof(System.Int64)); foreach (Int64 item in partnerKeyList) { DataRow dr = table.NewRow(); dr[0] = item; table.Rows.Add(dr); } // Call the main method. If it succeeds we can close bool bSuccess = false; try { this.Cursor = Cursors.WaitCursor; Application.DoEvents(); bSuccess = TPartnerExtractsMain.CreateNewExtractFromPartnerKeys(txtExtractName.Text, txtExtractDescription.Text, table, 0, chkExcludeInactive.Checked, chkExcludeNonMailing.Checked, chkExcludeNoSolicitations.Checked, this); } finally { this.Cursor = Cursors.Default; } if (bSuccess) { Close(); } }
/// <summary> /// common procedure that will load all settings in the given directory, and run a report and /// compare the result with results /// from previous, using the csv and the txt output /// </summary> public void TestReport(String ASettingsDirectory) { String[] fileEntries; string fileName; if (!Directory.Exists(".." + System.IO.Path.DirectorySeparatorChar + ".." + System.IO.Path.DirectorySeparatorChar + "Reporting" + System.IO.Path.DirectorySeparatorChar + "TestData" + System.IO.Path.DirectorySeparatorChar + ASettingsDirectory)) { TLogging.Log("Test for " + ASettingsDirectory + " does not exist yet!"); return; } try { /* get all xml files in the given directory (assume we are starting it from testing\_bin\debug */ fileEntries = Directory.GetFiles(PathToTestData + ASettingsDirectory, "*.xml"); foreach (string s in fileEntries) { fileName = s.Substring(0, s.IndexOf(".xml")); System.Console.Write(Path.GetFileName(fileName) + ' '); FCalculator.ResetParameters(); FCalculator.GetParameters().Load(fileName + ".xml"); if (FCalculator.GenerateResultRemoteClient()) { FCalculator.GetResults().WriteBinaryFile(FCalculator.GetParameters(), "report.bin"); FCalculator.GetParameters().Save( PathToTestData + ASettingsDirectory + System.IO.Path.DirectorySeparatorChar + "LogParametersAfterCalc.log", true); FCalculator.GetResults().WriteCSV( FCalculator.GetParameters(), PathToTestData + ASettingsDirectory + System.IO.Path.DirectorySeparatorChar + "LogResults.log", "FIND_BEST_SEPARATOR", true); if (!System.IO.File.Exists(fileName + ".csv")) { /* create a new reference file */ FCalculator.GetResults().WriteCSV(FCalculator.GetParameters(), fileName + ".csv"); } else { FCalculator.GetResults().WriteCSV(FCalculator.GetParameters(), fileName + ".csv.new"); } if (!System.IO.File.Exists(fileName + ".txt")) { /* create a new reference file */ PrintTxt(FCalculator.GetResults(), FCalculator.GetParameters(), fileName + ".txt"); } else { PrintTxt(FCalculator.GetResults(), FCalculator.GetParameters(), fileName + ".txt.new"); } if (System.IO.File.Exists(fileName + ".csv.new")) { /* compare the files */ Assert.AreEqual(true, TTextFile.SameContent(fileName + ".csv", fileName + ".csv.new"), "the csv files should be the same: " + fileName); System.IO.File.Delete(fileName + ".csv.new"); } if (System.IO.File.Exists(fileName + ".txt.new")) { /* compare the files */ /* requires compilation with directive TESTMODE being set, so that the date of the report printout is constant */ // TODO: ignore the date, and also ignore the version number // TODO: define sections which should be compared, and which should be ignored. Overwrite with blanks? Assert.AreEqual(true, TTextFile.SameContent(fileName + ".txt", fileName + ".txt.new"), "the txt files should be the same: " + fileName); System.IO.File.Delete(fileName + ".txt.new"); } /* todo: test if something was written to the log file (e.g. parameter not found, etc); */ /* make a copy of the file before running the report, and compare with the new version */ /* this proves difficult, because it runs against the server */ /* once the progress of the report is fed back, we can compare the two output files */ /* test if there is a detail report */ if (FCalculator.GetParameters().Exists("param_detail_report_0") == true) { TestDetailReport(PathToTestData + ASettingsDirectory + System.IO.Path.DirectorySeparatorChar, PathToSettingsData); } } else { Assert.Fail("Report calculation did not finish, was cancelled on the server"); } } } catch (Exception e) { if (e.GetType() != typeof(NUnit.Framework.AssertionException)) { System.Console.WriteLine(e.Message); System.Console.WriteLine(e.StackTrace); } throw; } }
public void TestAdjustGiftBatch() { int GiftBatchNumber = ImportAndPostGiftBatch(); TGet_GLM_Info getGLM_InfoBeforeTest73 = new TGet_GLM_Info(FLedgerNumber, "0200", "7300"); TGet_GLM_Info getGLM_InfoBeforeTest35 = new TGet_GLM_Info(FLedgerNumber, "0200", "3500"); string formletterTemplateFile = TAppSettingsManager.GetValue("ReceiptTemplate.file", "../../csharp/ICT/Testing/lib/MFinance/SampleData/AnnualReceiptTemplate.html"); Encoding encodingOfHTMLfile = TTextFile.GetFileEncoding(formletterTemplateFile); StreamReader sr = new StreamReader(formletterTemplateFile, encodingOfHTMLfile, false); string FileContent = sr.ReadToEnd(); sr.Close(); string receiptsBefore; string receiptsPDF; TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber, "Annual", new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent, null, String.Empty, null, String.Empty, "de-DE", out receiptsPDF, out receiptsBefore); Assert.AreNotEqual(0, receiptsBefore.Trim().Length, "old receipt must not be empty"); int AdjustBatchNumber; TAdjustmentWebConnector.GiftRevertAdjust(FLedgerNumber, GiftBatchNumber, -1, false, -1, DateTime.Today, GiftAdjustmentFunctionEnum.AdjustGift, false, -1.0m, out AdjustBatchNumber); bool BatchIsUnposted; string CurrencyCode; GiftBatchTDS BatchTDS = TGiftTransactionWebConnector.LoadGiftTransactionsForBatch( FLedgerNumber, AdjustBatchNumber, out BatchIsUnposted, out CurrencyCode); // find the transaction to modify Int32 ToModify = (BatchTDS.AGiftDetail[1].GiftTransactionNumber == 2)?1:0; // change the amount from 20 to 25 BatchTDS.AGiftDetail[ToModify].GiftTransactionAmount = 25; // the money should go to field 35 instead of field 73 BatchTDS.AGiftDetail[ToModify].RecipientKey = 35000000; // TODO change of donor // BatchTDS.Gift[1].DonorKey = TVerificationResultCollection VerificationResult; if (TGiftTransactionWebConnector.SaveGiftBatchTDS(ref BatchTDS, out VerificationResult) != TSubmitChangesResult.scrOK) { Assert.Fail("Adjustment Gift Batch was not saved: " + VerificationResult.BuildVerificationResultString()); } int generatedGlBatchNumber; if (!TGiftTransactionWebConnector.PostGiftBatch(FLedgerNumber, AdjustBatchNumber, out generatedGlBatchNumber, out VerificationResult)) { Assert.Fail("Adjustment Gift Batch was not posted: " + VerificationResult.BuildVerificationResultString()); } TGet_GLM_Info getGLM_InfoAfterTest73 = new TGet_GLM_Info(FLedgerNumber, "0200", "7300"); TGet_GLM_Info getGLM_InfoAfterTest35 = new TGet_GLM_Info(FLedgerNumber, "0200", "3500"); // Test balance on the related account/Costcentre Assert.AreEqual(getGLM_InfoBeforeTest73.YtdActual - 20, getGLM_InfoAfterTest73.YtdActual, "The amount of 20 should be derived from the 73 costcentre"); Assert.AreEqual(getGLM_InfoBeforeTest35.YtdActual + 25, getGLM_InfoAfterTest35.YtdActual, "The amount of 25 should be added to the 35 costcentre"); // Test the number of rows on the gift receipt. // the difference should be 3 lines removed, 3 lines added. no double donations. string receiptsAfter; TReceiptingWebConnector.CreateAnnualGiftReceipts(FLedgerNumber, "Annual", new DateTime(DateTime.Today.Year, 1, 1), new DateTime(DateTime.Today.Year, 12, 31), FileContent, null, String.Empty, null, String.Empty, "de-DE", out receiptsPDF, out receiptsAfter); receiptsBefore = THttpBinarySerializer.DeserializeFromBase64(receiptsBefore); receiptsAfter = THttpBinarySerializer.DeserializeFromBase64(receiptsAfter); TLogging.Log("TestAdjustGiftBatch Diff:"); TLogging.Log(TTextFile.Diff(receiptsBefore, receiptsAfter)); string[] diff = TTextFile.Diff(receiptsBefore, receiptsAfter).Trim().Split(Environment.NewLine); Assert.AreEqual(6, diff.Length, "difference on receipts are 6 lines"); }
/// <summary> /// read the designer file and add the strings to the main file /// </summary> /// <param name="AMainFilename"></param> /// <param name="ADataDefinitionStore"></param> /// <param name="ADbHelpTranslationWriter">dummy cs file that is used to provide the strings to gettext</param> /// <returns>true if the file should be parsed for translatable strings</returns> public static bool Execute(string AMainFilename, TDataDefinitionStore ADataDefinitionStore, StreamWriter ADbHelpTranslationWriter) { string DesignerFileName = GetDesignerFilename(AMainFilename); StreamReader readerDesignerFile = null; StreamWriter writer = null; if (AMainFilename.EndsWith(".Designer.cs") || AMainFilename.EndsWith("AssemblyInfo.cs")) { return(false); } if (File.Exists(Path.GetDirectoryName(AMainFilename) + Path.DirectorySeparatorChar + System.IO.Path.GetFileNameWithoutExtension(AMainFilename.Replace("-generated", string.Empty)) + ".yaml")) { // do not generate translation code for already generated files; // but still let gettext parse this file for Catalog.GetString return(true); } if (AMainFilename.Contains("-generated.")) { // do not generate translation code for already generated files return(false); } if (File.Exists(DesignerFileName)) { readerDesignerFile = new StreamReader(DesignerFileName); writer = new StreamWriter(AMainFilename + ".new"); } StreamReader readerMainFile = new StreamReader(AMainFilename); // find the call to InitializeComponent string line = ""; bool ContainsCatalogGetStringCall = false; while (!readerMainFile.EndOfStream && !line.Contains("InitializeComponent();")) { line = readerMainFile.ReadLine(); CheckLineAndAddDBHelp(line, ADataDefinitionStore, ADbHelpTranslationWriter); if (line.Contains("Catalog.GetString")) { ContainsCatalogGetStringCall = true; } if (writer != null) { writer.WriteLine(line); } } if (readerDesignerFile == null) { // this is just a normal code file without designer code if (!readerMainFile.EndOfStream) { // TODO: be more strict with missing designer file! //readerMainFile.Close(); //throw new Exception("the file " + AMainFilename + " should have a designer file!"); Console.WriteLine("the file " + AMainFilename + " should have a designer file!"); } readerMainFile.Close(); return(ContainsCatalogGetStringCall); } if (readerMainFile.EndOfStream) { readerMainFile.Close(); readerDesignerFile.Close(); writer.Close(); throw new Exception("Problem: cannot find InitializeComponent in " + AMainFilename); } string identation = "".PadLeft(line.IndexOf("InitializeComponent()")); writer.WriteLine(identation + "#region CATALOGI18N"); // empty line for uncrustify writer.WriteLine(); writer.WriteLine( identation + "// this code has been inserted by GenerateI18N, all changes in this region will be overwritten by GenerateI18N"); // parse the designer files and insert all labels etc into the main file while (!readerDesignerFile.EndOfStream) { string designerLine = readerDesignerFile.ReadLine(); // catch all .Text = , but also TooltipsText = , but ignore lblSomethingText = new ... if (designerLine.Contains("Text = \"")) { bool trailingColon = false; string content = designerLine.Substring( designerLine.IndexOf("\"") + 1, designerLine.LastIndexOf("\"") - designerLine.IndexOf("\"") - 1); if (content.EndsWith(":")) { trailingColon = true; content = content.Substring(0, content.Length - 1); } // see also FormWriter.cs, SetControlProperty; it also calls ProperI18NCatalogGetString try { if (TFormWriter.ProperI18NCatalogGetString(content)) { writer.WriteLine(identation + designerLine.Substring(0, designerLine.IndexOf(" = ")).Trim() + " = Catalog.GetString(\"" + content + "\")" + (trailingColon ? " + \":\"" : string.Empty) + ";"); ADbHelpTranslationWriter.WriteLine("Catalog.GetString(\"" + content + "\");"); } } catch (Exception e) { if (e.Message == "Problem with \\r or \\n") { throw new Exception("Problem with \\r or \\n in file " + DesignerFileName + ": " + designerLine); } else { throw; } } } } writer.WriteLine(identation + "#endregion"); readerDesignerFile.Close(); bool skip = false; while (!readerMainFile.EndOfStream) { line = readerMainFile.ReadLine(); if (line.Trim().StartsWith("#region CATALOGI18N")) { skip = true; } if (!skip) { CheckLineAndAddDBHelp(line, ADataDefinitionStore, ADbHelpTranslationWriter); writer.WriteLine(line); } if (skip && line.Trim().StartsWith("#endregion")) { skip = false; } } writer.Close(); readerMainFile.Close(); TTextFile.UpdateFile(AMainFilename, true); return(true); }
/// <summary> /// add new translations to the po file /// </summary> public static void WriteUpdatedPoFile(string APoFilePath, SortedList <string, string> ANewTranslations) { List <string> pofile = new List <string>(); if (ANewTranslations.Keys.Count > 0) { TLogging.Log("updating " + APoFilePath); // parse the whole po file StreamReader sr = new StreamReader(APoFilePath); Encoding enc = new UTF8Encoding(false); StreamWriter sw = new StreamWriter(APoFilePath + ".new", false, enc); string line = sr.ReadLine(); while (line != null) { if (line.StartsWith("msgid \"")) { StringCollection OriginalLines; string messageId = TPoFileParser.ParsePoLine(sr, ref line, out OriginalLines); if (pofile.Contains(messageId)) { // ignore this instance TPoFileParser.ParsePoLine(sr, ref line, out OriginalLines); TLogging.Log("duplicate messageid: " + messageId); } else { pofile.Add(messageId); } foreach (string s in OriginalLines) { sw.WriteLine(s); } if (ANewTranslations.ContainsKey(messageId)) { // skip msgstr line TPoFileParser.ParsePoLine(sr, ref line, out OriginalLines); sw.WriteLine(String.Format("msgstr \"{0}\"", ANewTranslations[messageId])); ANewTranslations.Remove(messageId); } } else { sw.WriteLine(line); line = sr.ReadLine(); } } sr.Close(); sw.Close(); TTextFile.UpdateFile(APoFilePath); foreach (string key in ANewTranslations.Keys) { TLogging.Log("Warning: cannot find in po file: " + key); } } }