Esempio n. 1
0
        public static List <TaskEntity> ReadCsvFile(string FileName)
        {
            List <TaskEntity> result = new List <TaskEntity>();

            try
            {
                using (var reader = new StreamReader(FileName))
                {
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        try
                        {
                            var records = csv.EnumerateRecords(new TaskEntity());
                            foreach (var r in records)
                            {
                                result.Add(r);
                            }
                        }
                        catch (Exception)
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
                Console.WriteLine(e.StackTrace);
            }

            return(result);
        }
Esempio n. 2
0
        public static void EverySecondThursdayoftheWeek()
        {
            string dir = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

            using (var reader = new StreamReader(dir + @"\CSVDatas.csv"))
                using (var csv = new CsvReader(reader))
                {
                    var            record     = new CSVData();
                    var            records    = csv.EnumerateRecords(record);
                    List <CSVData> newRecords = new List <CSVData>();
                    using (var writer = new StreamWriter(dir + @"\CSVDatas_Output.csv"))
                    {
                        foreach (var r in records)
                        {
                            DateTime dateValue;
                            if (!DateTime.TryParse(r.Date, out dateValue))
                            {
                                r.Date = "";
                            }
                            CSVData newRecord = new CSVData();
                            newRecord.Name = r.Name;
                            newRecord.Date = r.Date;
                            newRecords.Add(newRecord);
                        }
                        using (var csv1 = new CsvWriter(writer))
                        {
                            csv1.WriteRecords(newRecords);
                        }
                    }
                }
        }
Esempio n. 3
0
        static void Login()
        {
            Console.WriteLine("Please Enter your Username");
            string username = Console.ReadLine();

            Console.WriteLine("Please Enter your Password");
            string password = Console.ReadLine();

            using (var reader = new StreamReader("../Users.csv"))
                using (var csv = new CsvReader(reader))
                {
                    var record = new Member();
                    csv.Configuration.HasHeaderRecord = false;
                    var records = csv.EnumerateRecords(record);
                    foreach (var r in records)
                    {
                        if (r.Username == username && r.Password == password)
                        {
                            Menu(String.Concat(r.GetType()));
                        }
                        else
                        {
                            Console.WriteLine("Invaild Username or Password try again");
                            Login();
                        }
                    }
                }
        }
        private void _buildPackageFromCsvFile()
        {
            string filePath = EditorUtility.OpenFilePanel("Select CSV file to read", "", "csv");

            if (string.IsNullOrEmpty(filePath))
            {
                Debug.LogWarning("[TextDataPackageInspector] Invalid file path was specified");
                return;
            }

            using (StreamReader csvFileStreamReader = new StreamReader(filePath))
            {
                using (CsvReader csvReader = new CsvReader(csvFileStreamReader, CultureInfo.InvariantCulture))
                {
                    var record  = new TextRecord();
                    var records = csvReader.EnumerateRecords(record);

                    var packageData = _initPackageData();

                    foreach (var currRecord in records)
                    {
                        var parsedData = _getKeyValuePairByLocaleType(currRecord, mCurrSelectedType);

                        packageData.Add(new TextDataPackage.TextDataEntity {
                            mKey = parsedData.Item1, mValue = parsedData.Item2
                        });
                    }

                    mCurrEditedObject.mData = packageData;
                }
            }
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            DbContextOptionsBuilder <ActorContext> optionsBuilder = new DbContextOptionsBuilder <ActorContext>();

            optionsBuilder.UseSqlServer(@"Server=actors-db;Database=Actors;User=sa;Password=Your_password123");

            using (ActorContext context = new ActorContext(optionsBuilder.Options)) {
                context.ChangeTracker.QueryTrackingBehavior = QueryTrackingBehavior.NoTracking;
                context.Database.Migrate();

                Parser.Default.ParseArguments <Options>(args)
                .WithParsed <Options>(o => {
                    if (o.Import)
                    {
                        //import contacts from csv
                        using (StreamReader reader = new StreamReader("/data/name.basics.tsv")) {
                            Configuration config = new Configuration();
                            config.Delimiter     = "\t";

                            int counter = 0;
                            using (CsvReader csv = new CsvReader(reader, config)) {
                                foreach (ActorRecord record in csv.EnumerateRecords(new ActorRecord()))
                                {
                                    Person person = new Person();

                                    //parse csv data
                                    int birthYear = 0;
                                    Int32.TryParse(record.BirthYear, out birthYear);
                                    int deathYear = -1;
                                    Int32.TryParse(record.DeathYear, out deathYear);

                                    if (!context.Persons.Any(x => x.Nconst == record.Nconst))
                                    {
                                        //map csv to models.
                                        person.Nconst    = record.Nconst;
                                        person.Name      = record.PrimaryName;
                                        person.BirthYear = birthYear;
                                        person.DeathYear = deathYear == -1 ? null: (int?)deathYear;

                                        context.Add(person);

                                        //only save after 1000 entries to speed things up a bit.
                                        if (counter % 1000 == 0)
                                        {
                                            context.SaveChanges();
                                            counter = 0;
                                        }
                                        counter += 1;
                                    }
                                }
                            }
                        }

                        //save anything that hasn't been saved yet.
                        context.SaveChanges();
                    }
                });
            }
        }
Esempio n. 6
0
        public async Task PullSODump(string dumpUrl)
        {
            using (var httpClient = new HttpClient())
            {
                var response = await httpClient.GetAsync(dumpUrl);

                response.EnsureSuccessStatusCode();

                using (var stream = await response.Content.ReadAsStreamAsync())
                    using (var reader = new StreamReader(stream))
                        using (var csv = new CsvReader(reader))
                            using (var db = _dbService.GetConnection())
                            {
                                await ResetDumpTable(db);

                                var table = new DataTable();
                                table.Columns.Add("Id", typeof(int));
                                table.Columns.Add("LocaleId", typeof(int));
                                table.Columns.Add("Hash", typeof(string));
                                table.Columns.Add("NormalizedHash", typeof(string));
                                table.Columns.Add("CreationDate", typeof(DateTime));
                                table.Columns.Add("ModifiedDate", typeof(DateTime));
                                table.Columns.Add("LastSeenDate", typeof(DateTime));
                                table.Columns.Add("Translation", typeof(string));
                                table.Columns.Add("TranslationOverride", typeof(string));

                                var str = new SODumpString();

                                foreach (var s in csv.EnumerateRecords(str))
                                {
                                    table.Rows.Add(s.Id,
                                                   s.LocaleId,
                                                   s.Hash,
                                                   s.NormalizedHash,
                                                   s.CreationDate,
                                                   s.ModifiedDate,
                                                   s.LastSeenDate,
                                                   s.Translation == "NULL" ? null : s.Translation,
                                                   s.TranslationOverride == "NULL" ? null : s.TranslationOverride);
                                }

                                var copyDb = (SqlConnection)db.InnerConnection;
                                using (var copy = new SqlBulkCopy(copyDb))
                                {
                                    copy.DestinationTableName = "dbo.SODumpTable";
                                    foreach (DataColumn c in table.Columns)
                                    {
                                        copy.ColumnMappings.Add(new SqlBulkCopyColumnMapping(c.ColumnName, c.ColumnName));
                                    }

                                    copyDb.Open();
                                    copy.WriteToServer(table);
                                }
                            }
            }
        }
        public void Web_Test_FromCsvTestData()
        {
            using (var reader = new StreamReader(Environment.CurrentDirectory + @"\..\..\..\TestDataArtifacts\DummyData.csv"))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    var record  = new User();
                    var records = csv.EnumerateRecords(record);

                    foreach (var columnData in records)
                    {
                        //Populates test data object from csv values
                        User testData = new User()
                        {
                            fname      = columnData.fname.Trim(),
                            lname      = columnData.lname.Trim(),
                            username   = columnData.username.Trim(),
                            password   = columnData.password.Trim(),
                            customer   = columnData.customer.Trim(),
                            role       = columnData.role.Trim(),
                            email      = columnData.email.Trim(),
                            cellnumber = columnData.cellnumber.Trim(),
                        };

                        //Creates a test per iteration
                        var currentTest = Core.ExtentReport.CreateTest(
                            MethodBase.GetCurrentMethod().ToString().Replace("Void", "").Replace("()", ""),
                            "This is a demo test for a basic Web UI test using selenium. <br/> "
                            + "<br/><b>Test data being used: </b><br/>"
                            + " first name = " + testData.fname + "<br/> "
                            + " last name = " + testData.lname + "<br/> "
                            + "username = "******"<br/> "
                            + " password = "******"<br/> "
                            + " customer = " + testData.customer + "<br/> "
                            + " role = " + testData.role + "<br/> "
                            + " email = " + testData.email + "<br/> "
                            + " cell number = " + testData.cellnumber + "<br/> "
                            );

                        //Creates Selenium instance
                        WebUtils seleniumInstance = new WebUtils();

                        //Creates a driver instance & reporting instance
                        AngularJsProtractor angularSystem = new AngularJsProtractor(seleniumInstance, currentTest);

                        angularSystem.WebTablePageInstance.NavigateToWebPage("http://www.way2automation.com/angularjs-protractor/webtables/");
                        angularSystem.WebTablePageInstance.AddUserToTable(testData);
                        angularSystem.WebTablePageInstance.ValidateUserWasAdded(testData, true);

                        //Closes the instance of the driver
                        seleniumInstance.GetDriver.Quit();
                    }
                }
        }
