Represents a reader that provides fast, cached, dynamic access to CSV data.
The number of records is limited to System.Int32.MaxValue - 1.
상속: CsvReader, IListSource
예제 #1
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            #else
            int absenceTypeIDIndex = _AbsenceTypeIDIndex;
            int absenceDescriptionIndex = _AbsenceDescriptionIndex;
            #endif

            Dictionary<int, ImportFileAbsenceData> data = new Dictionary<int, ImportFileAbsenceData>();

            //Add Absence
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                int systemID = int.Parse(csv[absenceTypeIDIndex]);
                string absenceName = csv[absenceDescriptionIndex];
                if (!data.ContainsKey(systemID))
                    data.Add(systemID, new ImportFileAbsenceData(_CurrentRow, new ImportAbsenceData(systemID, absenceName, csv[_AbsenceCharIDIndex])));
                else
                    message(string.Format(GetLocalized("AbsenceExists"), _CurrentRow, systemID));
            }
            csvDataEndRead();

            List<ImportAbsenceData> list = new List<ImportAbsenceData>(data.Count);
            foreach (ImportFileAbsenceData value in data.Values)
                list.Add(value.Data);
            SaveDataResult saveDataResult =  _AbsenceService.ImportAbsence(list);
            list = (List<ImportAbsenceData>)saveDataResult.Data;
            foreach (ImportAbsenceData value in list)
            {
                message(string.Format(GetLocalized("AbsenceNotImportedInDB"), data[value.SystemID].RecordNumber, value.SystemID));
            }
        }
 public static DataTable loadFromCSV(string pathName, bool isHeader, DataTable table)
 {
     using(CachedCsvReader csv = new CachedCsvReader(new StreamReader(pathName), false)) {
         table.Load(csv);
     }
     return table;
 }
예제 #3
0
		private void button1_Click(object sender, EventArgs e)
		{
			using (CachedCsvReader csv = new CachedCsvReader(new StringReader(CsvReaderSampleData.SampleData1), true))
			{
				dataGrid1.DataSource = csv;
			}

			button2.Enabled = true;
		}
예제 #4
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            int systemID1Index = csv.GetFieldIndex(_VLID);
            int regionNameIndex = csv.GetFieldIndex(_RegionName);
            #else
            int systemID1Index = _VLIDIndex;
            int regionNameIndex = _RegionNameIndex;
            #endif
            Dictionary<string, Region> dbRegionHash = getDBRegionList();
            Dictionary<string, long> countrySysKeyIDKey = getDBCountryListSysKeyIDKey();
            List<Region> importRegionList = new List<Region>();

            int i = 1;
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                string regionName = csv[regionNameIndex];
                string keyCountry = csv[systemID1Index];
                string keyRegion = keyCountry + regionName;

                if (!dbRegionHash.ContainsKey(keyRegion))
                {
                    if (countrySysKeyIDKey.ContainsKey(keyCountry))
                    {
                        Region region = new Region();
                        region.CountryID = countrySysKeyIDKey[keyCountry];
                        region.LanguageID = SharedConsts.NeutralLangId;
                        region.Name = regionName;
                        region.Import = true;
                        region.RegionSysID = regionName;
                        importRegionList.Add(region);
                        dbRegionHash.Add(keyRegion, region);
                    }
                    else
                    {
                        message(string.Format(GetLocalized("CountryNotExistsDB"), _CurrentRow, _VLID, keyCountry));
                    }
                }
                else
                {
                    message(string.Format(GetLocalized("RegiontExistsDB"), i, keyRegion));
                }
                i++;
            }
            csvDataEndRead();

            SaveOrUpdateList<Region>(_RegionService, importRegionList);
        }
예제 #5
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            #else
            int persIDIndex = _PersIDIndex;
            int codeIndex = _CodeIndex;
            int codeNameIndex = _CodeNameIndex;
            int beginTimeIndex = _BeginTimeIndex;
            int endTimeIndex = _EndTimeIndex;
            #endif

            Dictionary<string, ImportFileLongTimeAbsenceData> data = new Dictionary<string, ImportFileLongTimeAbsenceData>();
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                short code = short.Parse(csv[codeIndex]);
                string persID = csv[persIDIndex];
                DateTime beginTime = DateTime.ParseExact(csv[beginTimeIndex], "yyyyMMdd", null);
                string endTimeStr = csv[endTimeIndex];
                if (string.IsNullOrEmpty(endTimeStr)) endTimeStr = DateTimeSql.SmallDatetimeMaxStr;
                DateTime endTime = DateTime.ParseExact(endTimeStr, "yyyyMMdd", null);
                string key = persID + code.ToString() + beginTime.ToString() + endTime.ToString();
                if (!data.ContainsKey(key))
                {
                    ImportLongTimeAbsenceData lta= new ImportLongTimeAbsenceData();
                    lta.PersID = persID;
                    lta.BeginTime = beginTime;
                    lta.EndTime = endTime;
                    lta.Code = code;
                    lta.CodeName = csv[codeNameIndex];
                    data.Add(key, new ImportFileLongTimeAbsenceData(_CurrentRow, lta));
                }
                else
                    message(string.Format(GetLocalized("LongTimeAbsenceExists"), _CurrentRow, persID, code, beginTime, endTime));
            }
            csvDataEndRead();

            List<ImportLongTimeAbsenceData> list = new List<ImportLongTimeAbsenceData>(data.Count);
            foreach (ImportFileLongTimeAbsenceData value in data.Values)
                list.Add(value.Data);
            SaveDataResult saveDataResult = _EmployeeService.LongTimeAbsenceService.ImportLongTimeAbsence(list);
            list = (List<ImportLongTimeAbsenceData>)saveDataResult.Data;
            foreach (ImportLongTimeAbsenceData value in list)
            {
                string key = value.PersID.ToString() + value.Code.ToString () + value.BeginTime.ToString() + value.EndTime.ToString();
                message(string.Format(GetLocalized("LongTimeAbsenceNotAssignToEmployee"), data[key].RecordNumber, value.PersID));
            }
        }
예제 #6
0
        static string composeOutLine(CachedCsvReader csv, AccountType accType)
        {
            string[] outArr = new string[9];

            switch (accType)
            {
                case AccountType.OsobniKonto:
                    outArr[OutColumn.Cislo] = String.Format("\"{0}\"", csv[12]);
                    outArr[OutColumn.Datum] = String.Format("\"{2}/{1}/{0}\"", csv[01].Split('/'));
                    outArr[OutColumn.Prijemce] = String.Format("\"{0}\"", csv[03]);
                    outArr[OutColumn.Kategorie] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.S] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Vydej] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Prijem] = String.Format("\"{0}\"", csv[02]);
                    outArr[OutColumn.Celkem] = String.Format("\"{0}\"", "");
                    //outArr[OutColumn.Poznamka] = String.Format("\"{0} {1} {2} {3} {4}\"", csv[10], csv[0], csv[07], csv[13], csv[11]);
                    outArr[OutColumn.Poznamka] = joinSelectedStringsFromCsv(csv, " * ", 13, 11, 10, 0, 7);

                    break;
                case AccountType.Hypoteka:
                    outArr[OutColumn.Cislo] = String.Format("\"{0}\"", csv[11]);
                    outArr[OutColumn.Datum] = String.Format("\"{2}/{1}/{0}\"", csv[01].Split('/'));
                    outArr[OutColumn.Prijemce] = String.Format("\"{0}\"", csv[04]);
                    outArr[OutColumn.Kategorie] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.S] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Vydej] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Prijem] = String.Format("\"{0}\"", csv[03]);
                    outArr[OutColumn.Celkem] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Poznamka] = joinSelectedStringsFromCsv(csv, " * ", 0, 9, 10);
                    break;
                case AccountType.SporiciUcet:
                    outArr[OutColumn.Cislo] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Datum] = String.Format("\"{2}/{1}/{0}\"", csv[01].Split('/'));
                    outArr[OutColumn.Prijemce] = String.Format("\"{0}\"", csv[05]);
                    outArr[OutColumn.Kategorie] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.S] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Vydej] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Prijem] = String.Format("\"{0}\"", csv[03]);
                    outArr[OutColumn.Celkem] = String.Format("\"{0}\"", "");
                    outArr[OutColumn.Poznamka] = joinSelectedStringsFromCsv(csv, " * ", 17, 14, 15, 10, 0, 16);
                    break;
                default:
                    break;
            }

            string outStr = String.Join(";", outArr);
            return outStr;
        }
