Exemplo n.º 1
0
        public void Export(string ac_filename, string[] dbffiles, int[] index)
        {
            int steps = dbffiles.Length;
            DBFReader dbf = new DBFReader(dbffiles[0]);
            int nfeature = dbf.RecordCount;
            var buf = new DataCube<float>(index.Length, steps, nfeature);
            string[] field = new string[index.Length];
            for (int i = 0; i < index.Length; i++)
            {
                field[i] = dbf.Fields[index[i]].Name;
            }
              
            dbf.Close();

            for (int t = 0; t < steps; t++)
            {
                dbf = new DBFReader(dbffiles[t]);
                for (int n = 0; n < dbf.RecordCount; n++)
                {
                    var obj = dbf.NextRecord();
                    for (int i = 0; i < index.Length; i++)
                    {
                        buf[i, t, n] = float.Parse(obj[index[i]].ToString());
                    }
                }
                dbf.Close();
            }
            buf.Variables = field;
            DataCubeStreamWriter ac = new DataCubeStreamWriter(ac_filename);
            ac.WriteAll(buf);
        }
Exemplo n.º 2
0
        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");
            }
        }
Exemplo n.º 3
0
 public void ReadSample()
 {
     using (var reader = new DBFReader(TestPath))
     {
         Assert.That(reader.RecordCount, EqualTo(1));
     }
 }
Exemplo n.º 4
0
        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");
                }
        }
Exemplo n.º 5
0
        public static List <Inv> GetInvoiceList()
        {
            if (!File.Exists("inv.dbf"))
            {
                throw new FileNotFoundException("File \"inv.dbf\" not found!");
            }

            using (Stream rs = File.Open("inv.dbf", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite))
            {
                var rdr = new DBFReader(rs);
                rdr.CharEncoding = Encoding.GetEncoding(874);
                List <Inv> invoice_list = new List <Model.Inv>();

                for (int i = 0; i < rdr.RecordCount; i++)
                {
                    try
                    {
                        object[] obj = rdr.NextRecord();

                        invoice_list.Add(new Inv
                        {
                            docnum = (string)obj[0],
                            email  = (string)obj[1],
                            status = (string)obj[2]
                        });
                    }
                    catch (Exception)
                    {
                        break;
                    }
                }

                return(invoice_list);
            }
        }
Exemplo n.º 6
0
 public void ReadSample([CallerMemberName] string name = null)
 {
     using (var reader = new DBFReader(TestPath(name)))
     {
         Assert.That(reader.RecordCount, EqualTo(1));
     }
 }
Exemplo n.º 7
0
        private void button1_Click(object sender, EventArgs e)
        {
            DBFReader dbf = new DBFReader("d:\\skl\\3\\TOVAR.DBF");

            dbf.Open();

            DBFColumn     s    = null;
            List <string> keys = new List <string>();
            int           i;

            for (i = 0; i < 2; i++)
            {
                s = dbf.GetColumn(i);
                keys.Add(s.ColumnName);
            }

            IDataRecord irow;
            string      key;

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

            for (i = 0; i < dbf.Count; i++)
            {
                irow = (IDataRecord)dbf[i];
                key  = ((DBFRow)irow).GetKey(keys.ToArray());
                data.Add(key, irow);
            }

            dbf.Close();
        }
Exemplo n.º 8
0
        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");
                }
        }
