Beispiel #1
0
        public void CSV_Zeilen_werden_korrekt_formatiert() {
            var sut = new CSV();
            var result = sut.Formatiere_CSV_Zeilen(new[] {
                "Name;Alter;Stadt",
                "Peter;42;New York",
                "Paul;57;London",
                "Mary;35;Munich",
                "Jaques;66;Paris",
                "Yuri;23;Moscow",
                "Stephanie;47;Stockholm",
                "Nadia;29;Madrid"
            });

            Assert.That(result, Is.EqualTo(new[] {
                "|Name     |Alter|Stadt    |",
                "+---------+-----+---------+",
                "|Peter    |42   |New York |",
                "|Paul     |57   |London   |",
                "|Mary     |35   |Munich   |",
                "|Jaques   |66   |Paris    |",
                "|Yuri     |23   |Moscow   |",
                "|Stephanie|47   |Stockholm|",
                "|Nadia    |29   |Madrid   |"
            }));
        }
Beispiel #2
0
 public static CSV GetInstance()
 {
     if (csv == null)
     {
         csv = new CSV();
     }
     return csv;
 }
        public void Breiteste_Spalte_inkl_Überschrift_bestimmt_die_Breite() {
            var sut = new CSV();
            var result = sut.Spaltenbreiten_ermitteln(new[] {
                new CSVZeile { Werte = new[] { "Lange Überschrift", "A", "B" } },
                new CSVZeile { Werte = new[] { "X", "Breit", "C" } }
            });

            Assert.That(result, Is.EqualTo(new[]{17, 5, 1}));
        } 
        public void Eine_einzelne_CSV_Zeile_wird_formatiert() {
            var sut = new CSV();
            var result = sut.Zeilen_formatieren(new[] {
                new CSVZeile { Werte = new[] { "A", "B", "C" } }
            }, new[] { 3, 4, 5 });

            Assert.That(result, Is.EqualTo(new[] {
                "|A  |B   |C    |",
                "+---+----+-----+"
            }));
        } 
Beispiel #5
0
        private static bool IsFirstFrame(CSV csv, int frameId)
        {
            // first frame of the whole data set
            if (frameId == 1)
            {
                return(true);
            }

            var prevTrialId = csv.GetCell <int>("trial", frameId - 1);
            var currTrialId = csv.GetCell <int>("trial", frameId);

            return(prevTrialId != currTrialId);
        }
        public void Zeilen_werden_formatiert() {
            var sut = new CSV();
            var result = sut.Zeilen_formatieren(new[] {
                new CSVZeile { Werte = new[] { "A", "B", "C" } },
                new CSVZeile { Werte = new[] { "AAA", "BBBB", "CCCCC" } }
            }, new[] { 3, 4, 5 });

            Assert.That(result, Is.EqualTo(new[] {
                "|A  |B   |C    |",
                "+---+----+-----+",
                "|AAA|BBBB|CCCCC|"
            }));
        } 
        public void Korrekt_formatierte_CSV_Zeilen() {
            var sut = new CSV();
            var result = sut.CSV_Zeilen_erstellen(new[] {
                "Name;Alter;Stadt",
                "Peter;42;New York",
                "Paul;57;London",
            });

            Assert.That(result.Count(), Is.EqualTo(3));
            Assert.That(result.ElementAt(0).Werte, Is.EqualTo(new[]{"Name", "Alter", "Stadt"}));
            Assert.That(result.ElementAt(1).Werte, Is.EqualTo(new[]{"Peter", "42", "New York"}));
            Assert.That(result.ElementAt(2).Werte, Is.EqualTo(new[]{"Paul", "57", "London"}));
        }
Beispiel #8
0
        public void CSV_Read()
        {
            //Make a CSV file
            var data = Enumerable.Range(0, 10).Select(row => Enumerable.Range(0, 10).Select(col => row + col));
            var fn   = GetNewFileNameOnTempPath(".csv");

            System.IO.File.WriteAllText(fn, string.Join("\n", data.Select(row => string.Join(",", row))));

            //Now read it
            var fnInfo = File.FromPath(fn);

            Assert.AreEqual(data, CSV.ReadFromFile(fnInfo));
        }
