public static string GetProj4ProjectionParameter(string prjPathFileName)
        {
            string proj4Parameter = string.Empty;

            try
            {
                if (!File.Exists(prjPathFileName))
                {
                    var projectionWindow = new ProjectionWindow();
                    if (projectionWindow.ShowDialog().GetValueOrDefault())
                    {
                        proj4Parameter = projectionWindow.Proj4ProjectionParameters;
                        File.WriteAllText(prjPathFileName, Proj4Projection.ConvertProj4ToPrj(projectionWindow.Proj4ProjectionParameters));
                    }
                }
                else
                {
                    string wkt = File.ReadAllText(prjPathFileName);
                    proj4Parameter = Proj4Projection.ConvertPrjToProj4(wkt);
                }
            }
            catch (Exception ex)
            {
                GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
            }

            return(proj4Parameter);
        }
Example #2
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 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);
        }
        public ProjectionWindow(string initializeProj4String, string descriptionText, string checkBoxContent)
        {
            proj4Parameters = initializeProj4String;

            InitializeComponent();
            commonProjectionViewModel = commonProjection.DataContext as CommonProjectionViewModel;
            otherProjectionViewModel  = otherProjection.DataContext as OtherProjectionViewModel;
            commonProjectionViewModel.SelectedProj4ProjectionParameters = initializeProj4String;

            viewModel   = new ProjectionSelectionViewModel(descriptionText, checkBoxContent);
            DataContext = viewModel;

            Messenger.Default.Register <bool>(this, viewModel, (result) =>
            {
                if (result)
                {
                    string proj4ProjectionParameter      = viewModel.SelectedProj4Parameter;
                    var selectedOtherProjectionViewModel = viewModel.SelectedViewModel as OtherProjectionViewModel;
                    if (selectedOtherProjectionViewModel != null && selectedOtherProjectionViewModel.SelectedProjectionType == SearchProjectionType.Custom)
                    {
                        proj4ProjectionParameter = viewModel.SelectedProj4Parameter;
                        string projectionWkt     = Proj4Projection.ConvertProj4ToPrj(proj4ProjectionParameter);
                        if (!string.IsNullOrEmpty(projectionWkt))
                        {
                            DialogResult = result;
                        }
                        else
                        {
                            System.Windows.Forms.MessageBox.Show(GisEditor.LanguageManager.GetStringResource("ProjectionSelectionWindowProj4InvalidText"), GisEditor.LanguageManager.GetStringResource("ProjectionSelectionWindowProj4InvalidCaption"), System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        DialogResult = result;
                    }

                    SaveProjectionWindowStateToXml();
                    if (!string.IsNullOrEmpty(proj4ProjectionParameter))
                    {
                        viewModel.SelectedProj4Parameter = proj4ProjectionParameter;
                    }
                }
                else
                {
                    DialogResult = result;
                }
            });
            Closing += (s, e) => Messenger.Default.Unregister(this);
            HelpContainer.Content = GetHelpButton();
        }
Example #6
0
 protected virtual void SaveInternalProj4ProjectionParametersCore(FeatureLayer featureLayer, string proj4ProjectionParameters)
 {
     if (!string.IsNullOrEmpty(ExtensionFilter))
     {
         var uri = GetUri(featureLayer);
         if (uri != null && uri.Scheme.Equals("file") && File.Exists(uri.LocalPath))
         {
             string proj4PathFileName = uri.LocalPath;
             proj4PathFileName = Path.ChangeExtension(proj4PathFileName, ".prj");
             string internalProj = Proj4Projection.ConvertProj4ToPrj(proj4ProjectionParameters);
             File.WriteAllText(proj4PathFileName, internalProj);
         }
     }
 }
        private static void SavePrjFile(string shapeFileName, string parameters)
        {
            string wkt     = Proj4Projection.ConvertProj4ToPrj(parameters);
            string prjPath = Path.ChangeExtension(shapeFileName, "prj");

            if (!File.Exists(prjPath))
            {
                File.WriteAllText(prjPath, wkt);
            }
            else
            {
                File.Delete(prjPath);
                File.WriteAllText(prjPath, wkt);
            }
        }
        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);
        }
