static void Main(string[] args) { var reportsExporter = new ReportsExporter(); var importer = new CSVImporter(File.ReadLines(FileName).Skip(1), new[] { reportsExporter }); if (!importer.Import()) { System.Console.WriteLine($"Struggling to import file(s) {FileName}"); return; } var reports = reportsExporter.GetReportService(); System.Console.WriteLine($"Top {NumberOfPopularItems} popular items."); foreach (var product in reports.TopMostPopularProducts(NumberOfPopularItems)) { System.Console.WriteLine($"Item Code - {product.ItemCode} | Price - {product.Price:C} | Description - {product.Description}"); } System.Console.WriteLine($"Average order value - {reports.AverageOrderValue()}"); System.Console.WriteLine(); System.Console.WriteLine($"Total value of discounts after {DiscountPercentage}% discount for item {DiscountedItem} - {reports.TotalValueOfDiscountsIssuedIfForProduct(DiscountedItem, DiscountPercentage)}"); System.Console.WriteLine(); System.Console.WriteLine($"Press any key to exit."); System.Console.ReadLine(); }
public void SetParameter(String key, Object parameter) { switch (key) { case "CSVImporter": { _csvImporter = parameter as CSVImporter; break; } case "ImportHeaders": { List <string> importHeaders = parameter as List <string>; ObservableCollection <string> headers = new ObservableCollection <string>(); foreach (string curHeader in importHeaders) { headers.Add(curHeader); } ImportHeaders = headers; break; } case "StandardFields": { List <StandardFieldAttribute> standardFields = parameter as List <StandardFieldAttribute>; ObservableCollection <StandardFieldAttribute> fields = new ObservableCollection <StandardFieldAttribute>(); foreach (StandardFieldAttribute curField in standardFields) { fields.Add(curField); } StandardFields = fields; break; } } }
public async Task CreateVaultExportThenImport() { Vault sourceVault = new Vault(); int count = 5000; for (int i = 0; i < count; i++) { Credential credential = CredentialTests.CreateRandomCredential(_rng); credential.AddToVault(sourceVault, false); } VaultExporter exporter = new VaultExporter( Common.ExportFormat.cachyCSV1_0, Common.ExportWrapping.Raw); byte[] csv = exporter.Export(sourceVault); string csvString = System.Text.Encoding.UTF8.GetString(csv); Vault destVault = new Vault(); CSVImporter importer = new CSVImporter(csvString); await importer.ImportToVault(destVault, VaultExporter.GetFieldMappings()); for (int i = 0; i < count; i++) { Credential sourceCredential = sourceVault.Credentials[i]; Credential destCredential = destVault.Credentials[i]; Assert.IsTrue(sourceCredential.SimpleCompare(destCredential) == 0); } }
/// <summary> /// Raises the activated event when the Import menu item is invoked. /// </summary> /// <param name='sender'> /// The Gtk.MenuItem. /// </param> /// <param name='args'> /// Arguments. /// </param> void OnImportActivated(object sender, EventArgs args) { var fc = new Gtk.FileChooserDialog("Choose a file to import", null, Gtk.FileChooserAction.Open, "Cancel", Gtk.ResponseType.Cancel, "Import", Gtk.ResponseType.Accept); try { fc.SetCurrentFolder("/media/LocalD/SolidProject/Tools/DataMorphose/plugins/ImportExport/test/DemoDB/Text/"); // then create a filter for files. For example .csvdb: // filter is not necessary if you wish to see all files in the dialog Gtk.FileFilter filter = new Gtk.FileFilter(); filter.Name = "CSV database"; filter.AddPattern("*.csvdb"); fc.AddFilter(filter); if (fc.Run() == (int)Gtk.ResponseType.Accept) { CSVImporter importer = new CSVImporter(/*firstRawIsHeader*/ true); DataModel model = morphose.GetModel(); Database db = importer.importDBFromFiles(fc.Filename); model.BeginUpdate(); model.DB = db; model.EndUpdate(); } } finally { fc.Destroy(); } }
static void Main(string[] args) { string filePath = "Examples/CSV/Santander.csv"; CSVImporter importer = new CSVImporter(new System.IO.FileInfo(filePath)); List <Transaction> transactions = SantanderCSVParser.Parse(importer).ToList(); Console.WriteLine($"Found {transactions.Count} transactions"); string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); string fullPath = Path.Combine(path, "SQLite", "budjit.db"); var builder = new DbContextOptionsBuilder <BudjitContext>().UseSqlite($"DataSource={fullPath}"); BudjitContext context = new BudjitContext(builder.Options); context.Database.Migrate(); ITransactionsRepository repo = new TransactionRepository(context); repo.Create(transactions); List <Transaction> databaseTransactions = repo.GetAll().ToList(); int count = 1; foreach (Transaction trans in databaseTransactions) { Console.WriteLine($"{count} - {trans.Description}"); count++; } Console.ReadLine(); }
public TemperatureProfilePresenter([NotNull] ApplicationPresenter applicationPresenter, [NotNull] TemperatureProfileView view, [NotNull] TemperatureProfile tp) : base(view, "ThisProfile.HeaderString", tp, applicationPresenter) { _applicationPresenter = applicationPresenter; _tp = tp; _csvImporter = new CSVImporter(true); }
public void GivenANumberOfSalesTransactionsForMultipleOrdersWhenImportedThenAListOfOrdersAndProductsShouldBeCorrectlyBuilt() { var mockExporter = new Mock <IExporter>(); var exportedOrders = new Order[] { }; var exportedProducts = new Product[] { }; mockExporter .Setup(exporter => exporter.Export(It.IsNotNull <Order[]>(), It.IsNotNull <Product[]>())) .Returns(true) .Callback <Order[], Product[]>((orders, products) => { exportedOrders = orders; exportedProducts = products; }); var csvImporter = new CSVImporter(new[] { "2470,29/05/2016,GROBI4014501,Groovi Baby Plate A6 Large Bird & Branch,4.79,1", "2471,29/05/2016,COLLCEM12,Collall Photoglue,2.99,4" }, new[] { mockExporter.Object }); var wasImportSuccessful = csvImporter.Import(); Assert.IsTrue(wasImportSuccessful); Assert.AreEqual(2, exportedOrders.Length); Assert.AreEqual("2470", exportedOrders[0].Id); Assert.AreEqual(1, exportedOrders[0].Transactions.Length); Assert.AreEqual(new DateTime(2016, 05, 29), exportedOrders[0].Transactions[0].Timestamp); Assert.AreEqual(1, exportedOrders[0].Transactions[0].Quantity); Assert.AreEqual("GROBI4014501", exportedOrders[0].Transactions[0].Product.ItemCode); Assert.AreEqual(4.79m, exportedOrders[0].Transactions[0].Product.Price); Assert.AreEqual("Groovi Baby Plate A6 Large Bird & Branch", exportedOrders[0].Transactions[0].Product.Description); Assert.AreEqual("2471", exportedOrders[1].Id); Assert.AreEqual(1, exportedOrders[1].Transactions.Length); Assert.AreEqual(new DateTime(2016, 05, 29), exportedOrders[1].Transactions[0].Timestamp); Assert.AreEqual(4, exportedOrders[1].Transactions[0].Quantity); Assert.AreEqual("COLLCEM12", exportedOrders[1].Transactions[0].Product.ItemCode); Assert.AreEqual(2.99m, exportedOrders[1].Transactions[0].Product.Price); Assert.AreEqual("Collall Photoglue", exportedOrders[1].Transactions[0].Product.Description); Assert.AreEqual(2, exportedProducts.Length); Assert.AreEqual("GROBI4014501", exportedProducts[0].ItemCode); Assert.AreEqual(4.79m, exportedProducts[0].Price); Assert.AreEqual("Groovi Baby Plate A6 Large Bird & Branch", exportedProducts[0].Description); Assert.AreEqual("COLLCEM12", exportedProducts[1].ItemCode); Assert.AreEqual(2.99m, exportedProducts[1].Price); Assert.AreEqual("Collall Photoglue", exportedProducts[1].Description); mockExporter.VerifyAll(); }
static void Main(string[] args) { var csvImporter = new CSVImporter<Customer>(); var customers = csvImporter.Extract("..\\..\\sample.csv"); foreach (var c in customers) { Console.WriteLine("Customer({0}) : {1} lives at {2}",c.Id,c.Name,c.Address); } }
void LoadAdventurers() { List <AdventurerData> adventurerInfo = CSVImporter.GenerateList <AdventurerData>(ADVENTURER_INFO_PATH); for (int i = 0; i < adventurerInfo.Count; i++) { string creatureID = adventurerInfo[i].name; adventurerList[creatureID] = adventurerInfo[i]; } }
void LoadRooms() { List <RoomData> roomInfo = CSVImporter.GenerateList <RoomData> (ROOM_INFO_PATH); for (int i = 0; i < roomInfo.Count; i++) { string roomID = roomInfo [i].room_name; roomList [roomID] = roomInfo [i]; } }
public void Setup() { this.service = Substitute.For <FakeAlarmService>(); this.importer = new CSVImporter(this.service); this.importContext = new ImportContext { CaptionFormat = "{0}", CaptionPatterns = new [] { "\\W+" }, DateFormat = "dd.MM.yyyy HH:mm" }; }
void LoadNames() { List <NameData> nameInfo = CSVImporter.GenerateList <NameData> (NAME_INFO_PATH); for (int i = 0; i < nameInfo.Count; i++) { string nameID = nameInfo [i].title; nameList [nameID] = nameInfo [i]; } }
public TimeProfilePresenter([NotNull] ApplicationPresenter applicationPresenter, [NotNull] TimeProfileView view, [NotNull] TimeBasedProfile tp) : base(view, "ThisProfile.HeaderString", tp, applicationPresenter) { _tp = tp; _csvImporter = new CSVImporter(false); _usedIns = new ObservableCollection <UsedIn>(); TimeProfileTypes.Add(TimeProfileType.Relative); TimeProfileTypes.Add(TimeProfileType.Absolute); RefreshUsedIn(); }
void LoadAmmoData() { _ammoDataList = CSVImporter.GenerateList <AmmoData>(AssetBundleSync.Instance.GetFile(AMMO_FILE_PATH)); /* * for (int i = 0; i < _ammoList.Count; i++) * { * Debug.Log(_ammoList[i].Type + " " + _ammoList[i].Cost); * } */ }
public override string CSVFromDataTable(DataTable dt) { // We ignore the data table passed in - we have our data from Matches, which was initialized in CanParse. IEnumerable <CustomPropertyType> rgcpt = CustomPropertyType.GetCustomPropertyTypes(); // Build up the list of RosterBuster objects first List <RosterBuster> lstRb = new List <RosterBuster>(); foreach (Match ctMatch in Matches) { GroupCollection gc = ctMatch.Groups; try { DateTime dtStart = Convert.ToDateTime(gc["StartDate"].Value, CultureInfo.CurrentCulture); DateTime dtEnd = Convert.ToDateTime(gc["EndDate"].Value, CultureInfo.CurrentCulture); int hStart = Convert.ToInt32(gc["startZ"].Value.Substring(0, 2), CultureInfo.InvariantCulture); int mStart = Convert.ToInt32(gc["startZ"].Value.Substring(2, 2), CultureInfo.InvariantCulture); int hEnd = Convert.ToInt32(gc["endZ"].Value.Substring(0, 2), CultureInfo.InvariantCulture); int mEnd = Convert.ToInt32(gc["endZ"].Value.Substring(2, 2), CultureInfo.InvariantCulture); DateTime dtStartUtc = new DateTime(dtStart.Year, dtStart.Month, dtStart.Day, hStart, mStart, 0, DateTimeKind.Utc); DateTime dtEndUtc = new DateTime(dtStart.Year, dtStart.Month, dtStart.Day, hEnd, mEnd, 0, DateTimeKind.Utc); if (dtEndUtc.CompareTo(dtStartUtc) < 0) { dtEndUtc = dtEndUtc.AddDays(1); } lstRb.Add(new RosterBuster() { FlightDate = dtStart, FlightNumber = gc["FlightNum"].Value, BlockOut = dtStartUtc, BlockIn = dtEndUtc, Route = gc["route"].Value, TimeZone = gc["Timezone"].Value }); } catch (FormatException) { } } using (DataTable dtDst = new DataTable()) { dtDst.Locale = CultureInfo.CurrentCulture; CSVImporter.InitializeDataTable(dtDst); foreach (RosterBuster rb in lstRb) { CSVImporter.WriteEntryToDataTable(rb.ToLogbookEntry(), dtDst); } return(CsvWriter.WriteToString(dtDst, true, true)); } }
static void Main(string[] args) { List <GoodreadsItem> items = new CSVImporter().ImportItems(@"C:\Users\trmo\OneDrive - ViaUC\Courses\DBS\Session 6 - DQL - Data Query Language (SQL)\goodreads_library_export.csv"); DataBaseModelContainer container = new Converter().Convert(items); new GenreImporter().AddGenres(container.Books); new SQLExporter().Export(container); // GenreImporter genreImporter = new GenreImporter(); // genreImporter.FetchOneByOne(); }
public async void OnClosePopup(View item, object parameter) { if (item is SelectImportSourceView) { if (parameter != null) { Dictionary <string, object> parameters = parameter as Dictionary <string, object>; if (parameters != null) { CSVImporter csvImporter = (CSVImporter)parameters["CSVImporter"]; ImportSource importSource = (ImportSource)parameters["ImportSource"]; if (importSource.Format != Common.CSVFormat.Unknown) { List <ImportFieldMapping> mappings = CSVImporter.CreateMappings(importSource.Format); await csvImporter.ImportToVault(Vault, mappings); } else { App.Controller.ShowPopup( "vault.importmap", new KeyValuePair <string, object>("CSVImporter", csvImporter), new KeyValuePair <string, object>("ImportHeaders", csvImporter.Headers), new KeyValuePair <string, object>("StandardFields", Credential.StandardFields)); } } } } else if (item is ImportMappingView) { Dictionary <string, object> parameters = parameter as Dictionary <string, object>; if (parameters != null) { CSVImporter csvImporter = (CSVImporter)parameters["CSVImporter"]; List <ImportFieldMapping> mappings = (List <ImportFieldMapping>)parameters["Mappings"]; await csvImporter.ImportToVault(Vault, mappings); } } else if (item is VaultReportView) { string filter = (string)parameter; if (!String.IsNullOrEmpty(filter)) { Entry searchEntry = View.FindByName <Entry>("SearchEntry"); if (searchEntry != null) { searchEntry.Text = "@" + filter; } } } ResetIdleTime(); ClearSelectedCredential(true); NotifyPropertyChanged("FilteredCredentials"); }
public void SplitName() { CSVImporter importer = new CSVImporter(/*isFirstRowHeader*/ true); Table Customers = importer.importFromFile(Path.Combine(filePath, "Customers.txt")); // Split the column CustomerName into First/LastName SplitColumn sc = new SplitColumn(Customers, Customers.Columns[2], /*delimiter*/ ' '); sc.Redo(); Assert.IsTrue(Customers.Columns.Count == 12, "Column count is wrong"); }
public void ImporterUI() { Console.Clear(); Console.WriteLine("Please drag and drop the CSV file for import in this window."); string path = Console.ReadLine(); CSVImporter imp = new CSVImporter(); imp.Import(path); Console.Clear(); MainUI("Import finished."); }
public void DeduceColumnConstraints() { CSVImporter importer = new CSVImporter(/*isFirstRowHeader*/ true); Table table = importer.importFromFile(Path.Combine(filePath, "Categories.txt")); ColumnConstraints columnConstraints = new ColumnConstraints(); columnConstraints.DeducePrimaryKey(table); // We know that the first column Contains is a primary key bool isPrimaryKey = table.Columns[0].Meta.Constraints.ContainsKey(ConstraintKind.PrimaryKey); Assert.IsTrue(isPrimaryKey, "Column 0 not primary key!"); }
public void Expected_ID_Equal_To_Created_Table_ID() { // arrange DataTable dt = new DataTable(); object expected = 2; // act dt = CSVImporter.ConvertCSVtoDataTable("animals.csv"); object actual = dt.Rows[1][0]; // assert Assert.AreEqual(actual, expected); }
public override string CSVFromDataTable(DataTable dt) { // We ignore the data table passed in - we have our data from Matches, which was initialized in PreProcess. using (DataTable dtDst = new DataTable()) { dtDst.Locale = CultureInfo.CurrentCulture; CSVImporter.InitializeDataTable(dtDst); foreach (TASCFlight rb in lstMatches) { CSVImporter.WriteEntryToDataTable(rb.ToLogbookEntry(), dtDst); } return(CsvWriter.WriteToString(dtDst, true, true)); } }
public void ShouldThrowException_WhenFileNotPresent() { string fileLocation = "c:/somerandomfile.csv"; FileInfo fileInfo = new FileInfo(fileLocation); var mockFileAccess = new Mock <IFileAccess>(); mockFileAccess.Setup(x => x.Exists(fileInfo)).Returns(false); var fileAccess = mockFileAccess.Object; CSVImporter importer = new CSVImporter(fileInfo, fileAccess); Assert.ThrowsException <FileNotFoundException>(importer.Import); mockFileAccess.Verify(fa => fa.Exists(fileInfo), Times.AtLeastOnce()); mockFileAccess.Verify(fa => fa.ReadAllText(fileInfo), Times.Never()); }
public void GivenASalesTransactionWithACommaInTheDescriptionWhenImportedThenAListOfOrdersAndProductsShouldBeCorrectlyBuilt() { var mockExporter = new Mock <IExporter>(); var exportedOrders = new Order[] { }; var exportedProducts = new Product[] { }; mockExporter .Setup(exporter => exporter.Export(It.IsNotNull <Order[]>(), It.IsNotNull <Product[]>())) .Returns(true) .Callback <Order[], Product[]>((orders, products) => { exportedOrders = orders; exportedProducts = products; }); var csvImporter = new CSVImporter(new[] { "2508,05/06/2016,GROWO4008609,\"Groovi Border Plate Set Calendar, Relatives & Occasions\",15.99,1" }, new[] { mockExporter.Object }); var wasImportSuccessful = csvImporter.Import(); var order = exportedOrders.Single(); var transactions = order.Transactions; Assert.IsTrue(wasImportSuccessful); Assert.AreEqual("2508", order.Id); Assert.AreEqual(1, order.Transactions.Length); Assert.AreEqual(new DateTime(2016, 06, 05), transactions[0].Timestamp); Assert.AreEqual(1, transactions[0].Quantity); Assert.AreEqual("GROWO4008609", transactions[0].Product.ItemCode); Assert.AreEqual(15.99m, transactions[0].Product.Price); Assert.AreEqual("\"Groovi Border Plate Set Calendar, Relatives & Occasions\"", transactions[0].Product.Description); Assert.AreEqual(1, exportedProducts.Length); Assert.AreEqual("GROWO4008609", exportedProducts[0].ItemCode); Assert.AreEqual(15.99m, exportedProducts[0].Price); Assert.AreEqual("\"Groovi Border Plate Set Calendar, Relatives & Occasions\"", exportedProducts[0].Description); mockExporter.VerifyAll(); }
public void GivenASalesTransactionWithMultilpeQuotesAndCommaInTheDescriptionWhenImportedThenAListOfOrdersAndProductsShouldBeCorrectlyBuilt() { var mockExporter = new Mock <IExporter>(); var exportedOrders = new Order[] { }; var exportedProducts = new Product[] { }; mockExporter .Setup(exporter => exporter.Export(It.IsNotNull <Order[]>(), It.IsNotNull <Product[]>())) .Returns(true) .Callback <Order[], Product[]>((orders, products) => { exportedOrders = orders; exportedProducts = products; }); var csvImporter = new CSVImporter(new[] { "3466,20/11/2016,GROAC40345,\"Groovi, Guard 7\"\" x 7\"\"\",3.79,1" }, new[] { mockExporter.Object }); var wasImportSuccessful = csvImporter.Import(); var order = exportedOrders.Single(); var transactions = order.Transactions; Assert.IsTrue(wasImportSuccessful); Assert.AreEqual("3466", order.Id); Assert.AreEqual(1, order.Transactions.Length); Assert.AreEqual(new DateTime(2016, 11, 20), transactions[0].Timestamp); Assert.AreEqual(1, transactions[0].Quantity); Assert.AreEqual("GROAC40345", transactions[0].Product.ItemCode); Assert.AreEqual(3.79m, transactions[0].Product.Price); Assert.AreEqual("\"Groovi, Guard 7\"\" x 7\"\"\"", transactions[0].Product.Description); Assert.AreEqual(1, exportedProducts.Length); Assert.AreEqual("GROAC40345", exportedProducts[0].ItemCode); Assert.AreEqual(3.79m, exportedProducts[0].Price); Assert.AreEqual("\"Groovi, Guard 7\"\" x 7\"\"\"", exportedProducts[0].Description); mockExporter.VerifyAll(); }
public override string CSVFromDataTable(DataTable dt) { if (dt == null) { throw new ArgumentNullException("dt"); } using (DataTable dtDst = new DataTable()) { dtDst.Locale = dt.Locale; CSVImporter.InitializeDataTable(dtDst); foreach (DataRow dr in dt.Rows) { CrewLogFlight clf = new CrewLogFlight(dr); CSVImporter.WriteEntryToDataTable(clf.ToLogbookEntry(), dtDst); } return(CsvWriter.WriteToString(dtDst, true, true)); } }
public void DeduceColumnType() { CSVImporter importer = new CSVImporter(/*isFirstRowHeader*/ true); Table Categories = importer.importFromFile(Path.Combine(filePath, "Categories.txt")); foreach (Column column in Categories.Columns) { ColumnType.ResolveColumnType(column); } // ID Assert.IsTrue(Categories.Columns[0].Meta.Type == typeof(Int32), "Types differ."); // CategoryName Assert.IsTrue(Categories.Columns[1].Meta.Type == typeof(string), "Types differ."); // Description Assert.IsTrue(Categories.Columns[2].Meta.Type == typeof(string), "Types differ."); // Picture Assert.IsTrue(Categories.Columns[3].Meta.Type == typeof(string), "Types differ."); }
public override string CSVFromDataTable(DataTable dt) { if (dt == null) { throw new ArgumentNullException(nameof(dt)); } using (DataTable dtDst = new DataTable()) { dtDst.Locale = dt.Locale; CSVImporter.InitializeDataTable(dtDst); foreach (DataRow dr in dt.Rows) { MccPilot mcc = new MccPilot(dr); CSVImporter.WriteEntryToDataTable(mcc.ToLogbookEntry(), dtDst); } return(CsvWriter.WriteToString(dtDst, true, true)); } }
public void BuildAvatarLists() { _avatarList = CSVImporter.GenerateList <AvatarItem>(AssetBundleSync.Instance.GetFile(AVATAR_PATH)); _avatarDict = new Dictionary <string, List <AvatarItem> >(); for (int i = 0; i < _avatarList.Count; i++) { if (_avatarDict.ContainsKey(_avatarList[i].Type)) { _avatarDict[_avatarList[i].Type].Add(_avatarList[i]); } else { _avatarDict[_avatarList[i].Type] = new List <AvatarItem>(); _avatarDict[_avatarList[i].Type].Add(_avatarList[i]); } } }
public void ShouldImport_FromValidCSVFile() { string fileLocation = "c:/somerandomfile.csv"; FileInfo fileInfo = new FileInfo(fileLocation); var mockFileAccess = new Mock <IFileAccess>(); mockFileAccess.Setup(x => x.Exists(fileInfo)).Returns(true); mockFileAccess.Setup(x => x.ReadAllText(fileInfo)).Returns(csvData); var fileAccess = mockFileAccess.Object; CSVImporter importer = new CSVImporter(fileInfo, fileAccess); var result = importer.Import(); Assert.AreEqual <string>(csvData, result); mockFileAccess.Verify(fa => fa.Exists(fileInfo), Times.AtLeastOnce()); mockFileAccess.Verify(fa => fa.ReadAllText(fileInfo), Times.Once()); }
public override string CSVFromDataTable(DataTable dt) { if (dt == null) { throw new ArgumentNullException(nameof(dt)); } NormalizeColumnNames(dt); using (DataTable dtDst = new DataTable()) { dtDst.Locale = dt.Locale; CSVImporter.InitializeDataTable(dtDst); foreach (DataRow dr in dt.Rows) { eLogSite els = new eLogSite(dr); CSVImporter.WriteEntryToDataTable(els.ToLogbookEntry(), dtDst); } return(CsvWriter.WriteToString(dtDst, true, true)); } }
public void Setup() { this.service = Substitute.For<FakeAlarmService>(); this.importer = new CSVImporter(this.service); this.importContext = new ImportContext { CaptionFormat = "{0}", CaptionPatterns = new [] { "\\W+" }, DateFormat = "dd.MM.yyyy HH:mm" }; }