Beispiel #9
0
        //csv读取
        private void button2_Click(object sender, EventArgs e)
        {
            List <string[]> rowList_Write = CSV.ReadCSV("学生信息.csv");

            for (int i = 0; i < rowList_Write.Count; i++)
            {
                for (int j = 0; j < rowList_Write[i].Length; j++)
                {
                    Console.Write(rowList_Write[i][j] + "  ");
                }
                Console.WriteLine();
            }
        }
Beispiel #10
0
    public static void DecodeTable(string str)
    {
        Configs.Clear();
        str = StringUtils.Replace(str, '\r', '\n');
        str = StringUtils.Replace(str, "\n\n", '\n');
        List <List <string> > list = CSV.Parse(str);

        for (int i = 2, len = list.Count; i < len; i++)
        {
            PassScoreConfig item = new PassScoreConfig();
            item.Decode(list[i]);
            Configs.Add(item);
        }
    }
Beispiel #11
0
        public void Import_CSVWithFewerHeaderColumns_ThrowsInvalidOperationException()
        {
            //Arrange
            var headerColumns = new string[] { };
            var helper        = new CSV();
            //Act
            var ex = Assert.Throws <InvalidOperationException>(() => helper
                                                               .Import <Person>($@"{_assemblyPath}\files\SampleB.csv", ',',
                                                                                new string[] { "Name", "Age" }));

            //Assert
            Assert.Equal(typeof(InvalidOperationException), ex.GetType());
            Assert.Equal("Column header 2 - Column value mismatch 4", ex.Message);
        }
Beispiel #12
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            OpenFileDialog openFile = new OpenFileDialog()
            {
                DefaultExt = "csv", Title = "Open CSV", Multiselect = false
            };

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                data = new CSV(new FileStream(openFile.FileName, FileMode.Open));
                fileNameLabel.Text      = openFile.FileName;
                columnSelect.DataSource = data.AllKeys;
            }
        }
Beispiel #13
0
        public void Init()
        {
            CSV test_file = new CSV();

            test_airports = test_file.LoadAirports(ap_file_path);

            Assert.IsNotNull(test_airports);
            Assert.AreEqual(4, test_airports.Length);

            test_flights = test_file.LoadFlights(flights_file_path);

            Assert.IsNotNull(test_flights);
            Assert.AreEqual(48, test_flights.Length);
        }
Beispiel #14
0
        public static void LoadRegistry()
        {
            string[][] natureData = CSV.ReadCSVResource("Data/natures");

            List <Nature> natures = new List <Nature>();

            for (int i = 0; i < natureData.Length; i++)
            {
                string[] entry = natureData[i];

                if (entry.Length < 3)
                {
                    Debug.LogWarning("Not enough entries for nature data (" + entry + ")");
                    continue;
                }

                int    id;
                string name;

                string idString = entry[0];

                if (!int.TryParse(idString, out id))
                {
                    Debug.LogWarning("Invalid id passed (" + idString + ")");
                    continue;
                }

                name = entry[1];
                string boostName  = entry[2];
                string hinderName = entry[3];

                Stats <bool?> boosts = new Stats <bool?>()
                {
                    attack         = (boostName == "attack") ? true : (hinderName == "attack" ? false : (bool?)null),
                    defense        = (boostName == "defense") ? true : (hinderName == "defense" ? false : (bool?)null),
                    specialAttack  = (boostName == "specialAttack") ? true : (hinderName == "specialAttack" ? false : (bool?)null),
                    specialDefense = (boostName == "specialDefense") ? true : (hinderName == "specialDefense" ? false : (bool?)null),
                    speed          = (boostName == "speed") ? true : (hinderName == "speed" ? false : (bool?)null)
                };

                natures.Add(new Nature()
                {
                    id     = id,
                    name   = name,
                    boosts = boosts
                });
            }

            registry.SetValues(natures.ToArray());
        }
Beispiel #15
0
        public Config_CSVFile(string targetFileName, string delimiter = ",", bool useQuotes = false)
            : base(typeof(Config_CSVFile <T>)
                   , new object[] { targetFileName, delimiter, useQuotes })
        {
            target  = targetFileName;
            headers = CSV.ImportCSV(targetFileName, delimiter, useQuotes).First().ToList();
            List <string[]> lines = CSV.ImportCSV(targetFileName, delimiter, useQuotes).ToList();

            // Add a dictionary item with a list of aliases for each header, including the key.
            for (int i = 0; i < headers.Count; i++)
            {
                headerAliases.Add(headers[i], from line in lines select line[i]);
            }
        }
