Exemple #1
0
        private static void TestReadHttpConn()
        {
            //Open a web file...
            //-------------------------------------
            var oWebDBF  = new DbfFile(Encoding.GetEncoding(1252));
            var oWebFile = new WebClient();

            oWebDBF.Open(oWebFile.OpenRead("http://private.socialexplorer.com/State_vars1.dbf"));

            //read and print records to screen...
            var orecWeb = new DbfRecord(oWebDBF.Header);

            var ofs2 = new FileStream(Path.Combine(TestPath, "Webfile.txt"), FileMode.Create);
            var osw2 = new StreamWriter(ofs2);

            bool bIsForwardOnly = oWebDBF.IsForwardOnly;
            bool bIsReadOnly    = oWebDBF.IsReadOnly;

            while (oWebDBF.ReadNext(orecWeb))
            {
                osw2.WriteLine("index: " + orecWeb.RecordIndex + ": " + orecWeb);
            }

            osw2.Flush();
            osw2.Close();

            oWebDBF.Close();
        }
Exemple #2
0
        private static void DbfTestWrite(string filepath)
        {
            //编码Encoding.UTF8 中文字符占三字节 Encoding.GetEncoding(936) Encoding.Default中文字符占二字节
            var odbf = new DbfFile(Encoding.GetEncoding(936));

            odbf.Open(filepath, FileMode.Create);//FileMode.Create OpenOrCreate
            //创建列头
            //odbf.Header.AddColumn(new DbfColumn("编号", DbfColumn.DbfColumnType.Character, 20, 0));
            //odbf.Header.AddColumn(new DbfColumn("名称", DbfColumn.DbfColumnType.Character, 20, 0));
            //odbf.Header.AddColumn(new DbfColumn("地址", DbfColumn.DbfColumnType.Character, 20, 0));
            //odbf.Header.AddColumn(new DbfColumn("时间", DbfColumn.DbfColumnType.Date));
            //odbf.Header.AddColumn(new DbfColumn("余额", DbfColumn.DbfColumnType.Number, 15, 3));

            //var orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true };
            //List<User> list = User.GetList();
            ////foreach (var item in list)
            ////{
            //User item=list[0];
            //    orec[0] = item.UserCode;
            //    orec[1] = item.UserName;
            //    orec[2] = item.Address;
            //    orec[3] = item.date.ToString("yyyy-MM-dd HH:mm:ss");
            //    orec[4] = item.money.ToString();
            //    odbf.Write(orec, true);
            ////}

            //写入边界
            //odbf.Header.AddColumn(new DbfColumn("id", DbfColumn.DbfColumnType.Number, 19, 0));
            //var orec = new DbfRecord(odbf.Header) { AllowDecimalTruncate = true };
            //orec[0] = 1.ToString();
            //odbf.Write(orec, true);

            //写入图斑
            odbf.Header.AddColumn(new DbfColumn("图斑编码", DbfColumn.DbfColumnType.Character, 80, 0));
            odbf.Header.AddColumn(new DbfColumn("措施代码", DbfColumn.DbfColumnType.Character, 80, 0));
            odbf.Header.AddColumn(new DbfColumn("措施名称", DbfColumn.DbfColumnType.Character, 80, 0));
            odbf.Header.AddColumn(new DbfColumn("利用现状", DbfColumn.DbfColumnType.Character, 80, 0));
            odbf.Header.AddColumn(new DbfColumn("措施数量", DbfColumn.DbfColumnType.Number, 18, 15));
            odbf.Header.AddColumn(new DbfColumn("坡度", DbfColumn.DbfColumnType.Number, 18, 15));

            var orec = new DbfRecord(odbf.Header)
            {
                AllowDecimalTruncate = true
            };
            List <MapPolygon> list = MapPolygon.GetList();

            foreach (var item in list)
            {
                //MapPolygon item = list[0];
                orec[0] = item.Code;//顺序要与header顺序保持一致
                orec[1] = item.Mark;
                orec[2] = item.Name;
                orec[3] = item.State;
                orec[4] = item.Number.ToString();
                orec[5] = item.Slope.ToString();
                odbf.Write(orec, true);
            }
            odbf.Close();
        }
Exemple #3
0
 public void Dispose()
 {
     if (!_disposed)
     {
         if (_file != null)
         {
             _file.Close();
         }
         _disposed = true;
     }
 }
