Exemplo n.º 1
0
        public void MainMethodCode()
        {
            Uri arcgisOnlineURL = new Uri("http://services1.arcgis.com/47GG2ga246DGaLwa/arcgis/rest/services/FeatureServiceName/FeatureServer");

            ServiceConnectionProperties arcGISOnline = new ServiceConnectionProperties(arcgisOnlineURL);

            using (Geodatabase featureService = new Geodatabase(arcGISOnline))
            {
                using (FeatureClass featureClass = featureService.OpenDataset <FeatureClass>("0"))
                {
                    // Use the feature class opened from layer ID 0.
                }

                using (Table table = featureService.OpenDataset <Table>("4"))
                {
                    // Use the table opened from layer ID 4.
                }

                using (AttributedRelationshipClass attributedRelationshipClass = featureService.OpenDataset <AttributedRelationshipClass>("5"))
                {
                    // Use the attributed relationship class opened from layer ID 5.
                }

                try
                {
                    string idOfLayerWhichIsNotTable = "3";
                    featureService.OpenDataset <Table>(idOfLayerWhichIsNotTable);
                }
                catch (InvalidOperationException)
                {
                    // Handle Exception.
                }
            }
        }
Exemplo n.º 2
0
 private T GetDatasetFromGeodatabase <T>(Geodatabase gdb, string dataset, string featureDataset) where T : Table
 {
     if (!string.IsNullOrEmpty(featureDataset))
     {
         var fd = gdb.OpenDataset <FeatureDataset>(featureDataset);
         if (fd != null)
         {
             return(fd.OpenDataset <T>(dataset));
         }
     }
     return(gdb.OpenDataset <T>(dataset));
 }
