Exemple #1
0
 public DbfColumn(string sName, DbfColumnType type) : this(sName, type, 0, 0)
 {
     if (type == DbfColumnType.Number || type == DbfColumnType.Character)
     {
         throw new Exception("For number and character field types you must specify Length and Decimal Precision.");
     }
 }
Exemple #2
0
        /// <summary>
        /// Creates a COLUMN definition for the given column that can be used in a CREATE TABLE script
        /// </summary>
        /// <param name="colType">The DBF Column Type to be mapped</param>
        /// <param name="typeLength">The defined Length of the Column</param>
        /// <param name="colName">The Name of the Column</param>
        /// <returns></returns>
        public string GetColumnDefinition(DbfColumnType colType, int typeLength, string colName)
        {
            string dt = "";

            switch (colType)
            {
            case DbfColumnType.Boolean:
                dt = "BIT";
                break;

            case DbfColumnType.Date:
                dt = "DATE";
                break;

            case DbfColumnType.DateTime:
                dt = "DATETIME";
                break;

            case DbfColumnType.Currency:
            case DbfColumnType.Double:
            case DbfColumnType.Float:
            case DbfColumnType.Number:
            case DbfColumnType.Signedlong:
                dt = "DECIMAL";
                break;

            default:
                dt = "VARCHAR";
                break;
            }

            return("`" + colName + "` " + dt + (typeLength > 0 ? "(" + typeLength + ")" : ""));
        }
Exemple #3
0
        private static Type GetTypeOfColumn(DbfColumnType type, out string text)
        {
            Type   columntype;
            string stringtype;

            switch (type)
            {
            case DbfColumnType.Date:
                columntype = typeof(DateTime?);
                stringtype = "DateTime?";
                break;

            case DbfColumnType.Number:
                columntype = typeof(decimal?);
                stringtype = "decimal?";
                break;

            case DbfColumnType.Character:
                columntype = typeof(string);
                stringtype = columntype.ToString();
                break;

            case DbfColumnType.DateTime:
                stringtype = "DateTime?";
                columntype = typeof(DateTime?);
                break;

            default:
                throw new DbfMappingException("Нет сопоставлеия для типа " + type);
            }
            text = stringtype;
            return(columntype);
        }
Exemple #4
0
        /// <summary>
        /// Formats a value for inclusion in an INSERT statement
        /// </summary>
        /// <param name="colType"></param>
        /// <param name="value"></param>
        /// <returns></returns>
        public string FormatValueForInsert(DbfColumnType colType, string value)
        {
            string ret = "";

            switch (colType)
            {
            case DbfColumnType.Boolean:
                ret = (Convert.ToBoolean(value) == true ? "1" : "0");
                break;

            case DbfColumnType.Date:
            case DbfColumnType.DateTime:
                ret = "'" + Convert.ToDateTime(value).ToString("yyyy-MM-dd HH:mm:ss") + "'";
                break;

            case DbfColumnType.Currency:
            case DbfColumnType.Double:
            case DbfColumnType.Float:
            case DbfColumnType.Number:
            case DbfColumnType.Signedlong:
                if (value == "")
                {
                    value = "NULL";
                }
                ret = value.Replace("$", "");
                break;

            default:
                ret = "'" + value.Replace("'", "''") + "'";
                break;
            }

            return(ret);
        }
        private void AddColumn(string name, DbfColumnType type, byte length, byte decimalCount)
        {
            if (name.Length > 10)
            {
                name = name.Substring(0, 10);
            }

            if (length == 0)
            {
                throw new Exception("Length cannot be zero");
            }

            _map.Add(name, _columns.Count);

            _columns.Add(new DbfColumn
            {
                DataAddress  = _recordLength,
                Name         = name,
                Type         = type,
                Length       = length,
                DecimalCount = decimalCount
            });

            _recordLength += length;
            _headerLength += RECORD_LENGTH;

            _emptyRecord = null;
        }
Exemple #6
0
        /// <summary>
        /// Получить строкое представление типа подходящего для колонки таблицы
        /// </summary>
        /// <param name="type">тип данных колонки таблицы</param>
        /// <returns>строкое представление</returns>
        public static string GetTypeOfColumnS(DbfColumnType type)
        {
            string s;

            GetTypeOfColumn(type, out s);
            return(s);
        }
        public static DbfColumnType ConvertBack(string columnTypeString)
        {
            DbfColumnType columnType = DbfColumnType.Character;

            Enum.TryParse <DbfColumnType>(columnTypeString, out columnType);
            return(columnType);
        }
 public CalculatedDbfColumn(string columnName,
                            DbfColumnType columnType,
                            int length,
                            int decimalLength,
                            CalculatedDbfColumnType calculationType,
                            AreaUnit measurementUnit)
     : base(columnName, columnType, length, decimalLength)
 {
     this.calculationType = calculationType;
     this.areaUnit        = measurementUnit;
 }
 public CalculatedDbfColumn(string columnName,
                            DbfColumnType columnType,
                            int length,
                            int decimalLength,
                            CalculatedDbfColumnType calculationType,
                            DistanceUnit lengthUnit)
     : base(columnName, columnType, length, decimalLength)
 {
     this.calculationType = calculationType;
     this.lengthUnit      = lengthUnit;
 }
        private static Type GetColumnTypeFromDbfColumn(string columnType)
        {
            DbfColumnType dbfColumnType  = DbfColumnType.Character;
            DbfColumnType tempColumnType = DbfColumnType.Character;

            if (Enum.TryParse <DbfColumnType>(columnType, out tempColumnType))
            {
                dbfColumnType = tempColumnType;
            }
            return(GetColumnTypeFromDbfColumn(dbfColumnType));
        }