Esempio n. 8
0
 public void InsertByFile(string Chemin)
 {
     using (var reader = new StreamReader(Chemin))
         using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
         {
             var record  = new Pays();
             var records = csv.EnumerateRecords(record);
             foreach (Pays p in records)
             {
                 Insert(p);
             }
         }
 }
Esempio n. 9
0
 private IEnumerable <TRecord> GetRecords <TRecord>(string file)
     where TRecord : new()
 {
     using (var fileStream = File.OpenRead(file))
         using (var textStream = new StreamReader(fileStream))
             using (var csv = new CsvReader(textStream, IMDB_CSV_CONF))
             {
                 foreach (var item in csv.EnumerateRecords(new TRecord()))
                 {
                     yield return(item);
                 }
             }
 }
Esempio n. 10
0
        public void InsertByFile(string Chemin)
        {
            using (var reader = new StreamReader(Chemin))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.Delimiter             = ";";
                    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();

                    var record  = new Pays();
                    var records = csv.EnumerateRecords(record);
                    foreach (Pays pays in records)
                    {
                        Insert(pays);
                    }
                }
        }
Esempio n. 11
0
        public void insertfile(string path, string delimiter)
        {
            using (var reader = new StreamReader("pays.csv"))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.Delimiter             = delimiter;
                    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();

                    Pays record  = new Pays();
                    var  records = csv.EnumerateRecords(record);
                    foreach (Pays r in records)
                    {
                        this.InsertPays(r);
                    }
                }
        }