Exemplo n.º 9
0
        public void Export(string dbfile, string ascfile, int nrow, int ncol, int cellsize, float xcorner, float ycorner, float nodatavalue = -999)
        {
            DBFReader        dbf        = new DBFReader(dbfile);
            int              act_index  = dbf.GetFiledNameIndex("active");
            int              row_index  = dbf.GetFiledNameIndex("row");
            int              col_index  = dbf.GetFiledNameIndex("col");
            int              elev_index = dbf.GetFiledNameIndex("elev");
            DataCube <float> mat        = new DataCube <float>(1, nrow, ncol);
            int              nact       = 0;

            for (int n = 0; n < dbf.RecordCount; n++)
            {
                var obj = dbf.NextRecord();
                int row = int.Parse(obj[row_index].ToString());
                int col = int.Parse(obj[col_index].ToString());
                int act = int.Parse(obj[act_index].ToString());
                if (act > 0)
                {
                    mat[0, row - 1, col - 1] = float.Parse(obj[elev_index].ToString());
                    nact++;
                }
                else
                {
                    mat[0, row - 1, col - 1] = nodatavalue;
                }
            }

            dbf.Close();
            //  this.Save<float>(ascfile, Value, nrow, ncol, cellsize, xcorner, ycorner, nodatavalue);
        }
        public void SetTable(string tablename)
        {
            //Oped table file
            string filename = Path.Combine(FileName, tablename + ".dbf");

            dbf = new DotNetDBF.DBFReader(filename);
            dbf.CharEncoding = Encoding.GetEncoding("cp866");
        }
Exemplo n.º 11
0
        public void LoadDBFFile(string FileName, string IDColumn, string NameColumn, string LengthColumn, string LRColumn)
        {
            NewMessage("Reading: " + FileName);

            using (DBFReader dbr = new DBFReader(FileName))
            {
                while (!dbr.EndOfData)
                {
                    var    data    = dbr.ReadNext();
                    int    catchid = int.Parse(data[IDColumn].ToString());
                    string type    = data[NameColumn].ToString();
                    double length  = double.Parse(data[LengthColumn].ToString());
                    double lengthReductionFactor = double.Parse(data[LRColumn].ToString());

                    StreamClassification streamclass;
                    if (StreamClasses.TryGetValue(type, out streamclass))
                    {
                        Tuple <double, double> previous;
                        if (!ReductionFactors.TryGetValue(catchid, out previous))
                        {
                            previous = new Tuple <double, double>(0, 0);
                            ReductionFactors.Add(catchid, previous);
                        }

                        DataRow datarow = Data.Rows.Find(new object[] { catchid });
                        if (datarow == null)
                        {
                            datarow    = Data.NewRow();
                            datarow[0] = catchid;
                            Data.Rows.Add(datarow);
                        }


                        double summer = 0;
                        double winter = 0;

                        if (length > 0)
                        {
                            summer = 0.01 * MultiplicationFactor * Math.Pow(streamclass.StreamDepthSummer / (length * lengthReductionFactor / (streamclass.StreamVelocitySummer * 365.0 * 86400.0)), Exponent);
                            winter = 0.01 * MultiplicationFactor * Math.Pow(streamclass.StreamDepthWinter / (length * lengthReductionFactor / (streamclass.StreamVelocityWinter * 365.0 * 86400.0)), Exponent);
                        }

                        int i = StreamClasses.IndexOfKey(streamclass.StreamType);

                        datarow[i + 1] = length;
                        datarow[i + 4] = winter;
                        datarow[i + 8] = summer;
                        var newfact = new Tuple <double, double>(1.0 - (1.0 - previous.Item1) * (1 - summer), 1.0 - (1.0 - previous.Item2) * (1 - winter));
                        datarow[7]  = newfact.Item2;
                        datarow[11] = newfact.Item1;
                        ReductionFactors[catchid] = newfact;
                    }
                }
            }
        }