Exemple #11
0
 private int GetDecimalLength(DbfColumnType dbfColumnType, int maxLength)
 {
     if (dbfColumnType == DbfColumnType.Float)
     {
         return(maxLength < 4 ? maxLength : 4);
     }
     else
     {
         return(0);
     }
 }
        private static Collection <DbfColumn> ConvertToDbfColumns(IEnumerable <FeatureSourceColumn> featureSourceColumns)
        {
            Collection <DbfColumn> dbfColumns = new Collection <DbfColumn>();

            foreach (var column in featureSourceColumns)
            {
                DbfColumnType columnType = (DbfColumnType)Enum.Parse(typeof(DbfColumnType), column.TypeName);
                DbfColumn     dbfColumn  = new DbfColumn(column.ColumnName, columnType, column.MaxLength, GetDecimalLength(columnType, column.MaxLength));
                dbfColumns.Add(dbfColumn);
            }
            return(dbfColumns);
        }
        public AddFeatureSourceColumnViewModel()
        {
            columnTypes = new List <DbfColumnType>();
            var result = Enum.GetValues(typeof(DbfColumnType)).Cast <DbfColumnType>().Where(c => c != DbfColumnType.Null && c != DbfColumnType.Memo);

            foreach (var item in result)
            {
                columnTypes.Add(item);
            }

            columnType   = DbfColumnType.Character;
            columnName   = string.Empty;
            columnLength = "10";
        }
Exemple #14
0
        public AddNewColumnViewModel()
        {
            columnType            = DbfColumnType.Character;
            columnName            = string.Empty;
            length                = 20;
            decimalLength         = 0;
            decimalLengthIsEnable = false;
            lengthIsEnable        = true;
            columnTypeEnable      = true;

            isCalculatedVisbility = Visibility.Collapsed;
            calculationType       = CalculatedDbfColumnType.Area;
            measurementUnit       = AreaUnit.SquareMeters;
            isLengthUnitVisbility = Visibility.Hidden;
            IsEdited       = false;
            isEmptyChecked = true;
        }
Exemple #15
0
        /// <summary>
        /// Full spec constructor sets all relevant fields.
        /// </summary>
        /// <param name="sName"></param>
        /// <param name="type"></param>
        /// <param name="nLength"></param>
        /// <param name="nDecimals"></param>
        public DbfColumn(string sName, DbfColumnType type, int nLength, int nDecimals)
        {
            Name = sName;
            mType = type;
            mLength = nLength;

            if (type == DbfColumnType.Number)
                mDecimalCount = nDecimals;
            else
                mDecimalCount = 0;

            //perform some simple integrity checks...
            //-------------------------------------------

            //decimal precision:
            //we could also fix the length property with a statement like this: mLength = mDecimalCount + 2;
            if (mDecimalCount > 0 && mLength - mDecimalCount <= 1)
                throw new Exception("Decimal precision can not be larger than the length of the field.");

            if (mType == DbfColumnType.Integer)
                mLength = 4;

            if (mType == DbfColumnType.Binary)
                mLength = 1;

            if (mType == DbfColumnType.Date)
                mLength = 8; //Dates are exactly yyyyMMdd

            if (mType == DbfColumnType.Memo)
                mLength = 10; //Length: 10 Pointer to ASCII text field in memo file. pointer to a DBT block.

            if (mType == DbfColumnType.Boolean)
                mLength = 1;

            //field length:
            if (mLength <= 0)
                throw new Exception("Invalid field length specified. Field length can not be zero or less than zero.");
            else if (type != DbfColumnType.Character && type != DbfColumnType.Binary && mLength > 255)
            {
                throw new Exception(
                    "Invalid field length specified. For numbers it should be within 20 digits, but we allow up to 255. For Char and binary types, length up to 65,535 is allowed. For maximum compatibility use up to 255.");
            }
            else if ((type == DbfColumnType.Character || type == DbfColumnType.Binary) && mLength > 65535)
                throw new Exception("Invalid field length specified. For Char and binary types, length up to 65535 is supported. For maximum compatibility use up to 255.");
        }
        public void Read(BinaryReader reader)
        {
            // Read version
            if (reader.ReadByte() != 3)
            {
                throw new Exception("Only dbase version 3 is supported");
            }

            // Last update
            int year = (int)reader.ReadByte(), month = (int)reader.ReadByte(), day = (int)reader.ReadByte();

            LastUpdate = new DateTime(year + 1900, month, day);

            RecordCount = reader.ReadUInt32();

            // Ignore the header length and record length since they will be calced.
            reader.ReadUInt16();
            reader.ReadUInt16();

            // skip the header reserved bytes
            reader.ReadBytes(20);

            while (reader.PeekChar() != FIELD_DESCRIPTOR_TERMINATOR)
            {
                string        name = new String(reader.ReadChars(11)).TrimEnd((char)0);
                DbfColumnType type = (DbfColumnType)reader.ReadByte();

                // Ignore data address
                reader.ReadBytes(4);

                byte length       = reader.ReadByte();
                byte decimalCount = reader.ReadByte();

                // Skip the reserved bytes
                reader.ReadBytes(14);

                AddColumn(name, type, length, decimalCount);
            }

            reader.ReadByte();
        }
        private static Type GetColumnTypeFromDbfColumn(DbfColumnType columnType)
        {
            switch (columnType)
            {
            case DbfColumnType.Float:
            case DbfColumnType.Numeric:
                return(typeof(double));

            case DbfColumnType.Null:
                return(typeof(Nullable));

            case DbfColumnType.Date:

            //return typeof(DateTime);
            case DbfColumnType.Logical:
            case DbfColumnType.Character:
            case DbfColumnType.Memo:
            default:
                return(typeof(string));
            }
        }
        private static Type GetDataType(DbfColumnType dbfColumnType, int decimalLength)
        {
            switch (dbfColumnType)
            {
            case DbfColumnType.Number:
                return(decimalLength == 0 ? typeof(int) : typeof(decimal));

            case DbfColumnType.SignedLong:
                return(typeof(long));

            case DbfColumnType.Float:
                return(typeof(float));

            case DbfColumnType.Currency:
                return(typeof(decimal));

            case DbfColumnType.Date:
                return(typeof(DateTime));

            case DbfColumnType.DateTime:
                return(typeof(DateTime));

            case DbfColumnType.Boolean:
                return(typeof(bool));

            case DbfColumnType.Memo:
                return(typeof(string));

            case DbfColumnType.Double:
                return(typeof(double));

            case DbfColumnType.General:
            case DbfColumnType.Character:
                return(typeof(string));

            default:
                throw new ArgumentOutOfRangeException(nameof(dbfColumnType), dbfColumnType, null);
            }
        }