Exemple #4
0
        private DbItemsCollection getRelevantBlocks(bool NonRetain)
        {
            DbfFile dbf = new DbfFile(encoding);

            dbf.Open(blocksPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            DbfRecord record = new DbfRecord(dbf.Header);

            DbItemsCollection dbItemsCollection = new DbItemsCollection();

            while (dbf.ReadNext(record))
            {
                if (record.IsDeleted)
                {
                    continue;
                }
                try
                {
                    DbItem dbItem = new DbItem(record, DatabaseType.NormalBlocks);

                    if (dbItem.bBlockType == DbType10 ||
                        dbItem.bBlockType == DbType20) //DB
                    {
                        dbItemsCollection.Add(dbItem.DatabaseId, dbItem);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }

            dbf.Close();

            // Remove entries that only contain DbType10 or 20, or where
            // the attribute is identical.
            List <int> removeIndexes = new List <int>();

            foreach (var blockItem in dbItemsCollection.getDbItems())
            {
                if (!blockItem.Value.ContainsKey(DbType10) ||
                    !blockItem.Value.ContainsKey(DbType20) ||
                    blockItem.Value[DbType10].currentNonRetain == NonRetain)
                {
                    removeIndexes.Add(blockItem.Key);
                }
            }
            foreach (var key in removeIndexes)
            {
                dbItemsCollection.Remove(key);
            }
            return(dbItemsCollection);
        }
        /// <summary>
        /// create precipitation and temperature gage location file in txt or dbf file
        /// </summary>
        private void createGageLocationFile()
        {
            FormatType type = Format;

            if (type != FormatType.ARCSWAT_DBF && type != FormatType.ARCSWAT_TEXT)
            {
                return;
            }
            if (_stations == null || _stations.Count == 0)
            {
                return;
            }

            //for ArcSWAT 2012 text format
            if (type == FormatType.ARCSWAT_TEXT)
            {
                StringBuilder sb_p = new StringBuilder();
                StringBuilder sb_t = new StringBuilder();
                sb_p.AppendLine("ID,NAME,LAT,LONG,ELEVATION");
                sb_t.AppendLine("ID,NAME,LAT,LONG,ELEVATION");
                foreach (ECStationInfo info in _stations)
                {
                    sb_p.AppendLine(info.ToArcSWAT2012CSVGageLocation(true));  //precipitation
                    sb_t.AppendLine(info.ToArcSWAT2012CSVGageLocation(false)); //temperature
                }
                string pFileName = "pcp.txt";
                string tFileName = "tmp.txt";
                using (StreamWriter writer = new StreamWriter(_path + @"\" + pFileName))
                    writer.Write(sb_p.ToString());
                using (StreamWriter writer = new StreamWriter(_path + @"\" + tFileName))
                    writer.Write(sb_t.ToString());
            }
            else if (type == FormatType.ARCSWAT_DBF)
            {
                string  pFileName = "pcp.dbf";
                string  tFileName = "tmp.dbf";
                DbfFile pDBF      = createDBFGageLocationFile(_path + @"\" + pFileName);
                DbfFile tDBF      = createDBFGageLocationFile(_path + @"\" + tFileName);

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

                foreach (ECStationInfo info in _stations)
                {
                    info.ToArcSWAT2012CSVGageLocation(pDBF, true);
                    info.ToArcSWAT2012CSVGageLocation(tDBF, false);
                }
                pDBF.Close();
                tDBF.Close();
            }
        }
Exemple #6
0
        /// <summary>
        /// this method is called to obtain format of input file
        /// </summary>
        /// <returns></returns>
        protected override ITableStructure DoGetRowFormat()
        {
            DbfFile dbf = null;

            try
            {
                dbf = OpenReader();
                return(GetStructure(dbf));
            }
            finally
            {
                if (dbf != null)
                {
                    dbf.Close();
                }
            }
        }
Exemple #7
0
        /// <summary>
        /// Update SUBBLK.DBF
        /// This file contains the all blocks, which contains
        /// the actual NonRetain attribute and timestamp
        /// that will be shown in the block online.
        /// </summary>
        /// <param name="dbItemsCollection"></param>
        /// <param name="NonRetain"></param>
        /// <param name="newTime"></param>
        private void updateBlockItemsAttr(
            DbItemsCollection dbItemsCollection,
            bool NonRetain,
            string newTime = null)
        {
            DbfFile dbf = new DbfFile(encoding);

            dbf.Open(blocksPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);

            foreach (var blockItems in dbItemsCollection.getDbItems().Values)
            {
                if (!blockItems.ContainsKey(DbType10))
                {
                    continue;
                }

                // Update only if the current attribute state is different from the given one.
                if (!blockItems[DbType10].currentNonRetain == NonRetain)
                {
                    // update reader with the saved record
                    DbfRecord rec = dbf.Read(blockItems[DbType10].recIndex);
                    // Modify the record stored in memory
                    blockItems[DbType10].updateDbItemAttribute(
                        rec, NonRetain, newTime);
                    // Write the modified record to the database
                    dbf.Update(rec);

                    if (blockItems.ContainsKey(DbType20))
                    {
                        // update reader with the saved record
                        rec = dbf.Read(blockItems[DbType20].recIndex);
                        // Modify the record stored in memory
                        blockItems[DbType20].updateDbItemAttribute(
                            rec, NonRetain, newTime);
                        // Write the modified record to the database
                        dbf.Update(rec);
                    }
                }
                else
                {
                }
            }
            dbf.Close();
        }
Exemple #8
0
        /// <summary>
        /// reads content of input file into given data queue
        /// </summary>
        /// <param name="queue"></param>
        protected override void DoRead(IDataQueue queue)
        {
            DbfFile dbf = null;

            try
            {
                dbf = OpenReader();
                ITableStructure format = GetStructure(dbf);

                DbfRecord irec = new DbfRecord(dbf.Header);
                // for each record in input DBF
                while (dbf.ReadNext(irec))
                {
                    if (irec.IsDeleted)
                    {
                        continue;
                    }

                    object[] vals = new object[format.Columns.Count];
                    for (int i = 0; i < format.Columns.Count; i++)
                    {
                        vals[i] = irec[i];
                    }
                    var orec = new ArrayDataRecord(format, vals);
                    queue.PutRecord(new ArrayDataRecord(format, vals));
                }

                queue.PutEof();
            }
            catch (Exception e)
            {
                ProgressInfo.LogError(e);
                queue.PutError(e);
            }
            finally
            {
                if (dbf != null)
                {
                    dbf.Close();
                }
                queue.CloseWriting();
            }
            FinalizeBulkCopy();
        }
        //从源文件获取字段信息
        public List <R_FieldInf> GetFieldInfs(string path)
        {
            List <R_FieldInf> FieldInfs = new List <R_FieldInf>();
            string            dbfpath   = path;

            #region 该部分使用FastDBF获取字段名称  返回List<string> fieldNames
            DbfFile dbf = new DbfFile(Encoding.Default);
            dbf.Open(dbfpath, FileMode.Open);
            DbfHeader     dh         = dbf.Header;
            List <string> fieldNames = new List <string>();
            int           fieldCount = dh.ColumnCount;
            for (int index = 0; index < fieldCount; index++)
            {
                fieldNames.Add(dh[index].Name);
            }
            dbf.Close();
            #endregion

            #region 该部分使用Shapelib获取字段类型 返回List<string> fieldTypes
            //获取字段类型
            IntPtr        hDbf          = ShapeLib.DBFOpen(dbfpath, "rb+");//"rb"(只读)"rb+"(读/写)
            int           pointCount    = ShapeLib.DBFGetRecordCount(hDbf);
            List <string> fieldTypes    = new List <string>();
            StringBuilder stringBuilder = new StringBuilder(20);
            int           pnWidth       = 10;
            int           pnDecimals    = 10;
            for (int index = 0; index < fieldCount; index++)
            {
                string type = TypeConvert(ShapeLib.DBFGetFieldInfo(hDbf, index, stringBuilder, ref pnWidth, ref pnDecimals).ToString());
                fieldTypes.Add(type);
            }
            ShapeLib.DBFClose(hDbf);
            #endregion

            //实例化类型
            for (int index = 0; index < fieldCount; index++)
            {
                FieldInfs.Add(new R_FieldInf(fieldNames[index], fieldTypes[index]));
            }
            return(FieldInfs);
        }
Exemple #10
0
        public string CreateDbfFile(RegistryInfo registryInfo)
        {
            try
            {
                var workDirectory = Path.Combine(Directory.GetCurrentDirectory(), @"Abonents\" + registryInfo.Now.ToString("dd.MM.yyyy"));
                var dbfFilePath   = Path.Combine(workDirectory, $"{registryInfo.FileName}" + ".dbf");

                if (!Directory.Exists(workDirectory))
                {
                    Directory.CreateDirectory(workDirectory);
                }

                if (File.Exists(dbfFilePath))
                {
                    File.Delete(dbfFilePath);
                }

                var dbfFile = new DbfFile();
                dbfFile.Create(dbfFilePath);
                dbfFile.Header.Unlock();
                dbfFile.Header.AddColumn("FIO", DbfColumn.DbfColumnType.Character, 100, 0);
                dbfFile.Header.AddColumn("ACCOUNT", DbfColumn.DbfColumnType.Character, 20, 0);

                var record = new DbfRecord(dbfFile.Header, Encoding.GetEncoding(1251))
                {
                };
                foreach (Abonent row in registryInfo.Abonents)
                {
                    record[0] = row.Fio;
                    record[1] = row.Account;
                    dbfFile.Write(record, true);
                }
                dbfFile.Close();
                return(dbfFilePath);
            }
            catch (Exception ex)
            {
                throw new Exception($"Error in CreateDbfFile: {ex}");
            }
        }
Exemple #11
0
        static void Main(string[] args)
        {
            // Einfache Datenbank erstellen
            var odbf = new DbfFile(Encoding.GetEncoding(1252));

            odbf.Open(Path.Combine(TestPath, "libfintx.dbf"), FileMode.Create);

            // Header erstellen
            odbf.Header.AddColumn(new DbfColumn("StrCol", DbfColumn.DbfColumnType.Character, 20, 0));
            odbf.Header.AddColumn(new DbfColumn("DecCol1", DbfColumn.DbfColumnType.Number, 5, 1));
            odbf.Header.AddColumn(new DbfColumn("DecCol2", DbfColumn.DbfColumnType.Number, 5, 2));
            odbf.Header.AddColumn(new DbfColumn("DecCol3", DbfColumn.DbfColumnType.Number, 5, 3));
            odbf.Header.AddColumn(new DbfColumn("DecCol4", DbfColumn.DbfColumnType.Number, 15, 5));
            odbf.Header.AddColumn(new DbfColumn("NumCol1", DbfColumn.DbfColumnType.Number, 5, 0));
            odbf.Header.AddColumn(new DbfColumn("NumCol2", DbfColumn.DbfColumnType.Number, 10, 0));
            odbf.Header.AddColumn(new DbfColumn("DateCol1", DbfColumn.DbfColumnType.Date));
            odbf.Header.AddColumn(new DbfColumn("BoolCol1", DbfColumn.DbfColumnType.Boolean));

            // Datensatz hinzufügen
            var orec = new DbfRecord(odbf.Header)
            {
                AllowDecimalTruncate = true
            };

            orec[0] = "Torsten Klinger";
            orec[1] = "123.5";
            orec[2] = "12.35";
            orec[3] = "1.235";
            orec[4] = "1235.123456";
            orec[5] = "1235";
            orec[6] = "123567890";
            orec[7] = "11/07/2020";
            orec[8] = "f";
            odbf.Write(orec, true);

            // Verbindung schließen
            odbf.Close();
        }
Exemple #12
0
        //public List<Abonent> GetUrData(string path, string alias, string fileExtension)
        //{
        //    List<Abonent> abonents = new List<Abonent>();

        //    FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read);

        //    IWorkbook workBook;
        //    if (fileExtension.ToLower().Equals(".xls"))
        //    {
        //        workBook = new HSSFWorkbook(fs);
        //    }
        //    else
        //    {
        //        workBook = new XSSFWorkbook(fs);
        //    }

        //    ISheet sheet = workBook.GetSheetAt(0);

        //    for (int row_num = 0; row_num <= sheet.LastRowNum; row_num++)
        //    {
        //        var row = sheet.GetRow(row_num);

        //        if (row != null)
        //        {
        //            ulong Account = 0;
        //            var cell = row?.GetCell(1)?.ToString();
        //            if (string.IsNullOrEmpty(cell))
        //            {
        //                Console.WriteLine("Не попадёт в dbf row.RowNum: " + row.RowNum);
        //                continue;
        //            }

        //            if (!ulong.TryParse(cell, out Account)) //Ожидает, что второй столбец - л/с
        //            {
        //                Console.WriteLine("Не попадёт в dbf: " + row.GetCell(1).ToString());
        //                continue;
        //            }

        //            abonents.Add(new Abonent
        //            {
        //                Account = row.GetCell(1).ToString(),
        //                Fio = row.GetCell(2).ToString(),
        //                Address = row.GetCell(3).ToString(),
        //                Alias = alias
        //            });
        //        }
        //    }

        //    return abonents;
        //}

        public List <Abonent> GetFizDataFromDbf(string path)
        {
            List <Abonent> abonents      = new List <Abonent>();
            var            dbfFileToRead = new DbfFile();

            dbfFileToRead.Open(path, FileMode.Open);

            DbfRecord record = new DbfRecord(dbfFileToRead.Header);

            while (dbfFileToRead.ReadNext(record))
            {
                abonents.Add(
                    new Abonent()
                {
                    Fio     = record[1],
                    Account = record[2]
                }
                    );
            }
            dbfFileToRead.Close();

            return(abonents);
        }
Exemple #13
0
        /// <summary>
        /// Update BAUSTEIN.DBF (only timestamp, attribs buildup not known)
        /// This is needed for the compare function to detect the difference.
        /// </summary>
        /// <param name="NonRetain"></param>
        /// <param name="newTime"></param>
        private void updateBlocksListItemsAttr(
            DbItemsCollection dbItemsCollection,
            bool NonRetain,
            string newTime = null)
        {
            DbfFile dbf = new DbfFile(encoding);

            dbf.Open(blocksListPath, FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite);
            DbfRecord record = new DbfRecord(dbf.Header);

            while (dbf.ReadNext(record))
            {
                if (record.IsDeleted)
                {
                    continue;
                }
                try
                {
                    DbItem dbItem = new DbItem(record, DatabaseType.NormalBlocksList);

                    //Only one record with each ID
                    if (dbItemsCollection.getDbItems().ContainsKey(dbItem.DatabaseId) &&
                        dbItemsCollection.getDbItems()
                        [dbItem.DatabaseId][DbType10].currentNonRetain != NonRetain)
                    {
                        //Update attribute with new timestamp1
                        dbItem.updateDbItemAttribs(record, newTime);
                        dbf.Update(record);
                    }
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                }
            }
            dbf.Close();
        }
Exemple #14
0
        private void LoadMeasurementsFromFile(string filepath, DateTimeOffset lastmeasurementtimestamp, List <MeasurementModel> measurements)
        {
            //get previously copied file from the same temporary location it was copied to
            string tempfilepath = Path.Combine(Config.TempDirectory.GetPluginRootedPath(), Path.GetFileName(filepath));

            //Instantiate and open the file into a DBFFile object
            DbfFile dbf = new DbfFile();

            dbf.Open(tempfilepath, FileMode.Open);
            if (Config.VerboseLogging)
            {
                Log.Append(String.Format("Opened dbf file {0}", tempfilepath), true);
            }
            //Add new measurements from dbf since last measurement into list of measurements
            AddNewMeasurements(dbf, lastmeasurementtimestamp, measurements);

            //Close file and delete
            dbf.Close();
            File.Delete(tempfilepath);
            if (Config.VerboseLogging)
            {
                Log.Append(String.Format("Deleted dbf file {0}", tempfilepath), true);
            }
        }
Exemple #15
0
        private static void TestWriteNewDbf()
        {
            //create a simple DBF file and output to args[0]
            var odbf = new DbfFile(Encoding.GetEncoding(1252));

            odbf.Open(Path.Combine(TestPath, "TestNew2.dbf"), FileMode.Create);

            //create a header
            odbf.Header.AddColumn(new DbfColumn("StrCol", DbfColumn.DbfColumnType.Character, 20, 0));
            odbf.Header.AddColumn(new DbfColumn("DecCol1", DbfColumn.DbfColumnType.Number, 5, 1));
            odbf.Header.AddColumn(new DbfColumn("DecCol2", DbfColumn.DbfColumnType.Number, 5, 2));
            odbf.Header.AddColumn(new DbfColumn("DecCol3", DbfColumn.DbfColumnType.Number, 5, 3));
            odbf.Header.AddColumn(new DbfColumn("DecCol4", DbfColumn.DbfColumnType.Number, 15, 5));
            odbf.Header.AddColumn(new DbfColumn("NumCol1", DbfColumn.DbfColumnType.Number, 5, 0));
            odbf.Header.AddColumn(new DbfColumn("NumCol2", DbfColumn.DbfColumnType.Number, 10, 0));
            odbf.Header.AddColumn(new DbfColumn("DateCol1", DbfColumn.DbfColumnType.Date));
            odbf.Header.AddColumn(new DbfColumn("BoolCol1", DbfColumn.DbfColumnType.Boolean));

            //add some records...
            var orec = new DbfRecord(odbf.Header)
            {
                AllowDecimalTruncate = true
            };

            orec[0] = "Ahmed Test";
            orec[1] = "123.5";
            orec[2] = "12.35";
            orec[3] = "1.235";
            orec[4] = "1235.123456";
            orec[5] = "1235";
            orec[6] = "123567890";
            orec[7] = "11/07/2007";
            orec[8] = "f";
            odbf.Write(orec, true);

            orec[0] = "Stéfanié Singer";
            orec[1] = "-1.5";
            orec[2] = "-1.35";
            orec[3] = "1.235";
            orec[4] = "-1235.123";
            orec[5] = "15";
            orec[6] = "12345";             //put a decimal in integer, we won't throw an exception beacuse we do not test for that.
            orec[7] = "2008-12-21";
            orec[8] = "f";
            odbf.Write(orec, true);

            orec[0] = "Stéfanié Singer longer than fits in the DBF record!";
            orec[1] = "0.1";
            orec[2] = ".12";
            orec[3] = ".1";
            orec[4] = "";
            orec[5] = "-15";
            orec[6] = "-12345";             //put a decimal in integer, we won't throw an exception beacuse we do not test for that.
            orec[7] = "";
            orec[8] = "no";
            odbf.Write(orec);

            //overwrite first record with last record's data...
            orec.RecordIndex = 0;
            odbf.Write(orec);

            //odbf.Header.RecordCount = 50;
            odbf.WriteHeader();

            odbf.Close();


            //open the same DBF file we just output, and append a few records to it...
            odbf.Open(Path.Combine(TestPath, "TestNew2.dbf"), FileMode.Open);

            orec.Clear();
            orec[0] = "New record added!";
            orec[6] = "100";
            orec[8] = "t";
            odbf.Write(orec, true);

            orec[0] = "New record 2";
            orec[6] = "104";
            orec[8] = "y";
            odbf.Write(orec, true);

            orec[0] = "New record 3";
            orec[6] = "104";
            orec[8] = "TRUE";
            odbf.Write(orec, true);

            if (odbf.Read(0, orec))
            {
                orec[0] = "modified first record";
                odbf.Write(orec, true);
            }

            //read 3rd record and output to console...
            Console.WriteLine(odbf.Read(2).ToString());


            //now add a new record, forcing seek to end of file...
            orec.Clear();
            orec[0] = "New record 4";
            orec[6] = "500";
            orec[8] = "FALSE";
            odbf.Write(orec, true);


            odbf.Close();

            Console.ReadKey();
        }
Exemple #16
0
        static void ProcessConvert(dynamic info, NpgsqlConnection pgConnection)
        {
            bool errLog = log != null;

            if (info.skip != null)
            {
                return;
            }
            var    fields            = parseFields(info.fields);
            string insertCommandText = createInsertCommandString(info.pgTableName, fields);

            if (info.clearPgTable != null && info.clearPgTable)
            {
                clearPgTable(info.pgTableName, pgConnection);
            }
            var encoding = info.dbfEncoding != null ? info.dbfEncoding : "utf8";

            DbfFile f = new DbfFile(Encoding.GetEncoding(encoding));

            f.Open(info.path, FileMode.Open);
            DbfRecord record = new DbfRecord(f.Header);

            Console.Write("Dbf header: ");
            for (int i = 0; i < f.Header.ColumnCount; i++)
            {
                Console.Write("{0} {1}({2}) ", f.Header[i].Name, f.Header[i].ColumnTypeChar, f.Header[i].Length);
            }
            Console.WriteLine();
            int           count = 0;
            NpgsqlCommand command;
            var           start = DateTime.Now;

            //var transaction = pgConnection.BeginTransaction();
            while (f.ReadNext(record))
            {
                if (record.IsDeleted)
                {
                    continue;
                }
                command = pgConnection.CreateCommand();
                //command.Transaction = transaction;
                command.CommandText = insertCommandText;

                for (int i = 0; i < fields.Count; i++)
                {
                    var value = record[fields[i].dbfName].Trim();
                    if (value == "" || (f.Header[fields[i].dbfName].ColumnType == DbfColumn.DbfColumnType.Date && value == "00-1-1-1")) //empty date bug
                    {
                        value = null;
                    }
                    else
                    if (f.Header[fields[i].dbfName].ColumnType == DbfColumn.DbfColumnType.Date)
                    {
                        string date = value as String;
                        value = string.Format("{0}-{1}-{2} 01:00:00+06", date.Substring(0, 4), date.Substring(4, 2), date.Substring(6, 2));     //гори в аду javascript
                    }
                    command.Parameters.AddWithValue("@" + fields[i].pgName, value);
                }
                try
                {
                    command.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    var oldColor = Console.ForegroundColor;
                    Console.ForegroundColor = ConsoleColor.Red;
                    Console.WriteLine("Запись [{0}]: {1}", record.RecordIndex, dumpRecord(record));
                    Console.WriteLine("Ошибка сохранения: {0}", e.Message);
                    Console.ForegroundColor = oldColor;
                    if (errLog)
                    {
                        log.WriteLine("{0} [{1}]: {2}", info.pgTableName, record.RecordIndex, dumpRecord(record));
                        log.WriteLine("Ошибка: {0}", e.Message);
                        log.WriteLine("==============================================================================================================");
                    }
                }
                count++;
                if (count % 50 == 0)
                {
                    Console.Write("\rОбработано: {0}/{1} ({2:F2}%)", count, f.Header.RecordCount, (float)(count * 100) / f.Header.RecordCount);
                }
            }

            /*try
             * {
             *  transaction.Commit();
             * }
             * catch (Exception e)
             * {
             *  var oldColor = Console.ForegroundColor;
             *  Console.ForegroundColor = ConsoleColor.Red;
             *  Console.WriteLine("Ошибка транзакции: {0}", e.Message);
             *  Console.ForegroundColor = oldColor;
             * }*/
            f.Close();
            Console.WriteLine("\rТаблица \"{0}\": {1} записей [{2}]", info.pgTableName, count, DateTime.Now - start);
        }
Exemple #17
0
 public void TranslateData(string csvFile, string dbfFile)
 {
     if (args.Length == 2)
     {
         csvFile = args[0];
         dbfFile = args[1];
     }
     convertFileInfo(ref csvFile);
     convertFileInfo(ref dbfFile);
     try
     {
         DbfFile odbf = new DbfFile();
         odbf.Open(dbfFile, FileMode.OpenOrCreate);
         odbf.Header.AddColumn(new DbfColumn("SEQUENCE", DbfColumn.DbfColumnType.Number, 6, 0));
         odbf.Header.AddColumn(new DbfColumn("LEVEL", DbfColumn.DbfColumnType.Number, 2, 0));
         odbf.Header.AddColumn(new DbfColumn("LINENUM", DbfColumn.DbfColumnType.Character, 10, 0));
         odbf.Header.AddColumn(new DbfColumn("NAME", DbfColumn.DbfColumnType.Character, 50, 0));
         odbf.Header.AddColumn(new DbfColumn("ACCNTCODE", DbfColumn.DbfColumnType.Character, 10, 0));
         odbf.Header.AddColumn(new DbfColumn("TENANT", DbfColumn.DbfColumnType.Number, 2, 0));
         odbf.Header.AddColumn(new DbfColumn("COS", DbfColumn.DbfColumnType.Number, 2, 0));
         odbf.Header.AddColumn(new DbfColumn("EXG", DbfColumn.DbfColumnType.Number, 2, 0));
         DbfRecord orec = new DbfRecord(odbf.Header);
         orec.AllowDecimalTruncate = true;
         try
         {
             string[] lines = System.IO.File.ReadAllLines(csvFile, Encoding.GetEncoding(1251));
             int      count = 1;
             foreach (string line in lines)
             {
                 if (!line.StartsWith("No."))
                 {
                     string tmpStr = line;
                     orec[0] = (count++).ToString();
                     orec[1] = "1";
                     tmpStr  = tmpStr.Remove(0, tmpStr.IndexOf(";") + 1);
                     orec[2] = tmpStr.Substring(0, tmpStr.IndexOf(";")).Replace("Dial=", "");
                     tmpStr  = tmpStr.Remove(0, tmpStr.IndexOf(";") + 1);
                     orec[3] = tmpStr;
                     orec[4] = "";
                     orec[5] = "1";
                     orec[6] = "0";
                     orec[7] = "0";
                     odbf.Write(orec, true);
                 }
             }
         }
         catch (System.IO.FileNotFoundException ex)
         {
             Console.WriteLine("Ошибка: не найден файл *.CSV " + ex.Message);
         }
         finally
         {
             odbf.WriteHeader();
             odbf.Close();
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine("Ошибка: не найден файл данных *.CSV " + ex.Message);
     }
     finally
     {
         Console.WriteLine("\n Статус:  преобразования данных выполнено.");
     }
 }
Exemple #18
0
        private void GetFA(BackgroundWorker worker, Dictionary <string, Config.Podmiot> castomers, ref List <JPKFaktura> tab)
        {
            var    db     = new DbfFile(CodingName);
            int    wzSize = 0;
            string fail   = "";

            try
            {
                double index = 0;
                db.Open(Path.Combine(DbPath, "WZ.DBF"), FileMode.Open);
                JPKGenerator.SizeDB(db, ref wzSize);
                var dbRow = new DbfRecord(db.Header);

                db.Read(0, dbRow);
                do
                {
                    string failNr = dbRow["RF"].Trim() + "/" + dbRow["NRDOK"].Trim();

                    if (JPKGenerator.GetDate(dbRow["DATA"]) >= DateFrom && JPKGenerator.GetDate(dbRow["DATA"]) <= DateTo && !dbRow.IsDeleted && failNr.ToLower()[0] != 'w')
                    {
                        try
                        {
                            JPKFaktura row = new JPKFaktura();
                            fail     = "P_1";
                            row.P_1  = dbRow["DATA"];
                            fail     = "P_2";
                            row.P_2A = failNr;
                            fail     = "P_3A";
                            Config.Podmiot p = castomers[dbRow["KOD_K"].Trim()];
                            row.P_3A  = p.Id.PelnaNazwa;
                            fail      = "P_3B";
                            row.P_3B  = string.Format("{0}, {1} {2}", p.Adres.Ulica, p.Adres.KodPocztowy, p.Adres.Miejscowosc);
                            row.P_3C  = Jpk.Podmiot1.IdentyfikatorPodmiotu.PelnaNazwa;
                            row.P_3D  = Jpk.Podmiot1.AdresPodmiotu.Ulica + " " + Jpk.Podmiot1.AdresPodmiotu.NrDomu;
                            row.P_3D += (string.IsNullOrEmpty(Jpk.Podmiot1.AdresPodmiotu.NrLokalu) ? " " : "/" + Jpk.Podmiot1.AdresPodmiotu.NrLokalu) + " " + Jpk.Podmiot1.AdresPodmiotu.Miejscowosc;
                            fail      = "P_4B";
                            row.P_4B  = Jpk.Podmiot1.IdentyfikatorPodmiotu.NIP;
                            if (!System.Text.RegularExpressions.Regex.IsMatch(p.Id.NIP, @"^\d"))
                            {
                                fail = "P_5A";
                                try
                                {
                                    row.P_5A = (MSCountryCode_Type)Enum.Parse(typeof(MSCountryCode_Type), p.Id.NIP.Substring(0, 2));
                                }
                                catch { }
                            }
                            else
                            {
                                fail     = "P_5B";
                                row.P_5B = p.Id.NIP;
                            }
                            fail              = "P_6";
                            row.P_6           = row.P_1;
                            fail              = "P_13_1";
                            fail              = "stawka";
                            row.P_15          = JPKGenerator.GetDecimal(dbRow["WARTOSC"]);
                            row.P_16          = isMK;  // metoda kasowa
                            row.P_17          = false; //samofakturowanie
                            row.P_18          = false; // odwrotne obciążenie
                            fail              = "P_19";
                            row.P_20          = false;
                            row.P_21          = false;
                            row.P_23          = false;
                            row.P_106E_2      = false;
                            row.P_106E_3      = false;
                            row.RodzajFaktury = JPKFakturaRodzajFaktury.VAT;
                            if (dbRow[39].Trim().Length > 1)
                            {
                                if (dbRow[39].Trim()[0] == 'Z')
                                {
                                    row.RodzajFaktury = JPKFakturaRodzajFaktury.ZAL;
                                    row.ZALZaplata    = JPKGenerator.GetDecimal(dbRow["WARTOSC"]);
                                    row.ZALPodatek    = JPKGenerator.GetDecimal(dbRow["WARTVAT"]);
                                }
                            }

                            tab.Add(row);
                        }
                        catch (Exception ex)
                        {
                            MainStatic.ShowException(ex, "Bład faktury nr: " + failNr + " \n" + fail);
                        }
                    }
                    index++;
                    worker.ReportProgress((int)Math.Ceiling((index / wzSize) * 100), string.Format("Przetwarzanie danych z faktur: {0} %", (int)Math.Ceiling((index / wzSize) * 100)));
                }while (db.ReadNext(dbRow));
            }
            catch (Exception ex)
            {
                throw new Exception("Zmień kodowanie", ex);
            }
            finally
            {
                db.Close();
            }
        }
        public bool CreatePointFile(string path, string[] pointJson)
        {
            if (pointJson == null || pointJson.Length == 0)
            {
                return(false);
            }

            if (System.IO.Directory.Exists(path) == false)
            {
                Directory.CreateDirectory(path);
            }
            ShapeLib.ShapeType shpType = ShapeLib.ShapeType.Point;

            hShpPoint = ShapeLib.SHPCreate(path + "\\poi", shpType);
            DbfFile   odbf = CreateAttr(path, pointJson);
            DbfRecord orec = new DbfRecord(odbf.Header)
            {
                AllowDecimalTruncate = true
            };


            //逐个点录入属性信息及提取坐标
            for (int i = 0; i < pointJson.Length; i++)
            {
                //取出JSON中的属性信息
                JObject obj       = (JObject)JsonConvert.DeserializeObject(pointJson[i]);
                string  attrs     = obj["attr"].ToString();
                string  attrtypes = obj["attrtype"].ToString();
                string  geometry  = obj["geometry"].ToString();

                //将该点属性信息记录为List<PointInf>
                List <PointInf> pointinf   = new List <PointInf>();
                List <string>   values     = new List <string>();
                List <string>   types      = new List <string>();
                JToken          attrname   = (JToken)JsonConvert.DeserializeObject(attrs);
                int             listLenhth = 0;
                foreach (JProperty jp in attrname)
                {
                    values.Add(jp.Value.ToString());
                    listLenhth++;
                }
                JToken attrtype = (JToken)JsonConvert.DeserializeObject(attrtypes);
                foreach (JProperty jp in attrtype)
                {
                    types.Add(jp.Value.ToString());
                }
                for (int a = 0; a < listLenhth - 1; a++)
                {
                    pointinf.Add(new PointInf(values[a], types[a]));
                }

                try
                {
                    //生成坐标点
                    List <Point> geo    = CreatePointFilePointList(geometry);
                    double[]     xCoord = new double[1];
                    double[]     yCoord = new double[1];
                    xCoord[0] = geo[0].X;
                    yCoord[0] = geo[0].Y;
                    IntPtr pShp = ShapeLib.SHPCreateSimpleObject(shpType, 1, xCoord, yCoord, null);
                    ShapeLib.SHPWriteObject(hShpPoint, -1, pShp);
                    ShapeLib.SHPDestroyObject(pShp);

                    //录入属性信息
                    for (int a = 0; a < listLenhth - 1; a++)
                    {
                        if (pointinf[a].Type == "text")
                        {
                            orec[a] = pointinf[a].Value;
                        }
                        else
                        {
                            string c = pointinf[a].Value.ToString();
                            orec[a] = c;
                        }
                    }
                    odbf.Write(orec, true);
                }
                catch
                {
                    string c = pointinf[0].Value.ToString();
                }
            }
            //关闭
            odbf.Close();
            if (hShpPoint != IntPtr.Zero)
            {
                ShapeLib.SHPClose(hShpPoint);
            }

            return(true);
        }
Exemple #20
0
        public static void convertToDbf(string[] args, string s1, string s2)
        {
            //КОЛИЧЕСТВО ";" В СТРОКЕ
            string columnNames = s1;
            int    columnCount = 0;

            for (int i = 0; i < columnNames.Length; i++)
            {
                if (columnNames[i] == ';')
                {
                    columnCount++;
                }
            }
            //Чтение типов данных полей
            string columnTypes = s2;
            string csvFile     = args[0];
            string dbfFile     = args[1];

            if (args.Length == 2)
            {
                csvFile = args[0];
                dbfFile = args[1];
            }
            convertFileInfo(ref csvFile);
            convertFileInfo(ref dbfFile);
            try
            {
                //Создание нового DBF файла
                DbfFile odbf = new DbfFile(Encoding.GetEncoding(1251));
                odbf.Open(dbfFile, FileMode.OpenOrCreate);
                //ДОБАВЛЕНИЕ ЗАГОЛОВКОВ ИЗ СТРОКИ УКАЗАННОЙ В TextBox 5
                string str, col; char type;
                int    n1 = 0, n2 = 0, ind = 0;
                for (int k = 0; k < columnCount; k++)
                {
                    int kk = 0;
                    kk   = columnNames.IndexOf(';');
                    col  = columnNames.Substring(0, kk);
                    ind  = columnTypes.IndexOf(";");
                    str  = columnTypes.Substring(0, ind + 1);
                    type = str[0];
                    str  = str.Remove(0, 1);
                    n1   = Int32.Parse(str.Substring(0, str.IndexOf(",")));
                    str  = str.Remove(0, str.IndexOf(",") + 1);
                    n2   = Int32.Parse(str.Substring(0, str.IndexOf(";")));
                    if (type == 'N')
                    {
                        odbf.Header.AddColumn(new DbfColumn(col, DbfColumn.DbfColumnType.Number, n1, n2));
                    }
                    if (type == 'C')
                    {
                        odbf.Header.AddColumn(new DbfColumn(col, DbfColumn.DbfColumnType.Character, n1, n2));
                    }
                    columnNames = columnNames.Remove(0, columnNames.IndexOf(";") + 1);
                    columnTypes = columnTypes.Remove(0, columnTypes.IndexOf(";") + 1);
                }
                DbfRecord orec = new DbfRecord(odbf.Header);
                orec.AllowDecimalTruncate = true;
                orec.AllowIntegerTruncate = true;
                orec.AllowStringTurncate  = true;
                //Заполнение ячеек данными из CSV
                try
                {
                    string[] lines = System.IO.File.ReadAllLines(csvFile, Encoding.UTF8);
                    lines = lines.Reverse().Take(lines.Length - 1).Reverse().ToArray();
                    foreach (string line in lines)
                    {
                        if (!line.StartsWith("No."))
                        {
                            string tmpStr = line;
                            for (int k = 0; k < columnCount; k++)
                            {
                                string s  = tmpStr + ";";
                                int    kk = 0;
                                kk = s.IndexOf(';');
                                s  = s.Substring(0, kk);
                                if (s.IndexOf(",") > 0)
                                {
                                    s = s.Replace(",", ".");
                                }
                                byte[] bytes = Encoding.GetEncoding(1251).GetBytes(s);
                                s       = Encoding.GetEncoding(1251).GetString(bytes);
                                orec[k] = s;
                                tmpStr  = tmpStr.Remove(0, tmpStr.IndexOf(";") + 1);
                            }
                            odbf.Write(orec, true);
                        }
                    }
                }
                catch (System.IO.FileNotFoundException ex)
                {
                    MessageBox.Show("Ошибка: не найден файл *.CSV !" + ex.Message);
                }
                finally
                {
                    odbf.WriteHeader();
                    odbf.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Ошибка: не найден файл данных *.CSV ! " + ex.Message);
            }
            //finally
            //{
            //    MessageBox.Show("\n Конвертация в DBF выполнена!");
            //}
        }
Exemple #21
0
        /// <summary>
        /// writes content of data queue into output DBF file
        /// </summary>
        /// <param name="queue"></param>
        protected override void DoWrite(IDataQueue queue)
        {
            var dbf       = new DbfFile();
            var formatter = new BedValueFormatter(FormatSettings);

            try
            {
                if (File.Exists(GetWorkingFileName()))
                {
                    File.Delete(GetWorkingFileName());
                }
                dbf.Create(GetWorkingFileName());

                ITableStructure ts = queue.GetRowFormat;
                foreach (var col in ts.Columns)
                {
                    DbfColumn.DbfColumnType type;
                    int len = 0, scale = 0;
                    switch (col.DataType.Code)
                    {
                    case DbTypeCode.Array:
                    case DbTypeCode.Generic:
                    case DbTypeCode.Text:
                    case DbTypeCode.Xml:
                        type = DbfColumn.DbfColumnType.Memo;
                        break;

                    case DbTypeCode.Blob:
                        type = DbfColumn.DbfColumnType.Binary;
                        break;

                    case DbTypeCode.Datetime:
                        var dtype = (DbTypeDatetime)col.DataType;
                        if (dtype.SubType == DbDatetimeSubType.Date)
                        {
                            type = DbfColumn.DbfColumnType.Date;
                        }
                        else
                        {
                            type = DbfColumn.DbfColumnType.Character;
                            len  = DateTime.UtcNow.ToString("s").Length;
                        }
                        break;

                    case DbTypeCode.Float:
                        type  = DbfColumn.DbfColumnType.Number;
                        len   = 18;
                        scale = DefaultNumericScale;
                        break;

                    case DbTypeCode.Int:
                        if (AllowFoxProInteger)
                        {
                            type = DbfColumn.DbfColumnType.Integer;
                        }
                        else
                        {
                            type = DbfColumn.DbfColumnType.Number;
                            len  = 18;
                        }
                        break;

                    case DbTypeCode.Logical:
                        type = DbfColumn.DbfColumnType.Boolean;
                        break;

                    case DbTypeCode.Numeric:
                        type  = DbfColumn.DbfColumnType.Number;
                        len   = 18;
                        scale = ((DbTypeNumeric)col.DataType).Scale;
                        break;

                    case DbTypeCode.String:
                        var stype = (DbTypeString)col.DataType;
                        if (stype.IsBinary)
                        {
                            type = DbfColumn.DbfColumnType.Binary;
                        }
                        else if (stype.Length <= 254)
                        {
                            type = DbfColumn.DbfColumnType.Character;
                            len  = stype.Length;
                            if (len <= 0)
                            {
                                len = DefaultStringLength;
                            }
                        }
                        else
                        {
                            type = DbfColumn.DbfColumnType.Memo;
                        }
                        break;

                    default:
                        type = DbfColumn.DbfColumnType.Character;
                        len  = DefaultStringLength;
                        break;
                    }
                    dbf.Header.AddColumn(col.ColumnName, type, len, scale);
                }

                var orec = new DbfRecord(dbf.Header);
                while (!queue.IsEof)
                {
                    var record = queue.GetRecord();
                    orec.Clear();
                    for (int i = 0; i < ts.Columns.Count; i++)
                    {
                        record.ReadValue(i);
                        formatter.ReadFrom(record);
                        orec[i] = formatter.GetText();
                    }
                    dbf.Write(orec);
                }
            }
            finally
            {
                dbf.Close();
                queue.CloseReading();
            }
            FinalizeBulkCopy();
        }
Exemple #22
0
        static void Main(string[] args)
        {
            //if(args.Length < 2)
            //{
            //  //print help
            //  Console.WriteLine("\n\n");
            //  Console.WriteLine("Welcome to Social Explorer DBF 2 CSV Utility");
            //  Console.WriteLine("-------------------------------------------------");
            //  Console.WriteLine("\nParameters:");
            //  Console.WriteLine("1. input DBF file");
            //  Console.WriteLine("2. output CSV file");

            //  Console.WriteLine("\nOptional switches:");
            //  Console.WriteLine("/F  - format numbers so 5.5000 comes out as 5.5");
            //  Console.WriteLine("/P  - padded output, fixed width (/P trumps /F)");
            //  Console.WriteLine("/Q  - only output quotes when comma appears in data");

            //  Console.WriteLine("\n\nExample: dbf2csv \"in.dbf\" \"out.csv\" /P /Q");

            //}
            //else
            {
                ////check if input DBF file exists...
                //if(!File.Exists(args[0]))
                //{
                //  Console.WriteLine("Input file '" + args[0] + "' does not exist!");
                //  return;
                //}


                ////create output csv file overwrite if already exists.
                //if(File.Exists(args[1]))
                //{
                //  //ask to overwrite:
                //  Console.WriteLine("Output CSV file '" + args[1] + "' already exists.");
                //  Console.WriteLine("Would you like to overwrite it? Press 'Y' for yes: ");
                //  if(Console.ReadKey().KeyChar.ToString().ToUpper() != "Y")
                //    return;
                //}

                bool bSwitchF = false;
                bool bSwitchP = false;
                bool bSwitchQ = false;

                //for(int i=0;i<args.Length;i++)
                //  if(args[i] == "/F")
                //    bSwitchF = true;

                //for (int i = 0; i < args.Length; i++)
                //  if (args[i] == "/P")
                //    bSwitchP = true;

                //for (int i = 0; i < args.Length; i++)
                //  if (args[i] == "/Q")
                //    bSwitchQ = true;
                string inputputfn = "roads.dbf";
                string outputfn   = "roads1.csv";
                //open DBF file and create CSV output file...
                StreamWriter swcsv = new StreamWriter(outputfn, false, Encoding.Default);
                DbfFile      dbf   = new DbfFile(Encoding.UTF8);
                dbf.Open(inputputfn, FileMode.Open);


                ////output column names
                //for (int i = 0; i < dbf.Header.ColumnCount; i++)
                //{
                //  if(dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Binary &&
                //     dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Memo)
                //    swcsv.Write((i == 0 ? "": ",") + dbf.Header[i].Name);
                //  else
                //    Console.WriteLine("WARNING: Excluding Binary/Memo field '" + dbf.Header[i].Name + "'");

                //}

                //swcsv.WriteLine();
                Hashtable table = new Hashtable();
                //output values for all but binary and memo...
                DbfRecord orec = new DbfRecord(dbf.Header);
                while (dbf.ReadNext(orec))
                {
                    //output column values...
                    if (!orec.IsDeleted)
                    {
                        for (int i = 0; i < orec.ColumnCount; i++)
                        {
                            if (i != 1)
                            {
                                continue;
                            }
                            if (orec.Column(i).ColumnType == DbfColumn.DbfColumnType.Character)
                            {
                                //string values: trim, enclose in quotes and escape quotes with double quotes
                                string sval = orec[i];

                                char[]   split = { ' ', '-', '/', ';', '(', ')', '\'', '_', '#', '\"', '.' };
                                string[] token = sval.Split(split);
                                for (int j = 0; j < token.Length; j++)
                                {
                                    if (token[j].Length > 1)
                                    {
                                        if (!table.ContainsKey(token[j].ToLower()))
                                        {
                                            table.Add(token[j].ToLower(), "");
                                            swcsv.WriteLine(token[j].ToLower());
                                        }
                                    }
                                }

                                //end record with a linefeed or end column with a comma.
                                // if(i < orec.ColumnCount-1)
                                //  swcsv.Write(",");
                            }

                            //write line...
                            //swcsv.WriteLine();
                        }
                    }
                }


                //close files...
                swcsv.Flush();
                swcsv.Close();
                dbf.Close();
            }
        }
Exemple #23
0
        private void CreateFakturaWierszKorekta(BackgroundWorker worker, List <Product> products, ref List <JPKFaktura> tabDoc, ref List <JPKFakturaWiersz> tab)
        {
            var db     = new DbfFile(CodingName);
            int wzSize = 0;

            string fail = "";

            try
            {
                double index = 0;
                db.Open(Path.Combine(DbPath, "ZWA.DBF"), FileMode.Open);
                JPKGenerator.SizeDB(db, ref wzSize);
                var dbRow = new DbfRecord(db.Header);

                db.Read(0, dbRow);
                do
                {
                    string failNr = "";
                    try
                    {
                        if (tabDoc.Exists(f => f.P_2A == dbRow["NRDOK"].Trim() && f.RodzajFaktury == JPKFakturaRodzajFaktury.KOREKTA) && !dbRow.IsDeleted)
                        {
                            failNr = dbRow["NRDOK"].Trim();
                            int indexKor         = tabDoc.FindIndex(f => f.P_2A == dbRow["NRDOK"].Trim() && f.RodzajFaktury == JPKFakturaRodzajFaktury.KOREKTA);
                            int typ              = int.Parse(dbRow["TYP"].Trim());
                            JPKFakturaWiersz row = new JPKFakturaWiersz();
                            fail     = "P_2B";
                            row.P_2B = dbRow["NRDOK"].Trim();                                    // numer faktury
                            fail     = "P_12";
                            row.P_12 = JPKGenerator.GetVat(dbRow["PTU"].Trim());                 // stawka vat
                            fail     = "P_7";
                            Product prod = products.Find(pr => pr.Code == dbRow["SYMB"].Trim()); // towar / usługa
                            row.P_7  = prod.Name;
                            fail     = "P_8A";
                            row.P_8A = prod.Quantity;
                            fail     = "ilosc";
                            row.P_8B = JPKGenerator.GetDecimal(dbRow["ILOSC"]); // ilosc

                            fail     = "nettoU";
                            row.P_9A = JPKGenerator.GetDecimal(dbRow["CENA"]); // cena jednostkowa netto
                            fail     = "stawkaVAT";
                            decimal stawkaVat = 0;
                            try { stawkaVat = JPKGenerator.GetDecimal(dbRow["PTU"]); } catch { }
                            if (dbRow["RF"].Trim() != "F")
                            {
                                row.P_9A = (stawkaVat != 0 ? (row.P_9A * 100) / (stawkaVat + 100) : row.P_9A) / row.P_8B;
                            }

                            switch (typ)
                            {
                            case 1:
                                fail     = "typ1";
                                row.P_8B = -row.P_8B;
                                row.P_11 = row.P_9A * -row.P_8B;
                                if (dbRow["RF"].Trim() != "F")
                                {
                                    row.P_11A = JPKGenerator.GetDecimal(dbRow["WARTOSC"]);
                                }
                                break;

                            case 2:
                                fail = "typ2";
                                if ((decimal.Parse(dbRow["WARTKOR"].Trim().Replace(".", ",")) * stawkaVat * (decimal)0.01).ToString("0.00").Replace(",", ".") == dbRow["WARTKORV"].Trim())
                                {
                                    row.P_11 = -JPKGenerator.GetDecimal(dbRow["WARTKOR"]);
                                    if (dbRow["RF"].Trim() != "F")
                                    {
                                        row.P_11A = -JPKGenerator.GetDecimal(dbRow["WARTKOR"]) + JPKGenerator.GetDecimal(dbRow["WARTKORV"]);
                                    }
                                }
                                else
                                {
                                    row.P_11 = -JPKGenerator.GetDecimal(dbRow["WARTKOR"]) - JPKGenerator.GetDecimal(dbRow["WARTKORV"]);
                                    if (dbRow["RF"].Trim() != "F")
                                    {
                                        row.P_11A = -JPKGenerator.GetDecimal(dbRow["WARTKOR"]);
                                    }
                                }
                                break;

                            case 3:
                                fail = "typ3";
                                if (JPKGenerator.GetDecimal(dbRow["WARTKOR"]) * stawkaVat * (decimal)0.01 == JPKGenerator.GetDecimal(dbRow["WARTKORV"]))
                                {
                                    row.P_11 = JPKGenerator.GetDecimal(dbRow["WARTKOR"]);
                                    if (dbRow["RF"].Trim() != "F")
                                    {
                                        row.P_11A = JPKGenerator.GetDecimal(dbRow["WARTKOR"]) + JPKGenerator.GetDecimal(dbRow["WARTKORV"]);
                                    }
                                }
                                else
                                {
                                    row.P_11  = JPKGenerator.GetDecimal(dbRow["WARTKOR"]) - JPKGenerator.GetDecimal(dbRow["WARTKORV"]);
                                    row.P_11A = JPKGenerator.GetDecimal(dbRow["WARTKOR"]);
                                }
                                break;

                            case 4:
                                fail     = "typ4";
                                row.P_11 = 0;
                                break;
                            }
                            fail = "stawka";
                            switch (row.P_12)
                            {
                            case JPKFakturaWierszP_12.Item22:
                            case JPKFakturaWierszP_12.Item23:
                                tabDoc[indexKor].P_13_1 = tabDoc[indexKor].P_13_1 + row.P_11;
                                tabDoc[indexKor].P_14_1 = row.P_11 * JPKGenerator.GetVatValue(row.P_12);
                                break;

                            case JPKFakturaWierszP_12.Item8:
                            case JPKFakturaWierszP_12.Item7:
                                tabDoc[indexKor].P_13_2 = tabDoc[indexKor].P_13_2 + row.P_11;
                                tabDoc[indexKor].P_14_1 = row.P_11 * JPKGenerator.GetVatValue(row.P_12);
                                break;

                            case JPKFakturaWierszP_12.Item5:
                                tabDoc[indexKor].P_13_3 = tabDoc[indexKor].P_13_3 + row.P_11;
                                tabDoc[indexKor].P_14_1 = row.P_11 * JPKGenerator.GetVatValue(row.P_12);
                                break;

                            case JPKFakturaWierszP_12.Item0:
                                tabDoc[indexKor].P_13_6 = tabDoc[indexKor].P_13_6 + row.P_11;
                                break;

                            case JPKFakturaWierszP_12.zw:
                                tabDoc[indexKor].P_13_7 = tabDoc[indexKor].P_13_7 + row.P_11;
                                tabDoc[indexKor].P_19   = true;
                                tabDoc[indexKor].P_19A  = @"Ustawa z dnia 11.03.2004 o podatku od towarów i usług, art. 43 ust. 1";
                                break;
                            }
                            tab.Add(row);
                        }
                    }
                    catch (Exception ex)
                    {
                        MainStatic.ShowException(ex, "Bład pozycji faktury nr: " + failNr + "\n" + fail);
                    }
                    index++;
                    worker.ReportProgress((int)Math.Ceiling((index / wzSize) * 100), string.Format("Przetwarzanie pozycji faktur: {0} %", (int)Math.Ceiling((index / wzSize) * 100)));
                }while (db.ReadNext(dbRow));
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Błędne kodowanie"))
                {
                    throw new Exception("Zmień kodowanie", ex);
                }
                throw ex;
            }
            finally
            {
                db.Close();
            }
        }
Exemple #24
0
        static void Main(string[] args)
        {
            if (args.Length < 2)
            {
                //print help
                Console.WriteLine("\n\n");
                Console.WriteLine("Welcome to Social Explorer DBF 2 CSV Utility");
                Console.WriteLine("-------------------------------------------------");
                Console.WriteLine("\nParameters:");
                Console.WriteLine("1. input DBF file");
                Console.WriteLine("2. output CSV file");

                Console.WriteLine("\nOptional switches:");
                Console.WriteLine("/F  - format numbers so 5.5000 comes out as 5.5");
                Console.WriteLine("/P  - padded output, fixed width (/P trumps /F)");
                Console.WriteLine("/Q  - only output quotes when comma appears in data");
                Console.WriteLine("/E encoding - character encoding");

                Console.WriteLine("\n\nExample: dbf2csv \"in.dbf\" \"out.csv\" /P /Q /E Windows-1250");
            }
            else
            {
                //check if input DBF file exists...
                if (!File.Exists(args[0]))
                {
                    Console.WriteLine("Input file '" + args[0] + "' does not exist!");
                    return;
                }


                //create output csv file overwrite if already exists.
                if (File.Exists(args[1]))
                {
                    //ask to overwrite:
                    Console.WriteLine("Output CSV file '" + args[1] + "' already exists.");
                    Console.WriteLine("Would you like to overwrite it? Press 'Y' for yes: ");
                    if (Console.ReadKey().KeyChar.ToString().ToUpper() != "Y")
                    {
                        return;
                    }
                }
                var a = CodePagesEncodingProvider.Instance();
                Encoding.RegisterProvider(a);
                Encoding encoding = Encoding.GetEncoding(1252);
                bool     bSwitchF = false;
                bool     bSwitchP = false;
                bool     bSwitchQ = false;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "/F")
                    {
                        bSwitchF = true;
                    }
                }

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "/P")
                    {
                        bSwitchP = true;
                    }
                }

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "/Q")
                    {
                        bSwitchQ = true;
                    }
                }

                for (int i = 0; i < args.Length; i++)
                {
                    if ((args[i] == "/E") && ((i + 1) < args.Length))
                    {
                        encoding = Encoding.GetEncoding(args[i + 1]);
                    }
                }

                //open DBF file and create CSV output file...
                StreamWriter swcsv = new StreamWriter(args[1], false, encoding);
                DbfFile      dbf   = new DbfFile(encoding);
                dbf.Open(args[0], FileMode.Open);


                //output column names
                for (int i = 0; i < dbf.Header.ColumnCount; i++)
                {
                    if (dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Binary &&
                        dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Memo)
                    {
                        swcsv.Write((i == 0 ? "": ",") + dbf.Header[i].Name);
                    }
                    else
                    {
                        Console.WriteLine("WARNING: Excluding Binary/Memo field '" + dbf.Header[i].Name + "'");
                    }
                }

                swcsv.WriteLine();

                //output values for all but binary and memo...
                DbfRecord orec = new DbfRecord(dbf.Header);
                while (dbf.ReadNext(orec))
                {
                    //output column values...
                    if (!orec.IsDeleted)
                    {
                        for (int i = 0; i < orec.ColumnCount; i++)
                        {
                            if (orec.Column(i).ColumnType == DbfColumn.DbfColumnType.Character)
                            {
                                //string values: trim, enclose in quotes and escape quotes with double quotes
                                string sval = orec[i];

                                if (!bSwitchP)
                                {
                                    sval = orec[i].Trim();
                                }

                                if (!bSwitchQ || sval.IndexOf('"') > -1)
                                {
                                    sval = ("\"" + sval.Replace("\"", "\"\"") + "\"");
                                }

                                swcsv.Write(sval);
                            }
                            else if (orec.Column(i).ColumnType == DbfColumn.DbfColumnType.Date)
                            {
                                swcsv.Write(orec.GetDateValue(i).ToString("MM-dd-yyyy"));
                            }
                            else
                            {
                                if (bSwitchP)
                                {
                                    swcsv.Write(orec[i]);
                                }
                                else if (bSwitchF)
                                {
                                    swcsv.Write(FormatNumber(orec[i].Trim()));
                                }
                                else
                                {
                                    swcsv.Write(orec[i].Trim());
                                }
                            }

                            //end record with a linefeed or end column with a comma.
                            if (i < orec.ColumnCount - 1)
                            {
                                swcsv.Write(",");
                            }
                        }

                        //write line...
                        swcsv.WriteLine();
                    }
                }


                //close files...
                swcsv.Flush();
                swcsv.Close();
                dbf.Close();
            }
        }
Exemple #25
0
        private List <JPKFakturaWiersz> CreateFakturaWiersz(BackgroundWorker worker, ref List <JPKFaktura> tabDoc, List <Product> products)
        {
            List <JPKFakturaWiersz> tab = new List <JPKFakturaWiersz>();

            var db     = new DbfFile(CodingName);
            int wzSize = 0;

            string fail = "";

            try
            {
                double index = 0;
                db.Open(Path.Combine(DbPath, "WZA.DBF"), FileMode.Open);
                JPKGenerator.SizeDB(db, ref wzSize);
                var dbRow = new DbfRecord(db.Header);

                if (tab.Count == 0)
                {
                    db.Read(0, dbRow);
                    do
                    {
                        string failNr = dbRow["RF"].Trim() + "/" + dbRow["NRDOK"].Trim();
                        try
                        {
                            if (tabDoc.Exists(d => d.P_2A == failNr) && !dbRow.IsDeleted)
                            {
                                int indexDoc         = tabDoc.FindIndex(d => d.P_2A == failNr);
                                JPKFakturaWiersz row = new JPKFakturaWiersz();
                                fail     = "P_2B";
                                row.P_2B = failNr; // numer faktury
                                fail     = "P_12";
                                row.P_12 = JPKGenerator.GetVat
                                               (dbRow["PTU"]); // stawka vat
                                fail = "P_7";
                                Product prod = products.Find(pr => pr.Code == dbRow["SYMB"].Trim());
                                row.P_7  = prod.Name;
                                fail     = "P_8A";
                                row.P_8A = prod.Quantity;
                                fail     = "P_8B";
                                row.P_8B = JPKGenerator.GetDecimal(dbRow["ILOSC"]); // ilosc

                                decimal brutto = JPKGenerator.GetDecimal(dbRow["WARTOSC"]);
                                decimal netto  = 0;
                                decimal vat    = 0;

                                if (dbRow["RF"].Trim() == "F")                         // od netto
                                {
                                    row.P_9A = JPKGenerator.GetDecimal(dbRow["CENA"]); // cena jednostkowa netto
                                    netto    = decimal.Parse((row.P_9A * row.P_8B).ToString("0.00"));
                                    vat      = brutto - netto;
                                }
                                else // od brutto
                                {
                                    decimal stawkaVat = 0;
                                    try { stawkaVat = JPKGenerator.GetDecimal(dbRow["PTU"]); } catch { }
                                    netto = stawkaVat != 0 ? (brutto * 100) / (stawkaVat + 100) : brutto;
                                    if (netto != 0)
                                    {
                                        row.P_9A = netto / row.P_8B;
                                    }
                                    vat = brutto - netto;
                                }
                                fail     = "P_11";
                                row.P_11 = row.P_8B * row.P_9A;
                                if (dbRow["RF"].Trim() != "F")
                                {
                                    row.P_11A = brutto;                            // wartosc brutto, gdy faktura liczona jest od brutto
                                }
                                fail = "vaty";
                                switch (row.P_12)
                                {
                                case JPKFakturaWierszP_12.Item22:
                                case JPKFakturaWierszP_12.Item23:
                                    tabDoc[indexDoc].P_13_1 = tabDoc[indexDoc].P_13_1 + netto;
                                    tabDoc[indexDoc].P_14_1 = tabDoc[indexDoc].P_14_1 + vat;
                                    break;

                                case JPKFakturaWierszP_12.Item8:
                                case JPKFakturaWierszP_12.Item7:
                                    tabDoc[indexDoc].P_13_2 = tabDoc[indexDoc].P_13_2 + netto;
                                    tabDoc[indexDoc].P_14_2 = tabDoc[indexDoc].P_14_1 + vat;
                                    break;

                                case JPKFakturaWierszP_12.Item5:
                                    tabDoc[indexDoc].P_13_3 = tabDoc[indexDoc].P_13_3 + netto;
                                    tabDoc[indexDoc].P_14_3 = tabDoc[indexDoc].P_14_3 + vat;
                                    break;

                                case JPKFakturaWierszP_12.Item0:
                                    tabDoc[indexDoc].P_13_6 = tabDoc[indexDoc].P_13_6 + netto;
                                    break;

                                case JPKFakturaWierszP_12.zw:
                                    tabDoc[indexDoc].P_13_7 = tabDoc[indexDoc].P_13_7 + netto;
                                    tabDoc[indexDoc].P_19   = true;
                                    tabDoc[indexDoc].P_19A  = @"Ustawa z dnia 11.03.2004 o podatku od towarów i usług, art. 43 ust. 1";
                                    break;

                                case JPKFakturaWierszP_12.np:
                                    tabDoc[indexDoc].P_13_4 = tabDoc[indexDoc].P_13_4 + netto;
                                    tabDoc[indexDoc].P_18   = true;
                                    break;
                                }

                                tab.Add(row);
                            }
                        }
                        catch (Exception ex)
                        {
                            MainStatic.ShowException(ex, "Bład pozycji faktury nr: " + failNr + "\n" + fail);
                        }
                        index++;
                        worker.ReportProgress((int)Math.Ceiling((index / wzSize) * 100), string.Format("Przetwarzanie pozycji faktur: {0}%", (int)Math.Ceiling((index / wzSize) * 100)));
                    }while (db.ReadNext(dbRow));
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("Błędne kodowanie"))
                {
                    throw new Exception("Zmień kodowanie");
                }
                throw ex;
            }
            finally
            {
                db.Close();
            }

            return(tab);
        }
        /// <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);
        }
Exemple #27
0
        /// <summary>
        /// Создаёт аттач-файл для отправки по e-mail
        /// </summary>
        public void MakeRequest()
        {
            string template = "";

            using (StreamReader structure = new StreamReader(Settings.Templates + Service + "-ord-structure.tpl"))
            {
                template = structure.ReadToEnd();
            }
            if (string.IsNullOrEmpty(template))
            {
                throw new ApplicationException(string.Format("Шаблон структуры таблицы {0} пуст", Settings.Templates + Service + "-ord-structure.tpl"));
            }

            // Шаблон содержит структуру таблицы

            string tableName = Tid.ToString() + ".dbf";

            // Создадим объект Таблица
            DbfFile odbf = new DbfFile();

            // Откроем таблицу для записи в папку attachemts
            odbf.Open(Settings.Attachments + tableName, FileMode.Create);

            XElement root = XElement.Parse(stResponse);
            IEnumerable <XElement> fields =
                from el in root.Elements("fields")
                select el;

            string name;
            string type;
            string len;
            string p;

            foreach (XElement el in fields)
            {
                switch (el.Name.LocalName.ToString().ToLower())
                {
                case "field":                         // Поле
                    len  = "0";
                    p    = "0";
                    name = "";
                    type = "";
                    foreach (XAttribute attr in el.Attributes())
                    {
                        if (attr.Name.LocalName.ToLower() == "name")
                        {
                            name = attr.Value;
                        }
                        else if (attr.Name.LocalName.ToLower() == "type")
                        {
                            type = attr.Value;
                        }
                        else if (attr.Name.LocalName.ToLower() == "len")
                        {
                            len = attr.Value;
                        }
                        else if (attr.Name.LocalName.ToLower() == "p")
                        {
                            p = attr.Value;
                        }
                    }
                    if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(type))
                    {
                        throw new ApplicationException("Пропущены обязательные значения name или type в определении столбца");
                    }

                    odbf.Header.AddColumn(new DbfColumn(name, GetDbfType(type), int.Parse(len), int.Parse(p)));

                    break;

                default:
                    // Error = ErrTemplatelInvalid;
                    throw new ApplicationException("Ошибка структуры таблицы");
                }
            }

            // Создаём таблицу .DBF с заданной структурой
            odbf.WriteHeader();
            odbf.Close();

            // Формируем запрос Insert Into () Values()

            StringBuilder sb = new StringBuilder();

            sb.AppendFormat("Insert Into {0} (", tableName);
            int n = 0;

            foreach (KeyValuePair <string, string> kvp in Attributes)
            {
                sb.AppendFormat("{0}{1}", n++ != 0?", ": "", kvp.Key);
            }
            sb.Append(")\r\n Values( ");
            n = 0;
            foreach (KeyValuePair <string, string> kvp in Attributes)
            {
                sb.AppendFormat("{0}{1}", n++ != 0 ? ", " : "", kvp.Value);
            }
            sb.Append(");");

            Log("Выполняется запрос:\r\n{0}", sb.ToString());

            // Записываем атрибуты в файл .dbf
            using (OleDbConnection Connection =
                       new OleDbConnection(string.Format("Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Extended Properties=dbase 5.0;Data Source={0};",
                                                         Settings.Attachments)))
            {
                Connection.Open();
                using (OleDbCommand Command = new OleDbCommand(sb.ToString(), Connection))
                {
                    Command.ExecuteNonQuery();
                    Connection.Close();
                }
            }

            sb.Clear();
            sb = null;
        }
Exemple #28
0
        private void TestReadFile()
        {
            string[] args = { @"C:\Users\ziqiang.sun\Desktop\»ЄБъ-0279.dbf", @"C:\Users\ziqiang.sun\Desktop\TestNew2.dbf" };
            if (args.Length < 2)
            {
                //print help
                Console.WriteLine("\n\n");
                Console.WriteLine("Welcome to Social Explorer DBF 2 CSV Utility");
                Console.WriteLine("-------------------------------------------------");
                Console.WriteLine("\nParameters:");
                Console.WriteLine("1. input DBF file");
                Console.WriteLine("2. output CSV file");

                Console.WriteLine("\nOptional switches:");
                Console.WriteLine("/F  - format numbers so 5.5000 comes out as 5.5");
                Console.WriteLine("/P  - padded output, fixed width (/P trumps /F)");
                Console.WriteLine("/Q  - only output quotes when comma appears in data");

                Console.WriteLine("\n\nExample: dbf2csv \"in.dbf\" \"out.csv\" /P /Q");
            }
            else
            {
                //check if input DBF file exists...
                if (!File.Exists(args[0]))
                {
                    Console.WriteLine("Input file '" + args[0] + "' does not exist!");
                    return;
                }


                ////create output csv file overwrite if already exists.
                //if (File.Exists(args[1]))
                //{
                //    //ask to overwrite:
                //    Console.WriteLine("Output CSV file '" + args[1] + "' already exists.");
                //    Console.WriteLine("Would you like to overwrite it? Press 'Y' for yes: ");
                //    if (Console.ReadKey().KeyChar.ToString().ToUpper() != "Y")
                //        return;
                //}

                bool bSwitchF = false;
                bool bSwitchP = false;
                bool bSwitchQ = false;

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "/F")
                    {
                        bSwitchF = true;
                    }
                }

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "/P")
                    {
                        bSwitchP = true;
                    }
                }

                for (int i = 0; i < args.Length; i++)
                {
                    if (args[i] == "/Q")
                    {
                        bSwitchQ = true;
                    }
                }


                ////open DBF file and create CSV output file...
                //StreamWriter swcsv = new StreamWriter(args[1], false, Encoding.Default);
                //create a simple DBF file and output to args[0]
                DbfFile odbf = new DbfFile(Encoding.GetEncoding(936));
                odbf.Open(args[1], FileMode.Create);

                DbfFile dbf = new DbfFile(Encoding.GetEncoding(936));
                dbf.Open(args[0], FileMode.Open);


                ////output column names
                //for (int i = 0; i < dbf.Header.ColumnCount; i++)
                //{
                //    if (dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Binary &&
                //       dbf.Header[i].ColumnType != DbfColumn.DbfColumnType.Memo)
                //        swcsv.Write((i == 0 ? "" : ",") + dbf.Header[i].Name);
                //    else
                //        Console.WriteLine("WARNING: Excluding Binary/Memo field '" + dbf.Header[i].Name + "'");

                //}

                //output column names
                for (int i = 0; i < dbf.Header.ColumnCount; i++)
                {
                    odbf.Header.AddColumn(dbf.Header[i]);
                }

                //swcsv.WriteLine();

                //output values for all but binary and memo...
                DbfRecord orec = new DbfRecord(dbf.Header);
                while (dbf.ReadNext(orec))
                {
                    //output column values...
                    if (!orec.IsDeleted)
                    {
                        //if (orec["ZQZH"] != this.textBox1.Text.Trim())
                        //    break;
                        DbfRecord orec_out = new DbfRecord(odbf.Header);
                        orec_out.AllowDecimalTruncate = true;
                        for (int i = 0; i < orec.ColumnCount; i++)
                        {
                            orec_out[i] = orec[i].Replace("\0", "");
                        }
                        odbf.Write(orec_out);
                        //for (int i = 0; i < orec.ColumnCount; i++)
                        //{
                        //    if (orec.Column(i).ColumnType == DbfColumn.DbfColumnType.Character)
                        //    {
                        //        //string values: trim, enclose in quotes and escape quotes with double quotes
                        //        string sval = orec[i];

                        //        if (!bSwitchP)
                        //            sval = orec[i].Trim();

                        //        if (!bSwitchQ || sval.IndexOf('"') > -1)
                        //            sval = ("\"" + sval.Replace("\"", "\"\"") + "\"");

                        //        swcsv.Write(sval);

                        //    }
                        //    else if (orec.Column(i).ColumnType == DbfColumn.DbfColumnType.Date)
                        //    {
                        //        swcsv.Write(orec.GetDateValue(i).ToString("MM-dd-yyyy"));
                        //    }
                        //    else
                        //    {
                        //        if (bSwitchP)
                        //            swcsv.Write(orec[i]);
                        //        else if (bSwitchF)
                        //            swcsv.Write(FormatNumber(orec[i].Trim()));
                        //        else
                        //            swcsv.Write(orec[i].Trim());
                        //    }

                        //    end record with a linefeed or end column with a comma.
                        //    if (i < orec.ColumnCount - 1)
                        //    swcsv.Write(",");

                        //}

                        //write line...
                        //swcsv.WriteLine();
                    }
                }


                //close files...
                //swcsv.Flush();
                //swcsv.Close();

                odbf.WriteHeader();

                odbf.Close();
                dbf.Close();
            }
        }
