public override void Dispose() { if (_csvReader != null) { _csvReader.Close(); } }
private void Unload() { PersonLoader.Unload(); if (Reader != null) { Reader.Close(); Reader = null; } NeedsReset = false; }
/// <summary> /// Import the Transactions & accounts in the given file and return the first account. /// </summary> /// <param name="file"></param> /// <param name="count"></param> /// <returns></returns> public static int ImportCsv(MyMoney myMoney, Account acct, string file) { var uri = new Uri(file); var csvReader = new CsvReader(uri, Encoding.UTF8, null, 4096); csvReader.Delimiter = ','; int total = 0; while (csvReader.Read()) { if (csvReader.FieldCount != 3) { throw new NotSupportedException("Invalid CSV format expecting 3 columns [Date, Payee, Amount]"); } var field1Date = csvReader[0]; var field2Payee = csvReader[1]; var field3Amount = csvReader[2]; if (total == 0) { if (field1Date != "Date" || field2Payee != "Payee" || field3Amount != "Amount") { throw new NotSupportedException("Invalid CSV format The fist row is expected to be the header [Date, Payee, Amount]"); } } else { var dateTokens = field1Date.Split('-'); if (dateTokens.Length != 3) { throw new NotSupportedException("Invalid CSV format The Date needs to be specified in ISO8601 YYYY-MM-DD format : " + field1Date); } if (dateTokens[0].Length != 4) { throw new NotSupportedException("Invalid CSV format The Date Year must be 4 digits : " + field1Date); } Transaction t = myMoney.Transactions.NewTransaction(acct); t.Id = -1; t.Date = DateTime.Parse(field1Date); t.Payee = t.Payee = myMoney.Payees.FindPayee(field2Payee, true); t.Amount = decimal.Parse(field3Amount); myMoney.Transactions.Add(t); } total++; } csvReader.Close(); return(total); }
public void CloseClosesTheTextReader() { TextReader mockTextReader = Mocks.StrictMock <TextReader>(); mockTextReader.Close(); Mocks.ReplayAll(); CsvReader reader = new CsvReader(mockTextReader); reader.Close(); }
protected override void ProcessRecord() { Path = this.GetUnresolvedProviderPathFromPSPath(Path); csvReader = new CsvReader(Path); SetHeader(); if (this.ParameterSetName == "GetItem" && Index == -2) { Index = csvReader.IndexOf(Item); } WriteCsvObject(); csvReader.Close(); }
protected void LoadNewLanguage(Language language) { string path = GetPathByLanguage(language); CsvReader reader = new CsvReader(); if (reader.Open(path)) { //TODO: Optimize by reading only by file reading at a time, or add a cached string list m_stringTable = reader.ReadAllToMemory(); reader.Close(); m_selectedLanguage = language; } else { DebugUtil.LogError(string.Format("StringManager: Could not find {0}", path)); } }
public void Unload() { if (Reader != null) { Reader.Close(); Reader = null; } Person.ReleasePersonPool(); if (PlaceOfResidencePlaceOfSchool != null) { PlaceOfResidencePlaceOfSchool.Unload(); } if (PlaceOfResidencePlaceOfWork != null) { PlaceOfResidencePlaceOfWork.Unload(); } if (TripchainLoader != null) { TripchainLoader.Unload(); } }
public MainPage() { InitializeComponent(); ObservableCollection <TmiImage> tmiImageList = new ObservableCollection <TmiImage>(); try { StreamResourceInfo sri = null; try { Uri csvUri = new Uri("TmiPivotMetadata.csv", UriKind.Relative); sri = Application.GetResourceStream(csvUri); } catch (Exception exp2) { System.Diagnostics.Debug.WriteLine("### Exception while getting resource stream: {0}", exp2.ToString()); } using (CsvReader reader = new CsvReader(sri.Stream)) { HeaderRecord head = reader.ReadHeaderRecord(); while (reader.HasMoreRecords) { DataRecord rec = reader.ReadDataRecord(); tmiImageList.Add(createFromRecord(rec)); } reader.Close(); } } catch (Exception exp) { System.Diagnostics.Debug.WriteLine("### Exception while reading csv file: {0}", exp.ToString()); } MyPV.ItemsSource = tmiImageList; }
public DataObject FeaturesImport() { CsvReader read = new CsvReader(InOutStreams.GetPathIn(), true); DataTable table = read.ToTable(); int N = table.Rows.Count; int M = table.Columns.Count; // istanziazione della classe DataObject // facendo così si inizializzano la matrice ItemsFeats // e i vettori dei label (a 0.0 e 0) DataObject DataSet = new DataObject(N, M); int i = 0; foreach (DataRow r in table.Rows) { for (int j = 0; j < M; j++) { if (j < M - 1) { DataSet.ItemsFeatures[i][j] = Double.Parse((string)r[j]); } else if (j == M - 1) { DataSet.Categories[i] = ((string)r[j]); } } i++; } read.Close(); // una volta letto il dataset, convertiamo le categorie in label sempre // interi, ma ordinati da 0 a 5, in base all'ordine di apparimento dall'inizio CategorizeAsInts(DataSet); return(DataSet); }
public void SetMappingFile(string filename) { _mapping = new Dictionary<string, string>(); //TODO: Fix character encoding? try { var csv = new CsvReader(new StreamReader(filename)); String[] row = csv.Next(); while (row != null) { _mapping.Add(row[0], row[1]); row = csv.Next(); } csv.Close(); } catch (System.Exception ex) { logger.Error("Error settings mapping file: {0}", ex.Message); } }
public void SetMappingFile(string filename) { _mapping = new Dictionary <string, string>(); //TODO: Fix character encoding? try { var csv = new CsvReader(new StreamReader(filename)); String[] row = csv.Next(); while (row != null) { _mapping.Add(row[0], row[1]); row = csv.Next(); } csv.Close(); } catch (System.Exception ex) { logger.Error("Error settings mapping file: {0}", ex.Message); } }
public void FromStreamReader(StreamReader sr, CsvLineReadHandler LineRead) { CsvReader csv = new CsvReader(sr, 1024); try { int cnt = 1; while (csv.Read()) { int len = csv.FieldCount; string[] values = new string[len]; for (int i = 0; i < len; i++) { values[i] = csv[i]; } if (LineRead != null) { LineRead(values); } cnt++; } } finally { csv.Close(); } }
/// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { csvReader.Close(); }
private List <string[]> headerLines; // tracking - private: stores header lines from read-in //Methods// // method - public: reads in the action set from the associated file and sets the unit intelligence's action set to it // public void ReadInBehaviors() { //Error handling if (unitIntelligenceScript == null) { throw new MissingReferenceException("'Unit Intelligence' instance not assigned. Please assign the file in the Inspector and try again."); } if (actionSetFile == null) { throw new MissingReferenceException("CSV file 'Action Set File' not assigned. Please assign the file in the Inspector and try again."); } filePath = AssetDatabase.GetAssetPath(actionSetFile); //Gets file path if (filePath == "") { throw new MissingReferenceException("CSV file 'Action Set File' could not be found. Please assign a valid file in the Inspector and try again."); } if (filePath.Substring(filePath.Length - 3, 3) != "csv") { throw new MissingReferenceException("CSV file 'Action Set File' is not a valid .csv file. Please assign a valid file in the Inspector and try again."); } CsvReader reader = new CsvReader(filePath); headerLines = new List <string[]>(); //Skips header lines for (int i = 0; i < rowsToSkip; i++) { headerLines.Add(reader.ReadRow()); } //Initializes action list storage components LinkedList <Action> actionList = new LinkedList <Action>(); string currActionName = ""; string currBehaviorName = ""; Dictionary <string, string> currBehaviorParams = null; LinkedList <Consideration> currConsiderations = null; //iterates through sheet and parses out Actions while (true) { string[] currLine = reader.ReadRow(); //If no more lines, then break if (currLine == null) { //Constructs last action Behavior newBehavior = GenerateBehavior(currBehaviorName, currBehaviorParams); List <Consideration> newConsiderations = new List <Consideration>(currConsiderations.Count); foreach (Consideration curr in currConsiderations) { newConsiderations.Add(curr); } actionList.AddLast(new Action(currActionName, newBehavior, newConsiderations)); break; } //new Action if (currLine[0] != "") { //If not the first action, instantiate the Action if (currBehaviorParams != null && currConsiderations != null) { Behavior newBehavior = GenerateBehavior(currBehaviorName, currBehaviorParams); List <Consideration> newConsiderations = new List <Consideration>(currConsiderations.Count); foreach (Consideration curr in currConsiderations) { newConsiderations.Add(curr); } actionList.AddLast(new Action(currActionName, newBehavior, newConsiderations)); } //Resets counters currActionName = currLine[0]; currBehaviorName = currLine[1]; currBehaviorParams = new Dictionary <string, string>(); currConsiderations = new LinkedList <Consideration>(); } //new Behavior param if (currLine[2] != "") { currBehaviorParams.Add(currLine[2], currLine[3]); } //new Consideration if (currLine[4] != "") { float i = 0.0f; float cSlope = float.TryParse(currLine[6], out i) ? i : 0.0f; //Consideration curve slope float cExp = float.TryParse(currLine[7], out i) ? i : 0.0f; //Consideration curve exponent float cVert = float.TryParse(currLine[8], out i) ? i : 0.0f; //Y-Intercept (vertical shift) float cHoriz = float.TryParse(currLine[9], out i) ? i : 0.0f; //X-Intercept (horizontal shift) currConsiderations.AddLast(new Consideration(currLine[4], //Consideration name currLine[5], //Consideration curve type cSlope, cExp, cVert, cHoriz)); } } //Cleans up the reader reader.Close(); reader.Dispose(); //Adds actions to given Unit Intelligence unitIntelligenceScript.SetActions(actionList); }
public void ReadDataToDataGrid() { if (File.Exists(InputFilePath)) { if (Delimiter.Length == 1) { DataTable dataTable = new DataTable(); CsvReader csvReader = new CsvReader(InputFilePath); csvReader.ValueSeparator = Delimiter[0]; if (IsColumnNamesInFirstRow) { foreach (string column in csvReader.ReadHeaderRecord().Values) { dataTable.Columns.Add(column); } Collection <int> rowsNumber = new Collection <int>(); int i = 1; foreach (DataRecord dt in csvReader.ReadDataRecords()) { DataRow dr = dataTable.NewRow(); if (dt.Values.Count == dt.HeaderRecord.Values.Count) { foreach (string column in dt.HeaderRecord.Values) { dr[column] = dt[column]; } dataTable.Rows.Add(dr); } else { rowsNumber.Add(i); continue; } i++; } if (rowsNumber.Count > 0) { StringBuilder message = new StringBuilder("The following line(s) are invalid and has been ignored. " + Environment.NewLine + "Line Number: "); foreach (var item in rowsNumber) { message.Append(item.ToString() + ", "); } Messenger.Default.Send(new DialogMessage(message.Remove(message.Length - 2, 2).ToString(), null) { Caption = "Warning" }); } } else { dataTable.Columns.Add("Default"); foreach (string[] strArray in csvReader.ReadDataRecordsAsStrings()) { DataRow dr = dataTable.NewRow(); StringBuilder sb = new StringBuilder(); foreach (string str in strArray) { sb.Append(str + Delimiter); } if (sb.Length > 0) { dr["Default"] = sb.ToString().TrimEnd(Delimiter.ToCharArray()); dataTable.Rows.Add(dr); } } } PreviewDataTable = dataTable; csvReader.Close(); } } }