Esempio n. 12
0
        public void InsertFromCSV(string chemin)
        {
            using (var reader = new StreamReader(chemin))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.Delimiter             = ";";
                    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();
                    var record = new salles();
                    IEnumerable <salles> records = csv.EnumerateRecords(record);

                    foreach (salles salle in records)
                    {
                        insert(salle);
                    }
                }
        }
Esempio n. 13
0
 public void insertfil()
 {
     using (var reader = new StreamReader("pays.csv"))
         using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
         {
             csv.Configuration.Delimiter             = ";";
             csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();
             var record = new Pays();
             IEnumerable <Pays> records = csv.EnumerateRecords(record);
             Console.WriteLine(records);
             foreach (var r in records)
             {
                 insert(r);
             }
         }
 }
Esempio n. 14
0
        public void UnUsedPropertyTest()
        {
            var config = new CsvConfiguration(CultureInfo.InvariantCulture)
            {
                HeaderValidated   = null,
                MissingFieldFound = null,
            };

            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csv = new CsvReader(reader, config))
                        {
                            writer.WriteLine("Id,Name");
                            writer.WriteLine("1,one");
                            writer.WriteLine("2,two");
                            writer.Flush();
                            stream.Position = 0;

                            var record = new UnUsedProperty
                            {
                                Id     = -1,
                                Name   = "-one",
                                UnUsed = "nothing",
                            };

                            var count = 1;
                            foreach (var r in csv.EnumerateRecords(record))
                            {
                                if (count == 1)
                                {
                                    Assert.Equal(1, r.Id);
                                    Assert.Equal("one", r.Name);
                                    Assert.Equal("nothing", r.UnUsed);
                                }
                                else if (count == 2)
                                {
                                    Assert.Equal(2, r.Id);
                                    Assert.Equal("two", r.Name);
                                    Assert.Equal("nothing", r.UnUsed);
                                }

                                count++;
                            }
                        }
        }
        public void InsertFromCSV(string filename)
        {
            using (var reader = new StreamReader(filename))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                csv.Configuration.Delimiter = ";";
                csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();

                var record = new Placement_Obstacle();
                var records = csv.EnumerateRecords(record);

                foreach (Placement_Obstacle r in records)
                {
                    Console.WriteLine(r.Num_placement + "-" + r.Reservation.id + "-" + r.Obstacle.Id);
                    this.Insert(record);
                }
            }
        public void InsertByFile(string chemin)
        {
            using (var reader = new StreamReader(chemin))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.Delimiter             = ";";
                    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();
                    //var records = csv.GetRecords<Pays>();
                    var record  = new Reservation();
                    var records = csv.EnumerateRecords(record);

                    foreach (var item in records)
                    {
                        this.Insert(item);
                    }
                }
        }