Beispiel #16
0
        public void CSV_Write()
        {
            //Write data to CSV
            var data =
                Enumerable.Range(0, 10)
                .Select(row => Enumerable.Range(0, 10).Select(col => row + col).Cast <object>().ToArray())
                .ToArray();
            var fn = GetNewFileNameOnTempPath(".csv");

            CSV.WriteToFile(fn, data);

            //Confirm it's correct
            Assert.AreEqual(data, CSV.ReadFromFile(File.FromPath(fn)));
        }
Beispiel #17
0
        public void ParseTSV()
        {
            // Basic TSV test
            string[] line = CSV.ParseLine("1\t2\t3\t4\t5", '\t', '\"');
            Assert.AreEqual(line.Length, 5);
            Assert.AreEqual(line[3], "4");
            Assert.AreEqual(line[1], "2");

            // Test trailing blank item
            line = CSV.ParseLine("1\t2\t3\t4\t5\t", '\t', '\"');
            Assert.AreEqual(line.Length, 6);
            Assert.AreEqual(line[5], "");
            Assert.AreEqual(line[4], "5");
        }
Beispiel #18
0
        public void OnRequestManifest(List <Archive> archiveList)
        {
            CSV csv = new CSV();

            if (archiveList.Count == 0)
            {
                var list = PatchMgr._Patch_Assets;

                foreach (var myp in list)
                {
                    List <PatchAsset> pAssets = myp.Value;
                    foreach (var asset in pAssets)
                    {
                        csv.NewRow();
                        csv.WriteCol(0, ((int)asset.ArchiveId).ToString());
                        csv.WriteCol(1, asset.Hash.ToString());
                        csv.WriteCol(2, "");
                        csv.WriteCol(3, asset.CRC32.ToString());
                        csv.WriteCol(5, asset.Size.ToString());
                        csv.WriteCol(6, asset.MetaDataSize.ToString());
                        csv.WriteCol(7, String.IsNullOrEmpty(asset.File) ? 0 : 1);
                    }
                }
            }
            else
            {
                foreach (var archive in archiveList)
                {
                    var pAssets = PatchMgr._Patch_Assets.Where(m => m.Key.Id == (int)archive).First().Value;

                    foreach (var asset in pAssets)
                    {
                        csv.NewRow();
                        csv.WriteCol(0, ((int)archive).ToString());
                        csv.WriteCol(1, asset.Hash.ToString());
                        csv.WriteCol(2, "");
                        csv.WriteCol(3, asset.CRC32.ToString());
                        csv.WriteCol(5, asset.Size.ToString());
                        csv.WriteCol(6, asset.MetaDataSize.ToString());
                        csv.WriteCol(7, String.IsNullOrEmpty(asset.File) ? 0 : 1);
                    }
                }
            }

            PatcherFile p    = new PatcherFile();
            var         data = System.Text.ASCIIEncoding.ASCII.GetBytes(csv.ToText());

            QueueFileUpload(FileType.MANIFEST_SET, "MANIFEST", data, FileCompressionMode.WHOLE);
            ProcessFileUploadQueue();
        }
        private void ReadFromStorage()
        {
            var    baseDir = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
            string path    = Path.Combine(baseDir, "TrackingQuest.csv");

            if (!File.Exists(path))
            {
                return;
            }

            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                while (fs.Position < fs.Length)
                {
                    string[] data = CSV.Read(fs);

                    try
                    {
                        int       Id;
                        DateTime  trackTime;
                        string    QuestTypeText;
                        QuestType QuestType;
                        string    Serialized;

                        if (!int.TryParse(data[0], out Id))
                        {
                            continue;
                        }
                        DateTime.TryParse(data[1], out trackTime);
                        QuestTypeText = data[2];
                        Enum.TryParse <QuestType>(QuestTypeText, out QuestType);
                        Serialized = data[3];

                        if (!trackingAvailable.Any(x => x.Id == Id))
                        {
                            continue;
                        }
                        if (IsTrackingAvailable(QuestType, trackTime))
                        {
                            var tracker = trackingAvailable.Where(x => x.Id == Id).First();

                            trackingTime.Add(Id, trackTime);
                            tracker.IsTracking = true;
                            tracker.DeserializeData(Serialized);
                        }
                    }
                    catch { }
                }
            }
        }
