private async void AddLocalToMap(object sender, RoutedEventArgs e) { try { _gdb = await Geodatabase.OpenAsync(GDB_PATH); foreach (var table in _gdb.FeatureTables) { try { var flayer = new FeatureLayer { ID = table.Name, DisplayName = table.Name, FeatureTable = table }; MyMapView.Map.Layers.Add(flayer); MyMapView.SetView(flayer.FullExtent); } catch (Exception ex) { Console.WriteLine("Error creating feature layer: " + ex.Message, "Samples"); } } } catch (Exception ex) { Console.WriteLine("Error creating feature layer: " + ex.Message, "Samples"); } }
/// <summary> /// Gets the hierarcchical row that describes the selected feature /// </summary> /// <param name="selectedFeatures"></param> /// <returns></returns> public async Task<List<PopupContent>> GetPopupContent(Dictionary<BasicFeatureLayer, List<long>> selectedFeatures) { //_layersInMapFeatureClassMap = GetMapLayersFeatureClassMap(); //gets all the feature layers from the map and add it to the dictionary with the Feature class as its key var popupContents = new List<PopupContent>(); try { var objectIDS = _selection.GetObjectIDs(); if (_geodatabase == null) _geodatabase = await GetGDBFromLyrAsync(_featureLayer); var kvpMapMember = selectedFeatures.FirstOrDefault(s => s.Key.GetTable().GetName().Equals(_featureClassName)); foreach (var objectID in objectIDS) { //List<HierarchyRow> hrows = new List<HierarchyRow>(); //this makes the custom popup show only one record. //var newRow = await GetRelationshipChildren(_featureClassName, objectID); //hrows.Add(newRow); popupContents.Add(new DynamicPopupContent(kvpMapMember.Key, objectID, _featureClassName, this)); } } catch (Exception) { } return popupContents; }
static void Main(string[] args) { // get a geodatabase path from the command line or use this default: var gdbPath = @"C:\Data\SDK\GDB\LocalGovernment.gdb"; if (args.Count() > 0) gdbPath = args[0]; //Call Host.Initialize before constructing any objects from ArcGIS.Core try { Host.Initialize(); } catch (Exception e) { // Error (missing installation, no license, 64 bit mismatch, etc.) Console.WriteLine(string.Format("Initialization failed: {0}", e.Message)); return; } try { //if we are here, ArcGIS.Core is successfully initialized using (var gdb = new Geodatabase(gdbPath)) { IReadOnlyList<TableDefinition> definitions = gdb.GetDefinitions<FeatureClassDefinition>(); foreach (var fdsDef in definitions) { Console.WriteLine(TableString(fdsDef as TableDefinition)); } } Console.Read(); } catch (Exception e) { // Error (missing installation, no license, 64 bit mismatch, etc.) Console.WriteLine(string.Format("Cannot read file Geodatabase [{0}] error: {1}", gdbPath, e.Message)); return; } }
public void Release() { if (_geodatabase != null) { _openedTables.ForEach(table => { table.Close(); table.Dispose(); }); _openedTables.Clear(); _geodatabase.Close(); _geodatabase = null; _openedGeoDb = false; } }
/// <summary> /// 指定されたファイルジオデータベースに同名称既存のレイヤーの存在を検査する /// </summary> public bool FeatureClassExists(string geodatabase, string featureClassName) { try { var fileGDBpath = new FileGeodatabaseConnectionPath(new Uri(geodatabase)); using (Geodatabase gdb = new Geodatabase(fileGDBpath)) { FeatureClassDefinition featureClassDefinition = gdb.GetDefinition <FeatureClassDefinition>(featureClassName); featureClassDefinition.Dispose(); return(true); } } catch { return(false); } }
// Creates a feature layer from a local .geodatabase file private async void CreateFeatureLayers() { try { var gdb = await Geodatabase.OpenAsync(GDB_PATH); var table = gdb.FeatureTables.First(ft => ft.Name == "US-States"); _statesLayer = new FeatureLayer() { ID = table.Name, FeatureTable = table }; MyMapView.Map.Layers.Insert(1, _statesLayer); } catch (Exception ex) { MessageBox.Show("Error creating feature layer: " + ex.Message, "Samples"); } }
private void OpenGeodatabase() { if (_openedGeoDb) { return; } var fgdbPath = GetSetting("GDB_PATH"); if (fgdbPath == null) { throw new SettingsPropertyNotFoundException("The GDB_PATH setting was not found"); } _geodatabase = Geodatabase.Open(fgdbPath); _openedGeoDb = true; }
public void MainMethodCode() { Uri nonFederatedServerURL = new Uri("https://arcgis.server.example.com:6443/arcgis/rest/services/FeatureServiceName/FeatureServer"); // Note that for non-federated ArcGIS Server hosted feature services, the username and password have to be specified always. ServiceConnectionProperties nonFederatedArcGISServer = new ServiceConnectionProperties(nonFederatedServerURL) { User = "******", Password = "******" }; using (Geodatabase nonFederatedServerFeatureService = new Geodatabase(nonFederatedArcGISServer)) { // Use the feature service geodatabase. } Uri federatedServerURL = new Uri("http://arcgis.server.federated.with.portal.example.com/server/rest/services/Hosted/FeatureServiceName/FeatureServer"); // Note that for feature services hosted on ArcGIS Server federated with ArcGIS Portal, the username and password cannot be specified through the API. // Even if the username and password were specified, they will be disregarded. // Instead the Portal authorization has to be configured by adding the Portal to ArcGIS Pro with the user with which the connection should be established. // To connect to a Portal from a CoreHost application, use the ArcGIS.Core.SystemCore.ArcGISSignOn class to authenticate with the Portal. ServiceConnectionProperties federatedArcGISServer = new ServiceConnectionProperties(federatedServerURL); using (Geodatabase federatedServerFeatureService = new Geodatabase(federatedArcGISServer)) { // Use the feature service geodatabase. } Uri arcgisOnlineURL = new Uri("http://services1.arcgis.com/47GG2ga246DGaLwa/arcgis/rest/services/FeatureServiceName/FeatureServer"); // Similar to Federated Feature Services, note that for feature services hosted on ArcGIS Online, the username and password cannot be specified through the API. // Even if the username and password were specified, they will be disregarded. // Instead the connection will be established based on the ArcGIS Online user credentials used to login to ArcGIS Pro at startup. ServiceConnectionProperties arcGISOnline = new ServiceConnectionProperties(arcgisOnlineURL); using (Geodatabase arcGISOnlineFeatureService = new Geodatabase(arcGISOnline)) { // Use the feature service geodatabase. } }
//Illustrating updating a row in a File GDB private static async Task FileGeodatabaseWorkFlow() { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) using (Table table = fileGeodatabase.OpenDataset <Table>("EmployeeInfo")) { EditOperation editOperation = new EditOperation(); editOperation.Callback(context => { QueryFilter queryFilter = new QueryFilter { WhereClause = "COSTCTRN = 'Information Technology'" }; using (RowCursor rowCursor = table.Search(queryFilter, false)) { const string newITBuilding = "RD"; while (rowCursor.MoveNext()) { using (Row row = rowCursor.Current) { // 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(row); row["COSTCTR"] = 4900; row["COSTCTRN"] = "Research & Development"; // Rebrand It as R&D if you want to. row["LOCATION"] = Convert.ToString(row["LOCATION"]).Replace(Convert.ToString(row["BUILDING"]), newITBuilding); row["BUILDING"] = newITBuilding; row.Store(); // Has to be called after the store too context.Invalidate(row); } } } }, table); bool editResult = editOperation.Execute(); //This is required to persist the changes to the disk. bool saveResult = await Project.Current.SaveEditsAsync(); } }
private async Task StartGeodatabaseGeneration() { _generateButton.Enabled = false; // Update geodatabase path. _gdbPath = $"{Path.GetTempFileName()}.geodatabase"; // Create a task for generating a geodatabase (GeodatabaseSyncTask). _gdbSyncTask = await GeodatabaseSyncTask.CreateAsync(_featureServiceUri); // Get the (only) graphic in the map view. Graphic redPreviewBox = _myMapView.GraphicsOverlays.First().Graphics.First(); // Get the current extent of the red preview box. Envelope extent = redPreviewBox.Geometry as Envelope; // Get the default parameters for the generate geodatabase task. GenerateGeodatabaseParameters generateParams = await _gdbSyncTask.CreateDefaultGenerateGeodatabaseParametersAsync(extent); // Create a generate geodatabase job. GenerateGeodatabaseJob generateGdbJob = _gdbSyncTask.GenerateGeodatabase(generateParams, _gdbPath); // Handle the progress changed event with an inline (lambda) function to show the progress bar. generateGdbJob.ProgressChanged += (sender, e) => { // Get the job. GenerateGeodatabaseJob job = (GenerateGeodatabaseJob)sender; // Update the progress bar. UpdateProgressBar(job.Progress); }; // Show the progress bar. _progressBar.Hidden = false; // Start the job. generateGdbJob.Start(); // Get the result. _resultGdb = await generateGdbJob.GetResultAsync(); // Do the rest of the work. HandleGenerationCompleted(generateGdbJob); }
public static async Task <int> CountFeaturesAsync(Uri gdbUri, string featureClassName) { int retVal = -1; try { await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) { bool bExists = false; IReadOnlyList <FeatureClassDefinition> definitions = geodatabase.GetDefinitions <FeatureClassDefinition>(); foreach (FeatureClassDefinition def in definitions) { if (def.GetName().Equals(featureClassName) || def.GetAliasName().Equals(featureClassName)) { bExists = true; break; } } if (bExists) { using (Table table = geodatabase.OpenDataset <Table>(featureClassName)) { retVal = table.GetCount(); } } else { retVal = 0; Module1.Current.ModuleLogManager.LogDebug(nameof(CountFeaturesAsync), "Feature class " + featureClassName + " not found. Returning 0 features"); } } }); } catch (Exception e) { Module1.Current.ModuleLogManager.LogError(nameof(CountFeaturesAsync), "Exception: " + e.Message); } return(retVal); }
private void RegisterDatasets(Dictionary <Geodatabase, List <Table> > tablesByGeodatabase) { foreach (var pair in tablesByGeodatabase) { Geodatabase geodatabase = pair.Key; var definitions = geodatabase.GetDefinitions <FeatureClassDefinition>().ToLookup(d => d.GetName()); foreach (Table table in pair.Value) { var identity = new GdbTableIdentity(table); FeatureClassDefinition definition = definitions[identity.Name].FirstOrDefault(); ISourceClass sourceClass = CreateSourceClass(identity, definition); GeodatabaseBySourceClasses.Add(sourceClass, geodatabase); } } }
private async Task HandleGenerationCompleted(Geodatabase resultGdb) { // If the job completed successfully, add the geodatabase data to the map, // removing the version from the service. if (_generateGdbJob.Status == JobStatus.Succeeded) { MyMapView.Map.OperationalLayers.Clear(); // Loop through all feature tables in the geodatabase and add a new layer to the map. foreach (GeodatabaseFeatureTable table in resultGdb.GeodatabaseFeatureTables) { // Create a new feature layer for the table. FeatureLayer layer = new FeatureLayer(table); // Add the new layer to the map. MyMapView.Map.OperationalLayers.Add(layer); } // Best practice is to unregister the geodatabase. await _gdbSyncTask.UnregisterGeodatabaseAsync(resultGdb); // Tell the user that the geodatabase was unregistered. MessageBox.Show("Since no edits will be made, the local geodatabase has been unregistered per best practice."); } else { // Create a message to show the user. string message = "Generate geodatabase job failed"; // Show an error message (if there is one). if (_generateGdbJob.Error != null) { message += ": " + _generateGdbJob.Error.Message; } else { // If no error, show messages from the _generateGdbJob. var m = from msg in _generateGdbJob.Messages select msg.Message; message += ": " + string.Join <string>("\n", m); } MessageBox.Show(message); } }
public static async Task <double> CalculateTotalPolygonAreaAsync(Uri gdbUri, string featureClassName) { double dblRetVal = 0; try { bool bExists = await GeodatabaseTools.FeatureClassExistsAsync(gdbUri, featureClassName); if (!bExists) { return(dblRetVal); } await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) using (Table table = geodatabase.OpenDataset <Table>(featureClassName)) { QueryFilter queryFilter = new QueryFilter(); using (RowCursor aCursor = table.Search(queryFilter, false)) { while (aCursor.MoveNext()) { using (Feature feature = (Feature)aCursor.Current) { var geometry = feature.GetShape(); var area = GeometryEngine.Instance.Area(geometry); dblRetVal = dblRetVal + area; } } } } }); } catch (Exception e) { Module1.Current.ModuleLogManager.LogError(nameof(CalculateTotalPolygonAreaAsync), "Exception: " + e.Message); dblRetVal = -1; } return(dblRetVal); }
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 LookupItems() { QueuedTask.Run(() => { using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GdbPath)))) { IReadOnlyList <FeatureClassDefinition> fcdefinitions = fileGeodatabase.GetDefinitions <FeatureClassDefinition>(); lock (_lockGdbDefinitions) { _gdbDefinitions.Clear(); foreach (var definition in fcdefinitions) { _gdbDefinitions.Add(new GdbItem() { Name = definition.GetName(), Type = definition.DatasetType.ToString() }); } } IReadOnlyList <TableDefinition> tbdefinitions = fileGeodatabase.GetDefinitions <TableDefinition>(); lock (_lockGdbDefinitions) { foreach (var definition in tbdefinitions) { _gdbDefinitions.Add(new GdbItem() { Name = definition.GetName(), Type = definition.DatasetType.ToString() }); } } } }).ContinueWith(t => { if (t.Exception == null) { return; } var aggException = t.Exception.Flatten(); foreach (var exception in aggException.InnerExceptions) { System.Diagnostics.Debug.WriteLine(exception.Message); } }); }
public bool FeatureClassExists(string fileGDBPath, string featureClassName) { try { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(fileGDBPath)))) { FeatureClassDefinition featureClassDefinition = geodatabase.GetDefinition <FeatureClassDefinition>(featureClassName); featureClassDefinition.Dispose(); System.Diagnostics.Debug.WriteLine($"Feature class exists"); return(true); } } catch { // GetDefinition throws an exception if the definition doesn't exist System.Diagnostics.Debug.WriteLine($"Feature class does not exist"); return(false); } }
public async Task GetFeatureClassesInRelationshipClassAsync() { await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb")))) { IReadOnlyList <RelationshipClassDefinition> relationshipClassDefinitions = geodatabase.GetDefinitions <RelationshipClassDefinition>(); foreach (var relationshipClassDefintion in relationshipClassDefinitions) { IReadOnlyList <Definition> definitions = geodatabase.GetRelatedDefinitions(relationshipClassDefintion, DefinitionRelationshipType.DatasetsRelatedThrough); foreach (var definition in definitions) { MessageBox.Show($"Feature class in the RelationshipClass is:{definition.GetName()}"); } } } }); }
public void WorkItemService_LearningTest() { Polygon polygon = PolygonConstruction .StartPolygon(0, 0) .LineTo(0, 20) .LineTo(20, 20) .LineTo(20, 0) .ClosePolygon(); var rowCount = 4; TestUtils.InsertRows(_emptyIssuesGdb, _featureClassName, polygon, rowCount); try { var uri = new Uri(_emptyIssuesGdb, UriKind.Absolute); var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)); var table = geodatabase.OpenDataset <Table>(_featureClassName); Dictionary <Geodatabase, List <Table> > tablesByGeodatabase = new Dictionary <Geodatabase, List <Table> > { { geodatabase, new List <Table> { table } } }; IRepository stateRepository = new XmlWorkItemStateRepository(@"C:\temp\states.xml", null, null); IWorkItemRepository repository = new IssueItemRepository(tablesByGeodatabase, stateRepository); IWorkList workList = new GdbQueryWorkList(repository, "work list"); var items = workList.GetItems().Cast <IssueItem>().ToList(); Assert.AreEqual("Bart", items[0].IssueCodeDescription); Assert.AreEqual("Bart", items[1].IssueCodeDescription); Assert.AreEqual("Bart", items[2].IssueCodeDescription); Assert.AreEqual("Bart", items[3].IssueCodeDescription); } finally { TestUtils.DeleteAllRows(_emptyIssuesGdb, _featureClassName); } }
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(); } }
// Illustrates updating a feature in a File GDB. 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 (Feature feature = (Feature)rowCursor.Current) { MapPoint mapPoint = feature.GetShape() as MapPoint; // 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); // Note that to update the shape, you will need to create a new Shape object. feature.SetShape(new MapPointBuilder(mapPoint.X + 1, mapPoint.Y + 1, mapPoint.SpatialReference).ToGeometry()); feature.Store(); // 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 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 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()})"); } } }
public void MainMethodCode() { Uri serviceUrl = new Uri("https://arcgis.server.example.com:6443/arcgis/rest/services/FeatureServiceName/FeatureServer"); ServiceConnectionProperties arcGisServer = new ServiceConnectionProperties(serviceUrl) { User = "******", Password = "******" }; using (Geodatabase serverFeatureService = new Geodatabase(arcGisServer)) { FeatureClassDefinition featureClassDefinition = serverFeatureService.GetDefinition <FeatureClassDefinition>("0"); string shapeField = featureClassDefinition.GetShapeField(); IReadOnlyList <Field> fields = featureClassDefinition.GetFields(); TableDefinition tableDefinition = serverFeatureService.GetDefinition <TableDefinition>("4"); string objectIDField = tableDefinition.GetObjectIDField(); } }
private async Task <FeatureLayer> AddLocationsLayer() { var tablename = Settings.StLocationsTablename; var projGDBPath = Settings.STGdb; var gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(projGDBPath))); var pointFeatureLayer = FeatureClassCreator.GetFeatureLayer(MapView.Active.Map, tablename); if (pointFeatureLayer == null) { var urltable = projGDBPath + @"\" + tablename; await QueuedTask.Run(() => { pointFeatureLayer = LayerFactory.Instance.CreateFeatureLayer(new Uri(urltable), MapView.Active.Map, layerName: tablename); }); } return(pointFeatureLayer); }
public void OpenTopologyAndProcessDefinition() { // Open a geodatabase topology from a file geodatabase and process the topology definition. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb")))) using (Topology topology = geodatabase.OpenDataset <Topology>("Backcountry_Topology")) { ProcessDefinition(geodatabase, topology); } // Open a feature service topology and process the topology definition. const string TOPOLOGY_LAYER_ID = "0"; using (Geodatabase geodatabase = new Geodatabase(new ServiceConnectionProperties(new Uri("https://sdkexamples.esri.com/server/rest/services/GrandTeton/FeatureServer")))) using (Topology topology = geodatabase.OpenDataset <Topology>(TOPOLOGY_LAYER_ID)) { ProcessDefinition(geodatabase, topology); } }
public static void InsertRows(string path, string featureClassName, Geometry polygon, int rowCount) { var uri = new Uri(path, UriKind.Absolute); using (var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri))) { var definition = geodatabase.GetDefinition <FeatureClassDefinition>(featureClassName); string shapeField = definition.GetShapeField(); using (var featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName)) { for (var i = 0; i < rowCount; i++) { object value = "Bart"; InsertRow(featureClass, shapeField, polygon, value); } } } }
/// <summary> /// /// </summary> /// <returns></returns> public async Task DeleteReplicaFolderAsync() { var folderPath = GetReplicaFullPath(); try { var folders = Directory.GetDirectories(folderPath); foreach (var f in folders) { if (f.Contains("p13")) { var gdbs = Directory.GetFiles(f); foreach (var file in gdbs) { try { if (file.Contains(".geodatabase")) { var gdb = await Geodatabase.OpenAsync(file); gdb.Close(); } } catch (Exception ex) { Debug.WriteLine(ex.Message); } } } } if (MobileMapPackage != null) { MobileMapPackage.Close(); } Directory.Delete(folderPath, true); } catch (Exception ex) { Debug.WriteLine(ex.Message); } }
private static void ExploreTopologyAPI() { // 1) Open a geodatabase topology dataset from a file geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GRAND_TETON_GDB_FULL_PATH)))) using (Topology topology = geodatabase.OpenDataset <Topology>(GRAND_TETON_TOPO_NAME)) { /* * This API also works with *feature service* topology. For example, to connect to a feature service topology: * * const string TOPOLOGY_LAYER_ID = "0"; * * using (Geodatabase geodatabase = new Geodatabase(new ServiceConnectionProperties(new Uri("https://sdkexamples.esri.com/server/rest/services/GrandTeton/FeatureServer"))) * using (Topology topology = geodatabase.OpenDataset<Topology>(TOPOLOGY_LAYER_ID)) * { * } */ Console.WriteLine($"Topology name => {topology.GetName()}"); // 2) Explore the topology definition. ExploreTopologyDefinition(geodatabase, topology); // 3) Explore topology rules. ExploreTopologyRules(topology); // 4) Explore topology errors. ExploreTopologyErrors(topology); // 5) Explore topology validation. ExploreTopologyValidation(geodatabase, topology); // 6) Explore the topology graph. ExploreTopologyGraph(geodatabase, topology); } }
private Task addFeatureLayer() { Debug.WriteLine("addFeatureLayer enter"); return(ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() => { ArcGIS.Core.Data.DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.PostgreSQL) { AuthenticationMode = AuthenticationMode.DBMS, Instance = @"127.0.0.1", Database = "geomapmaker", User = "******", Password = "******", //Version = "dbo.DEFAULT" }; using (Geodatabase geodatabase = new Geodatabase(connectionProperties)) { // Use the geodatabase //CIMSqlQueryDataConnection sqldc = new CIMSqlQueryDataConnection() this.sqldc = new CIMSqlQueryDataConnection() { WorkspaceConnectionString = geodatabase.GetConnectionString(), GeometryType = esriGeometryType.esriGeometryPoint, OIDFields = "OBJECTID", Srid = "4326", SqlQuery = "select * from public.features where user_id = " + DataHelper.userID + " and ST_GeometryType(geom)='ST_Point'", Dataset = "features" }; featureLayer = (FeatureLayer)LayerFactory.Instance.CreateLayer(sqldc, MapView.Active.Map, layerName: DataHelper.userName + "'s points"); /* * string url = @"C:\Users\Douglas\Documents\testCollections\GeneWash.gdb\GeneWash.gdb\CrossSectionB\CSBMapUnitPolys"; //FeatureClass of a FileGeodatabase * * Uri uri = new Uri(url); * featureLayer = (FeatureLayer)LayerFactory.Instance.CreateLayer(uri, MapView.Active.Map); */ } })); }
public static Task <bool> FeatureClassExistsAsync(string fcName) { return(QueuedTask.Run(() => { try { using (Geodatabase projectGDB = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath)))) { using (FeatureClass fc = projectGDB.OpenDataset <FeatureClass>(fcName)) { return fc != null; } } } catch (Exception ex) { System.Diagnostics.Debug.WriteLine($@"FeatureClassExists Error: {ex.ToString()}"); return false; } })); }
public async Task <IGraphicsLayer> addGdbLayer(LayerDef eLayer, string dbFile, int start = 0, int maxFeatures = 0) { if (dbFile == null) { dbFile = _eMap.LocalGeoDbFileName; } string filePath = _prj.projDef.LocalFilePath + "\\" + dbFile; if (File.Exists(filePath)) { Geodatabase gdb = await Geodatabase.OpenAsync(filePath); IGraphicsLayer gLayer = await addGeodatabaseLayer( eLayer, gdb, start, maxFeatures); return(gLayer); } return(null); }
public void MainMethodCode() { // 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(@"C:\Data\LocalGovernment.gdb")))) { // Use the geodatabase. } // Each of the following would fail with GeodatabaseNotFoundOrOpenedException. try { Geodatabase geodatabase1 = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"Gibberish.gdb"))); Geodatabase geodatabase2 = new Geodatabase((FileGeodatabaseConnectionPath)null); } catch (GeodatabaseNotFoundOrOpenedException exception) { // Handle Exception. } }
private async void readGeoDatabase() { geodatabase = await Geodatabase.OpenAsync(mGeodatabasePath); if (geodatabase.GeodatabaseFeatureTables.Count > 0) { // データベース内の最初のテーブルを取得する mGdbFeatureTable = geodatabase.GeodatabaseFeatureTables.FirstOrDefault(); await mGdbFeatureTable.LoadAsync(); if (mGdbFeatureTable.LoadStatus == LoadStatus.Loaded) { myMap.OperationalLayers.RemoveAt(0); mFeatureLayer = new FeatureLayer(mGdbFeatureTable); myMap.OperationalLayers.Add(mFeatureLayer); } } }
public static Dictionary<string, FeatureClass> GetMapLayersFeatureClassMap(Geodatabase geodatabase) { 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; }
public async Task<GeodatabaseStatusInfo> SyncGeodatabase(string url, Geodatabase gdb, bool unregister, bool syncing) { Console.WriteLine("Starting Sync " + DateTime.Now + " --> " + syncing); var syncTask = new GeodatabaseSyncTask(new Uri(url)); var layerIdsAndName = new Dictionary<int, string>(); FeatureServiceInfo serviceInfo = await syncTask.GetServiceInfoAsync(); foreach (LayerServiceInfo layerServiceInfo in serviceInfo.Layers) { if (!layerIdsAndName.ContainsKey(layerServiceInfo.ID)) { layerIdsAndName.Add(layerServiceInfo.ID, layerServiceInfo.Name); } } var tcs = new TaskCompletionSource<GeodatabaseStatusInfo>(); Action<GeodatabaseStatusInfo, Exception> completionAction = (info, ex) => { if (ex != null) { tcs.SetException(ex); return; } tcs.SetResult(info); }; var syncProgress = new Progress<GeodatabaseStatusInfo>(); syncProgress.ProgressChanged += (sndr, sts) => Console.WriteLine("Status:" + sts.Status.ToString() + "," +" --> " + syncing + "," + sts.SubmissionTime + "," + sts.ResultUri); IDictionary<int, LayerSyncInfo> layerSync = null; layerSync = new Dictionary<int, LayerSyncInfo>(); foreach (var id_name in layerIdsAndName) { var layerQuery = new LayerSyncInfo { SyncDirection = SyncDirection.Bidirectional }; layerSync.Add(id_name.Key, layerQuery); } Action<UploadResult> uploadAction = result => { Console.Write(""); }; //should we remove sync direction since it should be defined in layers? var syncParams = new SyncGeodatabaseParameters(gdb) { RollbackOnFailure = false, UnregisterGeodatabase = unregister, LayerSyncInfos = layerSync, SyncDirection = SyncDirection.Bidirectional }; Console.WriteLine("Calling sync " + DateTime.Now); await syncTask.SyncGeodatabaseAsync(syncParams, gdb, completionAction, uploadAction, TimeSpan.FromSeconds(3), syncProgress, CancellationToken.None); return await tcs.Task; }
// Summary: // Add a layer in a geodatabase (aka. local layer) // The name of the layer and display options are specified in the LocalELayer // public async Task<IGraphicsLayer> addGeodatabaseLayer(LayerDef layerDef, Geodatabase gdb, int start = 0, int maxFeatures = 0) { if (layerDef == null || gdb == null) return null; GeodatabaseFeatureTable table = gdb.FeatureTables.FirstOrDefault(t => t.Name == layerDef.Name); if (table == null) return null; IS3GraphicsLayer gLayer = await featureTable2GraphicsLayer( table, start, maxFeatures, false); if (gLayer == null) return null; gLayer.ID = layerDef.Name; gLayer.MinScale = table.ServiceInfo.MinScale; gLayer.MaxScale = table.ServiceInfo.MaxScale; setGraphicLayerDisplayOptions(layerDef, gLayer); _map.Layers.Add(gLayer); return gLayer; }
private async void ReadRows() { if (_executeQuery) return; if (_gdbPath.IsEmpty()) return; if (SelectedTableName.IsEmpty()) return; _executeQuery = true; _columns.Clear(); _timer.Start(); OnPropertyChanged("IsExecutingQuery"); string tableName = SelectedTableName.Split(new char[] { '(', ')' }, StringSplitOptions.RemoveEmptyEntries)[1].Trim(); var data = new ObservableCollection<DynamicDataRow>(); try { //Note, we have to return something await TaskUtils.StartSTATask<int>(() => { using (Geodatabase gdb = new Geodatabase(_gdbPath)) { var table = gdb.OpenDataset<Table>(tableName); RowCursor cursor = table.Search(); IReadOnlyList<Field> flds = cursor.GetFields(); foreach (var fld in flds) { _columns.Add(new ColumnData() { AliasName = fld.AliasName ?? fld.Name, Name = fld.Name, FieldType = fld.FieldType }); } while (cursor.MoveNext()) { var row = new DynamicDataRow(); for (int v = 0; v < flds.Count; v++) { row[GetName(flds[v])] = GetValue(cursor.Current, v); } data.Add(row); } } return 0; }); } finally { ExtendListView.Columns = _columns; _timer.Stop(); lock(_theLock) { _rows.Clear(); _rows = null; _rows = data; } if (_rows.Count > 0) { TableHasNoRows = ""; } else { TableHasNoRows = "No rows returned"; } _executeQuery = false; OnPropertyChanged("Rows"); OnPropertyChanged("IsExecutingQuery"); } }
private void OpenGeodatabase() { if (_openedGeoDb) { return; } var fgdbPath = GetSetting("GDB_PATH"); if (fgdbPath == null) { throw new SettingsPropertyNotFoundException("The GDB_PATH setting was not found"); } _geodatabase = Geodatabase.Open(fgdbPath); _openedGeoDb = true; }
private void LookupItems() { QueuedTask.Run(() => { using (Geodatabase fileGeodatabase = new Geodatabase(GdbPath)) { IReadOnlyList<FeatureClassDefinition> fcdefinitions = fileGeodatabase.GetDefinitions<FeatureClassDefinition>(); lock (_lockGdbDefinitions) { _gdbDefinitions.Clear(); foreach (var definition in fcdefinitions) { _gdbDefinitions.Add(new GdbItem() {Name = definition.GetName(), Type = definition.DatasetType.ToString()}); } } IReadOnlyList<TableDefinition> tbdefinitions = fileGeodatabase.GetDefinitions<TableDefinition>(); lock (_lockGdbDefinitions) { foreach (var definition in tbdefinitions) { _gdbDefinitions.Add(new GdbItem() { Name = definition.GetName(), Type = definition.DatasetType.ToString() }); } } } }).ContinueWith(t => { if (t.Exception == null) return; var aggException = t.Exception.Flatten(); foreach (var exception in aggException.InnerExceptions) System.Diagnostics.Debug.WriteLine(exception.Message); }); }
public FgdbDatasetReader() { _settings = new Dictionary<string, string>(); _openedTables = new List<Table>(); _geodatabase = null; }
// Create feature layers from the given geodatabase file private async Task CreateFeatureLayers(Geodatabase gdb) { if (gdb.FeatureTables.Count() == 0) throw new ApplicationException("Downloaded geodatabase has no feature tables."); if (LocalBirdsLayer != null) MyMapView.Map.Layers.Remove(LocalBirdsLayer); var birdsTable = gdb.FeatureTables.First(); LocalBirdsLayer = new FeatureLayer() { ID = "Birds", DisplayName = "Local Birds", FeatureTable = birdsTable }; MyMapView.Map.Layers.Insert(2, LocalBirdsLayer); await MyMapView.SetViewAsync(birdsTable.Extent); }
private async void OpenGDB() { if (_executeQuery) return; if (_gdbPath.IsEmpty()) return; _executeQuery = true; _timer.Start(); OnPropertyChanged("IsExecutingQuery"); _tables.Clear(); if (_rows.Count > 0) { _rows.Clear(); _rows = new ObservableCollection<DynamicDataRow>(); ExtendListView.Columns = null; OnPropertyChanged("Rows"); } TableHasNoRows = ""; SelectedTableName = ""; try { await TaskUtils.StartSTATask<int>(() => { using (Geodatabase gdb = new Geodatabase(_gdbPath)) { IReadOnlyList<Definition> fcList = gdb.GetDefinitions<FeatureClassDefinition>(); IReadOnlyList<Definition> tables = gdb.GetDefinitions<TableDefinition>(); //////Uncomment for just Feature class in Feature Datasets ////IReadOnlyList<Definition> fdsList = gdb.GetDefinitions<FeatureDatasetDefinition>(); lock (_theLock) { //Feature class foreach (var fcDef in fcList) { _tables.Add(TableString(fcDef as TableDefinition)); } //Tables foreach (var def in tables) { _tables.Add(TableString(def as TableDefinition)); } //////Uncomment for just Feature class in Feature Datasets ////foreach (var fdsDef in fdsList) { //// IReadOnlyList<Definition> tableDefsInDataset = gdb.GetRelatedDefinitions(fdsDef, //// DefinitionRelationshipType.DatasetInFeatureDataset); //// foreach (var def in tableDefsInDataset) { //// if (def.DatasetType == DatasetType.FeatureClass) //// _tables.Add(TableString(def as TableDefinition)); //// } ////} } } return 0; }); } finally { _timer.Stop(); if (_tables.Count > 0) SelectedTableName = _tables[0]; else { MessageBox.Show("No tables or feature datasets read", _gdbPath); } _executeQuery = false; OnPropertyChanged("IsExecutingQuery"); } }