Esempio n. 17
0
        public List <WoWItem> ReadWoWCSV(string resourcePath, IProgress <int> progress)
        {
            var assembly      = Assembly.GetExecutingAssembly();
            var resourceName  = resourcePath;
            int recordsLength = 0;

            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (var reader = new StreamReader(stream))
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        var wowItems   = new WoWItem();
                        var allRecords = csv.EnumerateRecords(wowItems);
                        recordsLength = allRecords.Count <WoWItem>();
                    }

            var iterator = 0;

            assembly     = Assembly.GetExecutingAssembly();
            resourceName = resourcePath;
            using (Stream stream = assembly.GetManifestResourceStream(resourceName))
                using (var reader = new StreamReader(stream))
                    using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                    {
                        csv.Read();
                        csv.ReadHeader();

                        var records = new List <WoWItem>();
                        int percentComplete;
                        while (csv.Read())
                        {
                            var wowItemRecords = new WoWItem
                            {
                                Id   = csv.GetField("Id"),
                                Name = csv.GetField("Name")
                            };
                            records.Add(wowItemRecords);
                            iterator++;
                            percentComplete = (iterator * 100) / recordsLength;
                            progress.Report(percentComplete);
                        }
                        percentComplete = 100;
                        progress.Report(percentComplete);
                        return(records);
                    }
        }
