示例#1
0
        private void OutPutResults(IEnumerable <Feature> resultFeatures)
        {
            string exportPath = string.Empty;

            if (outputToFile && !string.IsNullOrEmpty(outputPathFileName))
            {
                exportPath = outputPathFileName;

                var args = new UpdatingTaskProgressEventArgs(TaskState.Updating);
                args.Message = "Creating File";
                OnUpdatingProgress(args);
            }

            FileExportInfo info = new FileExportInfo(resultFeatures.Where(f =>
            {
                var wellKnownType = f.GetWellKnownType();
                return(wellKnownType == WellKnownType.Polygon || wellKnownType == WellKnownType.Multipolygon);
            }), columnsToInclude, exportPath, Proj4Projection.ConvertProj4ToPrj(displayProjectionParameters));

            Export(info);
            //try
            //{
            //    ShpFileExporter exporter = new ShpFileExporter();
            //    exporter.ExportToFile(info);
            //}
            //catch (Exception ex)
            //{
            //    UpdatingTaskProgressEventArgs e = new UpdatingTaskProgressEventArgs(TaskState.Canceled);
            //    e.Error = new ExceptionInfo(ex.Message, ex.StackTrace, ex.Source);
            //    OnUpdatingProgress(e);
            //}
        }
        private void Output(IEnumerable <Feature> features, string path, string projection)
        {
            string         projectionInWKT = Proj4Projection.ConvertProj4ToPrj(projection);
            FileExportInfo info            = new FileExportInfo(features, columns, path, projectionInWKT);

            Export(info);
        }
        private void Split()
        {
            var args = new UpdatingTaskProgressEventArgs(TaskState.Updating);

            featureSource.Open();
            Collection <Feature> allFeatures = featureSource.GetAllFeatures(featureSource.GetDistinctColumnNames());
            var columns = featureSource.GetColumns();

            featureSource.Close();

            var featuresGroups = allFeatures.GroupBy(tmpFeature
                                                     => tmpFeature.ColumnValues[splitColumnName]).ToArray();

            int i     = 0;
            int count = exportConfigs.Count;

            foreach (var config in exportConfigs)
            {
                try
                {
                    string folderName = outputPath;
                    string fileName   = config.Value;
                    if (String.IsNullOrEmpty(fileName))
                    {
                        fileName = String.Format(CultureInfo.InvariantCulture, "{0}_{1}.shp", layerName, config.Key);
                    }

                    fileName = Path.ChangeExtension(fileName, ".shp");
                    string finalShapeFilePath = Path.Combine(folderName, fileName);
                    var    featureGroup       = featuresGroups.FirstOrDefault(group => group.Key == config.Key || (config.Key.Equals("<Blank>", StringComparison.Ordinal) && group.Key.Equals(string.Empty, StringComparison.Ordinal)));
                    if (featureGroup != null)
                    {
                        var info = new FileExportInfo(featureGroup, columns, finalShapeFilePath, wkt);
                        Export(info);
                    }

                    args.Current    = ++i;
                    args.UpperBound = count;
                    args.Message    = String.Format(CultureInfo.InvariantCulture, "Building... ({0}/{1})", args.Current, args.UpperBound);
                    OnUpdatingProgress(args);
                    isCanceled = args.TaskState == TaskState.Canceled;

                    if (isCanceled)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    var errorArgs = new UpdatingTaskProgressEventArgs(TaskState.Error);
                    errorArgs.Error = new ExceptionInfo(ex.Message, ex.StackTrace, ex.Source);
                    GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                    OnUpdatingProgress(errorArgs);
                    continue;
                }
            }
        }
        private void SaveFeaturesToTempFile(string tempFilePath)
        {
            var featuresToSimplify = GetFeaturesToSimplify();

            string         projectionInWKT = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
            FileExportInfo info            = new FileExportInfo(featuresToSimplify, GetColumns(), tempFilePath, projectionInWKT);

            ShapeFileExporter exporter = new ShapeFileExporter();

            exporter.ExportToFile(info);
        }
        private void Output(IEnumerable <Feature> bufferedFeatures, string path, string projection, bool dissolve = false)
        {
            string projectionInWKT = Proj4Projection.ConvertProj4ToPrj(projection);

            if (dissolve)
            {
                columns = new Collection <FeatureSourceColumn>();
                columns.Add(new FeatureSourceColumn("OBJECTID", DbfColumnType.Character.ToString(), 1));
                columns.Add(new FeatureSourceColumn("SHAPE", DbfColumnType.Character.ToString(), 12));
            }

            FileExportInfo info = new FileExportInfo(bufferedFeatures, columns, path, projectionInWKT);

            Export(info);
        }
 private void ExportCore(FileExportInfo info)
 {
     try
     {
         ShapeFileExporter exporter = new ShapeFileExporter();
         exporter.ExportToFile(info);
     }
     catch (Exception ex)
     {
         GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
         UpdatingTaskProgressEventArgs e = new UpdatingTaskProgressEventArgs(TaskState.Canceled);
         e.Error = new ExceptionInfo(ex.Message, ex.StackTrace, ex.Source);
         OnUpdatingProgress(e);
     }
 }
        private void PrepareTaskParameters(BufferTaskPlugin plugin)
        {
            FeatureSource featureSource = null;

            if (CurrentLayerHasSelectedFeatures && OnlyBufferSelectedFeatures)
            {
                ShapeFileExporter shpExporter     = new ShapeFileExporter();
                string            projectionInWKT = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);

                if (GisEditor.SelectionManager.GetSelectionOverlay() != null)
                {
                    var features = GisEditor.SelectionManager.GetSelectionOverlay().HighlightFeatureLayer
                                   .InternalFeatures.Where(f => f.Tag == SelectedFeatureLayer);
                    FileExportInfo info = new FileExportInfo(features, GetColumns(), tempShpFilePath, projectionInWKT);
                    shpExporter.ExportToFile(info);
                }
                featureSource = new ShapeFileFeatureSource(tempShpFilePath);
            }
            else
            {
                featureSource = SelectedFeatureLayer.FeatureSource;
            }

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

            if (OutputMode == OutputMode.ToFile)
            {
                plugin.OutputPathFileName = OutputPathFileName;
            }
            else
            {
                string tempPathFileName = Path.Combine(FolderHelper.GetCurrentProjectTaskResultFolder(), TempFileName) + ".shp";
                plugin.OutputPathFileName = tempPathFileName;
                OutputPathFileName        = tempPathFileName;
            }
            plugin.FeatureSource = featureSource;
            plugin.Distance      = Distance;
            plugin.Smoothness    = Smoothness;
            plugin.Capstyle      = CapStyle;
            plugin.MapUnit       = GisEditor.ActiveMap.MapUnit;
            plugin.DistanceUnit  = SelectedDistanceUnit;
            plugin.DisplayProjectionParameters = GisEditor.ActiveMap.DisplayProjectionParameters;
            plugin.Dissolve = NeedDissolve;
        }