Example #9
0
 private void InitializePlugin(MergeTaskPlugin plugin, List <FeatureSource> featureSources, FeatureSourceColumn[] columns)
 {
     if (OutputMode == OutputMode.ToFile)
     {
         plugin.OutputPathFileName = OutputPathFileName;
     }
     else
     {
         string tempPathFileName = Path.Combine(FolderHelper.GetCurrentProjectTaskResultFolder(), TempFileName) + ".shp";
         plugin.OutputPathFileName = tempPathFileName;
         OutputPathFileName        = tempPathFileName;
     }
     plugin.Wkt            = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
     plugin.FeatureSources = featureSources;
     plugin.Columns        = columns;
 }
        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;
        }
Example #11
0
 private void InitializePlugin(DissolveTaskPlugin plugin, FeatureSource featureSource)
 {
     plugin.Wkt           = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
     plugin.MatchColumns  = MatchColumns;
     plugin.OperatorPairs = OperatorPairs;
     plugin.FeatureSource = featureSource;
     if (OutputMode == OutputMode.ToFile)
     {
         plugin.OutputPathFileName = OutputPathFileName;
     }
     else
     {
         string tempPathFileName = Path.Combine(FolderHelper.GetCurrentProjectTaskResultFolder(), TempFileName) + ".shp";
         plugin.OutputPathFileName = tempPathFileName;
         OutputPathFileName        = tempPathFileName;
     }
 }
Example #12
0
 private void InitializePlugin(ClipTaskPlugin plugin, List <FeatureLayer> clippingLayerFeatureLayers)
 {
     if (OutputMode == OutputMode.ToFile)
     {
         plugin.OutputPathFileName = OutputPathFileName;
     }
     else
     {
         string tempPathFileName = Path.Combine(FolderHelper.GetCurrentProjectTaskResultFolder(), TempFileName) + ".shp";
         plugin.OutputPathFileName = tempPathFileName;
         OutputPathFileName        = tempPathFileName;
     }
     plugin.MasterLayerFeatureLayer    = MasterLayer;
     plugin.ClippingLayerFeatureLayers = clippingLayerFeatureLayers;
     plugin.Wkt          = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
     plugin.ClippingType = CurrentClippingType.ClippingType;
 }
Example #13
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);
            }
        }
Example #14
0
 private void InitializePlugin(SplitTaskPlugin plugin, FeatureSource featureSource, Dictionary <string, string> exportConfigs)
 {
     if (OutputMode == OutputMode.ToFile)
     {
         plugin.OutputPath = OutputPath;
     }
     else
     {
         plugin.OutputPath = FolderHelper.GetCurrentProjectTaskResultFolder();
         OutputPath        = plugin.OutputPath;
     }
     plugin.Wkt                  = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
     plugin.FeatureSource        = featureSource;
     plugin.SplitColumnName      = SelectedFeatureSourceColumn.ColumnName;
     plugin.ExportConfigs        = exportConfigs;
     plugin.LayerName            = SelectedLayerToSplit.Name;
     plugin.OverwriteOutputFiles = OverwriteOutputFiles;
 }
        private void BufferShapeFile()
        {
            var args          = new UpdatingTaskProgressEventArgs(TaskState.Updating);
            var currentSource = (ShapeFileFeatureSource)FeatureSource;

            if (!currentSource.IsOpen)
            {
                currentSource.Open();
            }

            var canceled      = false;
            var projectionWkt = Proj4Projection.ConvertProj4ToPrj(DisplayProjectionParameters);
            var helper        = new ShapeFileHelper(ShapeFileType.Polygon, outputPathFileName, currentSource.GetColumns(), projectionWkt);

            helper.CapabilityToFlush = 1000;
            helper.ForEachFeatures(currentSource, (f, currentProgress, upperBound, percentage) =>
            {
                try
                {
                    if (f.GetWellKnownBinary() != null)
                    {
                        //Feature bufferedFeature = f.Buffer(Distance, Smoothness, Capstyle, MapUnit, DistanceUnit);
                        //Feature bufferedFeature = SqlTypesGeometryHelper.Buffer(f, Distance, Smoothness, Capstyle, MapUnit, DistanceUnit);
                        Feature bufferedFeature = BufferFeature(f);
                        helper.Add(bufferedFeature);
                    }

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

                    canceled = args.TaskState == TaskState.Canceled;
                    return(canceled);
                }
                catch (Exception ex)
                {
                    GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex));
                    return(false);
                }
            });

            helper.Commit();
        }
