private void TaskManager_UpdatingProgress(object sender, UpdatingTaskProgressEventArgs e) { if (e.TaskState == TaskState.Completed && backgroundBuildingCallbacks.ContainsKey(e.TaskToken) && backgroundBuildingCallbacks[e.TaskToken] != null) { if (Application.Current != null) { Application.Current.Dispatcher.BeginInvoke(() => { backgroundBuildingCallbacks[e.TaskToken](); backgroundBuildingCallbacks.Remove(e.TaskToken); }); } else { backgroundBuildingCallbacks[e.TaskToken](); backgroundBuildingCallbacks.Remove(e.TaskToken); } } else if (e.TaskState == TaskState.Canceled && backgroundBuildingCallbacks.ContainsKey(e.TaskToken)) { backgroundBuildingCallbacks.Remove(e.TaskToken); } }
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 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 HandleExceptionFromInvalidFeature(string id, string message) { var args = new UpdatingTaskProgressEventArgs(TaskState.Error); args.Error = new ExceptionInfo(message, string.Empty, string.Empty); args.Message = id; OnUpdatingProgress(args); }
private bool ReportProgress(int current, int upperBound) { var progressPercentage = current * 100 / upperBound; var args = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage); args.Current = current; args.UpperBound = upperBound; OnUpdatingProgress(args); return(args.TaskState == TaskState.Canceled); }
private void IndexAdapter_BuildingIndex(object sender, BuildingIndexEventArgs e) { int progressPercentage = e.CurrentRecordIndex * 100 / e.RecordCount; var updatingArgs = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage); updatingArgs.Current = e.CurrentRecordIndex; updatingArgs.UpperBound = e.RecordCount; OnUpdatingProgress(updatingArgs); if (updatingArgs.TaskState == TaskState.Canceled) { e.Cancel = true; } }
private void FinalProcess(UpdatingTaskProgressEventArgs e) { ExceptionInfo exceptionInfo = new ExceptionInfo(); if (runningErrors.ContainsKey(e.TaskToken)) { exceptionInfo.Message = string.Join("\r\n", runningErrors[e.TaskToken].Select(s => s.Message)); runningErrors.Remove(e.TaskToken); } runningTasks[e.TaskToken](exceptionInfo); runningTasks.Remove(e.TaskToken); }
private void TaskManager_UpdatingProgress(object sender, UpdatingTaskProgressEventArgs e) { if (GisEditor.TaskManager.RunProcessesLocally && Application.Current != null) { Application.Current.Dispatcher.BeginInvoke(() => { OnUpdatingProgressInternal(e); }); } else { OnUpdatingProgressInternal(e); } }
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 GridFeatureSource_GeneratingGrid(object sender, GeneratingGridFeatureSourceEventArgs e) { if (e.GridPathFilename.Equals(OutputPathFileName, StringComparison.OrdinalIgnoreCase)) { int progressPercentage = e.GridIndex * 100 / e.GridCount; var updatingArgs = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage); updatingArgs.Current = e.GridIndex; updatingArgs.UpperBound = e.GridCount; OnUpdatingProgress(updatingArgs); if (updatingArgs.TaskState == TaskState.Canceled) { e.IsCanceled = true; } } }
private static bool UpdateProgress(Action <UpdatingTaskProgressEventArgs> updateAction, int index, int count) { var progressPercentage = index * 100 / count; var args = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage); args.Current = index; args.UpperBound = count; if (updateAction != null) { updateAction(args); } var isCanceled = args.TaskState == TaskState.Canceled; return(isCanceled); }
private void ProcessWithShapeFilesOnly() { int count = featureSources.Sum(f => { if (!f.IsOpen) { f.Open(); } return(f.GetCount()); }); var args = new UpdatingTaskProgressEventArgs(TaskState.Updating); var shapeFileFeatureSources = featureSources.OfType <ShapeFileFeatureSource>().ToList(); var shapeFileType = shapeFileFeatureSources.First().GetShapeFileType(); var currentProgress = 0; var shapeFileHelper = new ShapeFileHelper(shapeFileType, OutputPathFileName, columns, wkt); foreach (var featureSource in shapeFileFeatureSources) { shapeFileHelper.ForEachFeatures(featureSource, f => { if (f.GetWellKnownBinary() != null) { foreach (var featureColumn in columns) { if (!f.ColumnValues.Keys.Contains(featureColumn.ColumnName)) { f.ColumnValues.Add(featureColumn.ColumnName, "0"); } } shapeFileHelper.Add(new Feature(f.GetWellKnownBinary(), Guid.NewGuid().ToString(), f.ColumnValues)); } currentProgress++; var progressPercentage = currentProgress * 100 / count; args = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage); args.Current = currentProgress; args.UpperBound = count; OnUpdatingProgress(args); isCanceled = args.TaskState == TaskState.Canceled; return(isCanceled); }); } shapeFileHelper.Commit(); }
private Collection <Feature> MergeFeatures(Collection <Feature> sourceFeatures, IEnumerable <FeatureSourceColumn> featureColumns) { Collection <Feature> features = new Collection <Feature>(); int id = 0; int count = sourceFeatures.Count; var args = new UpdatingTaskProgressEventArgs(TaskState.Updating); foreach (Feature feature in sourceFeatures) { var current = id + 1; var progressPercentage = current * 100 / count; args = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage); args.Current = current; args.UpperBound = count; OnUpdatingProgress(args); isCanceled = args.TaskState == TaskState.Canceled; if (isCanceled) { break; } foreach (FeatureSourceColumn featureColumn in featureColumns) { if (!feature.ColumnValues.Keys.Contains(featureColumn.ColumnName)) { feature.ColumnValues.Add(featureColumn.ColumnName, "0"); } } try { if (!feature.GetShape().Validate(ShapeValidationMode.Simple).IsValid) { throw new Exception("This feature is invalid."); } features.Add(new Feature(feature.GetWellKnownBinary(), id.ToString(), feature.ColumnValues)); } catch (Exception ex) { GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex)); HandleExceptionFromInvalidFeature(feature.Id, ex.Message); } id++; } return(features); }
private void LogError(UpdatingTaskProgressEventArgs args) { string featureId = args.Message; string exceptionMessage = args.Error.Message; if (errorRecord == null) { errorRecord = new Dictionary <string, ErrorInfo>(); } if (!errorRecord.ContainsKey(featureId + exceptionMessage)) { errorRecord.Add(featureId + exceptionMessage, new ErrorInfo { ID = featureId, ErrorMessage = exceptionMessage }); } }
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(); }
private void OnUpdatingProgressInternal(UpdatingTaskProgressEventArgs e) { if (taskMonitorWindow == null) { taskMonitorWindow = new TaskMonitorWindow(); } TaskViewModel currentTask = taskMonitorWindow.RunningTasks.FirstOrDefault(t => t.TaskToken.Equals(e.TaskToken, StringComparison.Ordinal)); if (currentTask == null && e.TaskState != TaskState.Canceled && e.TaskState != TaskState.Completed) { currentTask = new TaskViewModel(e.TaskToken); if (e.Parameters.ContainsKey("Name")) { currentTask.Name = e.Parameters["Name"]; } if (e.Parameters.ContainsKey("Description")) { currentTask.Description = e.Parameters["Description"]; } lock (taskMonitorWindow.RunningTasks) { taskMonitorWindow.RunningTasks.Add(currentTask); } } else if (e.TaskState == TaskState.Updating) { currentTask.Progress = e.ProgressPercentage; } else if (e.TaskState == TaskState.Completed || e.TaskState == TaskState.Canceled) { lock (taskMonitorWindow.RunningTasks) { taskMonitorWindow.RunningTasks.Remove(currentTask); if (taskMonitorWindow.RunningTasks.Count == 0) { taskMonitorWindow.Close(); taskMonitorWindow = null; } } } }
protected override void RunCore() { try { using (FileStream fileStream = File.Create(OutputPathFileName)) { try { GridFeatureSource.GeneratingGrid += GridFeatureSource_GeneratingGrid; GridFeatureLayer.GenerateGrid(GridDefinition, GridInterpolationModel, fileStream); } catch (Exception e) { GisEditor.LoggerManager.Log(LoggerLevel.Debug, e.Message, new ExceptionInfo(e)); if (e is OutOfMemoryException) { throw e; } } finally { GridFeatureSource.GeneratingGrid -= GridFeatureSource_GeneratingGrid; } } } catch (OutOfMemoryException) { var args = new UpdatingTaskProgressEventArgs(TaskState.Canceled); args.Error = new ExceptionInfo("Small grid cell size causes out of memory exception. Please set a larger one.", string.Empty, string.Empty); OnUpdatingProgress(args); } catch (Exception ex) { var args = new UpdatingTaskProgressEventArgs(TaskState.Error); args.Error = new ExceptionInfo(ex.Message, string.Empty, string.Empty); OnUpdatingProgress(args); } }
private void TaskManager_UpdatingProgress(object sender, UpdatingTaskProgressEventArgs e) { if (e.TaskState == TaskState.Completed && runningTasks.ContainsKey(e.TaskToken) && runningTasks[e.TaskToken] != null) { if (Application.Current != null) { Application.Current.Dispatcher.BeginInvoke(() => { FinalProcess(e); }); } else { FinalProcess(e); } } else if (e.TaskState == TaskState.Canceled && runningTasks.ContainsKey(e.TaskToken)) { if (e.Error != null && !string.IsNullOrEmpty(e.Error.Message)) { System.Windows.Forms.MessageBox.Show(e.Error.Message, "Task Canceled", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Stop); } runningTasks.Remove(e.TaskToken); } else if (e.TaskState == TaskState.Error) { if (!runningErrors.ContainsKey(e.TaskToken)) { runningErrors.Add(e.TaskToken, new Collection <ExceptionInfo> { e.Error }); } else { runningErrors[e.TaskToken].Add(e.Error); } } }
private void BlendFeatures(IEnumerable <Feature> sourceFeatures) { IEnumerable <Feature> resultFeatures = null; if (isIntersect) { resultFeatures = IntersectFeatures(sourceFeatures); } else if (isCombine) { resultFeatures = CombineFeatures(sourceFeatures); } if (!isCanceled) { if (exceptionMessage != null) { UpdatingTaskProgressEventArgs e = new UpdatingTaskProgressEventArgs(TaskState.Error); e.Error = new ExceptionInfo(exceptionMessage.ToString(), string.Empty, string.Empty); OnUpdatingProgress(e); } OutPutResults(resultFeatures); } }
//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); } }
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; } } }
private void CreateShapeFile(ObservableCollection <FeatureSourceColumn> includedColumnsList , string OutputPath, Encoding ShapeFileEncoding, string csvFilePath , List <Feature> features , bool isIncludeAllFeatures , IEnumerable <MatchCondition> matchConditions , Action <UpdatingTaskProgressEventArgs> updateAction , Dictionary <string, string> invalidColumns) { Collection <DbfColumn> includeColumns = new Collection <DbfColumn>(); RemoveUnduplicateColumn(includedColumnsList); foreach (var column in includedColumnsList) { DbfColumnType tmpDbfColumnType = DbfColumnType.Character; if (Enum.TryParse(column.TypeName, out tmpDbfColumnType)) { DbfColumn dbfColumn = new DbfColumn(column.ColumnName, tmpDbfColumnType, column.MaxLength, 0); includeColumns.Add(dbfColumn); } } ShapeFileType shapeFileType = GetShapeFileType(features.FirstOrDefault()); if (shapeFileType != ShapeFileType.Null) { ShapeFileFeatureLayer.CreateShapeFile(shapeFileType, OutputPath, includeColumns, ShapeFileEncoding, OverwriteMode.Overwrite); var dataTable = DataJoinAdapter.ReadDataToDataGrid(csvFilePath, Delimiter); var featureRows = dataTable.Rows; var index = 0; var count = features.Count; ShapeFileFeatureLayer newShapeFileFeatureLayer = new ShapeFileFeatureLayer(OutputPath, GeoFileReadWriteMode.ReadWrite); newShapeFileFeatureLayer.SafeProcess(() => { newShapeFileFeatureLayer.EditTools.BeginTransaction(); foreach (var feature in features) { index++; try { var matchedDataRow = featureRows.Cast <DataRow>().FirstOrDefault(r => matchConditions.All(tmpCondition => feature.ColumnValues[tmpCondition.SelectedLayerColumn.ColumnName] == r[tmpCondition.SelectedDelimitedColumn.ColumnName].ToString())); if (matchedDataRow != null) { SetFeatureColumnValues(feature, matchedDataRow, includedColumnsList, invalidColumns); newShapeFileFeatureLayer.EditTools.Add(feature); } else if (isIncludeAllFeatures) { newShapeFileFeatureLayer.EditTools.Add(feature); } if (UpdateProgress(updateAction, index, count)) { break; } } catch (Exception ex) { var errorEventArgs = new UpdatingTaskProgressEventArgs(TaskState.Error); errorEventArgs.Error = new ExceptionInfo(string.Format(CultureInfo.InvariantCulture, "Feature id: {0}, {1}" , feature.Id, ex.Message) , ex.StackTrace , ex.Source); GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex)); errorEventArgs.Message = feature.Id; updateAction(errorEventArgs); } } newShapeFileFeatureLayer.EditTools.CommitTransaction(); }); SavePrjFile(OutputPath, DisplayProjectionParameters); } }
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); }
private void BufferAllFeatures() { FeaturesToBuffer = GetFeaturesToBuffer(FeatureSource); int bufferdFeaturesCount = 0; Collection <Feature> bufferedFeatures = new Collection <Feature>(); MultipolygonShape dissolvedShape = null; bool isCanceled = false; foreach (Feature feature in featuresToBuffer) { try { BaseShape shape = feature.GetShape(); MultipolygonShape bufferedShape = BufferShape(shape); Feature bufferedFeature = new Feature(bufferedShape.GetWellKnownBinary(), feature.Id, feature.ColumnValues); bufferedFeature.Tag = feature.Tag; bufferedFeatures.Add(bufferedFeature); if (dissolve) { if (dissolvedShape == null) { dissolvedShape = bufferedShape; dissolvedShape.Tag = feature.Tag; } else { //dissolvedShape = dissolvedShape.Union(bufferedShape); dissolvedShape = (MultipolygonShape)SqlTypesGeometryHelper.Union(dissolvedShape, bufferedShape); } } } catch (Exception ex) { var errorEventArgs = new UpdatingTaskProgressEventArgs(TaskState.Error); errorEventArgs.Error = new ExceptionInfo(string.Format(CultureInfo.InvariantCulture, "Feature id: {0}, {1}" , feature.Id, ex.Message) , ex.StackTrace , ex.Source); GisEditor.LoggerManager.Log(LoggerLevel.Debug, ex.Message, new ExceptionInfo(ex)); errorEventArgs.Message = feature.Id; OnUpdatingProgress(errorEventArgs); continue; } Interlocked.Increment(ref bufferdFeaturesCount); int progressPercentage = bufferdFeaturesCount * 100 / featuresToBuffer.Count; var updatingArgs = new UpdatingTaskProgressEventArgs(TaskState.Updating, progressPercentage); updatingArgs.Current = bufferdFeaturesCount; updatingArgs.UpperBound = featuresToBuffer.Count; OnUpdatingProgress(updatingArgs); if (updatingArgs.TaskState == TaskState.Canceled) { isCanceled = true; break; } } if (!isCanceled) { if (dissolve && dissolvedShape != null) { bufferedFeatures.Clear(); bufferedFeatures.Add(new Feature(dissolvedShape.GetWellKnownBinary(), "1", new Dictionary <string, string> { { "OBJECTID", "1" }, { "SHAPE", "MULTIPOLYGON" } }) { Tag = dissolvedShape.Tag }); } OnUpdatingProgress(new UpdatingTaskProgressEventArgs(TaskState.Updating) { Message = "Creating File" }); Output(bufferedFeatures, OutputPathFileName, DisplayProjectionParameters, Dissolve); } }
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); }
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(); } }