Exemplo n.º 3
0
        public ProcessingDataset OpenDataset(ProcessDatasetName name)
        {
            if (name == null)
            {
                return(null);
            }

            var featureClass = _geodatabase.OpenDataset <FeatureClass>(name.DatasetName);            // MCT
            var featureLayer = FindLayer(_map, featureClass);

            var layerProxy = featureLayer != null ? new LayerProxyAGP(featureLayer, _mapView) : null;

            return(new ProcessingDataset(name, featureClass, layerProxy, layerProxy));
        }
        /// <summary>
        /// Since the LocalGovernment Geodatabase does not have AttributedRelationshipClasses, the following method illustrates the behavior
        /// if such a dataset existed.
        /// </summary>
        public void 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 (AttributedRelationshipClass attributedRelationshipClass = geodatabase.OpenDataset <AttributedRelationshipClass>("LocalGovernment.GDB.ParcelToBuilding"))
                    using (FeatureClass parcelFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.Parcel"))
                        using (FeatureClass buildingFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.Building"))
                        {
                            QueryFilter parcelQueryFilter = new QueryFilter {
                                WhereClause = "APN = 1234 OR APN = 5678"
                            };
                            QueryFilter buildingQueryFilter = new QueryFilter {
                                WhereClause = "BUILDID = 4321 OR BUILDID = 8765"
                            };

                            Selection parcelsSelection  = parcelFeatureClass.Select(parcelQueryFilter, SelectionType.ObjectID, SelectionOption.Normal);
                            Selection buildingSelection = buildingFeatureClass.Select(buildingQueryFilter, SelectionType.ObjectID, SelectionOption.Normal);

                            IReadOnlyList <AttributedRelationship> relationshipsForOrigin      = null;
                            IReadOnlyList <AttributedRelationship> relationshipsForDestination = null;

                            try
                            {
                                relationshipsForOrigin      = attributedRelationshipClass.GetRelationshipsForOriginRows(parcelsSelection.GetObjectIDs());
                                relationshipsForDestination = attributedRelationshipClass.GetRelationshipsForDestinationRows(buildingSelection.GetObjectIDs());
                            }
                            finally
                            {
                                Dispose(relationshipsForOrigin);
                                Dispose(relationshipsForDestination);
                            }
                        }
        }
Exemplo n.º 5
0
        private void GetFeaturesAndAddAttachment()
        {
            // open the geodatabase
            using (var geodatabase = new Geodatabase(@"c:\ProSDKWorkshop\data\generic.gdb"))
            {
                // open the SamplePoints feature class
                var pointFeatureClass = geodatabase.OpenDataset <FeatureClass>("SamplePoints");

                // retrieve all features from the feature class
                using (var rowCursor = pointFeatureClass.Search())
                {
                    while (rowCursor.MoveNext())
                    {
                        // for each feature
                        using (var currentFeature = rowCursor.Current as Feature)
                        {
                            // add the sample picture as an attachment
                            currentFeature.AddAttachment(new Attachment("SamplePicture", "image/png",
                                                                        CreateMemoryStreamFromContentsOf(@"c:\ProSDKWorkshop\data\redlands.png")));
                        }
                    }
                }
            }

            // add the feature class as a layer to the active map
            LayerFactory.CreateFeatureLayer(new Uri(@"c:\ProSDKWorkshop\data\generic.gdb\SamplePoints"), MapView.Active.Map);
        }
Exemplo n.º 6
0
        public static async Task KeyPointsIntegration()
        {
            await QueuedTask.Run(() =>
            {
                using (Geodatabase gdb1 = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb1.ApplyEdits(() =>
                    {
                        FeatureClass voyageRiskKeyPoint = gdb1.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_VoyageRiskKeyPoint);
                        FeatureClassDefinition voyageRiskKeyPointDefinition = gdb1.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_VoyageRiskKeyPoint);
                        voyageRiskKeyPoint.DeleteRows(new QueryFilter()
                        {
                            WhereClause = "OBJECTID >= 1"
                        });
                        string shapeFieldName = voyageRiskKeyPointDefinition.GetShapeField();

                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskInternalPoint, 1);
                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskOutlinePoint, 0);
                        double midLocaRisk = Math.Pow(0.5, 3.03);
                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskLocaMidPoint, midLocaRisk);
                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskRiskMidPoint, 0.5);
                    });
                }
            });
        }
        protected override IEnumerable <BasicFeatureLayer> GetLayers(Map map)
        {
            if (string.IsNullOrEmpty(_path))
            {
                yield break;
            }

            // todo daro: ensure layers are not already in map
            using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(_path, UriKind.Absolute))))
            {
                IEnumerable <string> featureClassNames =
                    geodatabase.GetDefinitions <FeatureClassDefinition>()
                    .Select(definition => definition.GetName())
                    .Where(name => _issueFeatureClassNames.Contains(name));

                foreach (string featureClassName in featureClassNames)
                {
                    using (var featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName))
                    {
                        FeatureLayer featureLayer = LayerFactory.Instance.CreateFeatureLayer(
                            featureClass, MapView.Active.Map, LayerPosition.AddToTop);

                        featureLayer.SetExpanded(false);
                        featureLayer.SetVisibility(false);

                        yield return(featureLayer);
                    }
                }
            }
        }
Exemplo n.º 8
0
        public async void setDomainValuesFile(string db, string dataset, string fieldName, string sourceTarget, bool resetUI)
        {
            List <ComboData> domain = new List <ComboData>();
            await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                ArcGIS.Core.Data.TableDefinition def = null;
                try
                {
                    string table = dataset.Substring(dataset.LastIndexOf("\\") + 1);
                    ArcGIS.Core.Data.Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(db)));
                    using (ArcGIS.Core.Data.Table tab = geodatabase.OpenDataset <ArcGIS.Core.Data.Table>(table))
                    {
                        def    = tab.GetDefinition();
                        domain = getDomainValuesforTable(def, fieldName);
                    }
                }
                catch { raiseDomainErrorMessage(dataset, fieldName); }
                return;
            });

            if (resetUI == true)
            {
                resetDomainValuesUI(domain, sourceTarget);
            }
            else
            {
                resetDomainValuesUIFromConfig(domain, sourceTarget);
            }
            return;
        }
        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);
        }
