public void checkRAFwriting() { println("Writing in RAF mode ... "); if (File.Exists(TestRAFPath())) { File.Delete(TestRAFPath()); } using (var writer = new DBFWriter(TestRAFPath())) { var fields = new DBFField[2]; fields[0] = new DBFField("F1", NativeDbType.Char, 10); fields[1] = new DBFField("F2", NativeDbType.Numeric, 2); writer.Fields = fields; writer.WriteRecord("Red", 10); writer.WriteRecord("Blue", 20); } println("done."); println("Appending to this file"); using (var writer = new DBFWriter(TestRAFPath())) { writer.WriteRecord("Green", 33); writer.WriteRecord("Yellow", 44); } println("done."); }
public void checkDataType_N() { Decimal writtenValue; using ( Stream fos = File.Open(TestPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var writer = new DBFWriter()) { var field = new DBFField("F1", NativeDbType.Numeric, 15, 0); writer.Fields = new[] { field }; writtenValue = 123456789012345L; writer.AddRecord(writtenValue); writer.Write(fos); } using ( Stream fis = File.Open(TestPath(), FileMode.Open, FileAccess.Read)) using (var reader = new DBFReader(fis)) { var readValues = reader.NextRecord(); Assert.That(readValues[0], EqualTo(writtenValue), "Written Value Equals Read"); } }
/// <summary> /// New Blank Row Dynamic object that matches writer; /// </summary> /// <param name="writer">The writer.</param> /// <returns></returns> public static dynamic NewBlankRow(this DBFWriter writer) { var fields = writer.Fields.Select(it => it.Name).ToArray(); var obj = new object[fields.Length]; return(new Enumerable.DBFIntercepter(obj, fields)); }
public void checkDataType_M() { var fieldLength = 2400; MemoValue writtenValue; using (Stream fos = File.Open(TestMemoPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var writer = new DBFWriter { DataMemoLoc = Path.ChangeExtension(TestMemoPath(), "DBT") }) { var field = new DBFField("F1", NativeDbType.Memo); writer.Fields = new[] { field }; writtenValue = new MemoValue(GetCharacters(fieldLength)); writer.AddRecord(writtenValue); writer.Write(fos); } using (Stream fis = File.Open(TestMemoPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var reader = new DBFReader(fis) { DataMemoLoc = Path.ChangeExtension(TestMemoPath(), "DBT") }) { var readValues = reader.NextRecord(); Assert.That(readValues[0], EqualTo(writtenValue), "Written Value not equaling Read"); } }
public void checkLongCharLengthWithClipper() { var fieldLength = 750; string writtenValue; using ( Stream fos = File.Open(TestClipLongPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { var writer = new DBFWriter(); var field = new DBFField("F1", NativeDbType.Char, fieldLength); writer.Fields = new[] { field }; writtenValue = GetCharacters(fieldLength); writer.AddRecord(writtenValue); writer.Write(fos); } using ( Stream fis = File.Open(TestClipLongPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { var reader = new DBFReader(fis); Assert.That(reader.Fields.First().FieldLength, EqualTo(fieldLength)); var readValues = reader.NextRecord(); Assert.That(readValues[0], EqualTo(writtenValue), "Written Value not equaling Read"); } }
/// <summary> /// Writing to a DBF file /// </summary> /// <typeparam name="T">Generic type</typeparam> /// <param name="items"></param> /// <param name="winCoding">Encoding windows (1251), otherwise DOS (866)</param> /// <remarks>Only fields marked with the DbfField attribute are saved.</remarks> public static void Write <T>(string path, IEnumerable <T> items, bool winCoding = true) { if (string.IsNullOrWhiteSpace(path)) { throw new ArgumentException("Не указано имя файла", path); } if (File.Exists(path)) { throw new Exception($"Файл '{path}' c таким имененем уже существует, запись невозвожна."); } var instanse = Instance; var type = typeof(T); var props = type.GetProperties() .Where(p => p.CanRead) .ToList(); var saveProps = new List <PropertyInfo>(); var fields = new List <DBFField>(); foreach (var prop in props) { var fieldAttr = prop.GetCustomAttributes <DbfFieldAttribute>(false).FirstOrDefault(); if (fieldAttr == null) { continue; } saveProps.Add(prop); if (fieldAttr.DbType == NativeDbType.Date || fieldAttr.DbType == NativeDbType.Logical || fieldAttr.DbType == NativeDbType.Memo) { fields.Add(new DBFField(prop.Name, fieldAttr.DbType)); } else { fields.Add(new DBFField(prop.Name, fieldAttr.DbType, fieldAttr.Length, fieldAttr.Precision)); } } if (fields.Count == 0) { throw new Exception("У типа {type.Name} отсутствуют аттрибуты DbfField с описаниями полей в базе: DbType[, Length[, Precision]]"); } using (var fileStream = File.Create(path)) //Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite)) { using (var writer = new DBFWriter(fileStream)) { writer.CharEncoding = Configuration.GetEncoding(winCoding); writer.Fields = fields.ToArray(); foreach (var item in items) { var record = new object[saveProps.Count]; for (var i = 0; i < saveProps.Count; i++) { record[i] = saveProps[i].GetValue(item); } writer.WriteRecord(record); } } } }
public Task SaveAsync() { return(Task.Run(() => { Status = ReportStatus.ReportStatusSaving; string directoryNameOut = Settings.Default.DirectoryNameOut; using (var dbf = new DBFWriter { Fields = new[] { new DBFField("ls", NativeDbType.Char, 12), new DBFField("ls_old", NativeDbType.Char, 12), new DBFField("fio", NativeDbType.Char, 50), new DBFField("adress", NativeDbType.Char, 100), new DBFField("paymonth", NativeDbType.Numeric, 2), new DBFField("payyear", NativeDbType.Numeric, 4), new DBFField("sum", NativeDbType.Numeric, 14, 2), new DBFField("date", NativeDbType.Date), new DBFField("eval0", NativeDbType.Numeric, 12, 2), new DBFField("eval1", NativeDbType.Numeric, 12, 2), new DBFField("date_eval1", NativeDbType.Date), new DBFField("rgc_format", NativeDbType.Numeric, 1) }, CharEncoding = Encoding.GetEncoding("cp866") //koi8-u }) { foreach (var piple in Piples) { dbf.AddRecord(piple.Number, "", piple.FullName, piple.Adress, piple.DatePay.Month, piple.DatePay.Year, piple.Sum, piple.DatePay, 0, 0, piple.DatePay, 0); } using ( Stream fos = File.Open(directoryNameOut + "0500_polgaz_" + DateReport.ToString("dd.MM.yyyy") + ".dbf", FileMode.Create, FileAccess.Write)) { dbf.Write(fos); } } Status = ReportStatus.ReportStatusSaved; })); }
public static ManageDataResult AddInvoiceRecord(Inv inv_to_add) { if (!File.Exists("inv.dbf")) { throw new FileNotFoundException("File \"inv.dbf\" not found!"); } try { using (Stream stream = File.Open("inv.dbf", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read)) { var reader = new DBFReader(stream); reader.CharEncoding = Encoding.GetEncoding(874); List <Inv> invoice_list = new List <Model.Inv>(); var writer = new DBFWriter(stream); for (int i = 0; i < reader.RecordCount; i++) { try { object[] obj = reader.NextRecord(); // add existing record first writer.AddRecord((string)obj[0], (string)obj[1], (string)obj[2]); } catch (Exception) { break; } } // add a target record writer.AddRecord(inv_to_add.docnum, inv_to_add.email, inv_to_add.status); } return(new ManageDataResult { success = true, message = "success" }); } catch (Exception ex) { //Console.WriteLine("File is in use by another process."); return(new ManageDataResult { success = false, message = ex.Message }); } }
public void WriteSample([CallerMemberName] string name = null) { var field = new DBFField { Name = "F1", DataType = NativeDbType.Numeric }; var writer = new DBFWriter { Fields = new[] { field } }; writer.AddRecord(3); using ( Stream fos = File.Open(TestPath(name), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { writer.Write(fos); } }
public void checkProxy() { var fieldLength = 2400; string writtenValue; using ( Stream fos = File.Open(TestSelectPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { using (var writer = new DBFWriter { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { ; var field = new DBFField("F1", NativeDbType.Memo); var field2 = new DBFField("F2", NativeDbType.Numeric, 10); var field3 = new DBFField("F3", NativeDbType.Char, 10); writer.Fields = new[] { field, field2, field3 }; writtenValue = "alpha"; writer.AddRecord(new MemoValue(GetCharacters(fieldLength)), 10, writtenValue); writer.Write(fos); } } using ( Stream fis = File.Open(TestSelectPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) { using (var reader = new DBFReader(fis) { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { var readValues = reader.AllRecords <ITestInterface>(); Assert.That(readValues.First().F3, StartsWith(writtenValue), "Written Value not equaling Read"); } } }
public void checkSelectDynamic() { var fieldLength = 2400; string writtenValue; string writtenMemo; using ( Stream fos = File.Open(TestSelectPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var writer = new DBFWriter { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { var field = new DBFField("F1", NativeDbType.Memo); var field2 = new DBFField("F2", NativeDbType.Numeric, 10); var field3 = new DBFField("F3", NativeDbType.Char, 10); writer.Fields = new[] { field, field2, field3 }; writtenValue = "alpha"; writtenMemo = GetCharacters(fieldLength); writer.AddRecord(new MemoValue(writtenMemo), 10, writtenValue); writer.Write(fos); } using ( Stream fis = File.Open(TestSelectPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var reader = new DBFReader(fis) { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { reader.SetSelectFields("F1", "F3"); var readValues = reader.DynamicAllRecords().First(); Assert.That(readValues.F1.ToString(), EqualTo(writtenMemo), "Written Value not equaling Read"); Assert.That(readValues.F3, EqualTo(writtenValue), "Written Value not equaling Read"); } }
/// <summary> /// Adds the record. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value.</param> public static void AddRecord(DBFWriter writer, IDBFIntercepter value) { writer.AddRecord(writer, value); }
/// <summary> /// Adds the record. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value.</param> public static void AddRecord(this DBFWriter writer, Enumerable.IDBFIntercepter value) { writer.AddRecord(value.GetDataRow()); }
//private TimeSheetModel[] _models; //public TimeSheetToDbf(TimeSheetModel[] models) //{ // _models = models; //} public byte[] GenerateDbf(TimeSheetModel[] models) { var fields = new List <DBFField> { new DBFField("IdDep", NativeDbType.Numeric, 50, 0), new DBFField("DepSName", NativeDbType.Char, 350, 0), new DBFField("IdTs", NativeDbType.Numeric, 50, 0), new DBFField("TsDateSt", NativeDbType.Date), new DBFField("TsDateEnd", NativeDbType.Date), new DBFField("TsDateComp", NativeDbType.Date), new DBFField("IdEmployee", NativeDbType.Numeric, 50, 0), new DBFField("EFirstname", NativeDbType.Char, 50, 0), new DBFField("ELastName", NativeDbType.Char, 50, 0), new DBFField("EPatronymi", NativeDbType.Char, 50, 0), new DBFField("EPostname", NativeDbType.Char, 50, 0), new DBFField("EStufRate", NativeDbType.Float, 50, 0), new DBFField("RecDate", NativeDbType.Date), new DBFField("RecStatus", NativeDbType.Char, 50, 0), new DBFField("RecHours", NativeDbType.Char, 50, 0), }; var writer = new DBFWriter { Fields = fields.ToArray() }; //writer.AddRecord(3, "s", 3, DateTime.Now, DateTime.Now, DateTime.Now, 3, // "3", "3", "3", "3", 3, DateTime.Now, "3", 3); var addRecList1 = new List <object>(); var addRecList2 = new List <object>(); var addRecList3 = new List <object>(); foreach (var model in models) { addRecList1.Clear(); addRecList1.Add(1); addRecList1.Add(model.DepartmentName); addRecList1.Add(1); addRecList1.Add(model.DateBeginPeriod); addRecList1.Add(model.DateEndPeriod); addRecList1.Add(model.DateComposition); foreach (var paper in model.Papers) { foreach (var empl in paper.Employees) { addRecList2.Clear(); addRecList2.AddRange(addRecList1.ToArray()); addRecList2.Add(1); addRecList2.Add(empl.Surname); addRecList2.Add(empl.Name); addRecList2.Add(empl.Patronymic); addRecList2.Add(empl.Post); addRecList2.Add((float)empl.StaffRate); //addRecList2.Add(1); foreach (var rec in empl.Records) { addRecList3.Clear(); addRecList3.AddRange(addRecList2.ToArray()); addRecList3.Add(DateTime.Now); addRecList3.Add(rec.DayStatus); addRecList3.Add(rec.Value); writer.AddRecord(addRecList3.ToArray()); } } } } var fos = new MemoryStream(); { writer.Write(fos); } return(fos.ToArray()); }
public void checkDynamicProxyWhere() { var fieldLength = 2400; string writtenValue; using ( Stream fos = File.Open(TestSelectPath(), FileMode.OpenOrCreate, FileAccess.ReadWrite)) using (var writer = new DBFWriter { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { var field = new DBFField("F1", NativeDbType.Memo); var field2 = new DBFField("F2", NativeDbType.Numeric, 10); var field3 = new DBFField("F3", NativeDbType.Char, 10); writer.Fields = new[] { field, field2, field3 }; writtenValue = "alpha"; writer.AddRecord(new MemoValue(GetCharacters(fieldLength)), 10, writtenValue); writer.AddRecord(new MemoValue(GetCharacters(fieldLength)), 12, "beta"); writer.Write(fos); } using (var reader = new DBFReader(TestSelectPath()) { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { var readValues = reader.DynamicAllRecords(); Assert.That(Equals(readValues.Count(), 2), "All Records not matching"); } using (var reader = new DBFReader(TestSelectPath()) { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { var readValues = reader.DynamicAllRecords(whereColumn: "F2", whereColumnEquals: 10); Assert.That(Equals(readValues.Count(), 1), "All Records not matching"); } using (var reader = new DBFReader(TestSelectPath()) { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { var readValues = reader.DynamicAllRecords(whereColumn: "F2", whereColumnEquals: 12); Assert.That(Equals(readValues.Count(), 1), "All Records not matching"); } using (var reader = new DBFReader(TestSelectPath()) { DataMemoLoc = Path.ChangeExtension(TestSelectPath(), "DBT") }) { var readValues = reader.DynamicAllRecords(whereColumn: "F2", whereColumnEquals: 13); Assert.That(Equals(readValues.Count(), 0), "All Records not matching"); } }
public byte[] GenerateDbf(DtoTimeSheet timeSheet) { var fields = new List <DBFField> { new DBFField("IdTs", NativeDbType.Numeric, 50, 0), //Идентификатор табеля new DBFField("TsDateSt", NativeDbType.Date), //Табель с new DBFField("TsDateEnd", NativeDbType.Date), //Табель по new DBFField("TsDateComp", NativeDbType.Date), //Дата составления табеля new DBFField("IdDep", NativeDbType.Numeric, 50, 0), //Идентификатор структурного подразделения new DBFField("DepSName", NativeDbType.Char, 350, 0), //Короткое название структ. подразделения new DBFField("DepFName", NativeDbType.Char, 350, 0), //Полное название структ подразделение new DBFField("ETabNum", NativeDbType.Char, 350, 0), //Табельный номер сотрудника new DBFField("IdEmployee", NativeDbType.Numeric, 50, 0), //Идентификатор сотрудника new DBFField("IdFactStaf", NativeDbType.Numeric, 50, 0), //Идентификатор фактической ставки сотр. new DBFField("EFirstname", NativeDbType.Char, 50, 0), //Фамилия new DBFField("ELastName", NativeDbType.Char, 50, 0), //Имя new DBFField("EPatronymi", NativeDbType.Char, 50, 0), //Отчество new DBFField("IdPost", NativeDbType.Numeric, 50, 0), //Идентификатор должности new DBFField("EPostname", NativeDbType.Char, 50, 0), //Название должности new DBFField("EStufRate", NativeDbType.Float, 50, 0), //Ставка new DBFField("IdShedule", NativeDbType.Numeric, 50, 0), //Идентификатор графика работы new DBFField("SheduleNam", NativeDbType.Char, 50, 0), //Название графика работы new DBFField("RecDate", NativeDbType.Date), //Дата new DBFField("IdDayStat", NativeDbType.Numeric, 50, 0), //Идентификатор статуса дня new DBFField("RecStatus", NativeDbType.Char, 50, 0), //Статус дня new DBFField("IdRec", NativeDbType.Char, 50, 0), //Идентификатор записи табеля new DBFField("RecHours", NativeDbType.Float, 50, 0), //Отработано часов }; var writer = new DBFWriter { Fields = fields.ToArray(), CharEncoding = Encoding.Default }; var addRecList1 = new List <object> { timeSheet.IdTimeSheet, timeSheet.DateBegin, timeSheet.DateEnd, timeSheet.DateComposition, timeSheet.Department.IdDepartment, timeSheet.Department.DepartmentSmallName, timeSheet.Department.DepartmentFullName }; var addRecList2 = new List <object>(); var addRecList3 = new List <object>(); foreach (var empl in timeSheet.Employees) { addRecList2.Clear(); addRecList2.AddRange(addRecList1.ToArray()); addRecList2.Add(empl.FactStaffEmployee.ItabN); addRecList2.Add(empl.FactStaffEmployee.IdEmployee); addRecList2.Add(empl.FactStaffEmployee.IdFactStaff); addRecList2.Add(empl.FactStaffEmployee.Surname); addRecList2.Add(empl.FactStaffEmployee.Name); addRecList2.Add(empl.FactStaffEmployee.Patronymic); addRecList2.Add(empl.FactStaffEmployee.Post.IdPost); addRecList2.Add(empl.FactStaffEmployee.Post.PostFullName); addRecList2.Add(empl.FactStaffEmployee.StaffRate); addRecList2.Add(empl.FactStaffEmployee.WorkShedule.IdWorkShedule); addRecList2.Add(empl.FactStaffEmployee.WorkShedule.WorkSheduleName); foreach (var rec in empl.Records) { addRecList3.Clear(); addRecList3.AddRange(addRecList2.ToArray()); addRecList3.Add(rec.Date); addRecList3.Add(rec.DayStays.IdDayStatus); addRecList3.Add(rec.DayStays.SmallDayStatusName); addRecList3.Add(rec.IdTimeSheetRecord.ToString()); addRecList3.Add(rec.JobTimeCount); writer.AddRecord(addRecList3.ToArray()); } } var fos = new MemoryStream(); { writer.Write(fos); } return(fos.ToArray()); }
private void ExportData() { var fileName = Project.Current.MapPath(FileName); if (string.IsNullOrWhiteSpace(fileName)) { throw new ArgumentNullException("Filename is not provided."); } if (!Overwrite && File.Exists(fileName)) { throw new Exception($"File '{FileName}' already exists."); } if (Overwrite && File.Exists(fileName)) { File.Delete(fileName); } using var stream = new FileStream(fileName, FileMode.CreateNew, FileAccess.Write); using var dataReader = GetDataSourceReader(_Output, DataSource, new DataSourceParameters() { IgnoreErrors = this.IgnoreErrors, Columns = this.SelectColumns, SkipColumns = this.SkipColumns }); var writer = new DBFWriter(stream); var dbFields = new List <DBFField>(); int columnCount = dataReader.FieldCount; var schema = dataReader.GetSchemaTable(); for (int i = 0; i < columnCount; i++) { var fieldName = dataReader.GetName(i) ?? string.Empty; var name = fieldName.Length <= 10 ? fieldName : fieldName.Substring(0, 10); var type = dataReader.GetFieldType(i); DBFField dbField = null; switch (Type.GetTypeCode(type)) { case TypeCode.Empty: case TypeCode.Object: case TypeCode.DBNull: throw new Exception($"Type '{type.FullName}' cannot be exported into DBF."); case TypeCode.Boolean: dbField = new DBFField(name, NativeDbType.Logical); break; case TypeCode.Char: int charSize = GetColumnMaxLength(name); dbField = new DBFField(name, NativeDbType.Char, charSize); break; case TypeCode.SByte: dbField = new DBFField(name, NativeDbType.Numeric, 5); break; case TypeCode.Byte: dbField = new DBFField(name, NativeDbType.Numeric, 5); break; case TypeCode.Int16: dbField = new DBFField(name, NativeDbType.Numeric, 6); break; case TypeCode.UInt16: dbField = new DBFField(name, NativeDbType.Numeric, 6); break; case TypeCode.Int32: dbField = new DBFField(name, NativeDbType.Numeric, 12); break; case TypeCode.UInt32: dbField = new DBFField(name, NativeDbType.Numeric, 12); break; case TypeCode.Int64: dbField = new DBFField(name, NativeDbType.Numeric, 19); break; case TypeCode.UInt64: dbField = new DBFField(name, NativeDbType.Numeric, 19); break; case TypeCode.Single: dbField = new DBFField(name, NativeDbType.Float, 19, 4); break; case TypeCode.Double: dbField = new DBFField(name, NativeDbType.Float, 19, 4); break; case TypeCode.Decimal: dbField = new DBFField(name, NativeDbType.Float, 19, 4); break; case TypeCode.DateTime: dbField = new DBFField(name, NativeDbType.Date); break; case TypeCode.String: int strSize = GetColumnMaxLength(fieldName); dbField = new DBFField(name, NativeDbType.Char, strSize); break; } dbFields.Add(dbField); } writer.Fields = dbFields.ToArray(); object[] values = new object[columnCount]; int[] lengths = new int[columnCount]; for (int i = 0; i < writer.Fields.Length; i++) { lengths[i] = writer.Fields[i].FieldLength; } while (dataReader.Read()) { for (int i = 0; i < columnCount; i++) { object value = dataReader.GetValue(i); if (value is string str && str.Length > lengths[i]) { value = str.Substring(0, lengths[i]); } values[i] = value; } writer.WriteRecord(values); } int GetColumnMaxLength(string columnName) { const int DefaultStringColumnSize = 254; if (schema == null || schema.Rows.Count <= 0) { return(DefaultStringColumnSize); } if (schema.Columns["ColumnName"] == null || schema.Columns["ColumnSize"] == null) { return(DefaultStringColumnSize); } foreach (DataRow row in schema.Rows) { var colName = Convert.ToString(row["ColumnName"]); if (string.Compare(colName, columnName, true) == 0) { int size = Convert.ToInt32(row["ColumnSize"]); if (size > 0 && size <= DefaultStringColumnSize) { return(size); } return(DefaultStringColumnSize); } } return(DefaultStringColumnSize); } }
/// <summary> /// Writes the record. /// </summary> /// <param name="writer">The writer.</param> /// <param name="value">The value.</param> public static void WriteRecord(DBFWriter writer, IDBFIntercepter value) { writer.WriteRecord(value); }
/// <summary> /// New Blank Row Dynamic object that matches writer; /// </summary> /// <param name="writer">The writer.</param> /// <returns></returns> public static dynamic NewBlankRow(DBFWriter writer) { return(writer.NewBlankRow()); }