예제 #7
0
        private void LoadCSVFile(String filename)
        {
            this.csvDisplayGrid.DataSource = null;
            this.csvDisplayGrid.Columns.Clear();
            this.csvDisplayGrid.Rows.Clear();

            lock (this.flag)
            {
                this.queue = new List<UserState>();
                this.retryQueue = new List<UserState>();
            }


            Stream f = File.Open(filename, FileMode.Open);
            using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(f, Encoding.UTF8), true))
            {
                this.csvDisplayGrid.DataSource = csv;
                while (this.csvDisplayGrid.Columns.Count > COLUMN_MAX)
                {
                    this.csvDisplayGrid.Columns.RemoveAt(6);
                }
                if (this.csvDisplayGrid.Columns.Count != COLUMN_MAX)
                {
                    MessageBox.Show("The file " + filename + " is not in the correct format");
                    this.csvDisplayGrid.DataSource = null;
                }
            }


            // now add a status column
            DataGridViewColumn status = new DataGridViewColumn();
            status.Name = "Upload Status";
            status.CellTemplate = new DataGridViewTextBoxCell();
            this.csvDisplayGrid.Columns.Add(status);

            DataGridViewColumn vid = new DataGridViewColumn();
            vid.Name = "Video ID";
            vid.CellTemplate = new DataGridViewTextBoxCell();
            this.csvDisplayGrid.Columns.Add(vid);

            this.Upload.Enabled = true;

            SetTitle();

            Trace.TraceInformation("Loaded csv file: " + filename + "successfully");

        }
예제 #8
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            int systemID1Index = csv.GetFieldIndex(_VLID);
            int systemID2Index = csv.GetFieldIndex(_CountryID);
            int countryNameIndex = csv.GetFieldIndex(_CountryName);
            #else
            int systemID1Index = _VLIDIndex;
            int systemID2Index = _CountryIDIndex;
            int countryNameIndex = _CountryNameIndex;
            #endif
            Dictionary<string, Country> dbCountryHash = getDBCountryListSysKey();
            List<Country> importCountryList = new List<Country>();

            Country country;
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                string key = csv[systemID1Index];
                if (dbCountryHash.ContainsKey(key))
                {
                    country = dbCountryHash[key];
                }
                else
                {
                    country = new Country();
                    country.SystemID2 = csv[systemID2Index];
                }
                country.Name = csv[countryNameIndex];
                country.Import = true;
                country.CountryLanguage = SharedConsts.NeutralLangId;
                country.LanguageID = SharedConsts.NeutralLangId;
                country.SystemID1 = byte.Parse(csv[systemID1Index]);
                if (country.IsNew && !dbCountryHash.ContainsKey(key))
                    dbCountryHash.Add(key, country);
                if (!importCountryList.Contains(country))
                    importCountryList.Add(country);
                else
                    message(string.Format(GetLocalized("CountryExists"), _CurrentRow, _VLID, key));
            }
            csvDataEndRead();

            SaveOrUpdateList<Country>(_IContryServise, importCountryList);
        }
예제 #9
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            int systemID1Index = csv.GetFieldIndex(_VLID);
            int workingDayIndex = csv.GetFieldIndex(_WorkingDay);
            #else
            int systemID1Index = _VLIDIndex;
            int workingDayIndex = _WorkingDayIndex;
            #endif
            Dictionary<string, YearlyWorkingDay> dbWorkingDayHash = getDBWorkingDayList();
            Dictionary<string, long> countrySysKeyIDKey = getDBCountryListSysKeyIDKey();
            List<YearlyWorkingDay> importWDayList = new List<YearlyWorkingDay>();

            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                string workingDay = csv[workingDayIndex];
                string keyCountry = csv[systemID1Index];
                string keyWorkingDay = keyCountry + workingDay;

                if (!dbWorkingDayHash.ContainsKey(keyWorkingDay))
                {
                    if (countrySysKeyIDKey.ContainsKey(keyCountry))
                    {
                        YearlyWorkingDay yearlyWorkingDay = new YearlyWorkingDay();
                        yearlyWorkingDay.CountryID = countrySysKeyIDKey[keyCountry];
                        yearlyWorkingDay.WorkingDay = DateTime.ParseExact(workingDay, "yyyyMMdd", null);
                        importWDayList.Add(yearlyWorkingDay);
                        dbWorkingDayHash.Add(keyWorkingDay, yearlyWorkingDay);
                    }
                    else
                    {
                        message(string.Format(GetLocalized("CountryNotExistsDB"), _CurrentRow, _VLID, keyCountry));
                    }
                }
                else
                {
                    message(string.Format(GetLocalized("WorkingDayExistsDB"), _CurrentRow));
                }
            }
            csvDataEndRead();

            SaveList<YearlyWorkingDay>(_IContryServise.YearlyWorkingDayService, importWDayList);
        }
예제 #10
0
        static void Main(string[] args)
        {
            List<MyTransaction> transactions = new List<MyTransaction>();

            //nacteme skutecnosti
            Console.WriteLine("Zpracování skutečností AceMoney");
            using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(ALLTRANSACTIONFILE, Encoding.GetEncoding("Windows-1250")), true, ',', '"'))
            {
                csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;
                int i = 0;
                foreach (string[] row in csv)
                {
                    i++;
                    Console.Write("{0}", i); Console.CursorLeft = 0;
                    transactions.AddRange(new AceMoneyTransaction(row).GetMyTransactions());
                }
            }

            //nacteme plany
            Console.WriteLine("Zpracování plánu AceMoney");
            using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(PLANFILE, Encoding.GetEncoding("Windows-1250")), true, ',', '"'))
            {
                csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;
                int i=0 ;
                foreach (string[] row in csv)
                {
                    i++;
                    Console.Write("{0}",i); Console.CursorLeft = 0;
                    transactions.AddRange(new AceMoneyPlan(row).GetMyTransactions());
                }
            }

            //zapiseme prepracovane transakce
            StreamWriter sw = new StreamWriter(OUTPUTFILE, false, Encoding.GetEncoding("Windows-1250"));
            foreach (MyTransaction myT in transactions)
            {
                sw.WriteLine(myT.CsvRowString);
            }
            sw.Flush();
            sw.Close();
        }
		public static void Run2(CachedCsvReader csv, int field)
		{
			using (csv)
			{
				string s;

				if (field == -1)
				{
					while (csv.ReadNextRecord())
					{
						for (int i = 0; i < csv.FieldCount; i++)
							s = csv[i];
					}
				}
				else
				{
					while (csv.ReadNextRecord())
						s = csv[field];
				}
			}
		}
예제 #12
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            int worldIDIndex = csv.GetFieldIndex(_WorldID);
            int hwgr_IDIndex = csv.GetFieldIndex(_HWGR_ID);
            int hwgr_NameIndex = csv.GetFieldIndex(_HWGR_Name);
            #else
            int worldIDIndex = _WorldIDIndex;
            int hwgr_IDIndex = _HWGR_IDIndex;
            int hwgr_NameIndex = _HWGR_NameIndex;
            #endif

            Dictionary<string, ImportFileHWGRData> data = new Dictionary<string, ImportFileHWGRData>();

            //Add HWGR
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                int worldID = int.Parse(csv[worldIDIndex]);
                int hwgrID = int.Parse(csv[hwgr_IDIndex]);
                string hwgrName = csv[hwgr_NameIndex];
                string key = worldID.ToString() + hwgrID.ToString();
                if (!data.ContainsKey(key))
                    data.Add(key, new ImportFileHWGRData(_CurrentRow ,new ImportHWGRData(hwgrID, worldID, hwgrName)));
                else
                    message(string.Format(GetLocalized("HWGRExists"), _CurrentRow, _WorldID, worldID, _HWGR_ID, hwgrID));
            }
            csvDataEndRead();

            List<ImportHWGRData> list = new List<ImportHWGRData>(data.Count);
            foreach (ImportFileHWGRData value in data.Values)
                list.Add(value.Data);
            SaveDataResult saveDataResult = _StoreService.HWGRService.ImportHWGR(list);
            list = (List<ImportHWGRData>)saveDataResult.Data;
            foreach (ImportHWGRData value in list)
            {
                string key = value.World_SystemID.ToString() + value.HWGR_SystemID.ToString();
                message(string.Format(GetLocalized("WorldNotExistsDB"), data[key].RecordNumber, _WorldID, value.World_SystemID));
            }
        }
		public static CachedCsvReader Run1(string path, int field)
		{
			CachedCsvReader csv = new CachedCsvReader(new StreamReader(path), false);

			string s;

			if (field == -1)
			{
				while (csv.ReadNextRecord())
				{
					for (int i = 0; i < csv.FieldCount; i++)
						s = csv[i];
				}
			}
			else
			{
				while (csv.ReadNextRecord())
					s = csv[field];
			}

			return csv;
		}
