private async Task <string> AddFeatureToLayer(Geometry geom, EllipseAttributes attributes) { string message = String.Empty; if (attributes == null) { message = "Attributes are Empty"; // For debug does not need to be resource return(message); } FeatureClass ellipseFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true); if (ellipseFeatureClass == null) { message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName(); return(message); } bool creationResult = false; FeatureClassDefinition ellipseDefinition = ellipseFeatureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Name = "Ellipse Feature Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = ellipseFeatureClass.CreateRowBuffer(); if (ellipseDefinition.FindField("Major") >= 0) { rowBuffer["Major"] = attributes.majorAxis; // Text } if (ellipseDefinition.FindField("Minor") >= 0) { rowBuffer["Minor"] = attributes.minorAxis; // Double } if (ellipseDefinition.FindField("DistUnit") >= 0) { rowBuffer["DistUnit"] = attributes.distanceunit; // Text } if (ellipseDefinition.FindField("Angle") >= 0) { rowBuffer["Angle"] = attributes.angle; // Double } if (ellipseDefinition.FindField("AngleUnit") >= 0) { rowBuffer["AngleUnit"] = attributes.angleunit; // Text } if (ellipseDefinition.FindField("CenterX") >= 0) { rowBuffer["CenterX"] = attributes.centerx; // Double } if (ellipseDefinition.FindField("CenterY") >= 0) { rowBuffer["CenterY"] = attributes.centery; // Double } rowBuffer["Shape"] = GeometryEngine.Instance.Project(geom, ellipseDefinition.GetSpatialReference()); Feature feature = ellipseFeatureClass.CreateRow(rowBuffer); feature.Store(); //To indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } catch (Exception ex) { message = ex.Message; } }, ellipseFeatureClass); await QueuedTask.Run(async() => { creationResult = await editOperation.ExecuteAsync(); }); if (!creationResult) { message = editOperation.ErrorMessage; } return(message); }
private async Task <string> AddFeatureToLayer(Geometry geom, CircleAttributes attributes) { string message = String.Empty; if (attributes == null) { message = "Attributes are Empty"; // For debug does not need to be resource return(message); } FeatureClass circleFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true); if (circleFeatureClass == null) { message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName(); return(message); } bool creationResult = false; FeatureClassDefinition circleDefinition = circleFeatureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Name = "Circular Feature Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = circleFeatureClass.CreateRowBuffer(); double distance = attributes.distance; if (IsDistanceCalcExpanded && (CircleType == CircleFromTypes.Diameter)) { distance *= 2.0; } if (circleDefinition.FindField("Distance") >= 0) { rowBuffer["Distance"] = distance; // Double } if (circleDefinition.FindField("DistUnit") >= 0) { rowBuffer["DistUnit"] = attributes.distanceunit; // Text } if (circleDefinition.FindField("DistType") >= 0) { rowBuffer["DistType"] = attributes.circletype; // Text } if (circleDefinition.FindField("CenterX") >= 0) { rowBuffer["CenterX"] = attributes.centerx; // Double } if (circleDefinition.FindField("CenterY") >= 0) { rowBuffer["CenterY"] = attributes.centery; // Double } rowBuffer["Shape"] = GeometryEngine.Instance.Project(geom, circleDefinition.GetSpatialReference()); Feature feature = circleFeatureClass.CreateRow(rowBuffer); feature.Store(); //To Indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } catch (Exception ex) { message = ex.Message; } }, circleFeatureClass); await QueuedTask.Run(async() => { creationResult = await editOperation.ExecuteAsync(); }); if (!creationResult) { message = editOperation.ErrorMessage; await Project.Current.DiscardEditsAsync(); } else { await Project.Current.SaveEditsAsync(); } return(message); }
private async Task <string> AddFeatureToLayer(Geometry geom, RangeAttributes attributes) { string message = String.Empty; if (attributes == null) { message = "Attributes are Empty"; // For debug does not need to be resource return(message); } FeatureClass ringFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true); if (ringFeatureClass == null) { message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName(); return(message); } bool creationResult = false; FeatureClassDefinition ringDefinition = ringFeatureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Name = "Ring Feature Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = ringFeatureClass.CreateRowBuffer(); if (ringDefinition.FindField("Distance") >= 0) { rowBuffer["Distance"] = attributes.distance; // Double } if (ringDefinition.FindField("DistUnit") >= 0) { rowBuffer["DistUnit"] = attributes.distanceunit; // Text } if (ringDefinition.FindField("Rings") >= 0) { rowBuffer["Rings"] = attributes.numRings; // Double } if (ringDefinition.FindField("CenterX") >= 0) { rowBuffer["CenterX"] = attributes.centerx; // Double } if (ringDefinition.FindField("CenterY") >= 0) { rowBuffer["CenterY"] = attributes.centery; // Double } if (ringDefinition.FindField("RRType") >= 0) { rowBuffer["RRType"] = attributes.ringorradial; // Double } // Ensure Z removed (this feature class does not have Z) var geoNoZ = geom; if (geom.HasZ) { PolylineBuilder pb = new PolylineBuilder((Polyline)geom); pb.HasZ = false; geoNoZ = pb.ToGeometry(); } rowBuffer["Shape"] = GeometryEngine.Instance.Project(geoNoZ, ringDefinition.GetSpatialReference()); Feature feature = ringFeatureClass.CreateRow(rowBuffer); feature.Store(); //To Indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } catch (Exception ex) { message = ex.Message; } }, ringFeatureClass); await QueuedTask.Run(async() => { creationResult = await editOperation.ExecuteAsync(); }); if (!creationResult) { message = editOperation.ErrorMessage; } return(message); }
private async Task SetupDefinitionDetailsAsync() { DefinitionDetails.Clear(); try { var lstDefs = await QueuedTask.Run <List <string> >(() => { Definition datasetDefinition = Dataset.DatasetDefinition; List <string> lstDefDetails = new List <string>(); if (datasetDefinition is TableDefinition) { TableDefinition tableDefinition = datasetDefinition as TableDefinition; lstDefDetails.Add($"Object ID Field: {tableDefinition.GetObjectIDField()}"); StringBuilder stringBuilder = new StringBuilder(); if (!(_datastore is FileSystemDatastore)) { lstDefDetails.Add($"Alias Name: {tableDefinition.GetAliasName()}"); lstDefDetails.Add($"CreatedAt Field: {tableDefinition.GetCreatedAtField()}"); lstDefDetails.Add($"Creator Field: {tableDefinition.GetCreatorField()}"); lstDefDetails.Add($"Subtype Field: {tableDefinition.GetSubtypeField()}"); lstDefDetails.Add($"Default Subtype Code: {tableDefinition.GetDefaultSubtypeCode()}"); lstDefDetails.Add($"EditedAt Field: {tableDefinition.GetEditedAtField()}"); lstDefDetails.Add($"Editor Field: {tableDefinition.GetEditorField()}"); lstDefDetails.Add($"Global ID Field: {tableDefinition.GetGlobalIDField()}"); lstDefDetails.Add($"Model Name: {tableDefinition.GetModelName()}"); foreach (var subtype in tableDefinition.GetSubtypes()) { stringBuilder.Append(subtype.GetCode()).Append(": ").Append(subtype.GetName()).Append(Environment.NewLine); } lstDefDetails.Add($"Subtypes: {stringBuilder}"); } stringBuilder = new StringBuilder(); foreach (Index index in tableDefinition.GetIndexes()) { stringBuilder.Append(index.GetName()).Append(","); string order = index.IsAscending() ? "Ascending" : "Descending"; stringBuilder.Append(order).Append(", "); string unique = index.IsUnique() ? "Unique" : "Not Unique"; stringBuilder.Append(unique); } lstDefDetails.Add($"Indexes: {stringBuilder}"); } if (datasetDefinition is FeatureClassDefinition) { FeatureClassDefinition featureClassDefinition = datasetDefinition as FeatureClassDefinition; if (!(_datastore is FileSystemDatastore)) { lstDefDetails.Add($"Area Field: {featureClassDefinition.GetAreaField()}"); lstDefDetails.Add($"Length Field: {featureClassDefinition.GetLengthField()}"); } lstDefDetails.Add($"Shape Field: {featureClassDefinition.GetShapeField()}"); lstDefDetails.Add($"Shape Type: {featureClassDefinition.GetShapeType()}"); lstDefDetails.Add($"Spatial Reference Name: {featureClassDefinition.GetSpatialReference().Name}"); Envelope extent = featureClassDefinition.GetExtent(); lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}"); } if (datasetDefinition is FeatureDatasetDefinition) { FeatureDatasetDefinition featureDatasetDefinition = datasetDefinition as FeatureDatasetDefinition; lstDefDetails.Add($"Spatial Reference Name: {featureDatasetDefinition.GetSpatialReference().Name}"); try { Envelope extent = featureDatasetDefinition.GetExtent(); lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}"); } catch (Exception) { lstDefDetails.Add("Could not get extent"); } } if (datasetDefinition is RelationshipClassDefinition) { RelationshipClassDefinition relationshipClassDefinition = datasetDefinition as RelationshipClassDefinition; lstDefDetails.Add($"Alias Name: {relationshipClassDefinition.GetAliasName()}"); lstDefDetails.Add($"Cardinality: {relationshipClassDefinition.GetCardinality()}"); lstDefDetails.Add($"Origin Class: {relationshipClassDefinition.GetOriginClass()}"); lstDefDetails.Add($"Destination Class: {relationshipClassDefinition.GetDestinationClass()}"); lstDefDetails.Add($"Origin Primary Key: {relationshipClassDefinition.GetOriginKeyField()}"); lstDefDetails.Add($"Origin Foreign Key: {relationshipClassDefinition.GetOriginForeignKeyField()}"); lstDefDetails.Add($"Is Attachement?: {relationshipClassDefinition.IsAttachmentRelationship()}"); lstDefDetails.Add($"Is Composite Relationship?: {relationshipClassDefinition.IsComposite()}"); } if (datasetDefinition is AttributedRelationshipClassDefinition) { AttributedRelationshipClassDefinition relationshipClassDefinition = datasetDefinition as AttributedRelationshipClassDefinition; lstDefDetails.Add($"Destination Key: {relationshipClassDefinition.GetDestinationKeyField()}"); lstDefDetails.Add($"Destination Foreign Key: {relationshipClassDefinition.GetDestinationForeignKeyField()}"); lstDefDetails.Add($"Object ID Field: {relationshipClassDefinition.GetObjectIDField()}"); } return(lstDefDetails); }); DefinitionDetails.AddRange(lstDefs); } catch (Exception exObj) { MessageBox.Show(exObj.Message, "Error"); } }
private async Task <string> AddFeatureToLayer(Geometry geom, LineAttributes attributes) { string message = String.Empty; if (attributes == null) { message = "Attributes are Empty"; // For debug does not need to be resource return(message); } FeatureClass lineFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true); if (lineFeatureClass == null) { message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName(); return(message); } bool creationResult = false; FeatureClassDefinition lineDefinition = lineFeatureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Name = "Line Feature Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = lineFeatureClass.CreateRowBuffer(); if (lineDefinition.FindField("Distance") >= 0) { rowBuffer["Distance"] = attributes.distance; // Double } if (lineDefinition.FindField("DistUnit") >= 0) { rowBuffer["DistUnit"] = attributes.distanceunit; // Text } if (lineDefinition.FindField("Angle") >= 0) { rowBuffer["Angle"] = attributes.angle; // Double } if (lineDefinition.FindField("AngleUnit") >= 0) { rowBuffer["AngleUnit"] = attributes.angleunit; // Text } if (lineDefinition.FindField("OriginX") >= 0) { rowBuffer["OriginX"] = attributes.originx; // Double } if (lineDefinition.FindField("OriginY") >= 0) { rowBuffer["OriginY"] = attributes.originy; // Double } if (lineDefinition.FindField("DestX") >= 0) { rowBuffer["DestX"] = attributes.destinationx; // Double } if (lineDefinition.FindField("DestY") >= 0) { rowBuffer["DestY"] = attributes.destinationy; // Double } // Ensure Geometry Has Z var geomZ = geom; if (!geom.HasZ) { PolylineBuilder pb = new PolylineBuilder((Polyline)geom); pb.HasZ = true; geomZ = pb.ToGeometry(); } rowBuffer["Shape"] = GeometryEngine.Instance.Project(geomZ, lineDefinition.GetSpatialReference()); Feature feature = lineFeatureClass.CreateRow(rowBuffer); feature.Store(); //To Indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } catch (Exception ex) { message = ex.Message; } }, lineFeatureClass); await QueuedTask.Run(async() => { creationResult = await editOperation.ExecuteAsync(); }); if (!creationResult) { message = editOperation.ErrorMessage; } return(message); }
protected async override void OnClick() { // get the feature layer that's selected in the table of contents var selectedLayers = MapView.Active.GetSelectedLayers(); var CADLayer = selectedLayers.OfType <FeatureLayer>().FirstOrDefault() as FeatureLayer; string CadFileName = ""; SpatialReference fcSR = null; if (CADLayer == null) { System.Windows.MessageBox.Show("Please select the CAD layer in the table of contents", "Layer Transform"); return; } double dMetersPerUnit = 1; string CadFeatClassNameForSelectedLayer = ""; //Run on MCT bool isValid = await QueuedTask.Run(() => { var CADFeatClass = CADLayer.GetFeatureClass(); var FilePathConnX = CADFeatClass.GetDatastore(); string sCADFilePath = FilePathConnX.GetConnectionString(); sCADFilePath = sCADFilePath.Replace("DATABASE=", ""); var FeatDS = CADFeatClass.GetFeatureDataset(); CadFileName = System.IO.Path.Combine(sCADFilePath, FeatDS.GetName()); string fileExtension = System.IO.Path.GetExtension(CadFileName); fileExtension = fileExtension.ToLower(); string sTargetFileName = System.IO.Path.GetFileNameWithoutExtension(CadFileName); sTargetWldFile = System.IO.Path.Combine(sCADFilePath, sTargetFileName + ".wld"); //get name for layer string FCName = CADFeatClass.GetName(); CadFeatClassNameForSelectedLayer = System.IO.Path.Combine(CadFileName, FCName); bool bIsCAD = fileExtension == ".dwg" || fileExtension == ".dgn" || fileExtension == ".dxf"; FeatureClassDefinition CADFeatClassDef = CADFeatClass.GetDefinition(); fcSR = CADFeatClassDef.GetSpatialReference(); bool bResult = bIsCAD & !fcSR.IsGeographic; //The addin requires that the CAD data is not in geographic coordinates if (bResult) { if (fcSR.IsProjected) { dMetersPerUnit = fcSR.Unit.ConversionFactor; //meters per unit } } return(bResult); }); // if not a valid CAD file if (!isValid) { System.Windows.MessageBox.Show("Please select the CAD layer in the table of contents." + Environment.NewLine + "CAD data in a geographic coordinate system is not supported.", "Transform CAD Layer"); return; } double dOriginX = 0; // Origin Northing(Y) coordinate double dOriginY = 0; // Origin Northing (Y) coordinate double dGridX = 0; // Grid Easting (X) coordinate double dGridY = 0; // Grid Northing (Y) coordinate double dScaleFactor = 1.0000; // Scale Factor double dRotation = 0.0000; // Rotation bool bSetGroundToGrid = false; #region Collect parameters from dialog var transformationDlg = new TransformationInput(); transformationDlg.Owner = FrameworkApplication.Current.MainWindow; TransformationViewModel VM = new TransformationViewModel(); transformationDlg.DataContext = VM; string sLastUsedParams = ""; bool bCancel = false; try { if (transformationDlg.ShowDialog() == true) { string sOriginX = VM.Transformation.OriginX; string sOriginY = VM.Transformation.OriginY; string sGridX = VM.Transformation.GridX; string sGridY = VM.Transformation.GridY; string sScaleFactor = VM.Transformation.ScaleFactor; string sRotation = VM.Transformation.Rotation; string sSetGroundToGrid = VM.Transformation.UpdateGround2Grid.ToString(); sLastUsedParams = sOriginX + "|" + sOriginY + "|" + sGridX + "|" + sGridY + "|" + sScaleFactor + "|" + sRotation + "|" + sSetGroundToGrid; bSetGroundToGrid = VM.Transformation.UpdateGround2Grid; if (!Double.TryParse(sOriginX, out dOriginX)) { MessageBox.Show("Local Easting (X) must be a number." + Environment.NewLine + "Press the Transform button again to retry.", "Local Easting (X)"); return; } if (!Double.TryParse(sOriginY, out dOriginY)) { MessageBox.Show("Local Northing (Y) must be a number." + Environment.NewLine + "Press the Transform button again to retry.", "Local Northing (Y)"); return; } if (!Double.TryParse(sGridX, out dGridX)) { MessageBox.Show("Grid Easting (X) must be a number." + Environment.NewLine + "Press the Transform button again to retry.", "Grid Easting (X)"); return; } if (!Double.TryParse(sGridY, out dGridY)) { MessageBox.Show("Grid Northing (Y) must be a number." + Environment.NewLine + "Press the Transform button again to retry.", "Grid Northing (Y)"); return; } if (!Double.TryParse(sScaleFactor, out dScaleFactor)) { MessageBox.Show("Scale Factor must be a number." + Environment.NewLine + "Press the Transform button again to retry.", "Scale Factor"); return; } if (dScaleFactor <= 0) { MessageBox.Show("Scale Factor must be greater than zero." + Environment.NewLine + "Press the Transform button again to retry.", "Scale Factor"); return; } if (!Double.TryParse(sRotation, out dRotation)) { MessageBox.Show("Rotation must be a number." + Environment.NewLine + "Press the Transform button again to retry.", "Rotation"); return; } if (bSetGroundToGrid) { var mapView = MapView.Active; if (mapView?.Map == null) { return; } var cimG2G = await mapView.Map.GetGroundToGridCorrection(); if (cimG2G == null) { cimG2G = new CIMGroundToGridCorrection(); } cimG2G.UseScale = true; cimG2G.ScaleType = GroundToGridScaleType.ConstantFactor; cimG2G.ConstantScaleFactor = dScaleFactor; cimG2G.UseDirection = true; //use direction offset cimG2G.Direction = dRotation; //direction offset angle cimG2G.Enabled = true; //turn ground to grid ON await mapView.Map.SetGroundToGridCorrection(cimG2G); } } else { // Canceled from dialog bCancel = true; return; } } finally { transformationDlg = null; if (!bCancel) { TransformCADDialog.Default["LastUsedParams"] = sLastUsedParams; TransformCADDialog.Default.Save(); //comment out if you only want to save settings within each app session } } #endregion var pFrom1 = new Coordinate2D(dOriginX, dOriginY); var pTo1 = new Coordinate2D(dGridX, dGridY); var dDeltaX = dGridX - dOriginX; var dDeltaY = dGridY - dOriginY; var pFrom2 = new Coordinate2D(pFrom1.X + (10000 / dMetersPerUnit), pFrom1.Y + (10000 / dMetersPerUnit)); var Rotated = GeometryEngine.Instance.Rotate(pFrom2.ToMapPoint(), pFrom1.ToMapPoint(), dRotation * Math.PI / 180); MapPoint RotatedAndScaled = (MapPoint)GeometryEngine.Instance.Scale(Rotated, pFrom1.ToMapPoint(), dScaleFactor, dScaleFactor); var RotatedScaledTranslated = new Coordinate2D(RotatedAndScaled.X + dDeltaX, RotatedAndScaled.Y + dDeltaY); if (WriteWorldFile(sTargetWldFile, pFrom1, pTo1, pFrom2, RotatedScaledTranslated)) { if (fcSR.IsUnknown && MapView.Active.Map.SpatialReference.IsProjected) {//if .prj is unknown use the active map's projection for the CAD file. fcSR = MapView.Active.Map.SpatialReference; } CancelableProgressorSource cps = new CancelableProgressorSource("Define Projection", "Canceled"); int numSecondsDelay = 5; bool bContinue = true; //The following code re-assigns or assigns the projection so that the CAD layer //can be redrawn in the correct location using the .wld file. await QueuedTask.Run(async() => { cps.Progressor.Max = (uint)numSecondsDelay; //check every second cps.Progressor.Value += 1; cps.Progressor.Message = "Creating and applying world file..."; await DefineProjectionAsync(CadFileName, fcSR, cps); bContinue = !cps.Progressor.CancellationToken.IsCancellationRequested; if (CADLayer.Parent is Layer) { MapView.Active.ZoomTo(CADLayer.Parent as GroupLayer); //Invalidate the layer to refresh display MapView.Active.Invalidate(CADLayer.Parent as GroupLayer, MapView.Active.Extent); } else { MapView.Active.ZoomTo(CADLayer as Layer); MapView.Active.Invalidate(CADLayer as Layer, MapView.Active.Extent); } }, cps.Progressor); if (!bContinue) { return; } } else { MessageBox.Show("The world file could not be created.", "Transform"); return; } }
public async void CreateNewFeatureAsync(object parameter) { string message = String.Empty; bool creationResult = false; //Generate geometry if polygon or polyline, if adding new feature is from using coordinates and not the map tool if (Convert.ToBoolean(parameter) == true) { if (GeometryType == GeometryType.Polyline || GeometryType == GeometryType.Polygon) { GeneratePolyGeometry(); } } IEnumerable <GDBProjectItem> gdbProjectItems = Project.Current.GetItems <GDBProjectItem>(); await QueuedTask.Run(() => { foreach (GDBProjectItem gdbProjectItem in gdbProjectItems) { using (Datastore datastore = gdbProjectItem.GetDatastore()) { //Unsupported datastores (non File GDB and non Enterprise GDB) will be of type UnknownDatastore if (datastore is UnknownDatastore) { continue; } Geodatabase geodatabase = datastore as Geodatabase; // Use the geodatabase. string geodatabasePath = geodatabase.GetPath(); if (geodatabasePath.Contains(ProSymbolEditorModule.WorkspaceString)) { //Correct GDB, open the current selected feature class FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(_currentFeatureClassName); using (featureClass) using (FeatureClassDefinition facilitySiteDefinition = featureClass.GetDefinition()) { EditOperation editOperation = new EditOperation(); editOperation.Name = "Military Symbol Insert"; editOperation.Callback(context => { try { RowBuffer rowBuffer = featureClass.CreateRowBuffer(); _symbolAttributeSet.PopulateRowBufferWithAttributes(ref rowBuffer); rowBuffer["Shape"] = GeometryEngine.Project(MapGeometry, facilitySiteDefinition.GetSpatialReference()); Feature feature = featureClass.CreateRow(rowBuffer); feature.Store(); //To Indicate that the attribute table has to be updated context.Invalidate(feature); } catch (GeodatabaseException geodatabaseException) { message = geodatabaseException.Message; } }, featureClass); var task = editOperation.ExecuteAsync(); creationResult = task.Result; if (!creationResult) { message = editOperation.ErrorMessage; } break; } } } } }); if (!creationResult) { MessageBox.Show(message); } }
protected async override void OnClick() { // get the feature layer that's selected in the table of contents var selectedLayers = MapView.Active.GetSelectedLayers(); var CADLayer = selectedLayers.OfType <FeatureLayer>().FirstOrDefault() as FeatureLayer; if (CADLayer == null) { System.Windows.MessageBox.Show("Please select the CAD layer in the table of contents", "Layer Grid Scale"); return; } double dMetersPerUnit = 1; string CadFeatClassNameForSelectedLayer = ""; //Run on MCT bool isValid = await QueuedTask.Run(() => { var CADFeatClass = CADLayer.GetFeatureClass(); var FilePathConnX = CADFeatClass.GetDatastore(); string sCADFilePath = FilePathConnX.GetConnectionString(); sCADFilePath = sCADFilePath.Replace("DATABASE=", ""); var FeatDS = CADFeatClass.GetFeatureDataset(); string CadFileName = System.IO.Path.Combine(sCADFilePath, FeatDS.GetName()); string fileExtension = System.IO.Path.GetExtension(CadFileName); fileExtension = fileExtension.ToLower(); string sTargetFileName = System.IO.Path.GetFileNameWithoutExtension(CadFileName); sTargetFile = System.IO.Path.Combine(sCADFilePath, sTargetFileName + ".wld"); //get name for layer string FCName = CADFeatClass.GetName(); CadFeatClassNameForSelectedLayer = System.IO.Path.Combine(CadFileName, FCName); FeatureClassDefinition CADFeatClassDef = CADFeatClass.GetDefinition(); var fcSR = CADFeatClassDef.GetSpatialReference(); if (fcSR.IsProjected) { dMetersPerUnit = fcSR.Unit.ConversionFactor; //meters per unit } bool bIsCAD = (fileExtension == ".dwg" || fileExtension == ".dgn" || fileExtension == ".dxf"); // zoom to the layer MapView.Active.ZoomTo(CADLayer); //Layer's ZoomTo extent is used to get a good reference point later return(bIsCAD & !fcSR.IsGeographic); //The addin requires that the CAD data is not in geographic coordinates }); // if not a valid CAD file if (!isValid) { System.Windows.MessageBox.Show("Please select the CAD layer in the table of contents." + Environment.NewLine + "CAD data in a geographic coordinate system is not supported.", "Scale CAD Layer"); return; } // get the scale from the user double dScaleFactor = 1.0000; var sf = new ScaleFactorInput(); sf.Owner = FrameworkApplication.Current.MainWindow; try { if (sf.ShowDialog() == true) { string sScaleFactor = sf.ScaleFactor.Text; if (!Double.TryParse(sScaleFactor, out dScaleFactor)) { MessageBox.Show("Please type a number", "Grid Scale"); return; } } else { // cancelled from dialog return; } } finally { sf = null; } //use the layer's ZoomTo extent to get the approximate location of the CAD file for the reference point var dataReferencePoint = (Coordinate2D)MapView.Active.Extent.Center; //this is sufficient for the reference point var secondPoint = new Coordinate2D(dataReferencePoint.X + (100 / dMetersPerUnit), dataReferencePoint.Y + (100 / dMetersPerUnit)); var dataReferencePointScaled = new Coordinate2D(dataReferencePoint.X * dScaleFactor, dataReferencePoint.Y * dScaleFactor); var SecondPointScaled = new Coordinate2D(secondPoint.X * dScaleFactor, secondPoint.Y * dScaleFactor); if (WriteWorldFile(sTargetFile, dataReferencePoint, secondPoint, dataReferencePointScaled, SecondPointScaled)) { await QueuedTask.Run(() => { //Remove and then re-add layer //remove layer var map = MapView.Active.Map; map.RemoveLayer(CADLayer.Parent as GroupLayer); var featureClassUri = new Uri(CadFeatClassNameForSelectedLayer); //Define the Feature Layer's parameters. var layerParams = new FeatureLayerCreationParams(featureClassUri) { //Set visibility IsVisible = true, }; var createdCadLayer = LayerFactory.Instance.CreateLayer <FeatureLayer>(layerParams, MapView.Active.Map); MapView.Active.ZoomTo(CADLayer); //ZoomTo the updated extent }); } else { MessageBox.Show("The world file could not be created.", "Grid Scale"); return; } }