示例#8
0
 protected override void RunCore()
 {
     if (featureSources.All(f => f is ShapeFileFeatureSource))
     {
         ProcessWithShapeFilesOnly();
     }
     else
     {
         var sourceFeatures = GetSourceFeatures();
         var resultFeatures = MergeFeatures(sourceFeatures, columns);
         if (!isCanceled)
         {
             var info = new FileExportInfo(resultFeatures, columns, outputPathFileName, wkt);
             Export(info);
         }
     }
 }
示例#9
0
        private void SaveFeaturesToTempFile()
        {
            string tempDir = Path.Combine(GisEditor.InfrastructureManager.TemporaryPath, TempPath);

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            tempFilePath = Path.Combine(tempDir, "BlendTemp.shp");

            List <Feature> featuresToBlend = null;

            if (BlendSelectedFeaturesOnly)
            {
                featuresToBlend = FilterSelectedFeatures();
            }

            //rename the IDs, becaue features from different layers may have the same ID.
            //and the exporter can not export features that have the same IDs
            featuresToBlend = RenameFeatureIds(featuresToBlend);
            string projectionInWKT = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);

            var columns = ColumnsToInclude.Select(c => c.ToFeatureSourceColumn()).ToList();

            if (IsIntersect)
            {
                tempFilesForIntersect = new List <string>();

                var featureGroups = featuresToBlend.GroupBy(feature => feature.Tag).ToList();
                foreach (var group in featureGroups)
                {
                    string path = Path.Combine(tempDir, string.Format("BlendTemp{0}.shp", ((Layer)group.Key).Name));
                    tempFilesForIntersect.Add(path);
                    FileExportInfo    info     = new FileExportInfo(group, columns, path, projectionInWKT);
                    ShapeFileExporter exporter = new ShapeFileExporter();
                    exporter.ExportToFile(info);
                }
            }
            else
            {
                FileExportInfo    info     = new FileExportInfo(featuresToBlend, columns, tempFilePath, projectionInWKT);
                ShapeFileExporter exporter = new ShapeFileExporter();
                exporter.ExportToFile(info);
            }
        }