Exemplo n.º 10
0
        public void GetTopologyRules()
        {
            using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\TestData\GrandTeton.gdb"))))
                using (Topology topology = geodatabase.OpenDataset <Topology>("Backcountry_Topology"))
                {
                    #region GetTopologyRules

                    using (TopologyDefinition topologyDefinition = topology.GetDefinition())
                    {
                        IReadOnlyList <TopologyRule> rules = topologyDefinition.GetRules();

                        Console.WriteLine($"There are {rules.Count} topology rules defined for the topology:");
                        Console.WriteLine("ID \t Origin Class \t Origin Subtype \t Destination Class \t Destination Subtype \t Rule Type");

                        foreach (TopologyRule rule in rules)
                        {
                            Console.Write($"{rule.ID}");

                            Console.Write(!String.IsNullOrEmpty(rule.OriginClass) ? $"\t{rule.OriginClass}" : "\t\"\"");

                            Console.Write(rule.OriginSubtype != null ? $"\t{rule.OriginSubtype.GetName()}" : "\t\"\"");

                            Console.Write(!String.IsNullOrEmpty(rule.DestinationClass) ? $"\t{rule.DestinationClass}" : "\t\"\"");

                            Console.Write(rule.DestinationSubtype != null ? $"\t{rule.DestinationSubtype.GetName()}" : "\t\"\"");

                            Console.Write($"\t{rule.RuleType}");

                            Console.WriteLine();
                        }
                    }

                    #endregion GetTopologyRules
                }
        }
Exemplo n.º 11
0
        public static async Task <string[]> QueryAoiEnvelopeAsync(Uri clipFileGdbUri, string clipName)
        {
            string[] arrRetValues = new string[2];
            Geometry aoiGeo       = null;
            int      intCount     = 0;
            await QueuedTask.Run(() =>
            {
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(clipFileGdbUri)))
                    using (Table table = geodatabase.OpenDataset <Table>(clipName))
                    {
                        //check for multiple buffer polygons and buffer AOI if we need to
                        QueryFilter queryFilter = new QueryFilter();
                        using (RowCursor cursor = table.Search(queryFilter, false))
                        {
                            while (cursor.MoveNext())
                            {
                                using (Feature feature = (Feature)cursor.Current)
                                {
                                    aoiGeo = feature.GetShape();
                                }
                                intCount++;
                            }
                        }
                    }
            });

            if (intCount > 1)
            {
                string        tmpClipBuffer = "tmpClipBuffer";
                BA_ReturnCode success       = await GeoprocessingTools.BufferAsync(clipFileGdbUri.LocalPath + "\\" + clipName, clipFileGdbUri.LocalPath + "\\" + tmpClipBuffer,
                                                                                   "0.5 Meters", "ALL");

                if (success == BA_ReturnCode.Success)
                {
                    await QueuedTask.Run(() =>
                    {
                        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(clipFileGdbUri)))
                            using (Table table = geodatabase.OpenDataset <Table>(tmpClipBuffer))
                            {
                                //check for multiple buffer polygons and buffer AOI if we need to
                                QueryFilter queryFilter = new QueryFilter();
                                using (RowCursor cursor = table.Search(queryFilter, false))
                                {
                                    while (cursor.MoveNext())
                                    {
                                        using (Feature feature = (Feature)cursor.Current)
                                        {
                                            aoiGeo   = feature.GetShape(); // Replace unbuffered geometry with buffered
                                            clipName = tmpClipBuffer;
                                        }
                                    }
                                }
                            }
                    });
                }
            }
            arrRetValues[0] = aoiGeo.Extent.XMin + " " + aoiGeo.Extent.YMin + " " + aoiGeo.Extent.XMax + " " + aoiGeo.Extent.YMax;
            arrRetValues[1] = clipFileGdbUri.LocalPath + "\\" + clipName;
            return(arrRetValues);
        }
        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);
        }
        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);
        }
Exemplo n.º 14
0
        protected void OnRowCreated(RowChangedEventArgs args)
        {
            // RowEvent callbacks are always called on the QueuedTask so there is no need
            // to wrap your code within a QueuedTask.Run lambda.

            // update a separate table when a row is created
            // You MUST use the ArcGIS.Core.Data API to edit the table. Do NOT
            // use a new edit operation in the RowEvent callbacks
            try
            {
                // update Notes table with information about the new feature
                var geoDatabase     = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(Project.Current.DefaultGeodatabasePath)));
                var table           = geoDatabase.OpenDataset <Table>("Notes");
                var tableDefinition = table.GetDefinition();
                using (var rowbuff = table.CreateRowBuffer())
                {
                    // add a description
                    rowbuff["Description"] = "OID: " + args.Row.GetObjectID().ToString() + " " + DateTime.Now.ToShortTimeString();
                    table.CreateRow(rowbuff);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show($@"Error in OnRowCreated for OID: {args.Row.GetObjectID()} : {e.ToString()}");
            }
        }