Example #16
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);
        }
Example #17
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);
        }
 private void InitializePlugin(SimplifyTaskPlugin plugin, FeatureSource featureSource)
 {
     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.PreserveTopology        = PreserveTopology;
     plugin.SelectedDistanceUnit    = SelectedDistanceUnit;
     plugin.SimplificationTolerance = SimplificationTolerance;
     plugin.MapUnit = GisEditor.ActiveMap.MapUnit;
     plugin.DisplayProjectionParameters = Proj4Projection.ConvertProj4ToPrj(GisEditor.ActiveMap.DisplayProjectionParameters);
 }
Example #19
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);
        }
Example #20
0
        protected override TaskPlugin GetTaskPluginCore()
        {
            ExportTaskPlugin exportTaskPlugin = new ExportTaskPlugin();

            exportTaskPlugin.NeedConvertMemoToCharacter = NeedConvertMemoToCharacter;
            if (OutputMode == OutputMode.ToFile)
            {
                exportTaskPlugin.OutputPathFileName = OutputPathFileName;
            }
            else
            {
                string tempPathFileName = Path.Combine(FolderHelper.GetCurrentProjectTaskResultFolder(), TempFileName) + ".shp";
                exportTaskPlugin.OutputPathFileName = tempPathFileName;
                OutputPathFileName = tempPathFileName;
            }
            exportTaskPlugin.ProjectionWkt          = Proj4Projection.ConvertProj4ToPrj(ProjectionParameter);
            exportTaskPlugin.InternalPrj4Projection = GisEditor.ActiveMap.DisplayProjectionParameters;
            switch (ExportMode)
            {
            case ExportMode.ExportMeasuredFeatures:
                FillMeasuredFeatures(exportTaskPlugin.FeaturesForExporting, exportTaskPlugin.FeatureSourceColumns);
                break;

            case ExportMode.ExportSelectedFeatures:
            default:
                foreach (var entry in this.ColumnEntities)
                {
                    if (entry.IsChecked)
                    {
                        exportTaskPlugin.FeatureSourceColumns.Add(new FeatureSourceColumn(entry.ColumnName, entry.ColumnType, entry.MaxLength));
                        exportTaskPlugin.CostomizedColumnNames[entry.ColumnName] = entry.EditedColumnName;
                    }
                }
                FillSelectedFeatures(exportTaskPlugin.FeatureIdsForExporting);
                exportTaskPlugin.FeatureLayer = SelectedFeatureLayer;
                break;
            }

            return(exportTaskPlugin);
        }