Exemplo n.º 12
0
        public static List <Data> ReadDBF(FileInfo fi)
        {
            const int INDEX_ACCOUNT  = 3;
            const int INDEX_KOD      = 4;
            const int INDEX_NAME     = 5;
            const int INDEX_RL       = 6;
            const int INDEX_R2       = 7;
            const int INDEX_CODE     = 8;
            const int INDEX_QUANTITY = 11;

            var datas = new List <Data>();

            try
            {
                using (var dbf_stream = File.Open(fi.FullName, FileMode.Open, FileAccess.ReadWrite))
                {
                    var reader = new DBFReader(dbf_stream)
                    {
                        CharEncoding = Encoding.Default
                    };

                    for (var j = 0; j < reader.RecordCount; j++)
                    {
                        try
                        {
                            Application.DoEvents();
                            var record = reader.NextRecord();

                            var data = new Data(
                                record[INDEX_ACCOUNT],
                                record[INDEX_NAME],
                                record[INDEX_KOD],
                                record[INDEX_CODE],
                                record[INDEX_RL],
                                record[INDEX_R2],
                                record[INDEX_QUANTITY]
                                );
                            datas.Add(data);
                        }
                        catch (Exception ex)
                        {
                            AppLogAndEventHelper.Instance.RaiseDebugInfo($"Строка = {j} Ошибка = {ex.Message}");
                            AppLogAndEventHelper.Instance.RaiseError(ex);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                AppLogAndEventHelper.Instance.RaiseError(ex);
            }

            return(datas);
        }
Exemplo n.º 13
0
        private Dictionary <string, IDataRecord> ReadData(DBFReader dbfr, List <string> keys)
        {
            string      key;
            IDataRecord irow;
            Dictionary <string, IDataRecord> data = new Dictionary <string, IDataRecord>();

            for (int i = 0; i < dbfr.Count; i++)
            {
                irow = (IDataRecord)dbfr[i];
                key  = ((DBFRow)irow).GetKey(keys.ToArray());
                data.Add(key, irow);
            }
            return(data);
        }
Exemplo n.º 14
0
 public void ReadTest()
 {
     using (var dbfstream = DbfsData("dbase_8b.dbf"))
         using (var memoStream = DbfsData("dbase_8b.dbt"))
             using (DBFReader dbfr = new DBFReader(dbfstream)
             {
                 DataMemo = memoStream
             })
             {
                 object[] record = dbfr.NextRecord();
                 //This line would hang issue #19 https://github.com/ekonbenefits/dotnetdbf/issues/19
                 Assert.Throws <DBTException>(() => record[5].ToString());
             }
 }
Exemplo n.º 15
0
        /// <summary>
        /// Return all the records. T should be interface with getter properties that match types and names of the database.
        /// Optionally instead of T being and interface you can pass in an anonymous object with properties that match that
        /// database and then you'll get an IEnumerable of that anonymous type with the data filled in.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="reader">The reader.</param>
        /// <param name="prototype">The prototype. Anonymous class instance</param>
        /// <returns></returns>
        public static IEnumerable <T> AllRecords <T>(this DBFReader reader, T prototype = null) where T : class
        {
            var tType = typeof(T);

            var tProperties = tType.GetProperties()
                              .Where(
                it =>
                Array.FindIndex(reader.Fields,
                                f => f.Name.Equals(it.Name, StringComparison.InvariantCultureIgnoreCase)) >= 0)
                              .ToList();
            var tProps = tProperties
                         .Select(
                it =>
                Array.FindIndex(reader.Fields,
                                jt => jt.Name.Equals(it.Name, StringComparison.InvariantCultureIgnoreCase)))
                         .Where(it => it >= 0)
                         .ToArray();

            var tOrderedProps = tProps.OrderBy(it => it).ToArray();
            var tReturn       = new List <T>();


            if (tType.GetCustomAttributes(typeof(CompilerGeneratedAttribute), false).Any())
            {
                var tAnon = reader.NextRecord(tProps, tOrderedProps);
                while (tAnon != null)
                {
                    tReturn.Add((T)Activator.CreateInstance(tType, tAnon));
                    tAnon = reader.NextRecord(tProps, tOrderedProps);
                }


                return(tReturn);
            }

            var t = reader.NextRecord(tProps, tOrderedProps);

            while (t != null)
            {
                var interceptor = new Enumerable.DBFInterceptor(t, tProperties.Select(it => it.Name).ToArray());

                tReturn.Add(interceptor.ActLike <T>(typeof(Enumerable.IDBFInterceptor)));
                t = reader.NextRecord(tProps, tOrderedProps);
            }


            return(tReturn);
        }
Exemplo n.º 16
0
        public void Test()
        {
            using (
                Stream fis =
                    File.Open(@"f:\st\dev\testdata\p.dbf",
                              FileMode.OpenOrCreate,
                              FileAccess.ReadWrite))
                using (var reader = new DBFReader(fis)
                {
                    DataMemoLoc = Path.ChangeExtension(@"f:\st\dev\testdata\p.dbf", "DBT")
                })
                {
                    var readValues = reader.NextRecord();

                    Console.WriteLine(readValues);
                }
        }
Exemplo n.º 17
0
        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
                });
            }
        }