Beispiel #20
0
        public void DeserializeExcludeColumns()
        {
            var csv = "TestString,IntProperty,NullableSingle\n" +
                      "Test String,57,12.35\n" +
                      "Test String,57,\n" +
                      "Test String,57,56.19\n" +
                      "Test String,57,\n" +
                      "\n";

            // Let's specifically allow null
            var settings = new CSVSettings
            {
                AllowNull = true,
                NullToken = string.Empty,
                IgnoreEmptyLineForDeserialization = true,
                ExcludedColumns = new [] { "TestString" }
            };

            // Try deserializing - we should see nulls in the TestString column
            var list = CSV.Deserialize <TestClassLastColumnNullableSingle>(csv, settings).ToList();

            Assert.AreEqual(4, list.Count);

            Assert.IsNull(list[0].TestString);
            Assert.AreEqual(57, list[0].IntProperty);
            Assert.AreEqual(12.35f, list[0].NullableSingle);

            Assert.IsNull(list[1].TestString);
            Assert.AreEqual(57, list[1].IntProperty);
            Assert.IsNull(list[1].NullableSingle);

            Assert.IsNull(list[2].TestString);
            Assert.AreEqual(57, list[2].IntProperty);
            Assert.AreEqual(56.19f, list[2].NullableSingle);

            Assert.IsNull(list[3].TestString);
            Assert.AreEqual(57, list[3].IntProperty);
            Assert.IsNull(list[3].NullableSingle);

            // Try serializing - we should no longer see a TestString column
            settings.LineSeparator = "\n";
            var backToCsv = CSV.Serialize(list, settings);

            Assert.AreEqual("IntProperty,NullableSingle\n" +
                            "57,12.35\n" +
                            "57,\n" +
                            "57,56.19\n" +
                            "57,\n", backToCsv);
        }
        public bool UpdateFromCSV(string csv)
        {
            bool flag;

            if (string.IsNullOrEmpty(csv))
            {
                flag = false;
            }
            else
            {
                string[] array = CSV.ToArray(csv);
                if (array.Length < 11)
                {
                    flag = false;
                }
                else
                {
                    this.ClassName   = array[0];
                    this.Column      = int.Parse(array[1]) - 2;
                    this.DisplayName = array[2];
                    this.DescLong    = array[3];
                    this.Origin      = array[4].Split(Convert.ToChar(" "));
                    string str = array[5];
                    if (str.IndexOf("KHELDIAN HERO", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        this.ClassType = Enums.eClassType.HeroEpic;
                    }
                    else if (str.IndexOf("ARACHNOSSOLDIER VILLAIN", StringComparison.OrdinalIgnoreCase) > -1 || str.IndexOf("ARACHNOSWIDOW VILLAIN", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        this.ClassType = Enums.eClassType.VillainEpic;
                    }
                    else if (str.IndexOf("HERO", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        this.ClassType = Enums.eClassType.Hero;
                    }
                    else if (str.IndexOf("VILLAIN", StringComparison.OrdinalIgnoreCase) > -1)
                    {
                        this.ClassType = Enums.eClassType.Villain;
                    }
                    this.Playable       = str != string.Empty;
                    this.DescShort      = array[6];
                    this.PrimaryGroup   = array[8];
                    this.SecondaryGroup = array[9];
                    this.PoolGroup      = array[10];
                    flag = true;
                }
            }
            return(flag);
        }
Beispiel #22
0
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            CSV csv = new CSV("TestData");

            System.Data.DataTable dataTableData = csv.GetDataTable();

            Form1 form1 = new Form1();

            form1.SetDataGridDataSource(dataTableData);

            Application.Run(form1);
        }
Beispiel #23
0
        private static string GetCondition(CSV stdCsv, int trialId)
        {
            var strategies = stdCsv.GetColumn("strategy", false);

            if (strategies.Length > trialId)
            {
                return(strategies[trialId]);
            }
            else
            {
                return("data not saved");
            }

            //return stdCsv.GetColumn("strategy", false)[trialId];
        }
Beispiel #24
0
        private KeyValuePair <bool, string> CheckFileType()
        {
            Regex reg   = new Regex(@"([^\.]+$)");
            Match match = reg.Match(FileName);

            BaseFile = match.ToString().Contains("xls") ? BaseFile = new Excel(FileName, FilePath)
                                                        : BaseFile = new CSV(FileName, FilePath);
            var results = FormatFile(JsonConvert.SerializeObject(BaseFile));

            ResultData = new FinancialItem().ParseData(results);
            File.Delete(FilePath);
            // send file to cosmos db
            // delete temporary file here
            return(ResultData);
        }
Beispiel #25
0
        private void cSVExportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            foreach (Form form in Application.OpenForms)
            {
                if (form.GetType() == typeof(CSV))
                {
                    form.Activate();
                    return;
                }
            }

            CSV cSV = new CSV();

            cSV.ShowDialog();
        }
        public void ParseTSV()
        {
            // Basic TSV test
            var line = CSV.ParseLine("1\t2\t3\t4\t5", CSVSettings.TSV);

            Assert.AreEqual(5, line.Length);
            Assert.AreEqual("4", line[3]);
            Assert.AreEqual("2", line[1]);

            // Test trailing blank item
            line = CSV.ParseLine("1\t2\t3\t4\t5\t", CSVSettings.TSV);
            Assert.AreEqual(6, line.Length);
            Assert.AreEqual("", line[5]);
            Assert.AreEqual("5", line[4]);
        }
        public Dictionary <int, string> GetHeader()
        {
            String header = CSV.ReadLine();

            string[] labels = header.Split(',');
            int      i      = 0;

            foreach (String label in labels)
            {
                Header.Add(i, label);
                i++;
            }

            return(Header);
        }
Beispiel #28
0
            public string[] Handle(CSV csv)
            {
                List <string> result = new();

                for (int i = 0; i < this.Array.GetLength(0); i++)
                {
                    List <string> lineItems = new();
                    for (int j = 0; j < this.Array.GetLength(1); j++)
                    {
                        lineItems.Add(this.Array[i, j]);
                    }
                    result.Add(string.Join(";", lineItems));
                }
                return(result.ToArray());
            }
Beispiel #29
0
        protected override Task OnGoAsync()
        {
            var ids = CSV.ParseIntegerRow(Configuration["HardcodedJobIds"]);

            if (ids == null || ids.Length == 0)
            {
                GoHangfireServer();
            }
            else
            {
                Log.Information("Executing {IDCount} hardcoded jobs IDs instead of running the server.", ids.Length);
                Parallel.ForEach(ids, jobId => GoHardcoded(jobId));
            }
            return(Task.CompletedTask);
        }
Beispiel #30
0
        public void TestFailingCSVLine()
        {
            string[] line = null;

            // Use a basic parse that will do its best but fail to recognize the problem
            line = CSV.ParseLine("1,\"two\",3,\"four, \"\"five");
            Assert.AreEqual(line.Length, 4);
            Assert.AreEqual(line[0], "1");
            Assert.AreEqual(line[1], "two");
            Assert.AreEqual(line[2], "3");
            Assert.AreEqual(line[3], "four, \"five");

            // Confirm that the more advanced parse will fail
            Assert.IsFalse(CSV.TryParseLine("1,\"two\",3,\"four, \"\"five", CSV.DEFAULT_DELIMITER, CSV.DEFAULT_QUALIFIER, out line));
        }
Beispiel #31
0
        public string listar()
        {
            string rpta = "";
            //usando codigo xhr

            ProductoBR             brproducto   = new ProductoBR();
            List <ProductoEntidad> listProducto = brproducto.ListarNegocio();

            if (listProducto != null && listProducto.Count > 0)
            {
                rpta = CSV.SerializarLista(listProducto);
            }

            return(rpta);
        }
 public void ParseSepLineTest()
 {
     Assert.AreEqual('|', CSV.ParseSepLine("sep=|"));
     Assert.AreEqual('|', CSV.ParseSepLine("sep=   |"));
     Assert.AreEqual('|', CSV.ParseSepLine("sep=|     "));
     Assert.AreEqual('|', CSV.ParseSepLine("sep=    |     "));
     Assert.AreEqual('|', CSV.ParseSepLine("sep = |"));
     Assert.AreEqual(',', CSV.ParseSepLine("sep=,"));
     Assert.AreEqual(',', CSV.ParseSepLine("sep = ,"));
     Assert.AreEqual(null, CSV.ParseSepLine("sep="));
     Assert.Throws <Exception>(() =>
     {
         CSV.ParseSepLine("sep= this is a test since separators can't be more than a single character");
     });
 }
Beispiel #33
0
        static PortalHelpers()
        {
            var d = new Dictionary <ReviewScopeEnum, string>();

            foreach (var row in CSV.ParseText(Properties.Settings.Default.ReviewScopeWorkflowMapCsv))
            {
                if (row.Length != 2)
                {
                    continue;
                }
                var scope = Parse.ParseEnum <ReviewScopeEnum>(row[0]);
                d[scope] = StringHelpers.TrimOrNull(row[1]);
            }
            WorkflowDefinitionNameByReviewScope = d.AsReadOnly();
        }
Beispiel #34
0
        /// <summary>
        /// Decodes an object.
        /// </summary>
        /// <param name="ContentType">Internet Content Type.</param>
        /// <param name="Data">Encoded object.</param>
        /// <param name="Encoding">Any encoding specified. Can be null if no encoding specified.</param>
        /// <param name="Fields">Any content-type related fields and their corresponding values.</param>
        ///	<param name="BaseUri">Base URI, if any. If not available, value is null.</param>
        /// <returns>Decoded object.</returns>
        /// <exception cref="ArgumentException">If the object cannot be decoded.</exception>
        public object Decode(string ContentType, byte[] Data, Encoding Encoding, KeyValuePair <string, string>[] Fields, Uri BaseUri)
        {
            string s;

            if (Encoding == null)
            {
                s = Encoding.UTF8.GetString(Data);
            }
            else
            {
                s = Encoding.GetString(Data);
            }

            return(CSV.Parse(s));
        }
Beispiel #35
0
        private void btnAdd_Click(object sender, EventArgs e)
        {
            frmAdd add = new frmAdd(csv.Customers.Count, this.csv.Customers);

            if (add.ShowDialog() == DialogResult.OK)
            {
                csv.Customers.Add(add.CNew);
                csv.WriteCSV();
                csv                     = new CSV("data.csv");
                bind.DataSource         = csv.Customers;
                dgvCustomers.DataSource = bind;
                dgvCustomers.Update();
                dgvCustomers.Show();
            }
        }
        internal void Marshall(string propertyName, XmlWriter xmlWriter)
        {
            xmlWriter.WriteStartElement(propertyName);

            if (IsSetCSV())
            {
                CSV.Marshall("CSV", xmlWriter);
            }
            if (IsSetJSON())
            {
                JSON.Marshall("JSON", xmlWriter);
            }

            xmlWriter.WriteEndElement();
        }
    protected void btnGerar_Click(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(txtArquivo.Text))
            {
                ltrOut.Text = "Informe o nome do arquivo com o layout CSV editado";
                return;
            }
            string cFile = MapPath(txtArquivo.Text);
            if (!File.Exists(cFile))
            {
                ltrOut.Text = "Arquivo não existe";
                return;
            }
            CSV csv = new CSV();
            csv.Load(cFile);

            DataTable tb = csv.data;
            if (tb.Columns.Count < 4)
            {

                ltrOut.Text = "É preciso ter ao menos 4 colunas";
                return;
            }

            StringBuilder sb = new StringBuilder();
            string cCampo;
            string cTamanho;
            string cTipo;
            string cRegFormat;
            int nPos = 1;

            sb.AppendLine("[RegLayout(@\"^1\")]");
            sb.AppendLine("public enum GenerateLayout \n{");

            // local dos campos
            int nPosNome = 1;
            int nPosComentario = 2;
            int nPosTamanho = 0;
            int nPosTipo = 3;

            foreach (DataRow row in tb.Rows)
            {
                // Campo1: Nome do campo
                cCampo = (string)row[nPosNome];
                if (!Regex.IsMatch(cCampo, @"[A-Za-z]\w+$"))
                {
                    ltrOut.Text = "Nome invalido na posição " + nPos + " - Campo: " + cCampo;
                    return;
                }
                // Campo2: Comentário descritivo do campo
                if (!string.IsNullOrEmpty((string)row[nPosComentario]))
                    sb.AppendLine("\t/// &lt;summary&gt;\n\t/// " + row[nPosComentario] + " \n\t/// &lt;/summary&gt;");

                // Campo3: Posição Inicial/final
                cRegFormat = "[RegFormat(RegType.P";
                // Colocar o numero da linha que define o tamanho
                cTamanho = (string)row[nPosTamanho]; 
                // Há documentações que é informado o tamanho e outros que é informado o numero de caracteres iniciais e final, aqui vou tratar os 2 casos
                string[] c = cTamanho.Replace(" a ", " ").Split(' ');
                if (c.Length >= 2)
                    cTamanho = (CobUtil.GetInt(c[1]) - CobUtil.GetInt(c[0]) + 1).ToString();

                else if (c.Length == 1)
                    cTamanho = c[0];

                else
                {
                    ltrOut.Text = "O tamanho não pode ser identificado '" + cTamanho + "' no Campo: " + cCampo;
                    return;
                }

                // Campo4: Tipo de Campo
                cTipo = (string)row[nPosTipo]; // Só será usado a primeira letra, edite no Excel/google doscs, o no CSV direto possíveis conversões de numeros para data ou valor
                cTipo = cTipo.Substring(0, 1).ToUpper(); // Desde a época do Cobol os tipos de dado e a forma de representa-los é muito parecido
                // 9 - Valores numéricos inteiros
                // V - Valores mão inteiros (double)
                // D - Datas
                // X - Textos
                // H - Hora
                if (!Regex.IsMatch(cTipo, "[9VDXHNA]"))
                {
                    ltrOut.Text = "Tipo Inválido '" + cTipo + "' no Campo: " + cCampo;
                    return;
                }
                if (cTipo == "N")
                    cTipo = "9";
                else if (cTipo == "A")
                    cTipo = "X";

                cRegFormat += cTipo; // Sendo que os tipos válidos são: 
                cRegFormat += ", " + cTamanho;

                // Campo5: Valor padrão do campo (caso exista)
                //if (tb.Columns.Count > 4 && !string.IsNullOrEmpty((string)row[4]))
                //    cRegFormat += ", Default =\"" + row[4] + "\"";

                // Fecha o atributo e coloca um informativo dos tamanhos de posição atual
                cRegFormat += ")] // " + nPos;
                nPos += CobUtil.GetInt(cTamanho);
                cRegFormat += "-" + (nPos - 1);

                // Por fim adiciona o campo
                sb.AppendLine("\t" + cRegFormat + "\n\t" + cCampo + ",\n");
                
            }
            sb.AppendLine("}");
            ltrOut.Text = "Copie e cole o código abaixo em um arquivo .CS<br/><hr/><pre>" + sb.ToString() + "</pre>";
        }
        catch (Exception ex)
        {
            ltrOut.Text = "<b>" + ex.Message + "</b><br/><pre>" + ex.StackTrace + "</pre>";
        }
    }
Beispiel #38
0
 public static CSV download(string tick, int days = 1)
 {
     CSV intraday = new CSV(tick, days);
     YahooIntraday.download(intraday);
     return intraday;
 }
Beispiel #39
0
 public static CSV openCache(string path)
 {
     CSV intraday = new CSV();
     YahooIntraday.openCache(intraday, path);
     return intraday;
 }
Beispiel #40
0
 public CSVTests()
 {
     _csv = new CSV();
     _csv.Load("file.csv");
 }
        public void Eine_leere_Aufzählung_von_Zeilen_wird_formatiert() {
            var sut = new CSV();
            var result = sut.Zeilen_formatieren(new CSVZeile[] { }, new[] { 3, 4, 5 });

            Assert.That(result, Is.Empty);
        } 
Beispiel #42
0
        private static void ExportToCSV(System.Data.DataTable datatable, CSV.CSVWriter csvwriter)
        {
            foreach (System.Data.DataRow row in datatable.Rows)
            {
                csvwriter.WriteItems(row.ItemArray);
            }

            csvwriter.Close();
        }