Exemplo n.º 15
0
        public static async Task <bool> AttributeExistsAsync(Uri gdbUri, string featureClassName, string fieldName)
        {
            bool bExists = false;
            await QueuedTask.Run(() =>
            {
                try
                {
                    using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri)))
                    {
                        using (Table table = geodatabase.OpenDataset <Table>(featureClassName))
                        {
                            TableDefinition definition = table.GetDefinition();
                            int idxField = definition.FindField(fieldName);
                            if (idxField > -1)
                            {
                                bExists = true;
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    Module1.Current.ModuleLogManager.LogError(nameof(AttributeExistsAsync),
                                                              "Exception: " + e.Message);
                }
            });

            return(bExists);
        }
Exemplo n.º 16
0
        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 = "geomapmaker2",
                    User = "******",
                    Password = "******",
                    //Version = "dbo.DEFAULT"
                };

                using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
                {
                    using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>("geomapmaker2.geomapmaker2.line_features"))
                    {
                        var layerParamsQueryDefn = new FeatureLayerCreationParams(featureClass)
                        {
                            IsVisible = true,
                            DefinitionFilter = new CIMDefinitionFilter()
                            {
                                Name = "User",
                                DefinitionExpression = "user_id = " + DataHelper.userID
                            }
                        };
                        featureLayer = LayerFactory.Instance.CreateLayer <FeatureLayer>(layerParamsQueryDefn, MapView.Active.Map);
                    }
                }
            }));
        }
Exemplo n.º 17
0
        /// <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);
        }
Exemplo n.º 18
0
        private async Task openDatabase(JObject props)
        {
            await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
            {
                //Get Layers that are NOT Group layers and are unchecked
                //var layers = MapView.Active.Map.Layers.ToList();
                //MapView.Active.Map.RemoveLayers(layers);

                // Opening a Non-Versioned SQL Server instance.
                ArcGIS.Core.Data.DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.PostgreSQL)
                {
                    AuthenticationMode = AuthenticationMode.DBMS,

                    // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
                    //Instance = @"127.0.0.1",
                    Instance = props["instance"].ToString(),

                    // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
                    //Database = "geomapmaker",
                    Database = props["database"].ToString(),

                    // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
                    //User = "******",
                    User = props["user"].ToString(),
                    //Password = "******",
                    Password = props["password"].ToString(),
                    //Version = "dbo.DEFAULT"
                };

                using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
                {
                    DataHelper.connectionString = geodatabase.GetConnectionString();
                    Debug.WriteLine("DataHelper.connectionString set to " + DataHelper.connectionString);

                    // Use the geodatabase

                    /*
                     * CIMSqlQueryDataConnection sqldc = new CIMSqlQueryDataConnection()
                     * {
                     *  WorkspaceConnectionString = geodatabase.GetConnectionString(),
                     *  GeometryType = esriGeometryType.esriGeometryPoint,
                     *  OIDFields = "OBJECTID",
                     *  Srid = "4326",
                     *  //SqlQuery = "select * from geomapmaker2.features where id = " + DataHelper.userID + " and ST_GeometryType(geom)='ST_Point'",
                     *  Dataset = "somepoints"
                     * };
                     * FeatureLayer flyr = (FeatureLayer)LayerFactory.Instance.CreateLayer(sqldc, MapView.Active.Map, layerName: DataHelper.userName + "'s points");
                     */
                    //FeatureClass fC = geodatabase.OpenDataset<FeatureClass>("somepoints");
                    //FeatureLayer flyr = LayerFactory.Instance.CreateFeatureLayer(fC, MapView.Active.Map);
                    var featureClasses = geodatabase.GetDefinitions <FeatureClassDefinition>();
                    foreach (FeatureClassDefinition fCD in featureClasses)
                    {
                        FeatureClass fC   = geodatabase.OpenDataset <FeatureClass>(fCD.GetName());
                        FeatureLayer flyr = LayerFactory.Instance.CreateFeatureLayer(fC, MapView.Active.Map);
                    }
                }
            });
        }
Exemplo n.º 19
0
 public Table OpenTable(string name)
 {
     // todo daro exception handling
     using (Geodatabase geodatabase = OpenGeodatabase())
     {
         return(geodatabase.OpenDataset <Table>(name));
     }
 }