示例#10
0
        private void SaveSelectedFeaturesToTempFile()
        {
            string tempDir = Path.Combine(GisEditor.InfrastructureManager.TemporaryPath, TempPath);

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            tempFilePath = Path.Combine(tempDir, "SplitTemp.shp");

            var selectedFeatures = HighlightFeatureLayer.InternalFeatures.Where(f => f.Tag == SelectedLayerToSplit);

            string         projectionInWKT = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
            FileExportInfo info            = new FileExportInfo(selectedFeatures, ColumnsInSelectedLayer, tempFilePath, projectionInWKT);

            ShapeFileExporter exporter = new ShapeFileExporter();

            exporter.ExportToFile(info);
        }
示例#11
0
        private void SaveSelectedFeaturesToTempFile()
        {
            string tempDir = Path.Combine(GisEditor.InfrastructureManager.TemporaryPath, TempPath);

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            tempFilePath = Path.Combine(tempDir, "DissolveTemp.shp");

            Collection <Feature> featuresToDissolve = GetFeaturesToDissolve();

            string         projectionInWKT = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
            FileExportInfo info            = new FileExportInfo(featuresToDissolve, GetColumnsOfSelectedLayer(), tempFilePath, projectionInWKT);

            ShapeFileExporter exporter = new ShapeFileExporter();

            exporter.ExportToFile(info);
        }
示例#12
0
        protected override void ExportToFileCore(FileExportInfo info)
        {
            if (info.FeaturesToExport.Count() == 0)
            {
                throw new OperationCanceledException("Feature count is zero.");
            }
            var groupedFeatures = info.FeaturesToExport.GroupBy(f =>
            {
                return(GetShapeFileType(f.GetShape()));
            });

            foreach (var group in groupedFeatures)
            {
                if (group.Key != ShapeFileType.Null)
                {
                    Export(group, info);
                }
            }
        }
示例#13
0
        private void SaveClippingLayer()
        {
            string tempDir = Path.Combine(GisEditor.InfrastructureManager.TemporaryPath, TempPath);

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            clippingLayerTempPath = Path.Combine(tempDir, "ClippingTemp.shp");

            Collection <Feature> clippingFeatures = null;
            var clipLayers = this.ClippingLayers.Where(l => l.IsSelected).Select(l => l.FeatureLayer);

            if (this.IsUseSelectedFeatures)
            {
                Collection <Feature> selectedFeatures = new Collection <Feature>();

                var selectionOverlay = GisEditor.SelectionManager.GetSelectionOverlay();

                if (selectionOverlay != null)
                {
                    var selectedFeaturesInThisLayer = selectionOverlay.HighlightFeatureLayer.InternalFeatures.Where(tmpFeature => clipLayers.Contains(tmpFeature.Tag));
                    foreach (var feature in selectedFeaturesInThisLayer)
                    {
                        selectedFeatures.Add(feature);
                    }
                }
                if (selectedFeatures.Count > 0)
                {
                    clippingFeatures = selectedFeatures;
                }
            }

            //we don't need columns from the clipping layers
            string         projectionInWKT = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
            FileExportInfo info            = new FileExportInfo(clippingFeatures, new FeatureSourceColumn[] { new FeatureSourceColumn("None", "String", 10) }, clippingLayerTempPath, projectionInWKT);

            ShapeFileExporter exporter = new ShapeFileExporter();

            exporter.ExportToFile(info);
        }