Example #21
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 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;

                switch (column.TypeName.ToUpperInvariant())
                {
                case "DOUBLE":
                    columnLenght  = columnLenght == 0 ? 10 : columnLenght;
                    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":
                    columnLenght  = columnLenght == 0 ? 255 : columnLenght;
                    decimalLength = 0;
                    break;
                }

                tabDbfColumns.Add(new TabDbfColumn(column.ColumnName, (DbfColumnType)Enum.Parse(typeof(DbfColumnType), column.TypeName, true), columnLenght, decimalLength, false, false));
            }

            TabFeatureLayer.CreateTabFile(featureLayerStructureParameters.LayerUri.OriginalString, tabDbfColumns, new Collection <Feature>(), OverwriteMode.Overwrite);
            TabFeatureLayer.BuildIndexFile(featureLayerStructureParameters.LayerUri.OriginalString);

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

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

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

            if (featureLayerStructureParameters.AddedFeatures.Count > 0)
            {
                resultLayer.Open();
                resultLayer.EditTools.BeginTransaction();
                foreach (var feature in featureLayerStructureParameters.AddedFeatures)
                {
                    resultLayer.EditTools.Add(feature);
                }
                resultLayer.EditTools.CommitTransaction();
                resultLayer.Close();
            }

            return(resultLayer);
        }
        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);
        }
        protected override FeatureLayer CreateFeatureLayerCore(ConfigureFeatureLayerParameters featureLayerStructureParameters)
        {
            bool hasFeatures = featureLayerStructureParameters.AddedFeatures.Count > 0;

            if (hasFeatures)
            {
                List <string> columns = featureLayerStructureParameters.AddedFeatures[0].ColumnValues.Keys.ToList();
                WKTColumn       = GetUniqueColumn(WKTColumn, columns, 0);
                LongitudeColumn = GetUniqueColumn(LongitudeColumn, columns, 0);
                LatitudeColumn  = GetUniqueColumn(LatitudeColumn, columns, 0);

                foreach (var feature in featureLayerStructureParameters.AddedFeatures)
                {
                    PointShape pointBaseShape = feature.GetShape() as PointShape;
                    if (pointBaseShape != null)
                    {
                        feature.ColumnValues[WKTColumn] = pointBaseShape.GetWellKnownText();
                    }
                    else
                    {
                        feature.ColumnValues[LongitudeColumn] = "";
                        feature.ColumnValues[LatitudeColumn]  = "";
                    }
                }
            }

            string layerPath = LayerPluginHelper.GetLayerUriToSave(featureLayerStructureParameters.LayerUri, ExtensionFilter);

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

            Collection <string> csvColumns = new Collection <string>();

            foreach (var column in featureLayerStructureParameters.AddedColumns)
            {
                csvColumns.Add(column.ColumnName);
            }

            string delimiter = ",";

            if (featureLayerStructureParameters.CustomData.ContainsKey("Delimiter"))
            {
                delimiter = featureLayerStructureParameters.CustomData["Delimiter"].ToString();
            }
            else if (featureLayerStructureParameters.WellKnownType != WellKnownType.Point && featureLayerStructureParameters.WellKnownType != WellKnownType.Multipoint)
            {
                delimiter = "\t";
            }

            DelimitedSpatialColumnsType csvMappingType = DelimitedSpatialColumnsType.WellKnownText;

            if (featureLayerStructureParameters.CustomData.ContainsKey("MappingType"))
            {
                csvMappingType = (DelimitedSpatialColumnsType)featureLayerStructureParameters.CustomData["MappingType"];
            }
            else
            {
                if (featureLayerStructureParameters.WellKnownType == WellKnownType.Point || featureLayerStructureParameters.WellKnownType == WellKnownType.Multipoint)
                {
                    csvMappingType = DelimitedSpatialColumnsType.XAndY;
                    featureLayerStructureParameters.CustomData["X"] = LongitudeColumn;
                    featureLayerStructureParameters.CustomData["Y"] = LatitudeColumn;
                    csvColumns.Add(LongitudeColumn);
                    csvColumns.Add(LatitudeColumn);
                    if (hasFeatures)
                    {
                        csvColumns.Add(WKTColumn);
                    }
                }
                else
                {
                    csvMappingType = DelimitedSpatialColumnsType.WellKnownText;
                    featureLayerStructureParameters.CustomData["WKT"] = WKTColumn;
                    if (hasFeatures)
                    {
                        csvColumns.Add(LongitudeColumn);
                        csvColumns.Add(LatitudeColumn);
                    }
                    csvColumns.Add(WKTColumn);
                }
            }

            CsvFeatureLayer.CreateDelimitedFile(featureLayerStructureParameters.LayerUri.OriginalString, csvColumns, delimiter, OverwriteMode.Overwrite);

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

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

            var resultLayer = new CsvFeatureLayer();

            resultLayer.DelimitedPathFilename = featureLayerStructureParameters.LayerUri.LocalPath;
            resultLayer.Delimiter             = delimiter;
            resultLayer.SpatialColumnType     = csvMappingType;
            resultLayer.RequireIndex          = false;

            if (featureLayerStructureParameters.CustomData.ContainsKey("X"))
            {
                resultLayer.XColumnName = featureLayerStructureParameters.CustomData["X"].ToString();
            }
            if (featureLayerStructureParameters.CustomData.ContainsKey("Y"))
            {
                resultLayer.YColumnName = featureLayerStructureParameters.CustomData["Y"].ToString();
            }
            if (featureLayerStructureParameters.CustomData.ContainsKey("WKT"))
            {
                resultLayer.WellKnownTextColumnName = featureLayerStructureParameters.CustomData["WKT"].ToString();
            }
            resultLayer.Open();
            if (featureLayerStructureParameters.AddedFeatures.Count > 0)
            {
                resultLayer.EditTools.BeginTransaction();
                foreach (var feature in featureLayerStructureParameters.AddedFeatures)
                {
                    resultLayer.EditTools.Add(feature);
                }
                resultLayer.EditTools.CommitTransaction();
            }
            CSVModel.BuildDelimitedConfigurationFile(resultLayer);
            resultLayer.Close();

            return(resultLayer);
        }
        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);
        }
        /// <summary>
        /// This method sets projection for raster layers.
        /// Just pass in the parameters it requires, then you don't need to do anything about raster layer's projection in your layer provider.
        /// </summary>
        /// <param name="infos">infos</param>
        internal static void SetInternalProjectionForRasterLayers(IEnumerable <RasterLayerInfo> infos)
        {
            string proj4StringForAll = string.Empty;
            bool   savePrjFileForAll = false;

            foreach (var info in infos)
            {
                string currentProj4 = string.Empty;
                info.Layer.Open();
                if (info.Layer.HasProjectionText)
                {
                    currentProj4 = info.Layer.GetProjectionText();
                }

                if (!string.IsNullOrEmpty(proj4StringForAll))
                {
                    info.Layer.InitializeProj4Projection(proj4StringForAll);
                    if (savePrjFileForAll)
                    {
                        File.WriteAllText(info.PrjFilePath, Proj4Projection.ConvertProj4ToPrj(proj4StringForAll));
                    }
                }
                else if (!string.IsNullOrEmpty(currentProj4))
                {
                    string proj4 = currentProj4;
                    if (proj4.Trim().Equals(Proj4Projection.GetEpsgParametersString(4326).Trim()))
                    {
                        if (info.Layer.HasBoundingBox)
                        {
                            if (!info.Layer.IsOpen)
                            {
                                info.Layer.Open();
                            }
                            if (info.Layer.GetBoundingBox().Width > 361)
                            {
                                var result = System.Windows.Forms.MessageBox.Show(GisEditor.LanguageManager.GetStringResource("LayerPluginHelperLayerNotWGText"), GisEditor.LanguageManager.GetStringResource("LayerPluginHelperProjectionNotMatchCaption"), System.Windows.Forms.MessageBoxButtons.YesNo);
                                if (result == System.Windows.Forms.DialogResult.Yes)
                                {
                                    proj4 = Proj4Projection.GetGoogleMapParametersString();
                                }
                            }
                        }
                    }
                    info.Layer.InitializeProj4Projection(proj4);
                }
                else if (IsDecimalDegree(info.Layer))
                {
                    info.Layer.InitializeProj4Projection(Proj4Projection.GetEpsgParametersString(4326));
                }
                else
                {
                    string           description      = GisEditor.LanguageManager.GetStringResource("selectAProjectionForAllLayersDescription");
                    ProjectionWindow projectionWindow = new ProjectionWindow("", description, "Apply For All Layers");
                    if (projectionWindow.ShowDialog().GetValueOrDefault())
                    {
                        info.Layer.InitializeProj4Projection(projectionWindow.Proj4ProjectionParameters);
                        savePrjFileForAll = true;
                        File.WriteAllText(info.PrjFilePath, Proj4Projection.ConvertProj4ToPrj(projectionWindow.Proj4ProjectionParameters));
                        if (projectionWindow.SyncProj4ProjectionForAll)
                        {
                            proj4StringForAll = projectionWindow.Proj4ProjectionParameters;
                        }
                    }
                    else
                    {
                        info.Layer.InitializeProj4Projection(string.Empty);
                    }
                }
            }
        }
        private void SimplifyShapeFile()
        {
            var args          = new UpdatingTaskProgressEventArgs(TaskState.Updating);
            var currentSource = (ShapeFileFeatureSource)FeatureSource;

            if (!currentSource.IsOpen)
            {
                currentSource.Open();
            }

            var canceled      = false;
            var shapeFileType = currentSource.GetShapeFileType();
            var projectionWkt = Proj4Projection.ConvertProj4ToPrj(DisplayProjectionParameters);
            var helper        = new ShapeFileHelper(shapeFileType, outputPathFileName, currentSource.GetColumns(), projectionWkt);

            try
            {
                helper.ForEachFeatures(currentSource, (f, currentProgress, upperBound, percentage) =>
                {
                    try
                    {
                        if (f.GetWellKnownBinary() != null)
                        {
                            SimplificationType simType = SimplificationType.DouglasPeucker;
                            if (preserveTopology)
                            {
                                simType = SimplificationType.TopologyPreserving;
                            }

                            var shape                 = f.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 feature = new Feature(simplifiedShape);
                                foreach (var item in f.ColumnValues)
                                {
                                    feature.ColumnValues[item.Key] = item.Value;
                                }
                                helper.Add(feature);
                            }
                        }

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

                        canceled = args.TaskState == TaskState.Canceled;
                        return(canceled);
                    }
                    catch (Exception e)
                    {
                        GisEditor.LoggerManager.Log(LoggerLevel.Debug, e.Message, new ExceptionInfo(e));
                        return(false);
                    }
                });
            }
            finally
            {
                helper.Commit();
            }
        }