Exemplo n.º 20
0
        public void Measure_performance_query_items_from_GDB()
        {
            Polygon polygon = PolygonConstruction
                              .StartPolygon(0, 0)
                              .LineTo(0, 20)
                              .LineTo(20, 20)
                              .LineTo(20, 0)
                              .ClosePolygon();

            Polygon areaOfInterest = PolygonConstruction
                                     .StartPolygon(0, 0)
                                     .LineTo(0, 100)
                                     .LineTo(100, 100)
                                     .LineTo(100, 0)
                                     .ClosePolygon();

            var rowCount = 10000;

            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");
                workList.AreaOfInterest = areaOfInterest;

                var filter = GdbQueryUtils.CreateSpatialFilter(areaOfInterest);

                var watch = new Stopwatch();
                watch.Start();

                IEnumerable <IWorkItem> items = workList.GetItems(filter);

                watch.Stop();
                Console.WriteLine($"{watch.ElapsedMilliseconds} ms");

                Assert.AreEqual(rowCount, items.Count());
            }
            finally
            {
                TestUtils.DeleteAllRows(_emptyIssuesGdb, _featureClassName);
            }
        }
Exemplo n.º 21
0
        public Row GetRow([NotNull] Geodatabase geodatabase)
        {
            Assert.ArgumentNotNull(geodatabase, nameof(geodatabase));

            using (var table = geodatabase.OpenDataset <Table>(Table.Name))
            {
                return(GdbQueryUtils.GetRow(table, ObjectId));
            }
        }
        private async Task <ObservableCollection <GDBBaseItem> > GetGDBItemsAsync()
        {
            var gdbItems = await QueuedTask.Run <ObservableCollection <GDBBaseItem> >(() =>
            {
                List <GDBBaseItem> lstGDBBaseItems = new List <GDBBaseItem>();
                //Database becomes the root node
                var path = Name;
                var root = new DatabaseGDBItem {
                    DBName = System.IO.Path.GetFileName(Name), Name = path, Path = path
                };
                lstGDBBaseItems.Add(root);
                // use the geodatabase to get all layers
                var fGdbPath = new FileGeodatabaseConnectionPath(new Uri(Name, UriKind.Absolute));
                using (var gdb = new Geodatabase(fGdbPath))
                {
                    IReadOnlyList <Definition> fcList = gdb.GetDefinitions <FeatureClassDefinition>();
                    //Feature class
                    foreach (FeatureClassDefinition fcDef in fcList)
                    {
                        var fc      = gdb.OpenDataset <FeatureClass>(fcDef.GetName());
                        var fd      = fc.GetFeatureDataset();
                        var fc_path = (fd == null) ? path : path + @"\" + fd.GetName();
                        fc.Dispose();
                        fd?.Dispose();
                        switch (fcDef.GetShapeType())
                        {
                        case GeometryType.Point:
                            var pointfcItem = new PointFCGDBItem {
                                Name = fcDef.GetName(), Path = fc_path
                            };
                            root.Children.Add(pointfcItem);
                            break;

                        case GeometryType.Polyline:
                            var linefcItem = new LineFCGDBItem {
                                Name = fcDef.GetName(), Path = fc_path
                            };
                            root.Children.Add(linefcItem);
                            break;

                        case GeometryType.Polygon:
                            var polyfcItem = new PolygonFCGDBItem {
                                Name = fcDef.GetName(), Path = fc_path
                            };
                            root.Children.Add(polyfcItem);
                            break;
                        }
                    }
                }
                root.IsExpanded = true;

                return(new ObservableCollection <GDBBaseItem>(lstGDBBaseItems));
            });

            return(gdbItems);
        }
Exemplo n.º 23
0
        public void SetUp()
        {
            // http://stackoverflow.com/questions/8245926/the-current-synchronizationcontext-may-not-be-used-as-a-taskscheduler
            SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());

            _geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(_emptyIssuesGdb, UriKind.Absolute)));

            // todo daro: test IssueRows as well!
            _issuePoints = _geodatabase.OpenDataset <FeatureClass>(_issuePointsFeatureClassName);
        }
