public async void setDomainValuesLayer(string dataset, string fieldName, string sourceTarget, bool resetUI) { List <ComboData> domain = new List <ComboData>(); await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { try { var lyr = Helpers.CreateFeatureLayer(new Uri(dataset), MapView.Active.Map); FeatureLayer flayer = lyr as FeatureLayer; ArcGIS.Core.Data.TableDefinition def = null; ArcGIS.Core.CIM.CIMDataConnection cim = flayer.GetDataConnection(); FeatureClass fclass = flayer.GetFeatureClass(); def = fclass.GetDefinition(); domain = getDomainValuesforTable(def, fieldName); } catch { raiseDomainErrorMessage(dataset, fieldName); } return; }); if (resetUI == true) { resetDomainValuesUI(domain, sourceTarget); } else { resetDomainValuesUIFromConfig(domain, sourceTarget); } return; }
public static FieldSetter ValidateTargetFields( this FieldSetter instance, FeatureClass featureClass, string parameterName) { if (instance == null) { return(null); } if (featureClass == null) { return(instance); } try { var fieldNames = featureClass.GetDefinition().GetFields().Select(f => f.Name); instance.ValidateTargetFields(fieldNames); } catch (Exception ex) { throw new InvalidConfigurationException( $"Parameter {parameterName} is invalid: {ex.Message}"); } return(instance); }
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 static void SetShape([NotNull] RowBuffer rowBuffer, [NotNull] Geometry geometry, FeatureClass featureClass) { string shapeFieldName = featureClass.GetDefinition().GetShapeField(); SetShape(rowBuffer, geometry, shapeFieldName); }
/// <summary> /// Check to make sure the enviornment is set up correctly before processing the users request /// /// </summary> /// <returns></returns> private async Task <bool> CheckRequirements() { if (_selectedMap == null) { MessageBox.Show("Select A Map In Domain Appointer Settings"); return(false); } if (_selectedLayer == null) { MessageBox.Show("Select A Layer in Domain Appointer Settings"); return(false); } if (_selectedField == null) { MessageBox.Show("Select a Field in Domain Appointer Settings"); } bool canEditData = false; await QueuedTask.Run(() => { canEditData = _selectedLayer.CanEditData(); }); if (!canEditData) { MessageBox.Show("Feature Layer '" + _selectedLayer.Name + "' Is not Editable"); return(false); } IEnumerable <Field> fields = null; await QueuedTask.Run(() => { Table table = _selectedLayer.GetTable(); if (table is FeatureClass) { FeatureClass featureclass = table as FeatureClass; using (FeatureClassDefinition def = featureclass.GetDefinition()) { fields = def.GetFields(); } } }); var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(_selectedField.ToLower())); if (match == null) { MessageBox.Show("The field '" + _selectedField + "' is Missing From '" + _selectedLayer.Name + "' Feature Layer"); return(false); } return(true); }
public static void ToGdbObjectMsgList( [NotNull] IEnumerable <Feature> features, [NotNull] ICollection <GdbObjectMsg> resultGdbObjects, [NotNull] ICollection <ObjectClassMsg> resultGdbClasses) { Stopwatch watch = null; if (_msg.IsVerboseDebugEnabled) { watch = Stopwatch.StartNew(); } var classesByClassId = new Dictionary <long, FeatureClass>(); // Optimization (in Pro, the Map SR seems to be generally equal to the FCs SR, if they match) bool omitDetailedShapeSpatialRef = true; foreach (Feature feature in features) { FeatureClass featureClass = feature.GetTable(); Geometry shape = feature.GetShape(); // NOTE: The following calls are expensive: // - Geometry.GetShape() (internally, the feature's spatial creation seems costly) // - FeatureClassDefintion.GetSpatialReference() // In case of a large feature count, they should be avoided on a per-feature basis: if (!classesByClassId.ContainsKey(featureClass.GetID())) { resultGdbClasses.Add(ToObjectClassMsg(featureClass)); classesByClassId.Add(featureClass.GetID(), featureClass); SpatialReference featureClassSpatialRef = featureClass.GetDefinition().GetSpatialReference(); if (!SpatialReference.AreEqual( featureClassSpatialRef, shape.SpatialReference, false, true)) { omitDetailedShapeSpatialRef = false; } } else { // TODO: Better solution: hash class ID with workspace handle in ToObjectClassMsg() // Make sure they are from the same workspace to avoid conflicting class ids Assert.AreEqual(classesByClassId[featureClass.GetID()].GetDatastore().Handle, featureClass.GetDatastore().Handle, "Conflicting class id from different workspaces. Please report."); } resultGdbObjects.Add(ToGdbObjectMsg(feature, shape, omitDetailedShapeSpatialRef)); } _msg.DebugStopTiming(watch, "Converted {0} features to DTOs", resultGdbObjects.Count); }
private async Task <Boolean> CheckRequirements() { if (_selectedMap == null) { MessageBox.Show("Select A Map In File Tile Opener Settings"); return(false); } if (_selectedFeatureLayer == null) { MessageBox.Show("Select A Layer in File Tile Opener Settings"); return(false); } if (_selectedField == null) { MessageBox.Show("Select a Field in File Tile Opener Settings"); } IEnumerable <Field> fields = null; await QueuedTask.Run(() => { Table table = _selectedFeatureLayer.GetTable(); if (table is FeatureClass) { FeatureClass featureclass = table as FeatureClass; using (FeatureClassDefinition def = featureclass.GetDefinition()) { fields = def.GetFields(); } } }); var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(_selectedField.ToLower())); if (match == null) { MessageBox.Show("This field '" + _selectedField + "' is Missing From '" + _selectedFeatureLayer.Name + "' Feature Layer", "Oops"); return(false); } // No need to check for whitespace. I disallow this in the 'view'. if (String.IsNullOrEmpty(_fileExtension)) { MessageBox.Show("Type or Choose a File Extension in File Tile Opener Settings"); return(false); } if (String.IsNullOrWhiteSpace(_fileWorkspace)) { MessageBox.Show("Type or Choose a File Workspace in File Tile Opener Settings"); return(false); } return(true); }
/// <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(); } }
public static SortedList <object, string> GetDomainFor(FeatureClass layer, string fieldName) { var definition = layer.GetDefinition(); var fieldIndex = definition.FindField(fieldName); var field = definition.GetFields()[fieldIndex]; var domain = field.GetDomain() as CodedValueDomain; return(domain?.GetCodedValuePairs()); }
/// <summary> /// Validates Conditions for user before attempting to edit the data /// </summary> /// <returns></returns> private async Task <bool> PrepStatus() { if (_selectedMap == null) { MessageBox.Show("Select A Map In Inspector Settings"); return(false); } if (_selectedLayer == null) { MessageBox.Show("Select A Layer in Inspector Settings"); return(false); } IEnumerable <Field> fields = null; FeatureClass featureclass = null; await QueuedTask.Run(() => { // Get the fields Table table = (_selectedLayer as FeatureLayer).GetTable(); if (table is FeatureClass) { featureclass = table as FeatureClass; using (FeatureClassDefinition def = featureclass.GetDefinition()) { fields = def.GetFields(); } } }); var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(InpsectorFieldName.ToLower())); if (match == null) { MessageBox.Show("Add field named '" + InpsectorFieldName + "' to '" + _selectedLayer.Name + "' layer of type Integer"); return(false); } match = fields.FirstOrDefault(field => (field.FieldType == FieldType.SmallInteger || field.FieldType == FieldType.Integer)); if (match == null) { MessageBox.Show("Add field named '" + InpsectorFieldName + "' to '" + _selectedLayer.Name + "' layer of type Integer"); return(false); } return(true); }
public static async Task <BA_ReturnCode> AddPolygonLayerAsync(Uri uri, CIMColor fillColor, bool isVisible, string displayName = "") { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (uri.IsFile) { strFileName = System.IO.Path.GetFileName(uri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(uri.LocalPath); } BA_ReturnCode success = BA_ReturnCode.UnknownError; await QueuedTask.Run(() => { FeatureClass fClass = null; // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. fClass = geodatabase.OpenDataset <FeatureClass>(strFileName); } if (String.IsNullOrEmpty(displayName)) { displayName = fClass.GetDefinition().GetAliasName(); } // Create symbology for feature layer var flyrCreatnParam = new FeatureLayerCreationParams(fClass) { Name = displayName, IsVisible = true, RendererDefinition = new SimpleRendererDefinition() { //SymbolTemplate = SymbolFactory.Instance.ConstructPolygonSymbol(fillColor).MakeSymbolReference() SymbolTemplate = SymbolFactory.Instance.ConstructPolygonSymbol( fillColor, SimpleFillStyle.Solid, SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, 0)) .MakeSymbolReference() } }; FeatureLayer fLayer = LayerFactory.Instance.CreateLayer <FeatureLayer>(flyrCreatnParam, MapView.Active.Map); fLayer.SetVisibility(isVisible); success = BA_ReturnCode.Success; }); return(success); }
double GetLength(FeatureClass fc, EnterpriseDatabaseType enterpriseDbType) { try { using (FeatureClassDefinition fcd = fc.GetDefinition()) { // the name of the length field changes depending on what enterprise geodatabase is used var areaFieldName = "Shape_Length"; switch (enterpriseDbType) { case EnterpriseDatabaseType.SQLServer: areaFieldName = "STLength"; break; } Field lengthField = fcd.GetFields().FirstOrDefault(x => x.Name.Contains(areaFieldName)); if (lengthField == null) { return(0); } System.Diagnostics.Debug.WriteLine(lengthField.Name); StatisticsDescription SumDesc = new StatisticsDescription(lengthField, new List <StatisticsFunction>() { StatisticsFunction.Sum }); TableStatisticsDescription tsd = new TableStatisticsDescription(new List <StatisticsDescription>() { SumDesc }); double sum = 0; try { sum = fc.CalculateStatistics(tsd).FirstOrDefault().StatisticsResults.FirstOrDefault().Sum; // exception is thrown on this line } catch { sum = Utilities.GetSumWorkAround(fc, lengthField.Name); } return(sum); } } catch (Exception ex) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(ex.ToString(), "Error"); return(0); } }
public ProcessingDataset(ProcessDatasetName datasetName, FeatureClass featureClass, IProcessingSelection processingSelection = null, IProcessingSymbology processingSymbology = null) { DatasetName = datasetName.DatasetName; WhereClause = datasetName.WhereClause; FeatureClass = featureClass ?? throw new ArgumentNullException(nameof(featureClass)); Selection = processingSelection ?? new NoProcessingSelection(); Symbology = processingSymbology ?? new NoProcessingSymbology(); var definition = FeatureClass.GetDefinition(); // bombs on joined FC ShapeType = definition.GetShapeType(); // MCT ShapeFieldName = definition.GetShapeField(); // MCT SpatialReference = definition.GetSpatialReference(); // MCT XYTolerance = SpatialReference.XYTolerance; }
public static async Task AddAoiBoundaryToMapAsync(Uri aoiUri, string displayName = "", double lineSymbolWidth = 1.0) { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (aoiUri.IsFile) { strFileName = System.IO.Path.GetFileName(aoiUri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(aoiUri.LocalPath); } await QueuedTask.Run(() => { FeatureClass fClass = null; // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. fClass = geodatabase.OpenDataset <FeatureClass>(strFileName); } if (String.IsNullOrEmpty(displayName)) { displayName = fClass.GetDefinition().GetAliasName(); } // Create symbology for feature layer var flyrCreatnParam = new FeatureLayerCreationParams(fClass) { Name = displayName, IsVisible = true, RendererDefinition = new SimpleRendererDefinition() { SymbolTemplate = SymbolFactory.Instance.ConstructPolygonSymbol( ColorFactory.Instance.BlackRGB, SimpleFillStyle.Null, SymbolFactory.Instance.ConstructStroke(ColorFactory.Instance.BlackRGB, lineSymbolWidth, SimpleLineStyle.Solid)) .MakeSymbolReference() } }; FeatureLayer fLayer = LayerFactory.Instance.CreateLayer <FeatureLayer>(flyrCreatnParam, MapView.Active.Map); }); }
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(); } }
private void OutputDefinition(Geodatabase geodatabase, TopologyDefinition topologyDefinition) { Console.WriteLine($"Topology cluster tolerance => {topologyDefinition.GetClusterTolerance()}"); Console.WriteLine($"Topology Z cluster tolerance => {topologyDefinition.GetZClusterTolerance()}"); IReadOnlyList <string> featureClassNames = topologyDefinition.GetFeatureClassNames(); Console.WriteLine($"There are {featureClassNames.Count} feature classes that are participating in the topology:"); foreach (string name in featureClassNames) { // Open each feature class that participates in the topology. using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(name)) using (FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition()) { Console.WriteLine($"\t{featureClass.GetName()} ({featureClassDefinition.GetShapeType()})"); } } }
double GetArea(FeatureClass fc) { try { using (FeatureClassDefinition fcd = fc.GetDefinition()) { // the name of the area field changes depending on what enterprise geodatabase is used var areaFieldName = "Shape_Area"; Field areaField = fcd.GetFields().FirstOrDefault(x => x.Name.Contains(areaFieldName)); if (areaField == null) { return(0); } System.Diagnostics.Debug.WriteLine(areaField.Name); // Output is "Shape.STArea()" as expected StatisticsDescription SumDesc = new StatisticsDescription(areaField, new List <StatisticsFunction>() { StatisticsFunction.Sum }); TableStatisticsDescription tsd = new TableStatisticsDescription(new List <StatisticsDescription>() { SumDesc }); double sum = 0; try { sum = fc.CalculateStatistics(tsd).FirstOrDefault().StatisticsResults.FirstOrDefault().Sum; // exception is thrown on this line } catch { sum = Utilities.GetSumWorkAround(fc, areaField.Name); } return(sum); } } catch (Exception ex) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(ex.ToString(), "Error"); return(0); } }
/// <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; } }
private async Task AddResultFeatures(FeatureClass fc) { EditOperation featOp = new EditOperation(); featOp.Callback(context => { foreach (Result result in Results) { using (RowBuffer row = fc.CreateRowBuffer()) { row["VehicleYear"] = result.Vehicle.Year; row["VehicleMake"] = result.Vehicle.Make; row["VehicleModel"] = result.Vehicle.Model; row["Vehicletype"] = result.Vehicle.Type; row["VehicleMPG"] = result.Vehicle.Mpg; row["OriginalSymbolColor"] = result.Color; row["PADDZone"] = result.PaddZone; row["DOEGasPricePerGallon"] = result.DollarsPerGallon; row["MilesPerDollar"] = result.MilesPerDollar; row["DriveDistanceMiles"] = result.DriveDistMi; row["ResultDateTime"] = result.ResultDateTimeUTC; row[fc.GetDefinition().GetShapeField()] = result.DriveServiceArea; using (Feature feat = fc.CreateRow(row)) { context.Invalidate(feat); } } } }, fc); bool success = await featOp.ExecuteAsync(); if (!success) { throw new Exception("Error adding result features: " + featOp.ErrorMessage); } success = await Project.Current.SaveEditsAsync(); if (!success) { throw new Exception("Failure while saving result features"); } }
/// <summary> /// Gets all the field in the selected layer that meets requirement and adds them to the drop down list /// </summary> private async void PopulateLayerFields() { _fields.Clear(); IEnumerable <Field> fields = null; FeatureClass featureclass = null; await QueuedTask.Run(() => { Table table = _selectedLayer.GetTable(); if (table is FeatureClass) { featureclass = table as FeatureClass; using (FeatureClassDefinition def = featureclass.GetDefinition()) { fields = def.GetFields(); } foreach (Field field in fields) { Domain domain = field.GetDomain(); if (domain != null) { FieldType fieldType = domain.GetFieldType(); if (fieldType == FieldType.SmallInteger || fieldType == FieldType.Integer) { _fields.Add(field.Name); } ; } } } }); if (_fields.Count <= 0) { MessageBox.Show("No Valid Fields in '" + _selectedLayer.Name + "' Feature Layer"); } }
/// <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 static FieldSetter CreateFieldSetter([CanBeNull] string text, [NotNull] FeatureClass featureClass, [NotNull] string parameterName, [CanBeNull] FindFieldCache findFieldCache = null) { Assert.ArgumentNotNull(featureClass, nameof(featureClass)); Assert.ArgumentNotNull(parameterName, nameof(parameterName)); try { var fieldSetter = FieldSetter.Create(text, findFieldCache); fieldSetter.ValidateTargetFields(featureClass.GetDefinition().GetFields()); return(fieldSetter); } catch (Exception ex) { throw new InvalidConfigurationException( $"Unable to create FieldSetter for parameter '{parameterName}': {ex.Message}", ex); } }
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(); }
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 async void cboLayerList_SelectionChanged(object sender, SelectionChangedEventArgs e) { string lname = cboLayerList.SelectedItem.ToString(); var mv = MapView.Active; FeatureLayer fl = mv.Map.FindLayers(lname).FirstOrDefault() as FeatureLayer; var fields = await QueuedTask.Run(() => { FeatureClass fc = fl.GetFeatureClass(); FeatureClassDefinition fcdef = fc.GetDefinition(); return(fcdef.GetFields()); }); lstFields.Items.Clear(); for (int i = 0; i < fields.Count; i++) { Field fld = fields[i]; if (fld.FieldType == FieldType.String) { lstFields.Items.Add(fld.Name); } } lstFields.SelectAll(); }
/// <summary> /// Adds the selected feature layer's field to the '_fields' collection /// </summary> private async void PopulateFeatureLayerFields() { _fields.Clear(); IEnumerable <Field> fields = null; FeatureClass featureclass = null; await QueuedTask.Run(() => { Table table = _selectedFeatureLayer.GetTable(); if (table is FeatureClass) { featureclass = table as FeatureClass; using (FeatureClassDefinition def = featureclass.GetDefinition()) { fields = def.GetFields(); } foreach (Field field in fields) { FieldType fieldType = field.FieldType; // Change field type acceptance here if (fieldType == FieldType.SmallInteger || fieldType == FieldType.Integer || fieldType == FieldType.String || fieldType == FieldType.Double || fieldType == FieldType.Single || fieldType == FieldType.GUID) { _fields.Add(field.Name); } ; } } }); if (_fields.Count <= 0) { MessageBox.Show("No Valid Fields in '" + _selectedFeatureLayer.Name + "' Feature Layer"); } }
//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; })); }
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 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 GeometryType GetShapeType([NotNull] FeatureClass featureClass) { Assert.ArgumentNotNull(featureClass, nameof(featureClass)); return(featureClass.GetDefinition().GetShapeType()); }
private async void GetMilitaryDomainsAsync(SymbolAttributeSet loadSet = null) { try { IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>(); await ArcGIS.Desktop.Framework.Threading.Tasks.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; string geodatabasePath = geodatabase.GetPath(); if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName) { //Correct GDB, open the current selected feature class _currentFeatureClass = geodatabase.OpenDataset<FeatureClass>(_currentFeatureClassName); using (_currentFeatureClass) { ArcGIS.Core.Data.FeatureClassDefinition facilitySiteDefinition = _currentFeatureClass.GetDefinition(); IReadOnlyList<ArcGIS.Core.Data.Field> fields = facilitySiteDefinition.GetFields(); MilitaryFieldsInspectorModel.PopulateDomains(fields); MilitaryFieldsInspectorModel.CheckLabelFieldsExistence(fields); } break; } } } }); //Check for affiliation tag if (_selectedStyleItem != null) { string identityCode = ""; if (_selectedStyleItem.Tags.ToUpper().Contains("FRIEND")) { identityCode = await GetDomainValueAsync("identity", "Friend"); } else if (_selectedStyleItem.Tags.ToUpper().Contains("HOSTILE")) { identityCode = await GetDomainValueAsync("identity", "Hostile/Faker"); } else if (_selectedStyleItem.Tags.ToUpper().Contains("NEUTRAL")) { identityCode = await GetDomainValueAsync("identity", "Neutral"); } else if (_selectedStyleItem.Tags.ToUpper().Contains("UNKNOWN")) { identityCode = await GetDomainValueAsync("identity", "Unknown"); } //Check name of style last to see if it has an affiliation, but no associated tag //But only do this if no tag existed if (identityCode == "") { if (_selectedStyleItem.Name.ToUpper().Contains(": FRIEND")) { identityCode = await GetDomainValueAsync("identity", "Friend"); } else if (_selectedStyleItem.Name.ToUpper().Contains(": HOSTILE")) { identityCode = await GetDomainValueAsync("identity", "Hostile/Faker"); } else if (_selectedStyleItem.Name.ToUpper().Contains(": NEUTRAL")) { identityCode = await GetDomainValueAsync("identity", "Neutral"); } else if (_selectedStyleItem.Name.ToUpper().Contains(": UNKNOWN")) { identityCode = await GetDomainValueAsync("identity", "Unknown"); } } if (identityCode != "") { foreach (DomainCodedValuePair dcvp in MilitaryFieldsInspectorModel.IdentityDomainValues) { if (dcvp.Code.ToString() == identityCode) { SymbolAttributeSet.DisplayAttributes.SelectedIdentityDomainPair = dcvp; break; } } } } //Load any passed in values to selected values for the domain combo boxes if (loadSet != null) { SymbolAttributeSet.DisplayAttributes.SelectedIdentityDomainPair = MilitaryFieldsInspectorModel.IdentityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Identity); SymbolAttributeSet.DisplayAttributes.SelectedEchelonDomainPair = MilitaryFieldsInspectorModel.EcholonDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Echelon); SymbolAttributeSet.DisplayAttributes.SelectedMobilityDomainPair = MilitaryFieldsInspectorModel.MobilityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Mobility); SymbolAttributeSet.DisplayAttributes.SelectedOperationalConditionDomainPair = MilitaryFieldsInspectorModel.OperationalConditionAmplifierDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.OperationalCondition); SymbolAttributeSet.DisplayAttributes.SelectedIndicatorDomainPair = MilitaryFieldsInspectorModel.TfFdHqDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Indicator); SymbolAttributeSet.DisplayAttributes.SelectedStatusDomainPair = MilitaryFieldsInspectorModel.StatusDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Status); SymbolAttributeSet.DisplayAttributes.SelectedContextDomainPair = MilitaryFieldsInspectorModel.ContextDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Context); SymbolAttributeSet.DisplayAttributes.SelectedModifier1DomainPair = MilitaryFieldsInspectorModel.Modifier1DomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Modifier1); SymbolAttributeSet.DisplayAttributes.SelectedModifier2DomainPair = MilitaryFieldsInspectorModel.Modifier2DomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.DisplayAttributes.Modifier2); SymbolAttributeSet.LabelAttributes.SelectedCredibilityDomainPair = MilitaryFieldsInspectorModel.CredibilityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.Credibility); SymbolAttributeSet.LabelAttributes.SelectedReinforcedDomainPair = MilitaryFieldsInspectorModel.ReinforcedDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.Reinforced); SymbolAttributeSet.LabelAttributes.SelectedReliabilityDomainPair = MilitaryFieldsInspectorModel.ReliabilityDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.Reliability); SymbolAttributeSet.LabelAttributes.SelectedCountryCodeDomainPair = MilitaryFieldsInspectorModel.CountryCodeDomainValues.FirstOrDefault(pair => pair.Code.ToString() == loadSet.LabelAttributes.CountryCode); } } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.ToString()); } }
private async Task<string> GetDomainValueAsync(string fieldName, string key) { try { IEnumerable<GDBProjectItem> gdbProjectItems = Project.Current.GetItems<GDBProjectItem>(); return await ArcGIS.Desktop.Framework.Threading.Tasks.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; string geodatabasePath = geodatabase.GetPath(); if (geodatabasePath == ProSymbolEditorModule.Current.MilitaryOverlaySchema.DatabaseName) { //Correct GDB, open the current selected feature class _currentFeatureClass = geodatabase.OpenDataset<FeatureClass>(_currentFeatureClassName); using (_currentFeatureClass) { ArcGIS.Core.Data.FeatureClassDefinition facilitySiteDefinition = _currentFeatureClass.GetDefinition(); IReadOnlyList<ArcGIS.Core.Data.Field> fields = facilitySiteDefinition.GetFields(); ArcGIS.Core.Data.Field foundField = fields.FirstOrDefault(field => field.Name == fieldName); if (foundField != null) { CodedValueDomain domain = foundField.GetDomain() as CodedValueDomain; return domain.GetCodedValue(key).ToString(); } } break; } } } return ""; }); } catch (Exception exception) { System.Diagnostics.Debug.WriteLine(exception.ToString()); } return null; }
//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; }); }