Exemplo n.º 18
0
        public void Export(ITriangularGrid grid, string ac_filename, string[] dbffiles, int[] index)
        {
            int steps = dbffiles.Length;
            int nfeature = grid.VertexCount;
            var buf = new DataCube<float>(index.Length, steps, nfeature);
            string[] field = new string[index.Length];
            for (int i = 0; i < steps; i++)
            {
                DBFReader dbf = new DBFReader(dbffiles[i]);
                var vec = new double[index.Length][];
                for (int t = 0; t < index.Length; t++)
                {
                    vec[t] = new double[dbf.RecordCount];
                }
                for (int n = 0; n < dbf.RecordCount; n++)
                {
                    var obj = dbf.NextRecord();
                    for (int t = 0; t < index.Length; t++)
                    {
                        vec[t][n] = double.Parse(obj[index[t]].ToString());
                    }
                }

                for (int t = 0; t < index.Length; t++)
                {
                    for (int k = 0; k < grid.VertexCount; k++)
                    {
                        var cells = grid.Topology.NodeConnectedCells[k];
                        double temp = 0;
                        for (int c = 0; c < cells.Length; c++)
                        {
                            temp += vec[t][cells[c]];
                        }
                        temp /= cells.Length;
                        buf[t, i, k] = (float)temp;
                    }
                    field[t] = dbf.Fields[index[t]].Name;
                }
                dbf.Close();
            }
            buf.Variables = field;
            DataCubeStreamWriter ac = new DataCubeStreamWriter(ac_filename);    
            ac.WriteAll(buf);
        }
Exemplo n.º 19
0
        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");
                }
            }
        }
Exemplo n.º 20
0
        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");
                }
        }
Exemplo n.º 21
0
        private object ImportText()
        {
            var fileName = Project.Current.MapPath(FileName);

            if (string.IsNullOrWhiteSpace(fileName) || !File.Exists(fileName))
            {
                throw new FileNotFoundException($"File '{fileName}' not found.");
            }

            using var stream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
            var reader = new DBFReader(stream);

            var table = new DataTable("DbfData");

            foreach (var field in reader.Fields)
            {
                var column = table.Columns.Add(field.Name, field.Type);
                switch (field.DataType)
                {
                case NativeDbType.Char:
                case NativeDbType.Memo:
                    column.MaxLength = field.FieldLength;
                    break;
                }
            }

            table.BeginLoadData();
            try
            {
                object[] records;
                while ((records = reader.NextRecord()) != null)
                {
                    table.Rows.Add(records);
                }
            }
            finally
            {
                table.EndLoadData();
            }

            return(table);
        }