Exemplo n.º 24
0
        /// <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();
                }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Illustrates deleting rows from a table in an enterprise geodatabase.
        /// </summary>
        /// <returns></returns>
        private static async Task EnterpriseGeodabaseWorkFlow()
        {
            // 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 (Table enterpriseTable = geodatabase.OpenDataset <Table>("LocalGovernment.GDB.piCIPCost"))
                {
                    EditOperation editOperation = new EditOperation();
                    editOperation.Callback(context =>
                    {
                        QueryFilter openCutFilter = new QueryFilter {
                            WhereClause = "ACTION = 'Open Cut'"
                        };

                        using (RowCursor rowCursor = enterpriseTable.Search(openCutFilter, 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();
                                }
                            }
                        }
                    }, enterpriseTable);

                    bool editResult = editOperation.Execute();

                    // 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();
                }
            }
        }
Exemplo n.º 26
0
 public static void UpdateFeatureGeometry(string path, string featureClassName, Geometry newGeometry, int oid)
 {
     using (var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(path, UriKind.Absolute))))
     {
         using (var featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName))
         {
             var feature = (Feature)GdbQueryUtils.GetRow(featureClass, oid);
             feature.SetShape(newGeometry);
             feature.Store();
         }
     }
 }
Exemplo n.º 27
0
        public static Row GetRow(string path, string tableName, long oid)
        {
            var uri = new Uri(path, UriKind.Absolute);

            using (var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(uri)))
            {
                using (var table = geodatabase.OpenDataset <Table>(tableName))
                {
                    return(GdbQueryUtils.GetRow(table, oid));
                }
            }
        }
Exemplo n.º 28
0
 public static void UpdateDescription(string path, string featureClassName, int oid)
 {
     using (var geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(path, UriKind.Absolute))))
     {
         using (var table = geodatabase.OpenDataset <Table>(featureClassName))
         {
             var row = GdbQueryUtils.GetRow(table, oid);
             row["Description"] = "Moe";
             row.Store();
         }
     }
 }
Exemplo n.º 29
0
 public static bool HasFeatureClass(this Geodatabase gdb, string name)
 {
     try
     {
         var table = gdb.OpenDataset <FeatureClass>(name);
         return(true);
     }
     catch (GeodatabaseTableException)
     {
     }
     return(false);
 }
Exemplo n.º 30
0
        /// <summary>
        /// Given that
        /// 1. A layer has been selected
        /// 2. A RelationshipClass has been selected
        /// 3. The Table/FeatureClass related to the Table/FeatureClass corresponding to the layer selected has Attachments enabled
        ///
        /// Then, this method will
        /// 1. Get all the rows of the Related Table/FeatureClass
        /// 2. Find if any row has Attachments which have the same name as the value of "OldAttachmentName"
        /// 3. Replace the Attachment Data for the matching Attachments with the Data corresponding to "NewAttachment"
        /// </summary>
        public void Work()
        {
            QueuedTask.Run(async() =>
            {
                using (Table table = (MapView.Active.Map.Layers.First(layer => layer.Name.Equals(SelectedLayer)) as FeatureLayer).GetTable())
                {
                    Geodatabase geodatabase = null;
                    if (table != null && table.GetDatastore() is Geodatabase)
                    {
                        geodatabase = table.GetDatastore() as Geodatabase;
                    }
                    if (geodatabase == null)
                    {
                        return;
                    }

                    Table relatedTable = geodatabase.OpenDataset <Table>(relatedFeatureClass);
                    if (!relatedTable.IsAttachmentEnabled())
                    {
                        return;
                    }

                    if (String.IsNullOrEmpty(OldAttachmentName))
                    {
                        return;
                    }
                    if (String.IsNullOrEmpty(NewAttachment) || !File.Exists(NewAttachment))
                    {
                        return;
                    }

                    using (MemoryStream newAttachmentMemoryStream = CreateMemoryStreamFromContentsOf(NewAttachment))
                    {
                        using (RowCursor rowCursor = relatedTable.Search(null, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Row row = rowCursor.Current)
                                {
                                    IEnumerable <Attachment> attachments = row.GetAttachments(null, true).Where(attachment => attachment.GetName().Equals(oldAttachmentName));
                                    foreach (Attachment attachment in attachments)
                                    {
                                        attachment.SetData(newAttachmentMemoryStream);
                                        row.UpdateAttachment(attachment);
                                    }
                                }
                            }
                        }
                    }
                }
            });
        }
        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;
        }
        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");
            }
        }