Esempio n. 18
0
        public static void LoadData()
        {
            List <SubjectRecord> subjectRecords = new List <SubjectRecord>();

            // Open csv to get subjects
            using (var reader = new StringReader(Properties.Resources.ScheduleOfUndergraduateUnits))
                using (var csv = new CsvReader(reader))
                {
                    var record  = new SubjectRecord();
                    var records = csv.EnumerateRecords(record);
                    foreach (var r in records)
                    {
                        var subjectRecord = (SubjectRecord)r.Clone();
                        subjectRecord.InitialSetup();
                        // Make sure the subject is being offered
                        if (subjectRecord.Actual.Semesters.Any())
                        {
                            // subject codes should be unique - if this code already exists then replace it
                            bool found = false;
                            for (int i = 0; i < subjectRecords.Count; i++)
                            {
                                if (subjectRecords[i].Code == subjectRecord.Code)
                                {
                                    found             = true;
                                    subjectRecords[i] = subjectRecord;
                                    break;
                                }
                            }
                            if (!found)
                            {
                                subjectRecords.Add(subjectRecord);
                            }
                            Debug.Assert(subjectRecords.Count(s => s.Code == subjectRecord.Code) == 1, "the code should appear exactly once");
                        }
                    }
                }

            foreach (SubjectRecord subject in subjectRecords)
            {
                MasterList.AddSubject(subject.Actual);
            }

            Debug.WriteLine("loaded subjects");

            StringBuilder descriptionBuilder = new StringBuilder();
Esempio n. 19
0
        //en commentaire le insertFromCSV


        public void InsertFromCSV(string filename)
        {
            using (var reader = new StreamReader(filename))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.Delimiter             = ";";
                    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();

                    var record  = new Avis();
                    var records = csv.EnumerateRecords(record);

                    foreach (Avis r in records)
                    {
                        Console.WriteLine(r.Id + "---" + r.Note);
                        //this.Insert();
                    }
                }
        }
Esempio n. 20
0
        public void MainCSV()
        {
            using (var reader = new StreamReader("fromages.csv"))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.Delimiter             = ";";
                    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();

                    var record  = new Fromage();
                    var records = csv.EnumerateRecords(record);

                    foreach (var item in records)
                    {
                        this.Insert(item);
                    }
                }
            Console.WriteLine("importation de fromage réussit");
        }
Esempio n. 21
0
        public void UnUsedPropertyTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csv = new CsvReader(reader))
                        {
                            csv.Configuration.Delimiter = ",";
                            writer.WriteLine("Id,Name");
                            writer.WriteLine("1,one");
                            writer.WriteLine("2,two");
                            writer.Flush();
                            stream.Position = 0;

                            csv.Configuration.HeaderValidated   = null;
                            csv.Configuration.MissingFieldFound = null;

                            var record = new UnUsedProperty
                            {
                                Id     = -1,
                                Name   = "-one",
                                UnUsed = "nothing",
                            };

                            var count = 1;
                            foreach (var r in csv.EnumerateRecords(record))
                            {
                                if (count == 1)
                                {
                                    Assert.AreEqual(1, r.Id);
                                    Assert.AreEqual("one", r.Name);
                                    Assert.AreEqual("nothing", r.UnUsed);
                                }
                                else if (count == 2)
                                {
                                    Assert.AreEqual(2, r.Id);
                                    Assert.AreEqual("two", r.Name);
                                    Assert.AreEqual("nothing", r.UnUsed);
                                }

                                count++;
                            }
                        }
        }
Esempio n. 22
0
        public void ReferenceTest()
        {
            using (var stream = new MemoryStream())
                using (var reader = new StreamReader(stream))
                    using (var writer = new StreamWriter(stream))
                        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                        {
                            csv.Configuration.Delimiter = ",";
                            writer.WriteLine("Id,Name");
                            writer.WriteLine("1,one");
                            writer.WriteLine("2,two");
                            writer.Flush();
                            stream.Position = 0;

                            csv.Configuration.HeaderValidated   = null;
                            csv.Configuration.MissingFieldFound = null;

                            var record = new HasReferences
                            {
                                Id        = -1,
                                Reference = new Reference
                                {
                                    Name = "one"
                                }
                            };

                            var count = 1;
                            foreach (var r in csv.EnumerateRecords(record))
                            {
                                if (count == 1)
                                {
                                    Assert.AreEqual(1, r.Id);
                                    Assert.AreEqual("one", r.Reference.Name);
                                }
                                else if (count == 2)
                                {
                                    Assert.AreEqual(2, r.Id);
                                    Assert.AreEqual("two", r.Reference.Name);
                                }

                                count++;
                            }
                        }
        }