Exemplo n.º 22
0
        /// <summary>
        /// Create a new Shapefile object and open a Shapefile. Note that streams of three files are required -
        /// the main file (.shp), the index file (.shx) and the dBASE table (.dbf). The three files
        /// must all have the same filename (i.e. shapes.shp, shapes.shx and shapes.dbf).
        /// </summary>
        /// <param name="mainStream">Stream of .shp for this Shapefile</param>
        /// <param name="indexStream">Stream of .shx for this Shapefile</param>
        /// <param name="dbfStream">relative path of .dbf for this Shapefile</param>
        /// <exception cref="ObjectDisposedException">Thrown if the Shapefile has been disposed</exception>
        /// <exception cref="ArgumentNullException">Thrown if the path parameter is null</exception>
        /// <exception cref="ArgumentException">Thrown if the path parameter is empty</exception>
        /// <exception cref="InvalidOperationException">Thrown if an error occurs parsing file headers</exception>
        public void Open(Stream mainStream, Stream indexStream, Stream dbfStream)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("Shapefile");
            }
            if (mainStream.Length < Header.HeaderLength)
            {
                throw new InvalidOperationException("Shapefile main file does not contain a valid header");
            }

            if (indexStream.Length < Header.HeaderLength)
            {
                throw new InvalidOperationException("Shapefile index file does not contain a valid header");
            }

            // read in and parse the headers
            byte[] headerBytes = new byte[Header.HeaderLength];

            _mainStream  = mainStream;
            _indexStream = indexStream;

            _mainStream.Read(headerBytes, 0, Header.HeaderLength);
            _mainHeader = new Header(headerBytes);
            _indexStream.Read(headerBytes, 0, Header.HeaderLength);
            _indexHeader = new Header(headerBytes);

            // set properties from the main header
            _type        = _mainHeader.ShapeType;
            _boundingBox = new RectangleD(_mainHeader.XMin, _mainHeader.YMin, _mainHeader.XMax, _mainHeader.YMax);

            // index header length is in 16-bit words, including the header - number of
            // shapes is the number of records (each 4 workds long) after subtracting the header bytes
            _count = (_indexHeader.FileLength - (Header.HeaderLength / 2)) / 4;

            dbfReader = new DBFReader(dbfStream, Encoding.ASCII);
            dbfReader.ResetReaderToEndOfHeader();
            // open the metadata database
            //OpenDb(dbfDirectory);

            _opened = true;
        }
Exemplo n.º 23
0
        /// <summary>
        /// Returns a list of dynamic objects whose properties and types match up with that database name.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="whereColumn">The where column name.</param>
        /// <param name="whereColumnEquals">What the were column should equal.</param>
        /// <returns></returns>
        static public IEnumerable <dynamic> DynamicAllRecords(this DBFReader reader, string whereColumn = null, dynamic whereColumnEquals = null)
        {
            var tProperties = reader.GetSelectFields().Select(it => it.Name).ToArray();

            int?tWhereColumn = null;

            if (!String.IsNullOrEmpty(whereColumn))
            {
                tWhereColumn = Array.FindIndex(tProperties,
                                               it => it.Equals(whereColumn, StringComparison.InvariantCultureIgnoreCase));
            }


            var tReturn = new List <object>();

            object[] t = reader.NextRecord();

            while (t != null)
            {
                if (tWhereColumn.HasValue)
                {
                    dynamic tO = t[tWhereColumn.Value];
                    if (!tO.Equals(whereColumnEquals))
                    {
                        t = reader.NextRecord();
                        continue;
                    }
                }


                var tIntercepter = new Enumerable.DBFIntercepter(t, tProperties);


                tReturn.Add(tIntercepter);
                t = reader.NextRecord();
            }


            return(tReturn);
        }
Exemplo n.º 24
0
        /// <summary>
        /// Returns a list of dynamic objects whose properties and types match up with that database name.
        /// </summary>
        /// <param name="reader">The reader.</param>
        /// <param name="whereColumn">The where column name.</param>
        /// <param name="whereColumnEquals">What the were column should equal.</param>
        /// <returns></returns>
        public static IEnumerable <dynamic> DynamicAllRecords(this DBFReader reader, string whereColumn = null,
                                                              dynamic whereColumnEquals = null)
        {
            var props = reader.GetSelectFields().Select(it => it.Name).ToArray();

            int?whereColumnIndex = null;

            if (!String.IsNullOrEmpty(whereColumn))
            {
                whereColumnIndex = Array.FindIndex(props,
                                                   it => it.Equals(whereColumn, StringComparison.InvariantCultureIgnoreCase));
            }


            var tReturn = new List <object>();
            var t       = reader.NextRecord();

            while (t != null)
            {
                if (whereColumnIndex is int i)
                {
                    dynamic tO = t[i];
                    if (!tO.Equals(whereColumnEquals))
                    {
                        t = reader.NextRecord();
                        continue;
                    }
                }


                var interceptor = new Enumerable.DBFInterceptor(t, props);


                tReturn.Add(interceptor);
                t = reader.NextRecord();
            }


            return(tReturn);
        }