示例#14
0
        private void SaveSelectedFeaturesToTempFile()
        {
            string tempDir = Path.Combine(GisEditor.InfrastructureManager.TemporaryPath, TempPath);

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }
            tempFilePath = Path.Combine(tempDir, "MergeTemp.shp");

            var selectionOverlay = GisEditor.SelectionManager.GetSelectionOverlay();

            if (selectionOverlay != null)
            {
                var selectedFeatures = selectionOverlay.HighlightFeatureLayer.InternalFeatures
                                       .Where(tmpFeature => SelectedLayers.Contains((Layer)tmpFeature.Tag));

                string            projectionInWKT = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
                FileExportInfo    info            = new FileExportInfo(selectedFeatures, GetColumnsOfSelectedLayers(), tempFilePath, projectionInWKT);
                ShapeFileExporter exporter        = new ShapeFileExporter();
                exporter.ExportToFile(info);
            }
        }
        protected override void RunCore()
        {
            //if (FeatureLayer != null && FeatureLayer.FeatureSource.LinkSources.Count > 0)
            //{
            //    hasLinkSource = true;
            //}

            if (FeaturesForExporting.Count == 0 && FeatureIdsForExporting.Count > 0 && FeatureLayer != null)
            {
                FeatureLayer.CloseAll();
                FeatureLayer.SafeProcess(() =>
                {
                    //if (FeatureLayer.FeatureSource.LinkSources.Count > 0)
                    //{
                    //    featuresForExporting = FeatureLayer.FeatureSource.GetFeaturesByIds(FeatureIdsForExporting, FeatureLayer.GetDistinctColumnNames());
                    //    hasLinkSource = true;
                    //}
                    //else
                    //{
                    //    featuresForExporting = FeatureLayer.QueryTools.GetFeaturesByIds(FeatureIdsForExporting, FeatureLayer.GetDistinctColumnNames());
                    //    hasLinkSource = false;
                    //}

                    featuresForExporting = FeatureLayer.QueryTools.GetFeaturesByIds(FeatureIdsForExporting, FeatureLayer.GetDistinctColumnNames());
                    hasLinkSource        = false;
                });
            }

            Proj4Projection proj4 = new Proj4Projection();

            proj4.InternalProjectionParametersString = InternalPrj4Projection;
            proj4.ExternalProjectionParametersString = Proj4Projection.ConvertPrjToProj4(ProjectionWkt);
            proj4.SyncProjectionParametersString();
            proj4.Open();

            Collection <Feature> exportFeatures = FeaturesForExporting;

            if (proj4.CanProject())
            {
                exportFeatures = new Collection <Feature>();
                foreach (var item in FeaturesForExporting)
                {
                    Feature newFeature = item;
                    newFeature = proj4.ConvertToExternalProjection(item);
                    exportFeatures.Add(newFeature);
                }
            }
            proj4.Close();

            #region This is a trick to fix that fox pro columns cannot write to dbf, convert all fox pro columns to character column type.

            if (hasLinkSource)
            {
                Collection <string> dateTimeColumns = new Collection <string>();
                Collection <string> dateColumns     = new Collection <string>();

                foreach (var item in FeatureSourceColumns)
                {
                    string doubleInBinary  = DbfColumnType.DoubleInBinary.ToString();
                    string integerInBinary = DbfColumnType.IntegerInBinary.ToString();
                    string dateTime        = DbfColumnType.DateTime.ToString();
                    string date            = DbfColumnType.Date.ToString();
                    string logical         = DbfColumnType.Logical.ToString();

                    if (item.TypeName.Equals(doubleInBinary, StringComparison.OrdinalIgnoreCase) ||
                        item.TypeName.Equals(integerInBinary, StringComparison.OrdinalIgnoreCase) ||
                        item.TypeName.Equals(dateTime, StringComparison.OrdinalIgnoreCase) ||
                        item.TypeName.Equals(date, StringComparison.OrdinalIgnoreCase) ||
                        item.TypeName.Equals(logical, StringComparison.OrdinalIgnoreCase))
                    {
                        item.TypeName = DbfColumnType.Character.ToString();
                    }
                }

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

                //foreach (var feature in exportFeatures)
                //{
                //    // Fill link column values into column values.
                //    foreach (var item in feature.LinkColumnValues)
                //    {
                //        string key = item.Key;
                //        string value = string.Join("\r\n", item.Value.Select(v => v.Value));
                //        feature.ColumnValues[key] = value;
                //        longLengthColumnNames[key] = value.Length;
                //    }
                //}

                // fix too long column value
                foreach (var key in longLengthColumnNames.Keys)
                {
                    FeatureSourceColumn column = FeatureSourceColumns.FirstOrDefault(f => f.ColumnName.Equals(key, StringComparison.OrdinalIgnoreCase));
                    if (column != null)
                    {
                        int length = longLengthColumnNames[key];
                        if (length > column.MaxLength)
                        {
                            column.MaxLength = length;
                        }
                    }
                }
            }

            #endregion This is a trick to fix that fox pro columns cannot write to dbf.

            if (NeedConvertMemoToCharacter)
            {
                foreach (var feature in exportFeatures)
                {
                    foreach (var item in FeatureSourceColumns)
                    {
                        if (item.TypeName.Equals(DbfColumnType.Memo.ToString(), StringComparison.OrdinalIgnoreCase))
                        {
                            item.TypeName  = DbfColumnType.Character.ToString();
                            item.MaxLength = 254;
                        }
                        else if (item.TypeName.Equals(DbfColumnType.Character.ToString(), StringComparison.OrdinalIgnoreCase) &&
                                 item.MaxLength > 254)
                        {
                            item.MaxLength = 254;
                        }
                        //if (feature.ColumnValues.ContainsKey(item.ColumnName) && feature.ColumnValues[item.ColumnName].Length > 254)
                        //{
                        //    feature.ColumnValues[item.ColumnName] = feature.ColumnValues[item.ColumnName].Substring(0, 254);
                        //}
                    }
                }
            }

            var info = new FileExportInfo(exportFeatures, FeatureSourceColumns, OutputPathFileName, ProjectionWkt);
            foreach (var item in CostomizedColumnNames)
            {
                info.CostomizedColumnNames.Add(item.Key, item.Value);
            }
            Export(info);
        }
        private void SimplifyAllFeatures()
        {
            UpdatingTaskProgressEventArgs args = null;

            var features = GetFeaturesFromTempFile().ToArray();
            int index    = 1;
            int count    = features.Count();

            SimplificationType simType = SimplificationType.DouglasPeucker;

            if (preserveTopology)
            {
                simType = SimplificationType.TopologyPreserving;
            }

            Collection <Feature> simplifiedFeatures = new Collection <Feature>();

            foreach (Feature feature in features)
            {
                try
                {
                    var       shape           = feature.GetShape();
                    var       areaShape       = shape as AreaBaseShape;
                    var       lineShape       = shape as LineBaseShape;
                    BaseShape simplifiedShape = null;

                    if (areaShape != null)
                    {
                        if (selectedDistanceUnit == "Decimal Degrees")
                        {
                            simplifiedShape = areaShape.Simplify(simplificationTolerance, simType);
                        }
                        else
                        {
                            simplifiedShape = areaShape.Simplify(mapUnit, simplificationTolerance, (DistanceUnit)converter.ConvertBack(selectedDistanceUnit, null, null, null), simType);
                        }
                    }
                    else if (lineShape != null)
                    {
                        if (selectedDistanceUnit == "Decimal Degrees")
                        {
                            simplifiedShape = lineShape.Simplify(simplificationTolerance, simType);
                        }
                        else
                        {
                            simplifiedShape = lineShape.Simplify(mapUnit, simplificationTolerance, (DistanceUnit)converter.ConvertBack(selectedDistanceUnit, null, null, null), simType);
                        }
                    }

                    if (simplifiedShape != null)
                    {
                        Feature newFeature = new Feature(simplifiedShape.GetWellKnownBinary(), feature.Id, feature.ColumnValues);
                        newFeature.Tag = feature.Tag;
                        simplifiedFeatures.Add(newFeature);
                    }
                }
                catch (Exception ex)
                {
                    args         = new UpdatingTaskProgressEventArgs(TaskState.Error);
                    args.Message = feature.Id;
                    args.Error   = new ExceptionInfo(ex.Message, ex.StackTrace, ex.Source);
                    GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                    OnUpdatingProgress(args);
                    continue;
                }

                var progressPercentage = index * 100 / count;
                args            = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage);
                args.Current    = index;
                args.UpperBound = count;
                OnUpdatingProgress(args);
                isCanceled = args.TaskState == TaskState.Canceled;
                if (isCanceled)
                {
                    break;
                }
                index++;
            }
            if (!isCanceled)
            {
                args         = new UpdatingTaskProgressEventArgs(TaskState.Updating);
                args.Message = "Creating File";
                OnUpdatingProgress(args);

                FileExportInfo info = new FileExportInfo(simplifiedFeatures, GetColumns(), outputPathFileName, displayProjectionParameters);
                Export(info);
            }
            //args = new UpdatingProgressLongRunningTaskPluginEventArgs(LongRunningTaskState.Completed);
            //args.Message = "Finished";
            //OnUpdatingProgress(args);
        }
 protected abstract void ExportToFileCore(FileExportInfo info);
 public void ExportToFile(FileExportInfo info)
 {
     ExportToFileCore(info);
 }
 protected void Export(FileExportInfo info)
 {
     ExportCore(info);
 }