Exemple #19
0
        private Type GetDataType(DbfColumnType columnType)
        {
            switch (columnType)
            {
            case DbfColumnType.Number:
                return(DecimalCount == 0 ? typeof(int) : typeof(decimal));

            case DbfColumnType.SignedLong:
                return(typeof(long));

            case DbfColumnType.Float:
                return(typeof(float));

            case DbfColumnType.Currency:
                return(typeof(decimal));

            case DbfColumnType.Date:
                return(typeof(DateTime));

            case DbfColumnType.DateTime:
                return(typeof(DateTime));

            case DbfColumnType.Boolean:
                return(typeof(bool));

            case DbfColumnType.Memo:
                return(typeof(string));

            case DbfColumnType.Double:
                return(typeof(double));

            case DbfColumnType.General:
            case DbfColumnType.Character:
                return(typeof(string));

            default:
                return(typeof(object));
            }
        }
        protected override FeatureLayer CreateFeatureLayerCore(ConfigureFeatureLayerParameters featureLayerStructureParameters)
        {
            string layerPath = LayerPluginHelper.GetLayerUriToSave(featureLayerStructureParameters.LayerUri, ExtensionFilter);

            if (string.IsNullOrEmpty(layerPath))
            {
                return(null);
            }
            featureLayerStructureParameters.LayerUri = new Uri(layerPath);

            Collection <TabDbfColumn> tabDbfColumns = new Collection <TabDbfColumn>();

            foreach (var column in featureLayerStructureParameters.AddedColumns)
            {
                var           columnLenght  = column.MaxLength;
                var           decimalLength = 0;
                DbfColumnType columnType    = DbfColumnType.Character;

                switch (column.TypeName.ToUpperInvariant())
                {
                case "DOUBLE":
                    columnLenght  = columnLenght == 0 ? 10 : columnLenght;
                    decimalLength = 4;
                    columnType    = DbfColumnType.Float;
                    break;

                case "DATE":
                case "DATETIME":
                    columnLenght  = columnLenght == 0 ? 10 : columnLenght;
                    decimalLength = 0;
                    columnType    = DbfColumnType.Date;
                    break;

                case "INTEGER":
                case "INT":
                    columnLenght  = columnLenght == 0 ? 10 : columnLenght;
                    decimalLength = 0;
                    columnType    = DbfColumnType.Numeric;
                    break;

                case "STRING":
                case "CHARACTER":
                    columnLenght  = columnLenght == 0 ? 255 : columnLenght;
                    decimalLength = 0;
                    columnType    = DbfColumnType.Character;
                    break;

                default:
                    break;
                }

                tabDbfColumns.Add(new TabDbfColumn(column.ColumnName, columnType, columnLenght, decimalLength, false, false));
            }

            if (featureLayerStructureParameters.CustomData.ContainsKey("SourceLayer"))
            {
                FeatureLayer sourcefeatureLayer = featureLayerStructureParameters.CustomData["SourceLayer"] as FeatureLayer;
                double       precisionInMeter   = TinyGeoFeatureLayer.GetOptimalPrecision(sourcefeatureLayer, GisEditor.ActiveMap.MapUnit, DistanceUnit.Meter, TinyGeoPrecisionMode.PreventSplitting);

                TinyGeoFeatureLayer.CreateTinyGeoFile(featureLayerStructureParameters.LayerUri.OriginalString, sourcefeatureLayer, GisEditor.ActiveMap.MapUnit, featureLayerStructureParameters.AddedColumns.Select(f => f.ColumnName).ToList(), "", precisionInMeter, Encoding.Default, featureLayerStructureParameters.WellKnownType);

                string prjPath = Path.ChangeExtension(featureLayerStructureParameters.LayerUri.OriginalString, "prj");
                File.WriteAllText(prjPath, Proj4Projection.ConvertProj4ToPrj(featureLayerStructureParameters.Proj4ProjectionParametersString));
            }

            var resultLayer = new TinyGeoFeatureLayer(featureLayerStructureParameters.LayerUri.OriginalString);

            return(resultLayer);
        }