Example #28
0
        protected override FeatureLayer CreateFeatureLayerCore(ConfigureFeatureLayerParameters featureLayerStructureParameters)
        {
            string layerPath = LayerPluginHelper.GetLayerUriToSave(featureLayerStructureParameters.LayerUri, ExtensionFilter);
            string fileName  = Path.GetFileNameWithoutExtension(layerPath);

            if (string.IsNullOrEmpty(layerPath))
            {
                return(null);
            }
            if (fileName.FirstOrDefault() != null && Char.IsNumber(fileName.FirstOrDefault()))
            {
                MessageBox.Show("Table name can not start with number.");
                return(null);
            }
            featureLayerStructureParameters.LayerUri = new Uri(layerPath);

            Collection <FeatureSourceColumn> columns = new Collection <FeatureSourceColumn>();

            System.Text.RegularExpressions.Regex regx = new System.Text.RegularExpressions.Regex(@"\W");
            foreach (var column in featureLayerStructureParameters.AddedColumns)
            {
                FeatureSourceColumn newColumn = column;
                if (newColumn.ColumnName.Equals("Null", StringComparison.Ordinal))
                {
                    newColumn.ColumnName = "Null_";
                }
                newColumn.ColumnName = regx.Replace(newColumn.ColumnName, string.Empty);
                columns.Add(newColumn);
            }

            string tableName = string.Empty;

            if (featureLayerStructureParameters.CustomData.ContainsKey("TableName"))
            {
                //if (createFeatureLayerParameters.Tag != null)
                //tableName = createFeatureLayerParameters.Tag.ToString().Split('|').First();
                tableName = featureLayerStructureParameters.CustomData["TableName"] as string;
            }
            else
            {
                tableName = Path.GetFileNameWithoutExtension(featureLayerStructureParameters.LayerUri.OriginalString);
            }

            FileGeoDatabaseFeatureLayer.CreateFileGeoDatabase(featureLayerStructureParameters.LayerUri.OriginalString);
            FileGeoDatabaseFeatureLayer.CreateTable(featureLayerStructureParameters.LayerUri.OriginalString, tableName, featureLayerStructureParameters.WellKnownType, columns);

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

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

            FileGeoDatabaseFeatureLayer fileGeoDatabaseFeatureLayer = new FileGeoDatabaseFeatureLayer(featureLayerStructureParameters.LayerUri.LocalPath, tableName);

            if (featureLayerStructureParameters.AddedFeatures.Count > 0)
            {
                fileGeoDatabaseFeatureLayer.Open();
                fileGeoDatabaseFeatureLayer.EditTools.BeginTransaction();
                foreach (var feature in featureLayerStructureParameters.AddedFeatures)
                {
                    fileGeoDatabaseFeatureLayer.EditTools.Add(feature);
                }
                fileGeoDatabaseFeatureLayer.EditTools.CommitTransaction();
                fileGeoDatabaseFeatureLayer.Close();
            }

            return(fileGeoDatabaseFeatureLayer);
        }
        protected override void RunCore()
        {
            var existingShapePathFileNames = ShapePathFileNames.Where(s => CheckShapeFileExists(s.Key));
            var upperBounds = GetUpperBounds(existingShapePathFileNames);

            CreateOutputPath(OutputPathFileName);
            var currentIndex = 0;

            foreach (var currentShapePathFileName in existingShapePathFileNames)
            {
                try
                {
                    string currentShapeFileName      = Path.GetFileName(currentShapePathFileName.Key);
                    string outputShapePathFileName   = Path.Combine(OutputPathFileName, currentShapeFileName);
                    string outputTempIdxPathFileName = Path.Combine(OutputPathFileName, "TMP" + currentShapeFileName);
                    outputTempIdxPathFileName = Path.ChangeExtension(outputTempIdxPathFileName, ".idx");

                    DeleteRelatedFiles(outputShapePathFileName);

                    Proj4Projection projection = new Proj4Projection();
                    projection.InternalProjectionParametersString = currentShapePathFileName.Value;
                    projection.ExternalProjectionParametersString = TargetProjectionParameter;
                    projection.Open();

                    //CreateShapeFileWithIndex(currentShapePathFileName.Key, outputShapePathFileName, outputTempIdxPathFileName, projection, upperBounds, ref current);

                    var currentFeatureSource = new ShapeFileFeatureSource(currentShapePathFileName.Key);
                    currentFeatureSource.Open();
                    string          projectionWkt = Proj4Projection.ConvertProj4ToPrj(TargetProjectionParameter);
                    ShapeFileHelper helper        = new ShapeFileHelper(currentFeatureSource.GetShapeFileType(), outputShapePathFileName, currentFeatureSource.GetColumns(), projectionWkt);

                    helper.ForEachFeatures(currentFeatureSource, f =>
                    {
                        if (f.GetWellKnownBinary() != null)
                        {
                            var newFeature = projection.ConvertToExternalProjection(f);
                            if (newFeature.CanMakeValid)
                            {
                                newFeature = newFeature.MakeValid();
                            }

                            if (newFeature.GetWellKnownType() != WellKnownType.GeometryCollection)
                            {
                                helper.Add(newFeature);
                            }
                        }

                        currentIndex++;
                        UpdatingTaskProgressEventArgs args = new UpdatingTaskProgressEventArgs(TaskState.Updating, currentIndex * 100 / upperBounds);
                        args.Current    = currentIndex;
                        args.UpperBound = upperBounds;
                        OnUpdatingProgress(args);
                        return(args.TaskState == TaskState.Canceled);
                    });

                    helper.Commit();
                    CreateDbfFile(currentShapePathFileName.Key, outputShapePathFileName);
                    //CreatePrjFile(outputShapePathFileName, TargetProjectionParameter);
                }
                catch (Exception ex)
                {
                    UpdatingTaskProgressEventArgs 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;
                }
            }
        }
        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);
        }