Esempio n. 23
0
        public async Task <IActionResult> UploadCSV(IFormFile file)
        {
            var fileName = file.Name;

            using (StreamReader reader = new StreamReader(file.OpenReadStream()))
            {
                using (CsvReader csv = new CsvReader(reader))
                {
                    TransactionImportCsvRecord record = new TransactionImportCsvRecord();
                    IEnumerable <TransactionImportCsvRecord> records = csv.EnumerateRecords(record);
                    foreach (TransactionImportCsvRecord r in records)
                    {
                        var category = await _context.Categories.Where(c => c.Name == r.Category.Trim()).FirstOrDefaultAsync();

                        if (category == null)
                        {
                            _context.Categories.Add(new Category()
                            {
                                Name = r.Category.Trim()
                            });
                            await _context.SaveChangesAsync();

                            category = await _context.Categories.Where(c => c.Name == r.Category).FirstOrDefaultAsync();
                        }

                        decimal amount = Convert.ToDecimal(r.Amount.Trim().Replace(",", "."));

                        Transaction transaction = new Transaction()
                        {
                            IsExtraneous = false,
                            User         = _user,
                            Amount       = r.Category == "Income" ? amount : -amount,
                            Date         = r.Date,
                            Category     = category
                        };

                        _context.Transactions.Add(transaction);
                    }
                    await _context.SaveChangesAsync();
                }
            }

            return(Ok());
        }
Esempio n. 24
0
        public IEnumerable <TransactionUpsertModel> ParseStreamToTransactionUpsertModels(Stream stream)
        {
            var transactions = new List <TransactionUpsertModel>();

            using var streamReader = new StreamReader(stream);
            using var csv          = new CsvReader(streamReader, CultureInfo.InvariantCulture);

            csv.Configuration.RegisterClassMap <TransactionUpsertModelMap>();

            var record = new TransactionUpsertModel();

            try
            {
                var records = csv.EnumerateRecords(record);

                foreach (var r in records)
                {
                    transactions.Add(new TransactionUpsertModel
                    {
                        Id         = r.Id,
                        Amount     = r.Amount,
                        Status     = r.Status,
                        ClientName = r.ClientName,
                        Type       = r.Type
                    });
                }
            }
            catch (CsvHelperException exception)
            {
                var message = "";
                if (exception.ReadingContext.Row == 1)
                {
                    message = "Invalid header format";
                }
                else if (exception.ReadingContext.Row > 1)
                {
                    message = "Invalid row format";
                }

                throw new CsvFileReadException(message, exception.ReadingContext.Record, exception.ReadingContext.Row);
            }

            return(transactions);
        }
Esempio n. 25
0
        private void импортCsvToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var ofd = new OpenFileDialog();

            ofd.Filter = "csv|*.csv";
            if (ofd.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            using (var fs = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read))
                using (var reader = new StreamReader(fs, Encoding.Default))
                    using (var csv = new CsvReader(reader, CultureInfo.CurrentCulture))
                    {
                        var itemcsv_      = new ItemCsv();
                        var listItemParse = new List <ItemCsv>();
                        var records       = csv.EnumerateRecords(itemcsv_);
                        foreach (var itemCsv in records)
                        {
                            if (string.IsNullOrEmpty(itemCsv.Russian))
                            {
                                continue;
                            }
                            var item = list.FirstOrDefault(x => x.SubStrings.Any(y => y.Key == itemCsv.Id));
                            if (item != null)
                            {
                                item.SubStrings[itemCsv.Id].Russian = itemCsv.Russian;
                            }
                        }
                    }

            using (var fs = new FileStream(Application.StartupPath + "\\tmp.bin", FileMode.Create,
                                           FileAccess.ReadWrite))
            {
                var xsr = new BinaryFormatter();
                xsr.Serialize(fs, list);
            }

            dataGridView1.Rows.Clear();
            foreach (var pair in list.SelectMany(item => item.SubStrings))
            {
                dataGridView1.Rows.Add(pair.Key, pair.Value.English, pair.Value.Russian);
            }
        }