예제 #14
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            int countryIDIndex = csv.GetFieldIndex(_VLID);
            int feastDateIndex = csv.GetFieldIndex(_FeastDate);
            #else
            int countryIDIndex = _VLIDIndex;
            int feastDateIndex = _FeastDateIndex;
            #endif

            Dictionary<string, ImportFeastsData> data = new Dictionary<string, ImportFeastsData>();
            int i = 1;
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                int countryID = int.Parse(csv[countryIDIndex]);
                DateTime feastDate = DateTime.ParseExact(csv[feastDateIndex], "yyyyMMdd", null);
                string key = countryID.ToString() + feastDate.ToString();
                if (!data.ContainsKey(key))
                    data.Add(key, new ImportFeastsData(i, new  ImportDaysData(countryID, feastDate)));
                else
                    message(string.Format(GetLocalized("FeastExists"), i, _CountryID, countryID, _FeastDate, feastDate));
                i++;
            }
            csvDataEndRead();

            List<ImportDaysData> list = new List<ImportDaysData>(data.Count);
            foreach (ImportFeastsData value in data.Values)
                list.Add(value.Data);
            SaveDataResult saveDataResult = _FeastService.ImportFeasts(list);
            list = (List<ImportDaysData>)saveDataResult.Data;
            foreach (ImportDaysData value in list)
            {
                string key = value.CountryID.ToString() + value.Date.ToString();
                message(string.Format(GetLocalized("CountryNotExistsDB"), data[key].RecordNumber, _VLID, value.CountryID));
            }
        }
예제 #15
0
        private static DataTable GetDataSetFromCsvFile(string filename)
        {
            var csvReader = new CachedCsvReader(File.OpenText(filename), true);

            var dt = new DataTable();
            foreach (var column in csvReader.Columns)
            {
                dt.Columns.Add(column.Name);
            }
            var headerRow = dt.NewRow();
            for (int i = 0; i < csvReader.Columns.Count; i++)
            {
                headerRow[i] = csvReader.Columns[i].Name;
            }
            dt.Rows.Add(headerRow);
            while (csvReader.ReadNextRecord())
            {
                var row = dt.NewRow();
                for (int i = 0; i < csvReader.FieldCount; i++)
                {
                    row[i] = csvReader[i];
                }
                dt.Rows.Add(row);
            }
            return dt;
        }
		public static void Run2(CachedCsvReader csv)
		{
			Run2(csv, -1);
		}
        private bool write2FreeFormat(string resultsForOneYear, int[] fields, StreamWriter writer, bool needWriteHeader, FormatType format)
        {
            StringBuilder sb = new StringBuilder();
            using (CachedCsvReader csv = new CachedCsvReader(new StringReader(resultsForOneYear), true))
            {
                if (csv.FieldCount < 27) return false;

                string date = "";
                if (needWriteHeader)
                {
                    string[] fieldNames = csv.GetFieldHeaders();
                    sb.Append(formatFreeFormatData(fieldNames[0], format, true));

                    foreach (int field in fields)
                    {
                        if (format == FormatType.SIMPLE_CSV)
                            sb.Append(",");
                        sb.Append(formatFreeFormatData(fieldNames[field], format, false));
                    }
                    sb.AppendLine();
                }
                while (csv.ReadNextRecord())
                {
                    date = csv[0];
                    sb.Append(formatFreeFormatData(date, format, true));

                    foreach (int field in fields)
                    {
                        if (format == FormatType.SIMPLE_CSV)
                            sb.Append(",");
                        sb.Append(formatFreeFormatData(csv[field], format, false));
                    }
                    sb.AppendLine();
                }

                checkLastDayofYear(date);
            }
            if (sb.Length > 0)
                writer.Write(sb.ToString());

            return sb.Length > 0;
        }
        /// <summary>
        /// Write data in given time range as ArcSWAT txt file
        /// </summary>
        /// <param name="startYear"></param>
        /// <param name="endYear"></param>
        /// <param name="destinationFolder"></param>
        /// <returns></returns>
        private bool save2ArcSWATAscii(int startYear, int endYear, string destinationFolder)
        {
            //get the file name using station name
            string timeAffix = getTimeAffix();
            string pFile = string.Format("{0}\\P{1}{2}.txt", Path.GetFullPath(destinationFolder), _id, timeAffix);  //precipitation
            string tFile = string.Format("{0}\\T{1}{2}.txt", Path.GetFullPath(destinationFolder), _id, timeAffix);  //temperature

            this.setProgress(0, string.Format("Processing station {0}", _id));
            this.setProgress(0, pFile);
            this.setProgress(0, tFile);

            int processPercent = 0;
            bool hasResults = false;
            string numberForamt = "F1";
            string temperatureFormat = "{0:"+numberForamt+"},{1:"+numberForamt+"}";
            StringBuilder pSb = new StringBuilder();
            StringBuilder tSb = new StringBuilder();
            clearFailureYears();
            clearUncompletedYears();
            for (int i = startYear; i <= endYear; i++)
            {
                setProgress(processPercent, string.Format("Downloading data for station: {0}, year: {1}", _id, i));
                string resultsForOneYear = this.retrieveAnnualDailyClimateData(i, true);
                if (resultsForOneYear.Length == 0)
                {
                    addFailureYear(i);
                    continue;
                }

                processPercent += 1;
                setProgress(processPercent, "Writing data");

                using (CachedCsvReader csv = new CachedCsvReader(new StringReader(resultsForOneYear), true))
                {
                    if (csv.FieldCount >= 27)
                    {
                        hasResults = true;

                        string lastDay = "";
                        while (csv.ReadNextRecord())
                        {
                            //add starting date
                            if (pSb.Length == 0)
                            {
                                DateTime date = DateTime.Now;
                                if (DateTime.TryParse(csv[0], out date))
                                {
                                    string startDate = string.Format("{0:yyyyMMdd}, Generated by Environment Canada Climate Data Reader",date);
                                    pSb.AppendLine(startDate);
                                    tSb.AppendLine(startDate);
                                }
                            }
                            lastDay = csv[0];

                            //write data
                            double p = ClimateString2Double(csv[TOTAL_PRECIPITATION_COL_INDEX]);
                            pSb.AppendLine(p.ToString(numberForamt));

                            double t_max = ClimateString2Double(csv[MAX_T_COL_INDEX]);
                            double t_min = ClimateString2Double(csv[MIN_T_COL_INDEX]);
                            tSb.AppendLine(string.Format(temperatureFormat, t_max, t_min));
                        }
                        checkLastDayofYear(lastDay);
                    }
                }
                processPercent += 1;
            }

            if (pSb.Length > 0)
                using (StreamWriter writer = new StreamWriter(pFile))
                    writer.Write(pSb.ToString());
            if (tSb.Length > 0)
                using (StreamWriter writer = new StreamWriter(tFile))
                    writer.Write(tSb.ToString());

            return hasResults;
        }
