public async Task UpdateFeatureAsync(long uid, Geometry geometry) { await QueuedTask.Run(() => { using (FeatureClass featureClass = Layer.GetFeatureClass()) { FeatureClassDefinition definition = featureClass?.GetDefinition(); string objectIdField = definition?.GetObjectIDField(); QueryFilter filter = new QueryFilter { WhereClause = $"{objectIdField} = {uid}" }; using (RowCursor existsResult = featureClass?.Search(filter, false)) { while (existsResult?.MoveNext() ?? false) { using (Row row = existsResult.Current) { Feature feature = row as Feature; feature?.SetShape(geometry); feature?.Store(); } } } } }); }
private ObservableCollection <string> GetAllCourse() { var task = QueuedTask.Run(() => { ObservableCollection <string> result = new ObservableCollection <string>(); using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { using (FeatureClass course = geodatabase.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_Course)) { using (RowCursor rowCursor = course.Search(null, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { result.Add(row.GetObjectID().ToString()); } } } } } return(result); }); return(task.Result); }
public override DateTime?GetDate() { DateTime? result = null; const string objectId = "RecordedAt"; IActiveView activeView = ArcUtils.ActiveView; IEnvelope envelope = activeView.Extent; ISpatialFilter spatialFilter = new SpatialFilterClass { Geometry = envelope, GeometryField = FeatureClass.ShapeFieldName, SpatialRel = esriSpatialRelEnum.esriSpatialRelContains, SubFields = objectId }; var existsResult = FeatureClass.Search(spatialFilter, false); IFeature feature = existsResult.NextFeature(); if (feature != null) { // ReSharper disable UseIndexedProperty int imId = existsResult.FindField(objectId); object value = feature.get_Value(imId); result = (DateTime)value; // ReSharper restore UseIndexedProperty } return(result); }
private void GetFeaturesAndAddAttachment() { // TODO // open the file geodatabase c:\ProSDKWorkshop\data\generic.gdb using (Geodatabase geodatabase = new Geodatabase(@"c:\ProSDKWorkshop\data\generic.gdb")) { using (FeatureClass pointFeatureClass = geodatabase.OpenDataset <FeatureClass>("SamplePoints")) { using (RowCursor features = pointFeatureClass.Search()) { while (features.MoveNext()) { Feature currentFeature = features.Current as Feature; currentFeature.AddAttachment(new Attachment("SamplePicture", "image/png", CreateMemoryStreamFromContentsOf(@"C:\ProSDKWorkshop\data\redlands.png"))); } } } } // TODO // open the SamplePoints feature class // TODO // retrieve all features by searching the feature class // TODO // for each feature add the attachment // TODO // add the sample picture as an attachment // add the feature class as a layer to the active map LayerFactory.CreateFeatureLayer(new Uri(@"c:\ProSDKWorkshop\data\generic.gdb\SamplePoints"), MapView.Active.Map); }
/// <summary> /// Calculate viewpoints along a vector line, e.g. road, path. /// </summary> /// <param name="gdbPath">Path to GDB</param> /// <param name="featureClassName">Feature class</param> /// <returns>Viewpoints</returns> private HashSet <SpatialUtils.ViewpointProps> GetLine(String gdbPath, String featureClassName) { HashSet <SpatialUtils.ViewpointProps> result = new HashSet <SpatialUtils.ViewpointProps>(); //using hash set to prevent duplicates, possible speed up with array using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(gdbPath)))) using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName)) { QueryFilter queryFilter = new QueryFilter { SubFields = "POINT_X, POINT_Y, ORIG_FID", PostfixClause = "ORDER BY ORIG_FID" }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { double previousX = Double.NaN; double previousY = Double.NaN; int previousFid = Int32.MinValue; while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { double pointX = Convert.ToDouble(row["POINT_X"]); double pointY = Convert.ToDouble(row["POINT_Y"]); int fid = Convert.ToInt32(row["ORIG_FID"]); if (fid == previousFid) { double length = Math.Sqrt(Math.Pow(pointX - previousX, 2) + Math.Pow(pointY - previousY, 2)); int steps = (int)Math.Floor(length / stepLength); double xStep = (pointX - previousX) / steps; double yStep = (pointY - previousY) / steps; for (int i = 0; i <= steps; i++) { Tuple <int, int> point = inputRaster.MapToPixel(previousX + xStep * i, previousY + yStep * i); result.Add(new SpatialUtils.ViewpointProps() { X = point.Item1, Y = point.Item2 }); } } else if (previousFid != Int32.MinValue) //endpoint { Tuple <int, int> point = inputRaster.MapToPixel(previousX, previousY); result.Add(new SpatialUtils.ViewpointProps() { X = point.Item1, Y = point.Item2 }); } previousX = pointX; previousY = pointY; previousFid = fid; } } } } return(result); }
/// <summary> /// Illustrates how to use the HasValueChanged() method. /// </summary> /// <returns></returns> private static async Task FileGeodatabaseWorkFlow() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("PollingPlace")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter queryFilter = new QueryFilter { WhereClause = "FULLADD LIKE '///%Lily Cache Ln///%'" }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition(); int shapeFieldIndex = featureClassDefinition.FindField(featureClassDefinition.GetShapeField()); while (rowCursor.MoveNext()) { using (Feature feature = (Feature)rowCursor.Current) { MapPoint mapPoint = feature.GetShape() as MapPoint; // Will be false. bool beforeChange = feature.HasValueChanged(shapeFieldIndex); // In order to update the Map and/or the attribute table. // Has to be called before any changes are made to the row context.Invalidate(feature); MapPoint newShape = new MapPointBuilder(mapPoint.X + 10, mapPoint.Y, mapPoint.SpatialReference).ToGeometry(); feature.SetShape(newShape); // Will be true. bool afterChange = feature.HasValueChanged(shapeFieldIndex); feature.Store(); //Will be false. bool afterStore = feature.HasValueChanged(shapeFieldIndex); // Has to be called after the store too context.Invalidate(feature); } } } }, featureClass); bool editResult = editOperation.Execute(); //This is required to persist the changes to the disk. bool saveResult = await Project.Current.SaveEditsAsync(); } }
private async Task ProcessAsync() { await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { IList <Layer> listLayers = MapView.Active.Map.GetLayersAsFlattenedList().ToList(); FeatureLayer l_ownShip = listLayers.First(l => l.Name == ConstDefintion.ConstLayer_OwnShipLayerName) as FeatureLayer; FeatureLayer l_targetShip = listLayers.First(l => l.Name == ConstDefintion.ConstLayer_TargetShipLayerName) as FeatureLayer; FeatureClass fc_ownShip = l_ownShip.GetFeatureClass(); FeatureClass fc_targetShip = l_targetShip.GetFeatureClass(); Feature f_ownShip; //获取本船的Feature QueryFilter qf = new QueryFilter() { ObjectIDs = new List <long>() { 1 } }; RowCursor rowCursor1 = fc_ownShip.Search(qf, false); rowCursor1.MoveNext(); Row row1 = rowCursor1.Current; f_ownShip = row1 as Feature; MapPoint p_ownship = f_ownShip.GetShape() as MapPoint; IList <MapPoint> points = new List <MapPoint>(); points.Add(CreateTargetShipPoint(p_ownship, -2, 6)); points.Add(CreateTargetShipPoint(p_ownship, 2, 6)); points.Add(CreateTargetShipPoint(p_ownship, -2, 2)); points.Add(CreateTargetShipPoint(p_ownship, 2, 2)); points.Add(CreateTargetShipPoint(p_ownship, -3, 1)); points.Add(CreateTargetShipPoint(p_ownship, 3, 1)); points.Add(CreateTargetShipPoint(p_ownship, -3, 5)); points.Add(CreateTargetShipPoint(p_ownship, 3, 5)); using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { foreach (MapPoint point in points) { gdb.ApplyEdits(() => { using (RowBuffer rowBuffer = fc_targetShip.CreateRowBuffer()) { rowBuffer["Shape"] = point; using (Feature feature = fc_targetShip.CreateRow(rowBuffer)) { feature.Store(); } } }); } } }); }
/// <summary> /// Goes to the next feature if applicable. A bool can be set if you want to keep the current scale or not /// </summary> /// <param name="featureLayer"></param> /// <param name="KeepScale"></param> public async void GoToNext(Layer featureLayer, bool KeepScale) { var basicfeaturelayer = _selectedLayer as BasicFeatureLayer; QueryFilter queryfilter = new QueryFilter(); queryfilter.WhereClause = InpsectorFieldName + " IS NULL"; try { await QueuedTask.Run(() => { basicfeaturelayer.ClearSelection(); FeatureClass featureclass = Utilities.ProUtilities.LayerToFeatureClass(_selectedLayer); using (RowCursor cursor = featureclass.Search(queryfilter, false)) { while (cursor.MoveNext()) { using (Feature feature = (Feature)cursor.Current) { var shape = feature.GetShape() as Geometry; Envelope envelope = shape.Extent; envelope.Expand(5, 5, true); if (!KeepScale) { MapView.Active.ZoomTo(envelope, null, false); } else { MapView.Active.PanTo(shape); // Okay, Scale implementation } // Get The Next Feature IReadOnlyDictionary <MapMember, List <long> > NextFeature = new Dictionary <MapMember, List <long> > { { _selectedLayer, new List <long> { feature.GetObjectID() } } }; _selectedMap.SetSelection(NextFeature, SelectionCombinationMethod.New); //queryfilter.WhereClause = "= " + feature.GetObjectID().ToString(); // _selectedLayer.Select(queryfilter, SelectionCombinationMethod.New); return; } } } }); } catch (Exception ex) { MessageBox.Show("Error: " + ex.Message); } }
public string GetFeatureFromPoint(int x, int y) { string result = string.Empty; IActiveView activeView = ArcUtils.ActiveView; if ((activeView != null) && InsideScale) { IMappedFeature mapFeature = CreateMappedFeature(null); string objectId = mapFeature.ObjectId; IScreenDisplay screenDisplay = activeView.ScreenDisplay; IDisplayTransformation dispTrans = screenDisplay.DisplayTransformation; IPoint pointLu = dispTrans.ToMapPoint(x - SizeLayer, y - SizeLayer); IPoint pointRd = dispTrans.ToMapPoint(x + SizeLayer, y + SizeLayer); IEnvelope envelope = new EnvelopeClass { XMin = pointLu.X, XMax = pointRd.X, YMin = pointLu.Y, YMax = pointRd.Y, SpatialReference = ArcUtils.SpatialReference }; envelope.Project(SpatialReference); ISpatialFilter spatialFilter = new SpatialFilterClass { Geometry = envelope, GeometryField = FeatureClass.ShapeFieldName, SpatialRel = esriSpatialRelEnum.esriSpatialRelContains, SubFields = objectId }; var existsResult = FeatureClass.Search(spatialFilter, false); IFeature feature; // ReSharper disable UseIndexedProperty while ((feature = existsResult.NextFeature()) != null) { int imId = existsResult.FindField(objectId); result = (string)feature.get_Value(imId); } // ReSharper restore UseIndexedProperty } return(result); }
public override double GetHeight(double x, double y) { double result = 0.0; IActiveView activeView = ArcUtils.ActiveView; if (activeView != null) { const string height = "Height"; const string groundLevelOffset = "GroundLevelOffset"; const double searchBox = 25.0; double xMin = x - searchBox; double xMax = x + searchBox; double yMin = y - searchBox; double yMax = y + searchBox; IEnvelope envelope = new EnvelopeClass { XMin = xMin, XMax = xMax, YMin = yMin, YMax = yMax }; ISpatialFilter spatialFilter = new SpatialFilterClass { Geometry = envelope, GeometryField = FeatureClass.ShapeFieldName, SpatialRel = esriSpatialRelEnum.esriSpatialRelContains, SubFields = string.Format("{0},{1}", height, groundLevelOffset) }; var existsResult = FeatureClass.Search(spatialFilter, false); IFeature feature; int count = 0; // ReSharper disable UseIndexedProperty while ((feature = existsResult.NextFeature()) != null) { int heightId = existsResult.FindField(height); int groundLevelOffsetId = existsResult.FindField(groundLevelOffset); var heightValue = (double)feature.get_Value(heightId); var groundLevelOffsetValue = (double)feature.get_Value(groundLevelOffsetId); result = result + heightValue - groundLevelOffsetValue; count++; } result = result / Math.Max(count, 1); // ReSharper restore UseIndexedProperty } return(result); }
public IFeature GetFeature(string imageId) { IMappedFeature mappedFeature = CreateMappedFeature(null); var fields = mappedFeature.Fields; string shapeFieldName = mappedFeature.ShapeFieldName; IQueryFilter filter = new QueryFilterClass { WhereClause = string.Format("ImageId = '{0}'", imageId), SubFields = string.Format("{0}, {1}", fields.Aggregate("ObjectId", (current, field) => string.Format ("{0}{1}{2}", current, string.IsNullOrEmpty(current) ? string.Empty : ", ", field.Key)), shapeFieldName) }; var existsResult = FeatureClass.Search(filter, false); return(existsResult.NextFeature()); }
private static Feature GetFeature(Geodatabase geodatabase, string featureClassName, long objectID) { using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName)) { QueryFilter queryFilter = new QueryFilter() { ObjectIDs = new List <long>() { objectID } }; using (RowCursor cursor = featureClass.Search(queryFilter)) { System.Diagnostics.Debug.Assert(cursor.MoveNext()); return((Feature)cursor.Current); } } }
private void SaveOwnShip() { if (CheckCanSave()) { var task = QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { FeatureClass ownShip = geodatabase.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_OwnShip); string shapeField = ownShip.GetDefinition().GetShapeField(); QueryFilter qf = new QueryFilter() { ObjectIDs = new List <long>() { 1 } }; geodatabase.ApplyEdits(() => { using (RowCursor rowCursor = ownShip.Search(qf, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { row[ConstDefintion.ConstFieldName_sog] = double.Parse(sog); row[ConstDefintion.ConstFieldName_cog] = double.Parse(cog); row[ConstDefintion.ConstFieldName_length] = double.Parse(length); row[ConstDefintion.ConstFieldName_width] = double.Parse(width); MapPoint p = MapPointBuilder.CreateMapPoint(double.Parse(locationX), double.Parse(locationY), 0, SpatialReferenceBuilder.CreateSpatialReference(4326)); MapPoint p_project = GeometryEngine.Instance.Project(p, SpatialReferenceBuilder.CreateSpatialReference(3857)) as MapPoint; row[shapeField] = p_project as ArcGIS.Core.Geometry.Geometry; row.Store(); } } } }); } }); task.Wait(); } }
/// <summary> /// workaround to get sum from enterprise gdb lenght/area fields /// see https://community.esri.com/message/889796-problem-using-shapestlength-field-in-the-calculatestatistics-method /// </summary> /// <param name="fc">feature class to get sum from</param> /// <param name="fieldName">fieldname to sum up</param> /// <returns>sum</returns> public static double GetSumWorkAround(FeatureClass fc, string fieldName) { try { using (FeatureClassDefinition fcd = fc.GetDefinition()) { double totalLen = 0.0; var cur = fc.Search(); while (cur.MoveNext()) { var feat = cur.Current; totalLen += Convert.ToDouble(feat[fieldName]); } return(totalLen); } } catch (Exception) { throw; } }
/// <summary> /// Get a RowCursor of the source /// </summary> /// <param name="Source">Feature class source</param> /// <param name="SearchGuid">Guid list</param> /// <param name="ListSearchFields">Searched field list</param> /// <param name="WhereField">Guid field name in where clause</param> /// <param name="FieldsName">Qualified field name list</param> /// <returns>RowCursor</returns> internal static RowCursor GetRowCursorFromFeatureClassAndGuidList(FeatureClass Source, List <Guid> SearchGuid, List <string> ListSearchFields, string WhereField, out List <Tuple <string, string> > FieldsName) { InitializeFields(TableFields: Source.GetDefinition().GetFields(), ListSearchFields: ListSearchFields, WhereField: WhereField, FieldsName: out FieldsName, ListFieldName: out string ListFieldName, SearchField: out string SearchField); List <string> stringGuids = FormatGuidToString(SearchGuid); StringBuilder sb = new StringBuilder(); foreach (string se in stringGuids) { sb.AppendFormat("{0} IN ({1}) OR ", SearchField, se); } string s = sb.ToString(); QueryFilter query = new QueryFilter() { SubFields = ListFieldName, WhereClause = s.Substring(0, s.Length - 4) }; return(Source.Search(query)); }
public IMappedFeature GetLocationInfo(string imageId) { IMappedFeature result = CreateMappedFeature(null); var fields = result.Fields; string shapeFieldName = result.ShapeFieldName; IQueryFilter filter = new QueryFilterClass { WhereClause = string.Format("ImageId = '{0}'", imageId), SubFields = string.Format("{0}, {1}", fields.Aggregate(string.Empty, (current, field) => string.Format ("{0}{1}{2}", current, string.IsNullOrEmpty(current) ? string.Empty : ", ", field.Key)), shapeFieldName) }; var existsResult = FeatureClass.Search(filter, false); IFeature feature = existsResult.NextFeature(); // ReSharper disable UseIndexedProperty if (feature != null) { foreach (var field in fields) { string name = field.Key; int nameId = existsResult.FindField(name); object item = feature.get_Value(nameId); result.UpdateItem(name, item); } var point = feature.Shape as IPoint; result.UpdateItem(shapeFieldName, point); } else { result = null; } // ReSharper restore UseIndexedProperty return(result); }
public void LoadFromFeatureClass(string layoutName, FeatureClass featureClass, string fieldList) { MapSeriesItems.Clear(); var oidName = featureClass.GetDefinition().GetObjectIDField(); QueryFilter getQf = new QueryFilter { SubFields = $@"{oidName},{fieldList}" }; var fields = fieldList.Split(new char [] { ',' }); if (fields.Length < 2) { throw new Exception($@"List of fields {fieldList} needs to contain at least ID and Name"); } // For Selecting all matching entries. using (var rowCursor = featureClass.Search(getQf)) { var oidIdx = rowCursor.FindField(oidName); var idIdx = rowCursor.FindField(fields[0]); var nameIdx = rowCursor.FindField(fields[1]); while (rowCursor.MoveNext()) { using (var row = rowCursor.Current) { var oid = Convert.ToInt64(row[oidIdx]); var id = Convert.ToInt32(row[idIdx]); var name = row[nameIdx].ToString(); if (string.IsNullOrEmpty(layoutName)) { MessageBox.Show("test"); } MapSeriesItems.Add(new MapSeriesItem { Oid = oid, Id = id, Name = name, LayoutName = layoutName }); } } } }
private void GetOwnShip() { var task = QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { FeatureClass ownShip = geodatabase.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_OwnShip); string shapeField = ownShip.GetDefinition().GetShapeField(); QueryFilter qf = new QueryFilter() { ObjectIDs = new List <long>() { 1 } }; using (RowCursor rowCursor = ownShip.Search(qf, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { sog = row[ConstDefintion.ConstFieldName_sog].ToString(); cog = row[ConstDefintion.ConstFieldName_cog].ToString(); length = row[ConstDefintion.ConstFieldName_length].ToString(); width = row[ConstDefintion.ConstFieldName_width].ToString(); ArcGIS.Core.Geometry.Geometry geometry = row[shapeField] as ArcGIS.Core.Geometry.Geometry; MapPoint p = geometry as MapPoint; MapPoint p_project = GeometryEngine.Instance.Project(p, SpatialReferenceBuilder.CreateSpatialReference(4326)) as MapPoint; locationX = p_project.X.ToString("0.0000"); locationY = p_project.Y.ToString("0.0000"); } } } } }); task.Wait(); }
private static void RiskAssessment(Geodatabase gdb, FeatureClass keyPoints, string maskPoint, double risk) { FeatureClass voyageMaskPoint = gdb.OpenDataset <FeatureClass>(maskPoint); using (RowCursor rowCursor = voyageMaskPoint.Search(null, false)) { while (rowCursor.MoveNext()) { using (Feature f = rowCursor.Current as Feature) { using (RowBuffer rowBuffer = keyPoints.CreateRowBuffer()) { rowBuffer[ConstDefintion.ConstFieldName_ddv] = risk; rowBuffer[ConstDefintion.ConstFieldName_Shape] = f.GetShape(); using (Feature feature = keyPoints.CreateRow(rowBuffer)) { feature.Store(); } } } } } }
/// <summary> /// GetStartingPointRow /// /// This routine opens up the starting points table and tries to read a row. This table is created in /// the default project workspace when the user first creates a starting point. /// /// If the table doesn't exist or is empty, we add an error to our results object a null row. /// If the table contains one row, we just return the row /// If the table contains more than one row, we return the first row, and log a warning message /// (this tool only works with one starting point) /// /// </summary> private Row GetStartingPointRow(Geodatabase defaultGeodatabase, ref LoadTraceResults results) { try { using (FeatureClass startingPointsFeatureClass = defaultGeodatabase.OpenDataset <FeatureClass>(StartingPointsTableName)) using (RowCursor startingPointsCursor = startingPointsFeatureClass.Search()) { if (startingPointsCursor.MoveNext()) { Row row = startingPointsCursor.Current; if (startingPointsCursor.MoveNext()) { // If starting points table has more than one row, append warning message results.Message += "Multiple starting points found. Only the first one was used."; startingPointsCursor.Current.Dispose(); } return(row); } else { // If starting points table has no rows, exit with error message results.Message += "No starting points found. Please create one using the Set Trace Locations tool.\n"; results.Success = false; return(null); } } } // If we cannot open the feature class, an exception is thrown catch (Exception) { results.Message += "No starting points found. Please create one using the Set Trace Locations tool.\n"; results.Success = false; return(null); } }
// /// <summary> /// Illustrates deleting features from a feature class in a file geodatabase. /// </summary> /// <returns></returns> private static async Task FileGeodatabaseWorkFlow() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) { using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("PollingPlace")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter queryFilter = new QueryFilter { WhereClause = "FULLADD LIKE '///%Lily Cache Ln///%'" }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { // In order to update the Map and/or the attribute table. Has to be called before the delete context.Invalidate(row); row.Delete(); } } } }, featureClass); bool editResult = editOperation.Execute(); //This is required to persist the changes to the disk. bool saveResult = await Project.Current.SaveEditsAsync(); } } }
//private Dictionary<string, FeatureClass> GetMapLayersFeatureClassMap() //{ // Dictionary<string, FeatureClass> lyrFeatureClassMap = new Dictionary<string, FeatureClass>(); // Map map = MapView.Active.Map; // if (map == null) // return null; // var layers = map.GetLayersAsFlattenedList().OfType<FeatureLayer>(); // foreach (var lyr in layers) // { // string fc = lyr.GetFeatureClass().GetName(); // FeatureClass featureClass = _geodatabase.OpenDataset<FeatureClass>(fc); // if (featureClass != null) // lyrFeatureClassMap.Add(lyr.Name, featureClass); // } // return lyrFeatureClassMap; //} private Task <string> GetAttributeValue(FeatureClass featureClass, string fieldName, long objectId) { return(QueuedTask.Run(() => { string value = ""; try { var oidField = featureClass.GetDefinition().GetObjectIDField(); QueryFilter queryFilter = new QueryFilter { WhereClause = string.Format("({0} in ({1}))", oidField, objectId) }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { value = Convert.ToString(row[fieldName]); } } } } catch (GeodatabaseFieldException fieldException) { // One of the fields in the where clause might not exist. There are multiple ways this can be handled: // Handle error appropriately } catch (Exception exception) { // logger.Error(exception.Message); } return value; })); }
// This method assumes that the polygon feature class contains a single feature. It was written // to count the number of points within an AOI public static async Task <int> CountPointsWithinInFeatureAsync(Uri pointFeatureGdbUri, string pointFeatureName, Uri polyFeatureGdbUri, string polyFeatureName) { int retVal = 0; Geometry polyGeometry = null; await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(polyFeatureGdbUri))) { using (Table table = geodatabase.OpenDataset <Table>(polyFeatureName)) { QueryFilter queryFilter = new QueryFilter(); double maxArea = -1; // We will report the points in the largest polygon if > 1 using (RowCursor cursor = table.Search(queryFilter, false)) { while (cursor.MoveNext()) { using (Feature feature = (Feature)cursor.Current) { Geometry areaGeo = feature.GetShape(); var area = GeometryEngine.Instance.Area(areaGeo); if (area > maxArea) { maxArea = area; polyGeometry = feature.GetShape(); } } } } } } if (polyGeometry != null) { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(pointFeatureGdbUri))) { bool bExists = false; IReadOnlyList <FeatureClassDefinition> definitions = geodatabase.GetDefinitions <FeatureClassDefinition>(); foreach (FeatureClassDefinition def in definitions) { if (def.GetName().Equals(pointFeatureName) || def.GetAliasName().Equals(pointFeatureName)) { bExists = true; break; } } if (bExists) { using (FeatureClass pointFeatureClass = geodatabase.OpenDataset <FeatureClass>(pointFeatureName)) { // Using a spatial query filter to find all features which have a certain district name and lying within a given Polygon. SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter { FilterGeometry = polyGeometry, SpatialRelationship = SpatialRelationship.Contains }; using (RowCursor aCursor = pointFeatureClass.Search(spatialQueryFilter, false)) { while (aCursor.MoveNext()) { using (Feature feature = (Feature)aCursor.Current) { retVal++; } } } } } else { Module1.Current.ModuleLogManager.LogError(nameof(CountPointsWithinInFeatureAsync), "Unable to locate point class " + pointFeatureName); } } } }); return(retVal); }
public async Task MainMethodCode() { // Opening a Non-Versioned SQL Server instance. DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. Instance = @"testMachine\testInstance", // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. Database = "LocalGovernment", // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. User = "******", Password = "******", Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) using (RelationshipClass relationshipClass = geodatabase.OpenDataset <RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections")) using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.luCodeViolation")) { List <Row> jeffersonAveViolations = new List <Row>(); QueryFilter queryFilter = new QueryFilter { WhereClause = "LOCDESC LIKE '///%Jefferson///%'" }; // If you need to *cache* the rows retrieved from the cursor for processing later, it is important that you don't use recycling in // the Search() method (i.e., useRecyclingCursor must be set to *false*). Also, the returned rows/features cached in the list // should be disposed when no longer in use so that unmanaged resources are not held on to longer than necessary. using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { jeffersonAveViolations.Add(rowCursor.Current); } } foreach (Row jeffersoneAveViolation in jeffersonAveViolations) { IReadOnlyList <Row> relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(new List <long> { jeffersoneAveViolation.GetObjectID() }); try { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { foreach (Row relatedDestinationRow in relatedDestinationRows) { try { relationshipClass.DeleteRelationship(jeffersoneAveViolation, relatedDestinationRow); } catch (GeodatabaseRelationshipClassException exception) { Console.WriteLine(exception); } } }, relationshipClass); bool editResult = editOperation.Execute(); } finally { Dispose(relatedDestinationRows); } } try { // If the table is non-versioned this is a no-op. If it is versioned, we need the Save to be done for the edits to be persisted. bool saveResult = await Project.Current.SaveEditsAsync(); } finally { Dispose(jeffersonAveViolations); } } }
public async static void CreatePolygonExpantion() { await QueuedTask.Run(() => { using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath)))) { gdb.ApplyEdits(() => { using (FeatureClass fcStaticObstructPolygon = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_StaticObstructPolygon)) { FeatureClassDefinition fcdStaticObstructPoint = gdb.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_StaticObstructPolygon); FeatureClass fcSOPBuffer = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPBuffer); FeatureClass fc_SOPIDEPoint = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPIDEPoint); fc_SOPIDEPoint.DeleteRows(new QueryFilter() { WhereClause = "OBJECTID >= 1" }); using (RowCursor rc = fcStaticObstructPolygon.Search(null, false)) { while (rc.MoveNext()) { using (Feature f = rc.Current as Feature) { int affectDis = Convert.ToInt32(f[ConstDefintion.ConstFieldName_AffectDis]); double affectDegree = (double)f[ConstDefintion.ConstFieldName_AffectDegree]; MapPoint p = f[fcdStaticObstructPoint.GetShapeField()] as MapPoint; GeodesicEllipseParameter geodesic = new GeodesicEllipseParameter() { Center = p.Coordinate2D, SemiAxis1Length = affectDis, SemiAxis2Length = affectDis, LinearUnit = LinearUnit.Meters, OutGeometryType = GeometryType.Polygon, AxisDirection = 0, VertexCount = 800 }; Geometry circle = GeometryEngine.Instance.GeodesicEllipse(geodesic, SpatialReferenceBuilder.CreateSpatialReference(3857)); using (RowBuffer rowBuffer = fcSOPBuffer.CreateRowBuffer()) { // Either the field index or the field name can be used in the indexer. rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = 0; rowBuffer["Shape"] = circle; using (Feature feature = fcSOPBuffer.CreateRow(rowBuffer)) { feature.Store(); } } using (RowBuffer rowBuffer = fc_SOPIDEPoint.CreateRowBuffer()) { // Either the field index or the field name can be used in the indexer. rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = affectDegree; rowBuffer["Shape"] = p; using (Feature feature = fc_SOPIDEPoint.CreateRow(rowBuffer)) { feature.Store(); } } } } } } }); } }); }
//private Dictionary<string, FeatureClass> GetMapLayersFeatureClassMap() //{ // Dictionary<string, FeatureClass> lyrFeatureClassMap = new Dictionary<string, FeatureClass>(); // Map map = MapView.Active.Map; // if (map == null) // return null; // var layers = map.GetLayersAsFlattenedList().OfType<FeatureLayer>(); // foreach (var lyr in layers) // { // string fc = lyr.GetFeatureClass().GetName(); // FeatureClass featureClass = _geodatabase.OpenDataset<FeatureClass>(fc); // if (featureClass != null) // lyrFeatureClassMap.Add(lyr.Name, featureClass); // } // return lyrFeatureClassMap; //} private Task<string> GetAttributeValue(FeatureClass featureClass, string fieldName, long objectId) { return QueuedTask.Run(() => { string value = ""; try { var oidField = featureClass.GetDefinition().GetObjectIDField(); QueryFilter queryFilter = new QueryFilter { WhereClause = string.Format("({0} in ({1}))", oidField, objectId) }; using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) { while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { value = Convert.ToString(row[fieldName]); } } } } catch (GeodatabaseFieldException ) { // One of the fields in the where clause might not exist. There are multiple ways this can be handled: // Handle error appropriately } catch (Exception exception) { System.Diagnostics.Debug.Write(exception.Message); } return value; }); }
public void MainMethodCode() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (Table employeeTable = fileGeodatabase.OpenDataset <Table>("EmployeeInfo")) { // This will be false because the "EmployeeInfo" table is not enabled for attachments. bool attachmentEnabledStatus = employeeTable.IsAttachmentEnabled(); using (Table inspectionTable = fileGeodatabase.OpenDataset <Table>("luCodeInspection")) { QueryFilter queryFilter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" }; using (RowCursor cursor = inspectionTable.Search(queryFilter)) // Using Recycling. { // Adding some attachments to illustrate updating attachments. bool hasRow = cursor.MoveNext(); using (Row currentRow = cursor.Current) { // The contentType is the MIME type indicating the type of file attached. Attachment pngAttachment = new Attachment("ImageAttachment.png", "image/png", CreateMemoryStreamFromContentsOf("geodatabaseAttachment.png")); long firstAttachmentId = currentRow.AddAttachment(pngAttachment); // Note that updating the attachment using the same object used to add the attachment will fail with ArgumentException. try { pngAttachment.SetName("SomethingElse.png"); currentRow.UpdateAttachment(pngAttachment); } catch (ArgumentException) { //Handle exception } // One would have to first get the attachment before updating it. IReadOnlyList <Attachment> attachments = currentRow.GetAttachments(new List <long> { firstAttachmentId }); attachments[0].SetData(CreateMemoryStreamFromContentsOf("Sample.xml")); attachments[0].SetContentType("text/xml"); attachments[0].SetName("XMLFile"); currentRow.UpdateAttachment(attachments[0]); } } } } // Opening a Non-Versioned SQL Server instance. DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. Instance = @"testMachine\testInstance", // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. Database = "LocalGovernment", // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. User = "******", Password = "******", Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) using (FeatureClass landUseCaseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.LandUseCase")) { QueryFilter filter = new QueryFilter { WhereClause = "CASETYPE = 'Rezoning'" }; using (RowCursor landUseCursor = landUseCaseFeatureClass.Search(filter, false)) { while (landUseCursor.MoveNext()) { Feature rezoningUseCase = (Feature)landUseCursor.Current; IReadOnlyList <Attachment> rezoningAttachments = rezoningUseCase.GetAttachments(); foreach (Attachment rezoningAttachment in rezoningAttachments) { if (!rezoningAttachment.GetName().ToLowerInvariant().Contains("rezoning")) { rezoningAttachment.SetName(rezoningAttachment.GetName().Replace(".pdf", "Rezoning.pdf")); rezoningUseCase.UpdateAttachment(rezoningAttachment); } } } } } }
/// <summary> /// Generates File List /// </summary> private async Task GenerateFileList() { _FileList.Clear(); switch (_FileLoadingMethod) { // All Features will be Processed case EnumFileLoadingMethod.All: await QueuedTask.Run(() => { using (RowCursor cursor = _selectedFeatureLayer.GetFeatureClass().Search(null, false)) { int fieldIndex = cursor.FindField(_selectedField); while (cursor.MoveNext()) { using (Row row = cursor.Current) { String value = Convert.ToString(row.GetOriginalValue(fieldIndex)); if (!_FileList.ContainsKey(value)) { _FileList.Add(value, true); } } } } }); break; // Only Selected Features will be Processed case EnumFileLoadingMethod.Selected: await QueuedTask.Run(() => { Selection selection = _selectedFeatureLayer.GetSelection(); IReadOnlyList <long> oidset = selection.GetObjectIDs(); FeatureClass featureclass = _selectedFeatureLayer.GetFeatureClass(); using (RowCursor cursor = featureclass.Search(null, false)) { // Get Users Selected Field From Feature Class int fieldIndex = cursor.FindField(_selectedField); // TODO: Cycle through all features... This can be slow update when sdk updates while (cursor.MoveNext()) { using (Row row = cursor.Current) { long oid = row.GetObjectID(); // Check if current feature is in selected feature OID set if (oidset.Contains(oid)) { String value = Convert.ToString(row.GetOriginalValue(fieldIndex)); if (!_FileList.ContainsKey(value)) { _FileList.Add(value, true); } } } } } }); break; // Exhaust The Enumerator case EnumFileLoadingMethod.None: break; } }
public static async Task <BA_ReturnCode> UpdateFeatureAttributesAsync(Uri gdbUri, string featureClassName, QueryFilter oQueryFilter, IDictionary <string, string> dictEdits) { bool modificationResult = false; string errorMsg = ""; await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName)) { FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition(); EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { using (RowCursor rowCursor = featureClass.Search(oQueryFilter, false)) { while (rowCursor.MoveNext()) { using (Feature feature = (Feature)rowCursor.Current) { // In order to update the the attribute table has to be called before any changes are made to the row context.Invalidate(feature); // Loop through fields to update foreach (string strKey in dictEdits.Keys) { int idxRow = featureClassDefinition.FindField(strKey); if (idxRow > -1) { feature[idxRow] = dictEdits[strKey]; } } feature.Store(); // Has to be called after the store too context.Invalidate(feature); } } } }, featureClass); try { modificationResult = editOperation.Execute(); if (!modificationResult) { errorMsg = editOperation.ErrorMessage; } } catch (GeodatabaseException exObj) { errorMsg = exObj.Message; } } }); if (String.IsNullOrEmpty(errorMsg)) { await Project.Current.SaveEditsAsync(); return(BA_ReturnCode.Success); } else { if (Project.Current.HasEdits) { await Project.Current.DiscardEditsAsync(); } Module1.Current.ModuleLogManager.LogError(nameof(UpdateFeatureAttributesAsync), "Exception: " + errorMsg); return(BA_ReturnCode.UnknownError); } }
public static async Task <IList <BA_Objects.Interval> > GetUniqueSortedValuesAsync(Uri gdbUri, string featClassName, string valueFieldName, string nameFieldName, double upperBound, double lowerBound) { IList <BA_Objects.Interval> lstInterval = new List <BA_Objects.Interval>(); if (gdbUri.IsFile) { string strFolderPath = System.IO.Path.GetDirectoryName(gdbUri.LocalPath); if (System.IO.Directory.Exists(strFolderPath)) { await QueuedTask.Run(() => { //get Dictionary of unique elevations from the vector att IDictionary <String, String> dictElev = new Dictionary <String, String>(); using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featClassName)) { FeatureClassDefinition def = featureClass.GetDefinition(); int idxElev = def.FindField(valueFieldName); int idxName = def.FindField(nameFieldName); if (idxElev < 0 || idxName < 0) { Module1.Current.ModuleLogManager.LogError(nameof(GetUniqueSortedValuesAsync), "A required field was missing from " + featClassName + ". Process failed!"); return; } using (RowCursor rowCursor = featureClass.Search(new QueryFilter(), false)) { while (rowCursor.MoveNext()) { using (Feature feature = (Feature)rowCursor.Current) { string strElev = Convert.ToString(feature[idxElev]); string strName = ""; if (feature[idxName] == null) { strName = "Name missing"; } else { strName = Convert.ToString(feature[idxName]); if (String.IsNullOrEmpty(strName)) { strName = "Name missing"; } } if (dictElev.ContainsKey(strElev)) { strName = dictElev[strElev] + ", " + strName; dictElev[strElev] = strName; } else { dictElev.Add(strElev, strName); } } } } } List <double> lstValidValues = new List <double>(); int nuniquevalue = dictElev.Keys.Count; double value = -1.0F; bool bSuccess = false; foreach (var strElev in dictElev.Keys) { bSuccess = Double.TryParse(strElev, out value); if ((int)(value - 0.5) < (int)upperBound && (int)value + 0.5 > (int)lowerBound) { lstValidValues.Add(value); } else if (value > upperBound || value < lowerBound) //invalid data in the attribute field, out of bound { Module1.Current.ModuleLogManager.LogError(nameof(GetUniqueSortedValuesAsync), "WARNING!! A monitoring site is ignored in the analysis! The site's elevation (" + value + ") is outside the DEM range (" + lowerBound + ", " + upperBound + ")!"); } } //add upper and lower bnds to the dictionary if (!dictElev.ContainsKey(Convert.ToString(upperBound))) { dictElev.Add(Convert.ToString(upperBound), "Not represented"); lstValidValues.Add(upperBound); } if (!dictElev.ContainsKey(Convert.ToString(lowerBound))) { dictElev.Add(Convert.ToString(lowerBound), "Min Value"); lstValidValues.Add(lowerBound); } // Sort the list lstValidValues.Sort(); // Add lower bound to interval list for (int i = 0; i < lstValidValues.Count - 1; i++) { BA_Objects.Interval interval = new BA_Objects.Interval(); interval.Value = i + 1; interval.LowerBound = lstValidValues[i]; double nextItem = lstValidValues[i + 1]; interval.UpperBound = nextItem; interval.Name = dictElev[Convert.ToString(nextItem)]; // use the upperbnd name to represent the interval lstInterval.Add(interval); } }); } } return(lstInterval); }
public void MainMethodCode() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (Table employeeTable = fileGeodatabase.OpenDataset <Table>("EmployeeInfo")) { // This will be false because the "EmployeeInfo" table is not enabled for attachments. bool attachmentEnabledStatus = employeeTable.IsAttachmentEnabled(); using (Table inspectionTable = fileGeodatabase.OpenDataset <Table>("luCodeInspection")) { QueryFilter queryFilter = new QueryFilter { WhereClause = "ACTION = '1st Notice'" }; using (RowCursor cursor = inspectionTable.Search(queryFilter)) // Using Recycling. { // Adding some attachments to illustrate getting specific attachments. bool hasRow = cursor.MoveNext(); using (Row currentRow = cursor.Current) { // The contentType is the MIME type indicating the type of file attached. Attachment pngAttachment = new Attachment("ImageAttachment.png", "image/png", CreateMemoryStreamFromContentsOf("geodatabaseAttachment.png")); long firstAttachmentId = currentRow.AddAttachment(pngAttachment); Attachment textAttachment = new Attachment("TextAttachment.txt", "text/plain", CreateMemoryStreamFromContentsOf("Sample.txt")); long secondAttachmentId = currentRow.AddAttachment(textAttachment); IReadOnlyList <Attachment> allAttachments = currentRow.GetAttachments(); int count = allAttachments.Count; // This will be 2 provided there were no attachments before we added attachments. // This will only give the attachment object for the first attachment id. IReadOnlyList <Attachment> firstAttachmentOnlyList = currentRow.GetAttachments(new List <long> { firstAttachmentId }); // This will only give the attachment object without the Data for the second attachment id. IReadOnlyList <Attachment> secondAttachmentInfoOnlyList = currentRow.GetAttachments(new List <long> { secondAttachmentId }, true); } } } } // Opening a Non-Versioned SQL Server instance. DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer) { AuthenticationMode = AuthenticationMode.DBMS, // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance. Instance = @"testMachine\testInstance", // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database. Database = "LocalGovernment", // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions. User = "******", Password = "******", Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) using (FeatureClass landUseCaseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.LandUseCase")) { QueryFilter filter = new QueryFilter { WhereClause = "CASETYPE = 'Rezoning'" }; using (RowCursor landUseCursor = landUseCaseFeatureClass.Search(filter, false)) { List <Attachment> rezoningAttachments = new List <Attachment>(); while (landUseCursor.MoveNext()) { Feature rezoningUseCase = (Feature)landUseCursor.Current; rezoningAttachments.AddRange(rezoningUseCase.GetAttachments()); } foreach (Attachment attachment in rezoningAttachments) { // Process rezoning attachments in someway. } } } }