Exemplo n.º 25
0
 /// <summary>
 /// Returns a list of dynamic objects whose properties and types match up with that database name.
 /// </summary>
 /// <param name="reader">The reader.</param>
 /// <param name="whereColumn">The where column name.</param>
 /// <param name="whereColumnEquals">What the were column should equal.</param>
 /// <returns></returns>
 public static IEnumerable <dynamic> DynamicAllRecords(DBFReader reader, string whereColumn = null,
                                                       dynamic whereColumnEquals            = null)
 {
     return(reader.DynamicAllRecords(whereColumn, (object)whereColumnEquals));
 }
Exemplo n.º 26
0
        /*
         * private void ExportDBF(Action<IEnumerable<FileInfo>> callBack)
         * {
         *  var filesToDownload = GetSelectedFiles();
         *  var disc = DiscoverRepository.GetInstance();
         *  var rep = DiscoverRepository.CurrentRepository;
         *  var convert = new DBConvert(folderBrowserDialog1.SelectedPath);
         *  var download = disc.DownloadCache(rep.Name, DiscoveredRepositoryCache.Files, filesToDownload);
         *  var localFiles = disc.CopyCacheTo(download, folderBrowserDialog1.SelectedPath);
         *  convert.ConvertDBC2DBF(localFiles.ToArray());
         *  foreach (var lf in localFiles)
         *      lf.Delete();
         *  callBack?.Invoke( localFiles.Select(f => new FileInfo(f.FullName.ToLower().TrimEnd('c') + "f"))?.ToArray());
         *  //return convert;
         * }
         *
         * private void ExportLocalDBF(Action<IEnumerable<FileInfo>> callBack)
         * {
         *  var filesToDownload = GetSelectedFiles();
         *  var disc = DiscoverRepository.GetInstance();
         *  var rep = DiscoverRepository.CurrentRepository;
         *  var wk = Path.Combine(@"c:\temp\sus", rep.Name);
         *  if (!Directory.Exists(wk))
         *      Directory.CreateDirectory(wk);
         *  var convert = new DBConvert(wk);
         *  var download = disc.DownloadCache(rep.Name, DiscoveredRepositoryCache.Files, filesToDownload);
         *  var localFiles = disc.CopyCacheTo(download, wk);
         *  convert.ConvertDBC2DBF(localFiles.ToArray());
         *  foreach (var lf in localFiles)
         *      lf.Delete();
         *  callBack?.Invoke(localFiles.Select(f => new FileInfo(f.FullName.ToLower().TrimEnd('c') + "f"))?.ToArray());
         *  //return convert;
         * }*/

        private void btnExport_Click(object sender, EventArgs e)
        {
            folderBrowserDialog1.SelectedPath = @"C:\";
            var selected = GetSelectedFiles("dbc");

            if ((selected?.Count() ?? 0) == 0)
            {
                MessageBox.Show("Selecione ao menos um arquivo compatível (.dbc)!", "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            var files = GetSelectedFiles().Where(f => f.Name.ToLower().EndsWith("dbc"));

            if (files?.Count() != selected?.Count())
            {
                MessageBox.Show("Apenas arquivos no formato DBC podem ser exportados para outros formatos\r\nOutras extensões serão ignoradas no processo",
                                "Atenção", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                return;
            }
            string type = "";

            FormExport.OpenDialog((format) => {
                type = format;
            });
            if (string.IsNullOrEmpty(type))
            {
                return;
            }
            if (folderBrowserDialog1.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            var workingFolder   = DBConvert.GetWorkingDirectory();
            var filesToDownload = GetSelectedFiles();
            var disc            = DiscoverRepository.GetInstance();
            var rep             = DiscoverRepository.CurrentRepository;

            type = Regex.Match(type, @"\w+", RegexOptions.IgnoreCase).Value.ToUpper();

            IEnumerable <FileInfo> dbfs = null;

            Action callbackExport = () =>
            {
                disc.ExportFiles2DBF(filesToDownload, (d) => dbfs = d, workingFolder);
            };
            var  tableManager = new DBFReader(workingFolder, DBVersion.Default);
            bool tdbf         = false;

            switch (type)
            {
            case "DBF":
                tdbf            = true;
                callbackExport += () => {
                    tdbf = true;
                };
                break;

            case "XML":
                callbackExport += () =>
                {
                    if (dbfs?.Any() != true)
                    {
                        return;
                    }
                    foreach (var dbf in dbfs)
                    {
                        tableManager.ToXML(dbf.Name);
                    }
                };
                break;

            case "CSV":
                callbackExport += () =>
                {
                    if (dbfs?.Any() != true)
                    {
                        return;
                    }
                    foreach (var dbf in dbfs)
                    {
                        tableManager.ToCSV(dbf.Name);
                    }
                };
                break;

            case "JSON":
                callbackExport += () =>
                {
                    if (dbfs?.Any() != true)
                    {
                        return;
                    }
                    foreach (var dbf in dbfs)
                    {
                        tableManager.ToJSON(dbf.Name);
                    }
                };
                break;
            }
            if (!tdbf)
            {
                callbackExport += () =>
                {
                    if (dbfs?.Any() != true)
                    {
                        return;
                    }
                    foreach (var dbf in dbfs)
                    {
                        dbf.Delete();
                    }
                };
            }
            else
            {
                callbackExport += () =>
                {
                    if (dbfs?.Any() != true)
                    {
                        return;
                    }
                    foreach (var dbf in dbfs)
                    {
                        dbf.MoveTo(Path.Combine(folderBrowserDialog1.SelectedPath, dbf.Name));
                    }
                };
            }
            callbackExport += () =>
            {
                tableManager.Dispose();
                //MessageBox.Show("Arquivos exportados com sucesso", "Conversão", MessageBoxButtons.OK, MessageBoxIcon.Information);
                Process.Start("explorer", folderBrowserDialog1.SelectedPath);
            };


            FormProgress.Run(callbackExport, (ex) =>
            {
                if (ex != null)
                {
                    MessageBox.Show("Ocorreu a sequinte excessão:\r\n" + ex, "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            });
        }
Exemplo n.º 27
0
        static void Main(string[] args)
        {
            // считывание настроек
            //for (i = 0; i < n; i++)

            string path1 = "D:\\skl\\3",
                   path2 = "D:\\skl\\1";

            string file1 = Path.Combine(path1, "TOVAR.DBF"),
                   file2 = Path.Combine(path2, "TOVAR.DBF");

            DBFReader dbfr1 = new DBFReader(file1),
                      dbfr2 = new DBFReader(file2);

            if (dbfr1.Open())
            {
                int i;
                #region ключевые поля
                DBFColumn     col;
                List <string> keys = new List <string>();

                for (i = 0; i < 2; i++)
                {
                    col = dbfr1.GetColumn(i);
                    keys.Add(col.ColumnName);
                }
                #endregion

                Dictionary <string, byte[]> data1 = dbfr1.ReadData(keys), data2 = null;
                Directory.CreateDirectory(path2);
                // файла нет
                if (!File.Exists(file2))
                {
                    File.Copy(file1, file2);
                }
                else
                {
                    if (dbfr2.Open())
                    {
                        data2 = dbfr2.ReadData(keys);
                    }
                }

                #region синхронизация

                string key;
                byte[] buf1, buf2;
                object obj1, obj2;

                foreach (KeyValuePair <string, byte[]> kvp in data1)
                {
                    key  = kvp.Key;
                    buf1 = kvp.Value;

                    char[] c = dbfr1.Encoding.GetChars(buf1);

                    if (data2.ContainsKey(key))
                    {
                        buf2 = data2[key];

                        for (i = 2; i < dbfr2.ColumnCount; i++)
                        {
                            col = dbfr2.GetColumn(i);

                            obj1 = buf1[col.Size];
                            obj2 = buf2[col.Size];
                            //if (T == typeof(int))  = "System.Convert.ToInt32(row1[i])";
                        }
                    }
                    else
                    {
                        data2.Add(key, buf1);
                    }
                }
                #endregion

                data1.Clear();
                data2.Clear();
                keys.Clear();
            }
            dbfr1.Close();
            dbfr2.Close();

            dbfr1 = null;
            dbfr2 = null;
        }
Exemplo n.º 28
0
        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");
            }
        }
Exemplo n.º 29
0
        /// <summary>
        /// Reading from a DBF file
        /// </summary>
        /// <typeparam name="T">Generic type</typeparam>
        /// <param name="path">File path</param>
        /// <param name="winCoding">Encoding windows (1251), otherwise DOS (866)</param>
        /// <param name="filter">Data filtering function</param>
        /// <param name="skip">Skip records</param>
        /// <param name="take">Get the number of records</param>
        /// <returns></returns>
        public static IList <T> Read <T>(
            string path,
            bool winCoding        = true,
            Func <T, bool> filter = null,
            int skip = 0,
            int take = int.MaxValue) where T : class
        {
            if (!File.Exists(path))
            {
                throw new FileNotFoundException("Файл не обнаружен", path);
            }

            var instanse = Instance;

            using (var fileStream = File.Open(path, FileMode.Open, FileAccess.Read))
            {
                var binaryReader = new BinaryReader(fileStream, Encoding.ASCII);
                var reader       = new DBFReader(fileStream);
                reader.CharEncoding = Configuration.GetEncoding(winCoding);

                var type  = typeof(T);
                var props = type.GetProperties()
                            .Where(p => p.CanWrite &&
                                   Array.FindIndex(reader.Fields, f => f.Name.Equals(p.Name, StringComparison.InvariantCultureIgnoreCase)) >= 0)
                            .ToList();
                Dictionary <PropertyInfo, int> propIndexDictionary = new Dictionary <PropertyInfo, int>();
                foreach (var prop in props)
                {
                    var index = Array.FindIndex(reader.Fields, f => f.Name.Equals(prop.Name, StringComparison.InvariantCultureIgnoreCase));
                    if (index >= 0)
                    {
                        propIndexDictionary.Add(prop, index);
                    }
                }

                var retval        = new List <T>();
                var rowValues     = reader.NextRecord();
                int filteredCount = 0;
                int addedCount    = 0;
                while (rowValues != null)
                {
                    var newObj = (T)Activator.CreateInstance(typeof(T));
                    foreach (var propIndex in propIndexDictionary)
                    {
                        var fieldValue = rowValues[propIndex.Value];
                        if (fieldValue != null)
                        {
                            var propValue = Convert.ChangeType(fieldValue, propIndex.Key.PropertyType);
                            propIndex.Key.SetValue(newObj, propValue);
                        }
                        else
                        {
                            //var t = propIndex.Key.PropertyType;
                            //propIndex.Key.SetValue(newObj, default(propIndex.Key.PropertyType)));
                        }
                    }

                    // Фильтрация
                    if (filter != null)
                    {
                        if (!filter(newObj))
                        {
                            rowValues = reader.NextRecord();
                            continue;
                        }
                    }
                    // Получить только указанный блок записей
                    filteredCount++;
                    if (filteredCount > skip)
                    {
                        if (addedCount >= take)
                        {
                            break;
                        }
                        retval.Add(newObj);
                        addedCount++;
                    }
                    rowValues = reader.NextRecord();
                }
                return(retval);
            }
        }
Exemplo n.º 30
0
 /// <summary>
 /// Return all the records. T should be interface with getter properties that match types and names of the database.
 /// Optionally instead of T being and interface you can pass in an anonymous object with properties that match that
 /// database and then you'll get an IEnumerable of that anonymous type with the data filled in.
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="reader">The reader.</param>
 /// <param name="prototype">The prototype. Anonymous class instance</param>
 /// <returns></returns>
 public static IEnumerable <T> AllRecords <T>(DBFReader reader, T prototype = null) where T : class
 {
     return(reader.AllRecords(prototype));
 }