示例#20
0
        private void ExportToFile(string fileName, IEnumerable <Feature> features, IEnumerable <FeatureSourceColumn> columns)
        {
            var info = new FileExportInfo(features, columns, fileName, wkt);

            Export(info);
        }
示例#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);
            }
        }
示例#22
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);
            }
        }
        //private IEnumerable<string> GetMatchColumnsFromString(string matchColumnsInString)
        //{
        //    string[] columns = matchColumnsInString.Split(',');
        //    return columns;
        //}

        private void Dissolve()
        {
            Collection <Feature> dissolvedFeatures = new Collection <Feature>();

            // get features to dissolve.
            Collection <Feature> featuresToDissolve = GetFeaturesToDissolve();

            // group features.
            var featureGroupByShapeType = featuresToDissolve.GroupBy(f =>
            {
                return(f.GetShape().GetType());
            });

            // collect export columns.
            var filteredFeatureColumns = new Collection <FeatureSourceColumn>();

            foreach (var matchColumn in this.matchColumns)
            {
                var tmpColumn = featureColumns.FirstOrDefault(f => f.ColumnName.Equals(matchColumn, StringComparison.Ordinal));
                if (tmpColumn != null)
                {
                    filteredFeatureColumns.Add(tmpColumn);
                }
            }

            foreach (var extraColumn in this.operatorPairs)
            {
                var tmpColumn = featureColumns.FirstOrDefault(f => f.ColumnName.Equals(extraColumn.ColumnName, StringComparison.Ordinal));
                if (tmpColumn != null)
                {
                    filteredFeatureColumns.Add(tmpColumn);
                }
            }

            filteredFeatureColumns.Add(new FeatureSourceColumn("Count", "Integer", 8));

            Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > > dissolveAction
                = new Action <IGrouping <Type, Feature>, Action <IEnumerable <Feature>, Dictionary <string, string> > >
                      ((groupByType, finalProcessAction) =>
            {
                //CancelTask(this.CancellationSource.Token, content, parameter);
                var groupByColumns = GroupByColumns(groupByType, this.matchColumns);
                groupByColumns.ForEach(groupFeature =>
                {
                    //CancelTask(this.CancellationSource.Token, content, parameter);
                    Dictionary <string, string> newColumnValues = new Dictionary <string, string>();
                    foreach (var tmpMatchColumn in this.matchColumns)
                    {
                        newColumnValues.Add(tmpMatchColumn, groupFeature.First().ColumnValues[tmpMatchColumn]);
                    }

                    foreach (var operatorPair in this.operatorPairs)
                    {
                        //CancelTask(this.CancellationSource.Token, content, parameter);
                        CollectNewColumnValues(groupFeature, newColumnValues, operatorPair);
                        var value        = newColumnValues[operatorPair.ColumnName];
                        var resultColumn = filteredFeatureColumns.FirstOrDefault(c => c.ColumnName.Equals(operatorPair.ColumnName));
                        if (resultColumn != null)
                        {
                            if (resultColumn.MaxLength < value.Length)
                            {
                                var indexOf = filteredFeatureColumns.IndexOf(resultColumn);
                                filteredFeatureColumns.RemoveAt(indexOf);
                                var newColumn = new FeatureSourceColumn(resultColumn.ColumnName, resultColumn.TypeName, value.Length);
                                filteredFeatureColumns.Insert(indexOf, newColumn);
                            }
                        }
                    }

                    newColumnValues.Add("Count", groupFeature.Count().ToString());

                    try
                    {
                        if (finalProcessAction != null)
                        {
                            finalProcessAction(groupFeature, newColumnValues);
                        }
                    }
                    catch (Exception e)
                    {
                        GisEditor.LoggerManager.Log(LoggerLevel.Debug, e.Message, new ExceptionInfo(e));
                        throw e;
                    }
                });
            });

            foreach (var groupByType in featureGroupByShapeType)
            {
                try
                {
                    //CancelTask(this.CancellationSource.Token, content, parameter);
                    if (groupByType.Key.IsSubclassOf(typeof(AreaBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            //MultipolygonShape dissolveShape = AreaBaseShape.Union(GetValidFeatures(tmpFeatures));
                            List <AreaBaseShape> areaShapes = GetValidFeatures(tmpFeatures)
                                                              .Select(f => f.GetShape())
                                                              .OfType <AreaBaseShape>()
                                                              .ToList();

                            MultipolygonShape dissolveShape = (MultipolygonShape)SqlTypesGeometryHelper.Union(areaShapes);

                            if (dissolveShape != null)
                            {
                                Feature dissolveFeature = new Feature(dissolveShape, tmpColumnValues);
                                dissolvedFeatures.Add(dissolveFeature);
                            }
                        });
                    }
                    else if (groupByType.Key.IsSubclassOf(typeof(LineBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            MultilineShape dissolveShape = new MultilineShape();
                            tmpFeatures.ForEach(tmpFeature =>
                            {
                                BaseShape tmpShape      = tmpFeature.GetShape();
                                LineShape tmpLine       = tmpShape as LineShape;
                                MultilineShape tmpMLine = tmpShape as MultilineShape;
                                if (tmpLine != null)
                                {
                                    dissolveShape.Lines.Add(tmpLine);
                                }
                                else if (tmpMLine != null)
                                {
                                    tmpMLine.Lines.ForEach(tmpLineInMLine => dissolveShape.Lines.Add(tmpLineInMLine));
                                }
                            });

                            if (dissolveShape.Lines.Count > 0)
                            {
                                dissolvedFeatures.Add(new Feature(dissolveShape, tmpColumnValues));
                            }
                        });
                    }
                    else if (groupByType.Key.IsSubclassOf(typeof(PointBaseShape)))
                    {
                        dissolveAction(groupByType, (tmpFeatures, tmpColumnValues) =>
                        {
                            MultipointShape multipointShape = new MultipointShape();
                            tmpFeatures.ForEach(tmpFeature =>
                            {
                                BaseShape tmpShape        = tmpFeature.GetShape();
                                PointShape tmpPoint       = tmpShape as PointShape;
                                MultipointShape tmpMPoint = tmpShape as MultipointShape;
                                if (tmpPoint != null)
                                {
                                    multipointShape.Points.Add(tmpPoint);
                                }
                                else if (tmpMPoint != null)
                                {
                                    tmpMPoint.Points.ForEach(tmpPointInMPointShape => multipointShape.Points.Add(tmpPointInMPointShape));
                                }
                            });
                            dissolvedFeatures.Add(new Feature(multipointShape, tmpColumnValues));
                        });
                    }
                    if (isCanceled)
                    {
                        break;
                    }
                }
                catch (Exception ex)
                {
                    var errorEventArgs = new UpdatingTaskProgressEventArgs(TaskState.Error);
                    errorEventArgs.Error = new ExceptionInfo(string.Format(CultureInfo.InvariantCulture, "Feature id: {0}, {1}"
                                                                           , groupByType.FirstOrDefault().Id, ex.Message)
                                                             , ex.StackTrace
                                                             , ex.Source);
                    GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                    errorEventArgs.Message = groupByType.FirstOrDefault().Id;
                    OnUpdatingProgress(errorEventArgs);
                    continue;
                }
            }
            if (!isCanceled)
            {
                string saveFolder = Path.GetDirectoryName(outputPathFileName);
                if (!Directory.Exists(saveFolder))
                {
                    Directory.CreateDirectory(saveFolder);
                }

                var info = new FileExportInfo(dissolvedFeatures, filteredFeatureColumns, outputPathFileName, Wkt);
                Export(info);
            }
        }