Exemple #21
0
        private void Export(IGrouping <ShapeFileType, Feature> group, FileExportInfo info)
        {
            string path = info.Path;

            if (File.Exists(path))
            {
                if (info.Overwrite)
                {
                    string[] suffixes = { ".shp", ".shx", ".ids", ".idx", ".dbf", ".prj" };
                    foreach (var suffix in suffixes)
                    {
                        string fileToRemove = Path.ChangeExtension(path, suffix);
                        if (File.Exists(fileToRemove))
                        {
                            File.Delete(fileToRemove);
                        }
                    }
                }
                else
                {
                    string dir       = Path.GetDirectoryName(path);
                    string fileName  = Path.GetFileNameWithoutExtension(path);
                    string extension = Path.GetExtension(path);

                    path = Path.Combine(dir, fileName + group.Key.ToString() + extension);
                }
            }

            var dbfColumns = info.Columns.Select(column =>
            {
                DbfColumnType columnType = (DbfColumnType)Enum.Parse(typeof(DbfColumnType), column.TypeName);
                DbfColumn dbfColumn      = new DbfColumn(column.ColumnName, columnType, column.MaxLength, GetDecimalLength(columnType, column.MaxLength));
                return(dbfColumn);
            });

            ShapeFileFeatureLayer.CreateShapeFile(group.Key, path, dbfColumns);
            ShapeFileFeatureLayer layer = new ShapeFileFeatureLayer(path, GeoFileReadWriteMode.ReadWrite);

            try
            {
                layer.Open();
                layer.EditTools.BeginTransaction();
                foreach (var feature in group)
                {
                    bool isValid    = true;
                    var  newFeature = feature;
                    if (!feature.IsValid())
                    {
                        if (feature.CanMakeValid)
                        {
                            newFeature = feature.MakeValid();
                        }
                        else
                        {
                            isValid = false;
                        }
                    }
                    if (isValid)
                    {
                        var featureSourceColumns = layer.FeatureSource.GetColumns();
                        var tempColumnNames      = featureSourceColumns.Select(column => column.ColumnName);

                        var validColumns = GeoDbf.GetValidColumnNames(tempColumnNames);
                        Dictionary <string, string> columnValues = new Dictionary <string, string>();
                        for (int i = 0; i < validColumns.Count(); i++)
                        {
                            var columnName = dbfColumns.ElementAt(i).ColumnName;
                            if (newFeature.ColumnValues.ContainsKey(columnName))
                            {
                                columnValues.Add(validColumns.ElementAt(i), newFeature.ColumnValues[columnName]);
                            }
                        }
                        Feature validFeature = new Feature(newFeature.GetWellKnownBinary(), newFeature.Id, columnValues);
                        layer.EditTools.Add(validFeature);
                    }
                }
                layer.EditTools.CommitTransaction();
                layer.Close();

                SavePrjFile(path, info.ProjectionWkt);
                RebuildDbf(path);
            }
            catch (Exception ex)
            {
                GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                if (layer.EditTools.IsInTransaction)
                {
                    layer.EditTools.CommitTransaction();
                }

                if (layer.IsOpen)
                {
                    layer.Close();
                }

                string[] suffixes = { ".shp", ".shx", ".ids", ".idx", ".dbf", ".prj" };
                foreach (var suffix in suffixes)
                {
                    string fileToRemove = Path.ChangeExtension(path, suffix);
                    if (File.Exists(fileToRemove))
                    {
                        File.Delete(fileToRemove);
                    }
                }
                throw new OperationCanceledException("Shapefile generates failed.", ex);
            }
        }
        private void CreateShapeFile(ObservableCollection <FeatureSourceColumn> includedColumnsList
                                     , string OutputPath, Encoding ShapeFileEncoding, string csvFilePath
                                     , List <Feature> features
                                     , bool isIncludeAllFeatures
                                     , IEnumerable <MatchCondition> matchConditions
                                     , Action <UpdatingTaskProgressEventArgs> updateAction
                                     , Dictionary <string, string> invalidColumns)
        {
            Collection <DbfColumn> includeColumns = new Collection <DbfColumn>();

            RemoveUnduplicateColumn(includedColumnsList);

            foreach (var column in includedColumnsList)
            {
                DbfColumnType tmpDbfColumnType = DbfColumnType.Character;
                if (Enum.TryParse(column.TypeName, out tmpDbfColumnType))
                {
                    DbfColumn dbfColumn = new DbfColumn(column.ColumnName, tmpDbfColumnType, column.MaxLength, 0);
                    includeColumns.Add(dbfColumn);
                }
            }

            ShapeFileType shapeFileType = GetShapeFileType(features.FirstOrDefault());

            if (shapeFileType != ShapeFileType.Null)
            {
                ShapeFileFeatureLayer.CreateShapeFile(shapeFileType,
                                                      OutputPath, includeColumns, ShapeFileEncoding, OverwriteMode.Overwrite);

                var dataTable   = DataJoinAdapter.ReadDataToDataGrid(csvFilePath, Delimiter);
                var featureRows = dataTable.Rows;
                var index       = 0;
                var count       = features.Count;

                ShapeFileFeatureLayer newShapeFileFeatureLayer = new ShapeFileFeatureLayer(OutputPath, GeoFileReadWriteMode.ReadWrite);
                newShapeFileFeatureLayer.SafeProcess(() =>
                {
                    newShapeFileFeatureLayer.EditTools.BeginTransaction();

                    foreach (var feature in features)
                    {
                        index++;
                        try
                        {
                            var matchedDataRow = featureRows.Cast <DataRow>().FirstOrDefault(r => matchConditions.All(tmpCondition => feature.ColumnValues[tmpCondition.SelectedLayerColumn.ColumnName]
                                                                                                                      == r[tmpCondition.SelectedDelimitedColumn.ColumnName].ToString()));

                            if (matchedDataRow != null)
                            {
                                SetFeatureColumnValues(feature, matchedDataRow, includedColumnsList, invalidColumns);
                                newShapeFileFeatureLayer.EditTools.Add(feature);
                            }
                            else if (isIncludeAllFeatures)
                            {
                                newShapeFileFeatureLayer.EditTools.Add(feature);
                            }

                            if (UpdateProgress(updateAction, index, count))
                            {
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            var errorEventArgs   = new UpdatingTaskProgressEventArgs(TaskState.Error);
                            errorEventArgs.Error = new ExceptionInfo(string.Format(CultureInfo.InvariantCulture, "Feature id: {0}, {1}"
                                                                                   , feature.Id, ex.Message)
                                                                     , ex.StackTrace
                                                                     , ex.Source);
                            GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                            errorEventArgs.Message = feature.Id;
                            updateAction(errorEventArgs);
                        }
                    }
                    newShapeFileFeatureLayer.EditTools.CommitTransaction();
                });

                SavePrjFile(OutputPath, DisplayProjectionParameters);
            }
        }
        protected override FeatureLayer CreateFeatureLayerCore(ConfigureFeatureLayerParameters featureLayerStructureParameters)
        {
            string layerPath = LayerPluginHelper.GetLayerUriToSave(featureLayerStructureParameters.LayerUri, ExtensionFilterCore);

            if (string.IsNullOrEmpty(layerPath))
            {
                return(null);
            }
            featureLayerStructureParameters.LayerUri = new Uri(layerPath);

            ShapeFileType shapeFileType = ShapeFileType.Null;

            switch (featureLayerStructureParameters.WellKnownType)
            {
            case WellKnownType.Multipoint:
                shapeFileType = ShapeFileType.Multipoint;
                break;

            case WellKnownType.Point:
                shapeFileType = ShapeFileType.Point;
                break;

            case WellKnownType.Line:
            case WellKnownType.Multiline:
                shapeFileType = ShapeFileType.Polyline;
                break;

            case WellKnownType.Polygon:
            case WellKnownType.Multipolygon:
                shapeFileType = ShapeFileType.Polygon;
                break;
            }

            Dictionary <string, DbfColumn>   dbfColumns    = new Dictionary <string, DbfColumn>();
            Collection <FeatureSourceColumn> addedColumns  = featureLayerStructureParameters.AddedColumns;
            Dictionary <string, string>      oldNewNames   = new Dictionary <string, string>();
            Collection <Feature>             addedFeatures = featureLayerStructureParameters.AddedFeatures;

            bool truncateLongColumn = featureLayerStructureParameters.LongColumnTruncateMode == LongColumnTruncateMode.Truncate;

            if (truncateLongColumn)
            {
                Dictionary <string, string> editColumns = new Dictionary <string, string>();
                if (featureLayerStructureParameters.CustomData.ContainsKey("EditedColumns"))
                {
                    editColumns = featureLayerStructureParameters.CustomData["EditedColumns"] as Dictionary <string, string>;
                }
                addedColumns = TruncateLongColumnNames(featureLayerStructureParameters.AddedColumns, oldNewNames, editColumns);
            }

            foreach (var column in addedColumns)
            {
                if (!string.IsNullOrEmpty(column.ColumnName))
                {
                    DbfColumn dbfColumn = column as DbfColumn;
                    if (dbfColumn != null)
                    {
                        if (dbfColumn.ColumnType == DbfColumnType.DoubleInBinary || dbfColumn.ColumnType == DbfColumnType.DateTime)
                        {
                            dbfColumn.Length        = 8;
                            dbfColumn.DecimalLength = 0;
                        }
                        else if (dbfColumn.ColumnType == DbfColumnType.IntegerInBinary)
                        {
                            dbfColumn.Length        = 4;
                            dbfColumn.DecimalLength = 0;
                        }
                    }
                    else
                    {
                        int columnLenght  = column.MaxLength;
                        int decimalLength = 0;

                        switch (column.TypeName.ToUpperInvariant())
                        {
                        case "DOUBLE":
                        case "NUMERIC":
                            columnLenght = columnLenght == 0 ? 10 : columnLenght;
                            if (columnLenght < 4)
                            {
                                columnLenght = 10;
                            }
                            decimalLength = 4;
                            break;

                        case "DATE":
                        case "DATETIME":
                            columnLenght  = columnLenght == 0 ? 10 : columnLenght;
                            decimalLength = 0;
                            break;

                        case "INTEGER":
                        case "INT":
                            columnLenght  = columnLenght == 0 ? 10 : columnLenght;
                            decimalLength = 0;
                            break;

                        case "STRING":
                        case "CHARACTER":
                            columnLenght  = columnLenght == 0 ? characterTypeLength : columnLenght;
                            decimalLength = 0;
                            break;

                        case "LOGICAL":
                            columnLenght  = 5;
                            decimalLength = 0;
                            break;
                        }

                        DbfColumnType type = DbfColumnType.Character;
                        if (column.TypeName.Equals("DOUBLE", StringComparison.InvariantCultureIgnoreCase))
                        {
                            column.TypeName = DbfColumnType.Float.ToString();
                        }
                        if (column.TypeName.Equals("INT", StringComparison.InvariantCultureIgnoreCase))
                        {
                            column.TypeName = DbfColumnType.Numeric.ToString();
                        }
                        bool isSuccess = Enum.TryParse <DbfColumnType>(column.TypeName, true, out type);
                        if (!isSuccess)
                        {
                            type = DbfColumnType.Character;
                        }

                        dbfColumn           = new DbfColumn(column.ColumnName, type, columnLenght, decimalLength);
                        dbfColumn.TypeName  = column.TypeName;
                        dbfColumn.MaxLength = column.MaxLength;
                    }
                    //Feature firstFeature = featureLayerStructureParameters.AddedFeatures.FirstOrDefault();

                    ////This is to fix that fox pro columns cannot write to dbf, convert all linked columns to character column type.
                    //string tempColumnName = column.ColumnName;
                    //if (oldNewNames.ContainsValue(column.ColumnName))
                    //{
                    //    tempColumnName = oldNewNames.FirstOrDefault(f => f.Value == column.ColumnName).Key;
                    //}
                    //if (tempColumnName.Contains(".") && firstFeature != null && firstFeature.LinkColumnValues.ContainsKey(tempColumnName))
                    //{
                    //    if (dbfColumn.ColumnType != DbfColumnType.Memo)
                    //    {
                    //        dbfColumn.ColumnType = DbfColumnType.Character;
                    //        dbfColumn.Length = characterTypeLength;
                    //        dbfColumn.DecimalLength = 0;
                    //    }
                    //}

                    dbfColumns[dbfColumn.ColumnName] = dbfColumn;
                }
            }

            bool convertMemoToCharacter = featureLayerStructureParameters.MemoColumnConvertMode == MemoColumnConvertMode.ToCharacter;

            Dictionary <string, int> columnLength = new Dictionary <string, int>();

            foreach (var feature in addedFeatures)
            {
                //foreach (var linkColumnValue in feature.LinkColumnValues)
                //{
                //    if (!feature.ColumnValues.ContainsKey(linkColumnValue.Key))
                //    {
                //        string[] values = linkColumnValue.Value.Select(v =>
                //        {
                //            if (v.Value == null)
                //            {
                //                return string.Empty;
                //            }
                //            if (v.Value is DateTime)
                //            {
                //                return ((DateTime)v.Value).ToShortDateString();
                //            }
                //            return v.Value.ToString();
                //        }).ToArray();
                //        if (values.All(v => string.IsNullOrEmpty(v) || string.IsNullOrWhiteSpace(v)))
                //        {
                //            if (oldNewNames.ContainsKey(linkColumnValue.Key))
                //                feature.ColumnValues[oldNewNames[linkColumnValue.Key]] = string.Empty;
                //            else
                //                feature.ColumnValues[linkColumnValue.Key] = string.Empty;
                //        }
                //        else
                //        {
                //            string tempColumName = linkColumnValue.Key;
                //            if (oldNewNames.ContainsKey(linkColumnValue.Key))
                //            {
                //                tempColumName = oldNewNames[linkColumnValue.Key];
                //            }
                //            string linkValue = string.Join(",", values);
                //            feature.ColumnValues[tempColumName] = linkValue;

                //            //Choose the max length
                //            if (columnLength.ContainsKey(tempColumName))
                //            {
                //                if (columnLength[tempColumName] < linkValue.Length)
                //                {
                //                    columnLength[tempColumName] = linkValue.Length;
                //                }
                //            }
                //            else
                //            {
                //                columnLength[tempColumName] = linkValue.Length > 254 ? 254 : linkValue.Length;
                //            }
                //        }
                //    }
                //}
                foreach (var item in oldNewNames)
                {
                    if (feature.ColumnValues.ContainsKey(item.Key))
                    {
                        feature.ColumnValues[oldNewNames[item.Key]] = feature.ColumnValues[item.Key];
                        feature.ColumnValues.Remove(item.Key);
                    }
                }
                if (!convertMemoToCharacter)
                {
                    foreach (var item in feature.ColumnValues)
                    {
                        if (item.Value.Length > characterTypeLength && dbfColumns[item.Key].ColumnType != DbfColumnType.Memo)
                        {
                            dbfColumns[item.Key].ColumnType    = DbfColumnType.Memo;
                            dbfColumns[item.Key].Length        = 4;
                            dbfColumns[item.Key].DecimalLength = 0;
                        }
                    }
                }
            }

            foreach (var column in dbfColumns)
            {
                Feature firstFeature = featureLayerStructureParameters.AddedFeatures.FirstOrDefault();
                //This is to fix that fox pro columns cannot write to dbf, convert all linked columns to character column type.
                string tempColumnName = column.Key;
                if (oldNewNames.ContainsValue(column.Key))
                {
                    tempColumnName = oldNewNames.FirstOrDefault(f => f.Value == column.Key).Key;
                }
                //if (tempColumnName.Contains(".") && firstFeature != null && firstFeature.LinkColumnValues.ContainsKey(tempColumnName))
                //{
                //    if (column.Value.ColumnType != DbfColumnType.Memo)
                //    {
                //        column.Value.ColumnType = DbfColumnType.Character;
                //        //column.Value.Length = characterTypeLength;
                //        column.Value.DecimalLength = 0;

                //        if (columnLength.ContainsKey(tempColumnName) && column.Value.Length < columnLength[tempColumnName])
                //        {
                //            column.Value.Length = columnLength[tempColumnName];
                //        }
                //    }
                //}
            }

            ShapeFileFeatureLayer.CreateShapeFile(shapeFileType,
                                                  featureLayerStructureParameters.LayerUri.OriginalString,
                                                  dbfColumns.Values,
                                                  DefaultEncoding,
                                                  OverwriteMode.Overwrite);

            string encodingPathFileName = Path.ChangeExtension(featureLayerStructureParameters.LayerUri.OriginalString, ".cpg");

            if (File.Exists(encodingPathFileName))
            {
                File.Delete(encodingPathFileName);
            }
            File.WriteAllText(encodingPathFileName, DefaultEncoding.CodePage.ToString(CultureInfo.InvariantCulture));

            string prjPath = Path.ChangeExtension(featureLayerStructureParameters.LayerUri.OriginalString, "prj");

            File.WriteAllText(prjPath, Proj4Projection.ConvertProj4ToPrj(featureLayerStructureParameters.Proj4ProjectionParametersString));

            ShapeFileFeatureLayer resultLayer = new ShapeFileFeatureLayer(featureLayerStructureParameters.LayerUri.LocalPath, GeoFileReadWriteMode.ReadWrite);

            if (addedFeatures.Count > 0)
            {
                resultLayer.Open();
                resultLayer.EditTools.BeginTransaction();
                foreach (var feature in addedFeatures)
                {
                    if (convertMemoToCharacter)
                    {
                        foreach (var item in dbfColumns)
                        {
                            if (feature.ColumnValues.ContainsKey(item.Key) && feature.ColumnValues[item.Key].Length > 254)
                            {
                                feature.ColumnValues[item.Key] = feature.ColumnValues[item.Key].Substring(0, 254);
                            }
                            if (feature.ColumnValues.ContainsKey(item.Key) && feature.ColumnValues[item.Key].Length > item.Value.MaxLength)
                            {
                                feature.ColumnValues[item.Key] = feature.ColumnValues[item.Key].Substring(0, item.Value.MaxLength);
                            }
                        }
                    }

                    resultLayer.EditTools.Add(feature);
                }
                resultLayer.EditTools.CommitTransaction();
                resultLayer.Close();
            }

            return(resultLayer);
        }
Exemple #24
0
 /// <summary>
 /// Create a new column fully specifying all properties.
 /// </summary>
 /// <param name="sName">column name</param>
 /// <param name="type">type of field</param>
 /// <param name="nLength">field length including decimal places and decimal point if any</param>
 /// <param name="nDecimals">decimal places</param>
 /// <param name="nDataAddress">offset from start of record</param>
 internal DbfColumn(string sName, DbfColumnType type, int nLength, int nDecimals, int nDataAddress)
     : this(sName, type, nLength, nDecimals)
 {
     _dataAddress = nDataAddress;
 }
Exemple #25
0
        /// <summary>
        /// Full spec constructor sets all relevant fields.
        /// </summary>
        /// <param name="sName"></param>
        /// <param name="type"></param>
        /// <param name="nLength"></param>
        /// <param name="nDecimals"></param>
        public DbfColumn(string sName, DbfColumnType type, int nLength, int nDecimals)
        {
            Name    = sName;
            _type   = type;
            _length = nLength;

            if (type == DbfColumnType.Number || type == DbfColumnType.Float)
            {
                _decimalCount = nDecimals;
            }
            else
            {
                _decimalCount = 0;
            }



            //perform some simple integrity checks...
            //-------------------------------------------

            //decimal precision:
            //we could also fix the length property with a statement like this: mLength = mDecimalCount + 2;
            if (_decimalCount > 0 && _length - _decimalCount <= 1)
            {
                throw new Exception("Decimal precision can not be larger than the length of the field.");
            }

            if (_type == DbfColumnType.Integer)
            {
                _length = 4;
            }

            if (_type == DbfColumnType.Binary)
            {
                _length = 1;
            }

            if (_type == DbfColumnType.Date)
            {
                _length = 8;  //Dates are exactly yyyyMMdd
            }
            if (_type == DbfColumnType.Memo)
            {
                _length = 10;  //Length: 10 Pointer to ASCII text field in memo file. pointer to a DBT block.
            }
            if (_type == DbfColumnType.Boolean)
            {
                _length = 1;
            }

            //field length:
            if (_length <= 0)
            {
                throw new Exception("Invalid field length specified. Field length can not be zero or less than zero.");
            }
            else if (type != DbfColumnType.Character && type != DbfColumnType.Binary && _length > 255)
            {
                throw new Exception("Invalid field length specified. For numbers it should be within 20 digits, but we allow up to 255. For Char and binary types, length up to 65,535 is allowed. For maximum compatibility use up to 255.");
            }
            else if ((type == DbfColumnType.Character || type == DbfColumnType.Binary) && _length > 65535)
            {
                throw new Exception("Invalid field length specified. For Char and binary types, length up to 65535 is supported. For maximum compatibility use up to 255.");
            }
        }
Exemple #26
0
        private void AddColumn(string name, DbfColumnType type, byte length, byte decimalCount)
        {
            if (name.Length > 10)
                name = name.Substring(0, 10);

            if (length == 0)
                throw new Exception("Length cannot be zero");

            _map.Add(name, _columns.Count);

            _columns.Add(new DbfColumn
            {
                DataAddress = _recordLength,
                Name = name,
                Type = type,
                Length = length,
                DecimalCount = decimalCount
            });

            _recordLength += length;
            _headerLength += RECORD_LENGTH;

            _emptyRecord = null;
        }
Exemple #27
0
 /// <summary>
 /// Create a new column fully specifying all properties.
 /// </summary>
 /// <param name="sName">column name</param>
 /// <param name="type">type of field</param>
 /// <param name="nLength">field length including decimal places and decimal point if any</param>
 /// <param name="nDecimals">decimal places</param>
 /// <param name="nDataAddress">offset from start of record</param>
 internal DbfColumn(string sName, DbfColumnType type, int nLength, int nDecimals, int nDataAddress)
     : this(sName, type, nLength, nDecimals)
 {
     mDataAddress = nDataAddress;
 }
Exemple #28
0
 public DbfColumn(string sName, DbfColumnType type)
     : this(sName, type, 0, 0)
 {
     if (type == DbfColumnType.Number || type == DbfColumnType.Character)
         throw new Exception("For number and character field types you must specify Length and Decimal Precision.");
 }
Exemple #29
0
        /// <summary>
        /// Получить тип данных подходящий для колонки таблицы
        /// </summary>
        /// <param name="type">тип данных колонки таблицы</param>
        /// <returns>системный тип</returns>
        public static Type GetTypeOfColumnT(DbfColumnType type)
        {
            string s;

            return(GetTypeOfColumn(type, out s));
        }
        private void DataJoinShapeFile()
        {
            var args = new UpdatingTaskProgressEventArgs(TaskState.Updating);
            ShapeFileFeatureSource currentSource = ShapeFileFeatureSource;

            if (!currentSource.IsOpen)
            {
                currentSource.Open();
            }
            var index = 0;
            var count = currentSource.GetAllFeatures(ReturningColumnsType.AllColumns).Count;

            Collection <DbfColumn> includeColumns = new Collection <DbfColumn>();

            RemoveUnduplicateColumn(IncludedColumnsList);

            foreach (var column in IncludedColumnsList)
            {
                DbfColumnType tmpDbfColumnType = DbfColumnType.Character;
                if (Enum.TryParse(column.TypeName, out tmpDbfColumnType))
                {
                    DbfColumn dbfColumn = new DbfColumn(column.ColumnName, tmpDbfColumnType, column.MaxLength, 0);
                    includeColumns.Add(dbfColumn);
                }
            }

            ShapeFileType shapeFileType = GetShapeFileType(currentSource.GetAllFeatures(ReturningColumnsType.AllColumns).FirstOrDefault());
            var           projectionWkt = Proj4Projection.ConvertProj4ToPrj(DisplayProjectionParameters);
            var           dataTable     = DataJoinAdapter.ReadDataToDataGrid(CsvFilePath, Delimiter);
            var           featureRows   = dataTable.Rows;

            var helper = new ShapeFileHelper(shapeFileType, OutputPathFileName, includeColumns, projectionWkt);

            helper.ForEachFeatures(currentSource, (f, currentProgress, upperBound, percentage) =>
            {
                try
                {
                    bool canceled = false;
                    if (f.GetWellKnownBinary() != null)
                    {
                        index++;
                        try
                        {
                            var matchedDataRow = featureRows.Cast <DataRow>().FirstOrDefault(r => MatchConditions.All(tmpCondition => f.ColumnValues[tmpCondition.SelectedLayerColumn.ColumnName]
                                                                                                                      == r[tmpCondition.SelectedDelimitedColumn.ColumnName].ToString()));

                            if (matchedDataRow != null)
                            {
                                SetFeatureColumnValues(f, matchedDataRow, IncludedColumnsList, InvalidColumns);
                                helper.Add(f);
                            }
                            else if (IsIncludeAllFeatures)
                            {
                                helper.Add(f);
                            }

                            if (UpdateProgress(OnUpdatingProgress, index, count))
                            {
                                canceled = true;
                            }
                        }
                        catch (Exception ex)
                        {
                            var errorEventArgs   = new UpdatingTaskProgressEventArgs(TaskState.Error);
                            errorEventArgs.Error = new ExceptionInfo(string.Format(CultureInfo.InvariantCulture, "Feature id: {0}, {1}"
                                                                                   , f.Id, ex.Message)
                                                                     , ex.StackTrace
                                                                     , ex.Source);
                            GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                            errorEventArgs.Message = f.Id;
                            OnUpdatingProgress(errorEventArgs);
                        }
                    }

                    args            = new UpdatingTaskProgressEventArgs(TaskState.Updating, percentage);
                    args.Current    = currentProgress;
                    args.UpperBound = upperBound;
                    OnUpdatingProgress(args);

                    canceled = args.TaskState == TaskState.Canceled;
                    return(canceled);
                }
                catch
                {
                    return(false);
                }
            });

            helper.Commit();

            SavePrjFile(OutputPathFileName, DisplayProjectionParameters);
        }
Exemple #31
0
        private void Export(IGrouping <ShapeFileType, Feature> group, FileExportInfo info)
        {
            string path = info.Path;

            if (File.Exists(path))
            {
                if (info.Overwrite)
                {
                    string[] suffixes = { ".shp", ".shx", ".ids", ".idx", ".dbf", ".prj" };
                    foreach (var suffix in suffixes)
                    {
                        string fileToRemove = Path.ChangeExtension(path, suffix);
                        if (File.Exists(fileToRemove))
                        {
                            File.Delete(fileToRemove);
                        }
                    }
                }
                else
                {
                    string dir       = Path.GetDirectoryName(path);
                    string fileName  = Path.GetFileNameWithoutExtension(path);
                    string extension = Path.GetExtension(path);

                    path = Path.Combine(dir, fileName + group.Key.ToString() + extension);
                }
            }

            var dbfColumns = info.Columns.Select(column =>
            {
                DbfColumnType columnType = DbfColumnType.Character;
                try
                {
                    columnType = (DbfColumnType)Enum.Parse(typeof(DbfColumnType), column.TypeName);
                }
                catch (Exception ex)
                {
                    GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                }
                int length = column.MaxLength;
                if (length > 254)
                {
                    length     = 254;
                    columnType = DbfColumnType.Memo;
                }
                else if (length <= 0)
                {
                    length = 254;
                }

                DbfColumn dbfColumn = new DbfColumn(column.ColumnName, columnType, length, GetDecimalLength(columnType, column.MaxLength));
                return(dbfColumn);
            });

            try
            {
                ConfigureFeatureLayerParameters parameters = new ConfigureFeatureLayerParameters();
                foreach (var column in dbfColumns)
                {
                    parameters.AddedColumns.Add(column);
                }
                foreach (var feature in group)
                {
                    var newFeature = feature;
                    if (!feature.IsValid())
                    {
                        newFeature = feature.MakeValid();
                    }
                    Feature validFeature = new Feature(newFeature.GetWellKnownBinary(), newFeature.Id, feature.ColumnValues);
                    //foreach (var item in feature.LinkColumnValues)
                    //{
                    //    validFeature.LinkColumnValues.Add(item.Key, item.Value);
                    //}
                    parameters.AddedFeatures.Add(validFeature);
                }
                parameters.LayerUri = new Uri(path);
                parameters.LongColumnTruncateMode = LongColumnTruncateMode.Truncate;
                parameters.MemoColumnConvertMode  = MemoColumnConvertMode.ToCharacter;
                switch (group.Key)
                {
                case ShapeFileType.Null:
                case ShapeFileType.Multipatch:
                default:
                    parameters.WellKnownType = WellKnownType.Invalid;
                    break;

                case ShapeFileType.Point:
                case ShapeFileType.PointZ:
                case ShapeFileType.PointM:
                case ShapeFileType.Multipoint:
                case ShapeFileType.MultipointM:
                case ShapeFileType.MultipointZ:
                    parameters.WellKnownType = WellKnownType.Point;
                    break;

                case ShapeFileType.Polyline:
                case ShapeFileType.PolylineZ:
                case ShapeFileType.PolylineM:
                    parameters.WellKnownType = WellKnownType.Line;
                    break;

                case ShapeFileType.Polygon:
                case ShapeFileType.PolygonZ:
                case ShapeFileType.PolygonM:
                    parameters.WellKnownType = WellKnownType.Polygon;
                    break;
                }
                parameters.CustomData["Columns"] = parameters.AddedColumns;
                parameters.CustomData["CustomizeColumnNames"] = true;
                parameters.CustomData["EditedColumns"]        = info.CostomizedColumnNames;
                parameters.Proj4ProjectionParametersString    = info.ProjectionWkt;
                var layerPlugin = GisEditor.LayerManager.GetActiveLayerPlugins <ShapeFileFeatureLayerPlugin>().FirstOrDefault();
                var layer       = layerPlugin.CreateFeatureLayer(parameters);
                SavePrjFile(path, info.ProjectionWkt);
                RebuildDbf(path);
            }
            catch (Exception ex)
            {
                GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));

                string[] suffixes = { ".shp", ".shx", ".ids", ".idx", ".dbf", ".prj" };
                foreach (var suffix in suffixes)
                {
                    string fileToRemove = Path.ChangeExtension(path, suffix);
                    if (File.Exists(fileToRemove))
                    {
                        File.Delete(fileToRemove);
                    }
                }
                throw new OperationCanceledException("Shapefile generates failed.", ex);
            }
        }
 public static string Convert(DbfColumnType columnType)
 {
     return(columnType.ToString());
 }