Exemple #29
0
 public void close()
 {
     odbf.Close();
 }
        // Download ket qua upload thanh cong
        public void Completed(Guid id, string downloadtype = "xml")
        {
            ITransactionService tranSrv = IoC.Resolve <ITransactionService>();
            Transaction         model   = tranSrv.Getbykey(id);

            if (model == null)
            {
                Response.Clear();
                Response.Write("<script type='text/javascript'>alert('Có lỗi trong quá trình tải dữ liệu! <br /> Lỗi: Không tồn tại file');</script>");
                Response.Redirect("/Home/Index");
                Response.End();
                Response.Flush();
            }
            if (downloadtype != "dbf" && downloadtype != "xml")
            {
                Response.Clear();
                Response.Redirect("/Home/PotentiallyError");
                Response.End();
                Response.Flush();
            }
            byte[] buffer = model.CompleteResult;

            if (buffer != null)
            {
                try
                {
                    if (downloadtype == "dbf")
                    {
                        // Khach hang
                        if (model.TypeTrans == 1)
                        {
                            var    bytestring = Utils.Decompress(buffer);
                            string _b2str     = Encoding.UTF8.GetString(bytestring);

                            //string[] strarr = _b2str.Replace("OK:", "").Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
                            //var xxx = strarr[1].Replace("-", "").Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            string[] strarr = _b2str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                            var      xxx    = strarr[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            DbfFile      _file = new DbfFile(Encoding.GetEncoding(1252));
                            MemoryStream m     = new MemoryStream();

                            _file.Open(m);

                            _file.Header.AddColumn(new DbfColumn("Account", DbfColumn.DbfColumnType.Character, 50, 0));
                            _file.Header.AddColumn(new DbfColumn("Password", DbfColumn.DbfColumnType.Character, 50, 0));

                            DbfRecord _record = new DbfRecord(_file.Header);

                            foreach (string item in xxx)
                            {
                                if (item.Contains(";"))
                                {
                                    var ix = item.Split(';');
                                    _record[0] = ix[0];
                                    _record[1] = ix[1];
                                    _file.Write(_record, true);
                                }
                            }

                            _file.WriteHeader();
                            _file.Close();

                            var fbuff = Utils.Compress(m.ToArray(), "khachhang.dbf");

                            if (fbuff != null)
                            {
                                Response.ContentType = "text/plain";
                                Response.OutputStream.Write(fbuff, 0, fbuff.Length);
                                Response.AddHeader("Content-Disposition", "attachment;filename=khachhangdbf.zip");
                            }
                            else
                            {
                                Response.Write(String.Format("<script type='text/javascript'>alert('Có lỗi trong quá trình tải dữ liệu!'); document.location = '/Transaction/Index?TypeTran={0}';</script>", model.TypeTrans));
                            }
                        }
                        // Hoa don phat hanh moi
                        else if (model.TypeTrans == 0 || model.TypeTrans == 3)
                        {
                            var      bytestring = Utils.Decompress(buffer);
                            string   _b2str     = Encoding.UTF8.GetString(bytestring);
                            string[] strarr     = _b2str.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);

                            var          xxx   = strarr[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            DbfFile      _file = new DbfFile(Encoding.GetEncoding(1252));
                            MemoryStream m     = new MemoryStream();

                            _file.Open(m);

                            _file.Header.AddColumn(new DbfColumn("FKey", DbfColumn.DbfColumnType.Character, 20, 0));
                            _file.Header.AddColumn(new DbfColumn("No", DbfColumn.DbfColumnType.Character, 20, 0));
                            _file.Header.AddColumn(new DbfColumn("Pattern", DbfColumn.DbfColumnType.Character, 20, 0));
                            _file.Header.AddColumn(new DbfColumn("Serial", DbfColumn.DbfColumnType.Character, 20, 0));
                            _file.Header.AddColumn(new DbfColumn("PublishDate", DbfColumn.DbfColumnType.Character, 20, 0));

                            DbfRecord _record = new DbfRecord(_file.Header);

                            foreach (string item in xxx)
                            {
                                if (item.Contains("_"))
                                {
                                    var ix = item.Split('_');
                                    _record[0] = ix[0];
                                    _record[1] = ix[1];
                                    //_record[2] = strarr[0];
                                    //_record[3] = ix.Length == 4 ? ix[2] : model.InvSerial;
                                    //_record[4] = ix.Length == 4 ? ix[3] : "";
                                    _record[2] = model.InvPattern;
                                    _record[3] = model.InvSerial;
                                    _record[4] = ix[3];
                                    _file.Write(_record, true);
                                }
                            }

                            _file.WriteHeader();
                            _file.Close();

                            string strName = "";
                            if (model.TypeTrans == 0)
                            {
                                strName = "hoadon";
                            }
                            else
                            {
                                strName = "hoadonlai";
                            }
                            var fbuff = Utils.Compress(m.ToArray(), strName + ".dbf");

                            if (fbuff != null)
                            {
                                Response.ContentType = "text/plain";
                                Response.OutputStream.Write(fbuff, 0, fbuff.Length);
                                Response.AddHeader("Content-Disposition", "attachment;filename=" + strName + "dbf.zip");
                            }
                            else
                            {
                                Response.Write(String.Format("<script type='text/javascript'>alert('Có lỗi trong quá trình tải dữ liệu!'); document.location = '/Transaction/Index?TypeTran={0}';</script>", model.TypeTrans));
                            }
                        }
                        // Hoa don huy
                        else if (model.TypeTrans == 2)
                        {
                            var          bytestring = Utils.Decompress(buffer);
                            string       _b2str     = Encoding.UTF8.GetString(bytestring);
                            string[]     strarr     = _b2str.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                            var          xxx        = strarr[1].Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            DbfFile      _file      = new DbfFile(Encoding.GetEncoding(1252));
                            MemoryStream m          = new MemoryStream();

                            _file.Open(m);

                            _file.Header.AddColumn(new DbfColumn("FKey", DbfColumn.DbfColumnType.Character, 20, 0));

                            DbfRecord _record = new DbfRecord(_file.Header);

                            foreach (string item in xxx)
                            {
                                _record[0] = item;
                                _file.Write(_record, true);
                            }

                            _file.WriteHeader();
                            _file.Close();

                            var fbuff = Utils.Compress(m.ToArray(), "hoadonhuy.dbf");

                            if (fbuff != null)
                            {
                                Response.ContentType = "text/plain";
                                Response.OutputStream.Write(fbuff, 0, fbuff.Length);
                                Response.AddHeader("Content-Disposition", "attachment;filename=hoadonhuydbf.zip");
                            }
                            else
                            {
                                Response.Write(String.Format("<script type='text/javascript'>alert('Có lỗi trong quá trình tải dữ liệu!'); document.location = '/Transaction/Index?TypeTran={0}';</script>", model.TypeTrans));
                            }
                        }
                    }
                    // downloadtype == "xml"
                    if (downloadtype == "xml")
                    {
                        // Khach hang
                        if (model.TypeTrans == 1)
                        {
                            var fff   = Utils.Decompress(buffer);
                            var fbuff = Utils.Compress(fff, "khachhang.xml");
                            Response.ContentType = "text/plain";
                            Response.OutputStream.Write(fbuff, 0, fbuff.Length);
                            Response.AddHeader("Content-Disposition", "attachment;filename=khachhang.zip");
                        }
                        // Hoa don moi
                        else if (model.TypeTrans == 0)
                        {
                            Response.ContentType = "text/plain";
                            Response.OutputStream.Write(buffer, 0, buffer.Length);
                            Response.AddHeader("Content-Disposition", "attachment;filename=hoadon.zip");
                        }
                        // Hoa don huy
                        else if (model.TypeTrans == 2)
                        {
                            Response.ContentType = "text/plain";
                            Response.OutputStream.Write(buffer, 0, buffer.Length);
                            Response.AddHeader("Content-Disposition", "attachment;filename=hoadonhuy.zip");
                        }
                        // Hoa don lai
                        else if (model.TypeTrans == 3)
                        {
                            Response.ContentType = "text/plain";
                            Response.OutputStream.Write(buffer, 0, buffer.Length);
                            Response.AddHeader("Content-Disposition", "attachment;filename=hoadonlai.zip");
                        }
                    }
                }
                catch (Exception ex)
                {
                    Response.Write(String.Format("<script type='text/javascript'>alert('Có lỗi trong quá trình tải dữ liệu!'); document.location = '/Transaction/Index?TypeTran={0}';</script>", model.TypeTrans));
                }
            }
            else
            {
                Response.Write(String.Format("<script type='text/javascript'>alert('Có lỗi trong quá trình tải dữ liệu!'); document.location = '/Transaction/Index?TypeTran={0}';</script>", model.TypeTrans));
            }
        }