Esempio n. 26
0
        public void EnumerateRecords_Disposed_ThrowsObjectDisposedExceptionTest()
        {
            var queue = new Queue <string[]>();

            queue.Enqueue(new[] { "Id", "Name" });
            queue.Enqueue(new[] { "1", "one" });
            queue.Enqueue(null);
            var parserMock = new ParserMock(queue);

            Foo record = null;
            IEnumerable <Foo> records;

            using (var csv = new CsvReader(parserMock))
            {
                records = csv.EnumerateRecords(record);
            }

            Assert.ThrowsException <ObjectDisposedException>(() => records.ToList());
        }
Esempio n. 27
0
        public void InsertFromCSV(string filename)
        {
            using (var reader = new StreamReader(filename))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    csv.Configuration.Delimiter = ";";
                    csv.Configuration.RegisterClassMap <FromageMap>();
                    csv.Configuration.PrepareHeaderForMatch = (string header, int index) => header.ToLower();

                    var record = new Fromage();
                    IEnumerable <Fromage> records = csv.EnumerateRecords(record);

                    foreach (Fromage r in records)
                    {
                        Console.WriteLine(r.Id + "-" + r.Name + "-" + r.Origin.Name);
                        this.Insert(record);
                    }
                }
        }
Esempio n. 28
0
        public void EnumerateRecords_Disposed_ThrowsObjectDisposedExceptionTest()
        {
            var parserMock = new ParserMock
            {
                new[] { "Id", "Name" },
                new[] { "1", "one" },
                null
            };

            Foo record = null;
            IEnumerable <Foo> records;

            using (var csv = new CsvReader(parserMock))
            {
                records = csv.EnumerateRecords(record);
            }

            Assert.Throws <ObjectDisposedException>(() => records.ToList());
        }
Esempio n. 29
0
        public List <AuctionItem> ReadAuctionCsv(string resourcePath, IProgress <int> progress)
        {
            int recordsLength = 0;

            using (var reader = new StreamReader(resourcePath))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    var auctionItem = new AuctionItem();
                    var allRecords  = csv.EnumerateRecords(auctionItem);
                    recordsLength = allRecords.Count <AuctionItem>();
                }

            var iterator = 0;

            using (var reader = new StreamReader(resourcePath))
                using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
                {
                    var auctionRecords = new List <AuctionItem>();
                    csv.Read();
                    csv.ReadHeader();


                    int percentComplete;
                    while (csv.Read())
                    {
                        var record = new AuctionItem
                        {
                            ItemString  = csv.GetField("ItemString"),
                            MarketValue = csv.GetField("MarketValue"),
                            MinBuyout   = csv.GetField("MinBuyout"),
                            Historical  = csv.GetField("Historical"),
                            NumAuctions = csv.GetField("NumAuctions")
                        };
                        auctionRecords.Add(record);
                        iterator++;
                        percentComplete = (iterator * 100) / recordsLength;
                        progress.Report(percentComplete);
                    }
                    percentComplete = 100;
                    progress.Report(percentComplete);
                    return(auctionRecords);
                }
        }
Esempio n. 30
0
        public int CsvHelper_Parse()
        {
            var rows = 0;

            CheckRowCount(File.OpenRead(_files[RowCount]));

            using var reader = new StreamReader(_files[RowCount]);
            using var csv    = new CsvReader(reader, _configuration);

            var record  = new Row();
            var records = csv.EnumerateRecords(record);

            foreach (var row in records)
            {
                CheckRowValues(row, rows + 1);
                rows++;
            }

            return(CheckReadCount(rows));
        }