예제 #19
0
 /// <summary>
 /// Initializes a new instance of the CsvBindingList class.
 /// </summary>
 /// <param name="csv"></param>
 public CsvBindingList(CachedCsvReader csv)
 {
     _csv       = csv;
     _count     = -1;
     _direction = ListSortDirection.Ascending;
 }
예제 #20
0
        static void Main(string[] args)
        {
            using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(@"e:\1.txt"), false, '\t'))       //http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader?msg=1294084#xx1294084xx
            {                                                                                                   //CachedCsvReader is used for MoveTo() method

                # region PDFinitialization

                Document document = new Document();
                Style style = document.Styles["Normal"];
                style.Font.Name = "Tahoma";
                style.Font.Size = 8;

                Section section = document.AddSection();
                //section.AddParagraph("Hello, World!");

                section.AddParagraph();

                Paragraph paragraph = section.AddParagraph();
                paragraph.Format.Font.Color = Color.FromCmyk(100, 30, 20, 50);
                //paragraph.AddFormattedText("Hello, World!", TextFormat.Underline);
                //AddFormattedText also returns an object:
                //FormattedText ft = paragraph.AddFormattedText("Small text",
                //  TextFormat.Bold);
                //ft.Font.Size = 6;

                csv.MoveTo(1);
                document.LastSection.AddParagraph("Sample: " + csv[1] + ", Date and time: " + csv[2], "Heading2");
                document.LastSection.AddParagraph();

                Table table = new Table();
                table.Borders.Width = 0.75;

                //Table table2 = new Table();
                //table2.Borders.Width = 0.75;
                //Column column2 = table2.AddColumn(Unit.FromCentimeter(3));
                //column2.Format.Alignment = ParagraphAlignment.Center;

                Column column = table.AddColumn(Unit.FromCentimeter(3));    //1st column
                column.Format.Alignment = ParagraphAlignment.Center;

                column.Table.AddColumn(Unit.FromCentimeter(2));             //2nd column
                column.Format.Alignment = ParagraphAlignment.Right;

                column.Table.AddColumn(Unit.FromCentimeter(2));             //3rd column
                column.Format.Alignment = ParagraphAlignment.Center;

                column.Table.AddColumn(Unit.FromCentimeter(2));             //4th column
                column.Format.Alignment = ParagraphAlignment.Center;

                column.Table.AddColumn(Unit.FromCentimeter(2));             //5th column
                column.Format.Alignment = ParagraphAlignment.Center;

                column.Table.AddColumn(Unit.FromCentimeter(2));             //6th column
                column.Format.Alignment = ParagraphAlignment.Center;

                column.Table.AddColumn(Unit.FromCentimeter(2));             //7th column
                column.Format.Alignment = ParagraphAlignment.Center;

                Row row = table.AddRow();
                row.Shading.Color = Colors.PaleGoldenrod;
                Cell cell = row.Cells[0];

                cell.AddParagraph("Measurement no.");

                row.Cells[1].AddParagraph("FW");
                row.Cells[2].AddParagraph("FWN");
                row.Cells[3].AddParagraph("HWL");
                row.Cells[4].AddParagraph("HWNL");
                row.Cells[5].AddParagraph("HWR");
                row.Cells[6].AddParagraph("HWNR");

                # endregion PDFinitialization

                #region loops

                for (int i = 0; i < 12; i=i+11)
                {

                    for (int j = 1; j < 10; j++)
                    {

                        csv.MoveTo(j); //row
                        //Console.Write(string.Format("{0} ", csv[i]));

                        FW.Add(double.Parse(csv[3], CultureInfo.InvariantCulture));
                        FWN.Add(double.Parse(csv[4], CultureInfo.InvariantCulture));
                        HWL.Add(double.Parse(csv[5], CultureInfo.InvariantCulture));
                        HWNL.Add(double.Parse(csv[6], CultureInfo.InvariantCulture));
                        HWR.Add(double.Parse(csv[7], CultureInfo.InvariantCulture));
                        HWNR.Add(double.Parse(csv[8], CultureInfo.InvariantCulture));

                        table.AddRow();

                        table.Rows[j - i].Cells[0].AddParagraph((j - i).ToString());
                        table.Rows[j - i].Cells[1].AddParagraph(csv[3]);
                        table.Rows[j - i].Cells[2].AddParagraph(csv[4]);
                        table.Rows[j - i].Cells[3].AddParagraph(csv[5]);
                        table.Rows[j - i].Cells[4].AddParagraph(csv[6]);
                        table.Rows[j - i].Cells[5].AddParagraph(csv[7]);
                        table.Rows[j - i].Cells[6].AddParagraph(csv[8]);

                        var descrStatFW = new DescriptiveStatistics(FW);
                        double KurtosisHW = descrStatFW.Kurtosis;
                        double SkewnessHW = descrStatFW.Skewness;

                        var descrStatFWN = new DescriptiveStatistics(FWN);
                        double KurtosisFWN = descrStatFWN.Kurtosis;
                        double SkewnessFWN = descrStatFWN.Skewness;

                        var descrStatHWL = new DescriptiveStatistics(HWL);
                        double KurtosisHWL = descrStatHWL.Kurtosis;
                        double SkewnessHWL = descrStatHWL.Skewness;

                        var descrStatHWNL = new DescriptiveStatistics(HWNL);
                        double KurtosisHWNL = descrStatHWNL.Kurtosis;
                        double SkewnessHWNL = descrStatHWNL.Skewness;

                        var descrStatHWR = new DescriptiveStatistics(HWR);
                        double KurtosisHWR = descrStatHWR.Kurtosis;
                        double SkewnessHWR = descrStatHWR.Skewness;

                        var descrStatHWNR = new DescriptiveStatistics(HWNR);
                        double KurtosisHWNR = descrStatHWNR.Kurtosis;
                        double SkewnessHWNR = descrStatHWNR.Skewness;

                        var histogram = new Histogram(FW, 4);
                        //double bucket3count = histogram[3].Count;
                        //double bucket3count = histogram.UpperBound;
                        //double bucket3count = histogram.DataCount;
                        //double bucket3count = histogram.BucketCount;
                        //double bucket3count = histogram[2].Width;                   //width of the bin
                        double bucket3count = histogram[0].LowerBound;                //histogram[0].LowerBound=histogram.LowerBound

                        Console.WriteLine();
                        Console.WriteLine(string.Format("{0} ", FW.Mean()));
                        Console.WriteLine();
                        Console.WriteLine(string.Format("{0} ", FW.StandardDeviation()));

                        Console.WriteLine();
                        Console.WriteLine(string.Format("{0} ", KurtosisHW));
                        Console.WriteLine();
                        Console.WriteLine(string.Format("{0} ", SkewnessHW));
                        Console.WriteLine();
                        Console.WriteLine(string.Format("{0} ", bucket3count));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("Mean");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(FW.Mean(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[10].Cells[2].AddParagraph(Math.Round(FWN.Mean(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[10].Cells[3].AddParagraph(Math.Round(HWL.Mean(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[10].Cells[4].AddParagraph(Math.Round(HWNL.Mean(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[10].Cells[5].AddParagraph(Math.Round(HWR.Mean(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[10].Cells[6].AddParagraph(Math.Round(HWNR.Mean(), 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("Standard dev.");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(FW.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[11].Cells[2].AddParagraph(Math.Round(FWN.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[11].Cells[3].AddParagraph(Math.Round(HWL.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[11].Cells[4].AddParagraph(Math.Round(HWNL.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[11].Cells[5].AddParagraph(Math.Round(HWR.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[11].Cells[6].AddParagraph(Math.Round(HWNR.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("2x Standard dev.");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(2 * FW.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[12].Cells[2].AddParagraph(Math.Round(2 * FWN.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[12].Cells[3].AddParagraph(Math.Round(2 * HWL.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[12].Cells[4].AddParagraph(Math.Round(2 * HWNL.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[12].Cells[5].AddParagraph(Math.Round(2 * HWR.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[12].Cells[6].AddParagraph(Math.Round(2 * HWNR.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("3x Standard dev.");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(3 * FW.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[13].Cells[2].AddParagraph(Math.Round(3 * FWN.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[13].Cells[3].AddParagraph(Math.Round(3 * HWL.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[13].Cells[4].AddParagraph(Math.Round(3 * HWNL.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[13].Cells[5].AddParagraph(Math.Round(3 * HWR.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[13].Cells[6].AddParagraph(Math.Round(3 * HWNR.StandardDeviation(), 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("Min");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(FW.Min(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[14].Cells[2].AddParagraph(Math.Round(FWN.Min(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[14].Cells[3].AddParagraph(Math.Round(HWL.Min(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[14].Cells[4].AddParagraph(Math.Round(HWNL.Min(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[14].Cells[5].AddParagraph(Math.Round(HWR.Min(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[14].Cells[6].AddParagraph(Math.Round(HWNR.Min(), 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("Max");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(FW.Max(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[15].Cells[2].AddParagraph(Math.Round(FWN.Max(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[15].Cells[3].AddParagraph(Math.Round(HWL.Max(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[15].Cells[4].AddParagraph(Math.Round(HWNL.Max(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[15].Cells[5].AddParagraph(Math.Round(HWR.Max(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[15].Cells[6].AddParagraph(Math.Round(HWNR.Max(), 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("Median");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(FW.Median(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[16].Cells[2].AddParagraph(Math.Round(FWN.Median(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[16].Cells[3].AddParagraph(Math.Round(HWL.Median(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[16].Cells[4].AddParagraph(Math.Round(HWNL.Median(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[16].Cells[5].AddParagraph(Math.Round(HWR.Median(), 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[16].Cells[6].AddParagraph(Math.Round(HWNR.Median(), 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("Kurtosis");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(KurtosisHW, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[17].Cells[2].AddParagraph(Math.Round(KurtosisFWN, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[17].Cells[3].AddParagraph(Math.Round(KurtosisHWL, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[17].Cells[4].AddParagraph(Math.Round(KurtosisHWNL, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[17].Cells[5].AddParagraph(Math.Round(KurtosisHWR, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[17].Cells[6].AddParagraph(Math.Round(KurtosisHWNR, 2).ToString(CultureInfo.InvariantCulture));

                        row = table.AddRow();
                        row.Shading.Color = Colors.PaleGoldenrod;
                        cell = row.Cells[0];
                        cell.AddParagraph("Skewness");
                        cell = row.Cells[1];
                        cell.AddParagraph(Math.Round(SkewnessHW, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[18].Cells[2].AddParagraph(Math.Round(SkewnessFWN, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[18].Cells[3].AddParagraph(Math.Round(SkewnessHWL, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[18].Cells[4].AddParagraph(Math.Round(SkewnessHWNL, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[18].Cells[5].AddParagraph(Math.Round(SkewnessHWR, 2).ToString(CultureInfo.InvariantCulture));
                        table.Rows[18].Cells[6].AddParagraph(Math.Round(SkewnessHWNR, 2).ToString(CultureInfo.InvariantCulture));

                        //table.SetEdge(0, 0, 2, 3, Edge.Box, BorderStyle.Single, 1.5, Colors.Black);

                        document.LastSection.Add(table);

                        PdfDocumentRenderer pdfRenderer = new PdfDocumentRenderer(false,
                        PdfFontEmbedding.Always);
                        pdfRenderer.Document = document;
                        pdfRenderer.RenderDocument();
                        string filename = "Sample_" + FileIndex.ToString() + ".pdf";
                        pdfRenderer.PdfDocument.Save(filename);
                    }

                    FileIndex++;
                }

                #endregion

                //PdfDocument inputDocument1 = PdfReader.Open("HelloWorld4.pdf", PdfDocumentOpenMode.Import);
                //PdfDocument inputDocument2 = PdfReader.Open("HelloWorld5.pdf", PdfDocumentOpenMode.Import);

                //PdfDocument outputDocument = new PdfDocument();

                // Show consecutive pages facing. Requires Acrobat 5 or higher.
                //outputDocument.PageLayout = PdfPageLayout.TwoColumnLeft;

                //// Iterate pages
                //int count = inputDocument.PageCount;
                //for (int idx = 0; idx < count; idx++)
                //{
                //    // Get the page from the external document...
                //    PdfPage page = inputDocument.Pages[idx];
                //    // ...and add it to the output document.
                //    outputDocument.AddPage(page);
                //}

                // Get some file names
                //string[] files = GetFiles();
                string[] files = { "Sample_1.pdf", "Sample_2.pdf" };

                // Open the output document
                PdfDocument outputDocument = new PdfDocument();

                // Iterate files
                foreach (string file in files)
                {
                    // Open the document to import pages from it.
                    PdfDocument inputDocument = PdfReader.Open(file, PdfDocumentOpenMode.Import);

                    // Iterate pages
                    int count = inputDocument.PageCount;
                    for (int idx = 0; idx < count; idx++)
                    {
                        // Get the page from the external document...
                        PdfPage page = inputDocument.Pages[idx];
                        // ...and add it to the output document.
                        outputDocument.AddPage(page);
                    }
                }

                // Save the document...
                const string filenameCombined = "ConcatenatedDocument1_tempfile.pdf";
                outputDocument.Save(filenameCombined);
                // ...and start a viewer.
                //Process.Start(filename);

            }
예제 #21
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            #else
            int persNumberIndex = _PersNumberIndex;
            int contractBeginIndex= _ContractBeginIndex;
            int contractEndIndex= _ContractEndIndex;
            int persIDIndex= _PersIDIndex;
            int lastNameIndex= _LastNameIndex;
            int firstNameIndex= _FirstNameIndex;
            int worldIDIndex= _WorldIDIndex;
            int hwgr_IDIndex = _HWGR_IDIndex;
            int storeIDIndex = _StoreIDIndex;
            int departmentIndex = _DepartmentIndex;
            int allInIndex = _AllInIndex;

            #endif
            if (csv.FieldCount < (allInIndex + 1))
            {
                throw new Exception(GetLocalized("EmployeeImportFileOldVersion"));
            }
            //CultureInfo.GetCultureInfo("en-US").NumberFormat
            NumberFormatInfo numberFormatInfo = new NumberFormatInfo();
            numberFormatInfo.CurrencyDecimalSeparator = ".";
            numberFormatInfo.CurrencyGroupSeparator = " ";
            numberFormatInfo.NumberDecimalSeparator = ".";
            numberFormatInfo.NumberGroupSeparator = " ";

            //numberFormatInfo.PositiveInfinitySymbol = "+";
            //numberFormatInfo.NegativeInfinitySymbol = "-";
            Dictionary<string, ImportFileEmployeeData> data = new Dictionary<string, ImportFileEmployeeData>();
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                string department = csv[departmentIndex];
                string worldID = csv[worldIDIndex];
                if (string.IsNullOrEmpty(worldID)) worldID = "-1";
                string hwgr_ID = csv[hwgr_IDIndex];
                if (string.IsNullOrEmpty(hwgr_ID)) hwgr_ID = "-1";
                string storeID = csv[storeIDIndex];
                string key = csv[persIDIndex];//storeID.ToString() + worldID.ToString() + hwgr_ID.ToString();
                if (string.IsNullOrEmpty(storeID)) storeID = "-1";
                string contractWorkingHours = csv[_ContractWorkingHoursIndex];
                if (string.IsNullOrEmpty(contractWorkingHours)) contractWorkingHours = "0";
                //else if (contractWorkingHours[0] == ',') contractWorkingHours = "0" + contractWorkingHours;
                string availableHolidays= csv[_AvailableHolidaysIndex];
                if (string.IsNullOrEmpty(availableHolidays)) availableHolidays = "0";
                //else if (availableHolidays[0] == ',') availableHolidays = "0" + availableHolidays;
                string balanceHours = csv[_BalanceHoursIndex];
                if (string.IsNullOrEmpty(balanceHours)) balanceHours = "0";
                //else if (balanceHours[0] == ',') balanceHours = "0" + balanceHours;
                string persNumber = csv[persNumberIndex];
                if (string.IsNullOrEmpty(persNumber)) persNumber = "0";
                if (!data.ContainsKey(key))
                {
                    ImportEmployeeData eData = new ImportEmployeeData();
                    eData.World_SystemID = int.Parse(worldID);
                    eData.HWGR_SystemID = int.Parse(hwgr_ID);
                    eData.Store_SystemID = int.Parse(storeID);
                    eData.PersID = key;
                    eData.FirstName = csv[firstNameIndex];
                    eData.LastName = csv[lastNameIndex];
                    eData.Department = department;
                    string contractBegin = csv[contractBeginIndex];
                    if (string.IsNullOrEmpty(contractBegin)) contractBegin = DateTimeSql.SmallDatetimeMinStr;
                    eData.ContractBegin = DateTime.ParseExact(contractBegin, "yyyyMMdd", null);
                    string contractEnd = csv[contractEndIndex];
                    if (string.IsNullOrEmpty(contractEnd)) contractEnd = DateTimeSql.SmallDatetimeMaxStr;
                    eData.ContractEnd = DateTime.ParseExact(contractEnd, "yyyyMMdd", null);
                    try
                    {
                        eData.ContractWorkingHours = decimal.Parse(contractWorkingHours, numberFormatInfo);
                        eData.AvailableHolidays = decimal.Parse(availableHolidays, numberFormatInfo);
                        eData.BalanceHours = decimal.Parse(balanceHours, numberFormatInfo);
                        eData.BalanceHours = eData.BalanceHours * 60;//minutes
                        eData.PersNumber = int.Parse(persNumber);
                        eData.AllIn = byte.Parse(csv[allInIndex]);
                    }
                    catch (FormatException ex)
                    {
                        message(string.Format(GetLocalized("NumberFormatError"),_CurrentRow,ex.Message));
                        continue;
                    }

                    if (eData.AllIn != 0)
                        eData.AllIn = 1;
                    if (eData.ContractEnd < eData.ContractBegin)
                    {
                        message(string.Format(GetLocalized("EmployeeContractDateError"), _CurrentRow, key, eData.ContractBegin, eData.ContractEnd));
                        continue;
                    }
                    else if (eData.ContractWorkingHours <= 0)
                    {
                        message(string.Format(GetLocalized("EmployeeContractTimeError"), _CurrentRow, key, eData.ContractWorkingHours));
                        continue;
                    }
                    data.Add(key, new ImportFileEmployeeData(_CurrentRow, eData));
                }
                else
                    message(string.Format(GetLocalized("EmployeeExists"), _CurrentRow, key));
            }
            csvDataEndRead();

            List<ImportEmployeeData> list = new List<ImportEmployeeData>(data.Count);
            foreach (ImportFileEmployeeData value in data.Values)
                list.Add(value.Data);
            ImportEmployeeResult importEmployeeResult = _EmployeeService.ImportEmployee(list);
            list = (List<ImportEmployeeData>)importEmployeeResult.DataError;
            if (list != null)
            {
                foreach (ImportEmployeeData value in list)
                {
                    string key = value.PersID;
                    switch (value.ImportError)
                    {
                        case EmployeeImportError.NotAssignToStore:
                            message(string.Format(GetLocalized("EmployeeNotAssignToStore"), data[key].RecordNumber, key));
                            break;
                        case EmployeeImportError.ContractBeginChange:
                            message(string.Format(GetLocalized("EmployeeIEContractBeginChange"), data[key].RecordNumber, key, data[key].Data.ContractBegin));
                            break;
                        case EmployeeImportError.ContractEndChangeAndLessImportDate:
                            message(string.Format(GetLocalized("EmployeeIEContractEndChangeAndLessImportDate"), data[key].RecordNumber, key, data[key].Data.ContractEnd));
                            break;
                        default:
                            goto case EmployeeImportError.NotAssignToStore;
                    }
                }
            }
            if (importEmployeeResult.DataChanged != null)
                _Result = importEmployeeResult.DataChanged;
            if (!importEmployeeResult.Success)
                throw new Exception("");
        }
예제 #22
0
        //Carrega dados do imóvel
        void BtnLoadImoClick(object sender, EventArgs e)
        {
            char separador = ';';
            System.Text.Encoding codificacao = null;
            if (radioButton6.Checked == true)
            {
                codificacao = Encoding.Default;
            }
            else if (radioButton5.Checked == true)
            {
                codificacao = Encoding.UTF8;
            }
            else if (radioButton7.Checked == true)
            {
                codificacao = System.Text.Encoding.GetEncoding("iso-8859-1");
            }

            openFileDialog1.Filter = "Arquivo CSV (*.csv)|*.csv|Arquivo TXT (*.txt)|*.txt";
            openFileDialog1.FileName = "";
            openFileDialog1.Title = "Carregar dados do imóvel...";
            openFileDialog1.RestoreDirectory = true;

            DialogResult result = openFileDialog1.ShowDialog();

            //Limpar tabela temporária
            dttemp.Clear();
            dttemp.Columns.Clear();

            if (result == DialogResult.OK)
            {
                arquivo = openFileDialog1.FileName;
                using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(arquivo, codificacao), true, separador))
                {
                    dttemp.Load(csv);

                    //Verifica se o arquivo tem 15 campos, para o caso de o usuário selecionar um arquivo errado
                    if (dttemp.Columns.Count == 15)
                    {
                        csv.ReadNextRecord();

                        txtImovel.Text = csv[0];
                        txtMunicipio.Text = csv[1];
                        txtMatricula.Text = csv[2];
                        txtComarca.Text = csv[3];
                        txtCartorio.Text = csv[4];
                        txtCodIncra.Text = csv[5];
                        txtArea.Text = csv[6];
                        txtAreaha.Text = csv[7];
                        textBox2.Text = csv[8];
                        txtProprietario.Text = csv[9];
                        cboMC.Text = csv[10];
                        cboLongitude.Text = csv[11];
                        cboFuso.Text = csv[12];
                        cboHemisferio.Text = csv[13];
                        txtDatum.Text = csv[14];
                    }
                    else
                    {
                        MessageBox.Show("Arquivo fora da especificação.");
                    }
                }
            }
        }
예제 #23
0
        //Ler arquivo
        void readCsv(string arquivo)
        {
            try
            {
                //verificar o caractere separador do arquivo csv ou texto
                // Já salvas as configurações setadas na memória
                char separador = ' ';
                if (radioButton1.Checked == true)
                {
                    separador = ';';
                    Properties.Settings.Default.Delimitador  = ';';
                }
                if (radioButton2.Checked == true)
                {
                    separador = '\t';
                    Properties.Settings.Default.Delimitador  = '\t';
                }

                System.Text.Encoding codificacao = null;
                if (radioButton6.Checked == true)
                {
                    codificacao = Encoding.Default;
                    Properties.Settings.Default.Codificacao  = "ansi";
                }
                else if (radioButton5.Checked == true)
                {
                    codificacao = Encoding.UTF8;
                    Properties.Settings.Default.Codificacao  = "utf8";
                }
                else if (radioButton7.Checked == true)
                {
                    codificacao = System.Text.Encoding.GetEncoding("iso-8859-1");
                    Properties.Settings.Default.Codificacao  = "iso";
                }

                //Salvas as configurações
                Properties.Settings.Default.Save();

                using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(arquivo, codificacao), true, separador))
                {
                    dt.Clear();
                    dt.Columns.Clear();
                    dt.Load(csv);

                    //Caso o arquivo seja apenas com Ponto;X;Y
                    if (dt.Columns.Count == 3)
                    {
                        dt2.Clear();
                        dt2.Columns.Clear();
                        dt2 = dt.Clone();
                        dt2.Columns[1].DataType = typeof(double);
                        dt2.Columns[2].DataType = typeof(double);
                        foreach (DataRow row in dt.Rows)
                        {
                            dt2.ImportRow(row);
                        }

                        //adiciona as colunas
                        if (dt2.Columns.Contains("Distancia") == true)
                        {
                            dt2.Columns.Remove("Distancia");
                            dt2.Columns.Add(new DataColumn("Distancia", typeof(string)));
                        }
                        else if (dt2.Columns.Contains("Distancia") == false)
                        {
                            dt2.Columns.Add(new DataColumn("Distancia", typeof(string)));
                        }

                        if (dt2.Columns.Contains("Azimute") == true)
                        {
                            dt2.Columns.Remove("Azimute");
                            dt2.Columns.Add(new DataColumn("Azimute", typeof(string)));
                        }
                        else if (dt2.Columns.Contains("Azimute") == false)
                        {
                            dt2.Columns.Add(new DataColumn("Azimute", typeof(string)));
                        }

                        if (dt2.Columns.Contains("Confrontante") == true)
                        {
                            dt2.Columns.Remove("Confrontante");
                            dt2.Columns.Add(new DataColumn("Confrontante", typeof(string)));
                        }
                        else if (dt2.Columns.Contains("Confrontante") == false)
                        {
                            dt2.Columns.Add(new DataColumn("Confrontante", typeof(string)));
                        }

                        if (dt2.Columns.Contains("Divisa") == true)
                        {
                            dt2.Columns.Remove("Divisa");
                            dt2.Columns.Add(new DataColumn("Divisa", typeof(string)));
                        }
                        else if (dt2.Columns.Contains("Divisa") == false)
                        {
                            dt2.Columns.Add(new DataColumn("Divisa", typeof(string)));
                        }

                        dataGridView1.DataSource = dt2;

                        //formata as casas decimais das coordenadas
                        formataCoordenadaTabela();
                    }

                    //Caso o arquivo seja com Ponto;X;Y;Distancia;Azimute;Confrontante;Divisa
                    else if (dt.Columns.Count == 7)
                    {
                        dt2.Clear();
                        dt2.Columns.Clear();
                        dt2 = dt.Clone();
                        dt2.Columns[1].DataType = typeof(Decimal);
                        dt2.Columns[2].DataType = typeof(Decimal);
                        foreach (DataRow row in dt.Rows)
                        {
                            dt2.ImportRow(row);
                        }

                        //Deixando as colunas editáveis
                        foreach (DataGridViewColumn column in dataGridView1.Columns)
                        {
                            if ((column.Name == "Distancia") || (column.Name == "Azimute") || (column.Name == "Confrontante") || (column.Name == "Divisa"))
                            {
                                column.ReadOnly = false;
                            }
                        }

                        dt2.Columns["Distancia"].ReadOnly = false;
                        dt2.Columns["Azimute"].ReadOnly = false;
                        dt2.Columns["Confrontante"].ReadOnly = false;
                        dt2.Columns["Divisa"].ReadOnly = false;

                        dataGridView1.DataSource = dt2;

                        //formata as casas decimais das coordenadas
                        formataCoordenadaTabela();
                    }
                    else
                    {
                        MessageBox.Show("Tabela fora da especificação.");
                    }
                }
            }

            catch (Exception  e)
            {
                MessageBox.Show("Erro ao abrir arquivo: Tabela fora da especificação.");
            }
        }
예제 #24
0
        //Carregar dados do Profissional
        void BtnLerProfClick(object sender, EventArgs e)
        {
            char separador = ';';
            System.Text.Encoding codificacao = null;
            if (radioButton6.Checked == true)
            {
                codificacao = Encoding.Default;
            }
            else if (radioButton5.Checked == true)
            {
                codificacao = Encoding.UTF8;
            }
            else if (radioButton7.Checked == true)
            {
                codificacao = System.Text.Encoding.GetEncoding("iso-8859-1");
            }

            openFileDialog1.Filter = "Arquivo CSV (*.csv)|*.csv|Arquivo TXT (*.txt)|*.txt";
            openFileDialog1.FileName = "";
            openFileDialog1.Title = "Carregar dados do Profissioanl...";
            openFileDialog1.RestoreDirectory = true;

            DialogResult result = openFileDialog1.ShowDialog();

            //Limpar tabela temporária
            dttemp.Clear();
            dttemp.Columns.Clear();

            if (result == DialogResult.OK)
            {
                arquivo = openFileDialog1.FileName;
                using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(arquivo, codificacao), true, separador))
                {
                    dttemp.Load(csv);

                    //Verifica se o arquivo começa com a palavra 'profissional', para o caso de o usuário selecionar um arquivo errado
                    if (dttemp.Columns.Contains("profissional") == true)
                    {
                        csv.ReadNextRecord();
                        textBox16.Text = csv[0];
                        txtRegistro.Text = csv[1];
                        txtCidade.Text = csv[2];
                    }
                    else
                    {
                        MessageBox.Show("Arquivo fora da especificação.");
                    }
                }
            }
        }
예제 #25
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            int worldIDIndex = csv.GetFieldIndex(_WorldID);
            int worldNameIndex = csv.GetFieldIndex(_WorldName);
            #else
            int worldIDIndex = _WorldIDIndex;
            int worldNameIndex = _WorldNameIndex;
            #endif
            Dictionary<string, World> dbWorldHash = getDBWorldHash();
            Dictionary<long, Store> dbStoreHash = getDBStoreList();
            Dictionary<string, StoreToWorld> dbStore_WorldHash = getStore_WorldHash();

            List<World> worldSaveList = new List<World>();
            List<StoreToWorld> store_WorldSaveList = new List<StoreToWorld>();

            bool isNew= false;
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                string worldID = csv[worldIDIndex];
                string worldName = csv[worldNameIndex];
                string key = worldID;
                World world;
                if (dbWorldHash.ContainsKey(key))
                {
                    world = dbWorldHash[key];
                }
                else
                {
                    world = new World();
                }
                world.ExSystemID = int.Parse(worldID);
                world.LanguageID = SharedConsts.NeutralLangId;
                world.Name = worldName;
                world.WorldTypeID = WorldType.World;
                world.Import = true;
                if (!worldSaveList.Contains(world))
                    worldSaveList.Add(world);
                else
                    message(string.Format(GetLocalized("WorldExists"), _CurrentRow, _WorldID, worldID));

                if (world.IsNew && !dbWorldHash.ContainsKey(key))
                {
                    dbWorldHash.Add(key, world);
                    isNew= true;
                }
            }
            csvDataEndRead();
            SaveOrUpdateList<World>(_IStoreService.WorldService,worldSaveList);

            if (isNew)
                dbWorldHash = getDBWorldHash();
            foreach (Store store in dbStoreHash.Values)
            {
                foreach (World world in dbWorldHash.Values)
                {
                    string key= store.ID.ToString () + world.ID.ToString ();
                    if (!dbStore_WorldHash.ContainsKey(key))
                    {
                        StoreToWorld store_world = new StoreToWorld(world.ID, store.ID);
                        store_WorldSaveList.Add(store_world);
                        dbStore_WorldHash.Add(key, store_world);
                    }
                }
            }
            if (dbStoreHash.Count == 0)
                message(GetLocalized("StoresNotExistsDB"));
            SaveList<StoreToWorld>(_IStoreService.StoreToWorldService, store_WorldSaveList);
        }
        /// <summary>
        /// Retrieve station basic information for given year.
        /// </summary>
        /// <param name="year"></param>
        /// <returns>If information has been successfully retrieved.</returns>
        /// <remarks>The time range of climate stations are different. If there is no data in one year, the station information
        /// can't be retrieved.</remarks>
        private bool retrieveStationBasicInformation(int year)
        {
            string header = retrieveHeader(year);
            if (header.Length == 0) return false;
            using (CachedCsvReader csv = new CachedCsvReader(new StringReader(header), false))
            {
                if (csv.FieldCount < 2) return false;

                csv.ReadNextRecord();   //station name
                _name = csv[1];

                csv.ReadNextRecord();   //province
                _province = csv[1];

                csv.ReadNextRecord();   //Latitude
                _latitude = csv[1];

                csv.ReadNextRecord();   //Lontitude
                _longitude = csv[1];

                csv.ReadNextRecord();   //Elevation
                _elevation = csv[1];

                return true;
            }
        }
예제 #27
0
        static string joinSelectedStringsFromCsv(CachedCsvReader csv, string delimiter, params int[] selectedIndexes)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append("\"");

            bool sthAdded = false;
            foreach (int index in selectedIndexes)
            {
                if (!String.IsNullOrEmpty(csv[index].ToString()))
                {
                    if (sthAdded) sb.Append(delimiter);
                    sb.Append(csv[index].ToString());
                    sthAdded = true;
                }
            }
            sb.Append("\"");

            return sb.ToString();
        }
        /// <summary>
        /// Write data in given time range as ArcSWAT dbf file
        /// </summary>
        /// <param name="startYear"></param>
        /// <param name="endYear"></param>
        /// <param name="destinationFolder"></param>
        /// <returns></returns>
        private bool save2ArcSWATdbf(int startYear, int endYear, string destinationFolder)
        {
            string timeAffix = getTimeAffix();
            string pFile = string.Format("{0}\\P{1}{2}.dbf", Path.GetFullPath(destinationFolder), _id, timeAffix);  //precipitation
            string tFile = string.Format("{0}\\T{1}{2}.dbf", Path.GetFullPath(destinationFolder), _id, timeAffix);  //temperature

            this.setProgress(0,string.Format("Processing station {0}", _id));
            this.setProgress(0, pFile);
            this.setProgress(0, tFile);

            //create the dbf structure based on ArcSWAT document
            DbfFile pDBF = new DbfFile();
            pDBF.Open(pFile, FileMode.Create);
            pDBF.Header.AddColumn(new DbfColumn("DATE", DbfColumn.DbfColumnType.Date));
            pDBF.Header.AddColumn(new DbfColumn("PCP", DbfColumn.DbfColumnType.Number, 5, 1));

            DbfFile tDBF = new DbfFile();
            tDBF.Open(tFile, FileMode.Create);
            tDBF.Header.AddColumn(new DbfColumn("DATE", DbfColumn.DbfColumnType.Date));
            tDBF.Header.AddColumn(new DbfColumn("MAX", DbfColumn.DbfColumnType.Number, 5, 1));
            tDBF.Header.AddColumn(new DbfColumn("MIN", DbfColumn.DbfColumnType.Number, 5, 1));

            DbfRecord pRec = new DbfRecord(pDBF.Header);
            DbfRecord tRec = new DbfRecord(tDBF.Header);

            int processPercent = 0;
            bool hasResults = false;
            clearFailureYears();
            clearUncompletedYears();
            for (int i = startYear; i <= endYear; i++)
            {
                setProgress(processPercent, string.Format("Downloading data for station: {0}, year: {1}", _id, i));
                string resultsForOneYear = this.retrieveAnnualDailyClimateData(i, true);
                if (resultsForOneYear.Length == 0)
                {
                    addFailureYear(i);
                    continue;
                }

                processPercent += 1;
                setProgress(processPercent, "Writing data");

                using (CachedCsvReader csv = new CachedCsvReader(new StringReader(resultsForOneYear), true))
                {
                    if (csv.FieldCount >= 27)
                    {
                        hasResults = true;

                        string date = "";
                        while (csv.ReadNextRecord())
                        {
                            date = csv[0];
                            double p = ClimateString2Double(csv[TOTAL_PRECIPITATION_COL_INDEX]);
                            pRec[0] = date;
                            pRec[1] = p.ToString();
                            pDBF.Write(pRec, true);

                            double t_max = ClimateString2Double(csv[MAX_T_COL_INDEX]);
                            double t_min = ClimateString2Double(csv[MIN_T_COL_INDEX]);
                            tRec[0] = date;
                            tRec[1] = t_max.ToString();
                            tRec[2] = t_min.ToString();
                            tDBF.Write(tRec, true);
                        }
                        checkLastDayofYear(date);
                    }
                }
                processPercent += 1;
            }
            pDBF.Close();
            tDBF.Close();

            return hasResults;
        }
예제 #29
0
        static void rewriteBankCSV(string file, AccountType accType)
        {
            string outFileName = "";
            switch (accType)
            {
                case AccountType.OsobniKonto:
                    outFileName = "banka.CSV";
                    break;
                case AccountType.Hypoteka:
                    outFileName = "hypo.CSV";
                    break;
                case AccountType.SporiciUcet:
                    outFileName = "sporici.CSV";
                    break;
                default:
                    break;
            }

            Console.WriteLine("Zpracovávám " + file);
            StreamWriter sw = new StreamWriter(String.Format(outFileName, file), false, Encoding.GetEncoding("Windows-1250"));
            using (CachedCsvReader csv = new CachedCsvReader(new StreamReader(file, Encoding.GetEncoding("Windows-1250")), true, ',', '"'))
            {
                csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;
                int fieldCount = csv.FieldCount;
                string[] headers = csv.GetFieldHeaders();
                while (csv.ReadNextRecord())
                {
                    string newLine = composeOutLine(csv, accType);
                    sw.WriteLine(newLine);
                }
            }
            sw.Flush();
            sw.Close();
        }
예제 #30
0
        public void CachedNoHeader()
        {
            var csv = new CachedCsvReader(new StringReader("12345678;Hello\r\n78945612;World"), false, ';');

            var dgv = new DataGridView();
            dgv.DataSource = csv;

            dgv.Refresh();
        }
예제 #31
0
        protected override void readCSVFile(CachedCsvReader csv)
        {
            #if(UseHeaders)
            int worldIDIndex = csv.GetFieldIndex(_WorldID);
            int hwgr_IDIndex = csv.GetFieldIndex(_HWGR_ID);
            int wgr_IDIndex = csv.GetFieldIndex(_WGR_ID);
            int wgr_NameIndex = csv.GetFieldIndex(_WGR_Name);
            #else
            int worldIDIndex = _WorldIDIndex;
            int hwgr_IDIndex = _HWGR_IDIndex;
            int wgr_IDIndex =  _WGR_IDIndex;
            int wgr_NameIndex = _WGR_NameIndex;
            #endif
            Dictionary<string, ImportDataWGR> data = new Dictionary<string, ImportDataWGR>();
            Dictionary<long, WGR> dbwgrHash = getDBwgrHash();
            List<WGR> wgrSaveList = new List<WGR>();

            //Add WGR
            int i = 1;
            while (csv.ReadNextRecord())
            {
                csvDataNextRow();
                int worldID = int.Parse(csv[worldIDIndex]);
                int hwgrID = int.Parse(csv[hwgr_IDIndex]);
                int wgrID = int.Parse(csv[wgr_IDIndex]);
                string wgrName = csv[wgr_NameIndex];
                string key = worldID.ToString() + hwgrID.ToString() + wgrID.ToString();
                if (!data.ContainsKey(key))
                {
                    data.Add(key, new ImportDataWGR(i, hwgrID, worldID, wgrID,wgrName,key));
                    if (!dbwgrHash.ContainsKey(wgrID))
                    {
                        WGR wgr = new WGR(wgrID, SharedConsts.NeutralLangId, wgrName);
                        wgr.Import = true;
                        wgrSaveList.Add(wgr);
                        dbwgrHash.Add(wgrID, wgr);
                    }
                }
                else
                {
                    message(string.Format(GetLocalized("WGRExists"), i, _WorldID, worldID, _HWGR_ID, hwgrID, _WGR_ID, wgrID));
                }
                i++;
            }
            csvDataEndRead();
            if (wgrSaveList.Count > 0)
            {
                SaveOrUpdateList<WGR>(_IStoreService.WGRService, wgrSaveList);
            }

            //Add HwgrToWgr
            List<HWGR_WGR_SysValuesShort> list = new List<HWGR_WGR_SysValuesShort>(data.Count);
            foreach (ImportDataWGR value in data.Values)
            {
                list.Add(new HWGR_WGR_SysValuesShort(value.HWGR_ID, value.WorldID, value.WGR_ID));
            }
            SaveDataResult saveDataResult= _IStoreService.HwgrToWgrService.Save_HWGR_WGR_Values(list);
            list = (List<HWGR_WGR_SysValuesShort>)saveDataResult.Data;
            foreach (HWGR_WGR_SysValuesShort value in list)
            {
                string key = value.World_SystemID.ToString() + value.HWGR_SystemID.ToString() + value.WGR_SystemID.ToString();
                message(string.Format(GetLocalized("HWGRNotExistsDB"), data[key].RecordNumber, _WorldID, value.World_SystemID, _HWGR_ID, value.HWGR_SystemID));
            }
        }