예제 #1
0
        private int CheckPolygonPoints(
            [NotNull] IEnumerable <PolygonPoints> polygonPointsToCheck)
        {
            Assert.ArgumentNotNull(polygonPointsToCheck, nameof(polygonPointsToCheck));

            Dictionary <int, List <PolygonPointsError> > errorsByTable =
                GetErrorsByTable(polygonPointsToCheck);

            int errorCount = 0;

            foreach (KeyValuePair <int, List <PolygonPointsError> > pair in errorsByTable)
            {
                int tableIndex = pair.Key;
                List <PolygonPointsError> errors = pair.Value;

                var featureClass = (IFeatureClass)InvolvedTables[tableIndex];
                Dictionary <int, PolygonPointsError> errorsByOid = GetErrorsByOid(errors);

                const bool recycle = true;
                foreach (
                    IFeature polygonFeature in
                    GdbQueryUtils.GetFeatures(featureClass, errorsByOid.Keys, recycle))
                {
                    IGeometry errorGeometry = polygonFeature.ShapeCopy;

                    PolygonPointsError error = errorsByOid[polygonFeature.OID];

                    errorCount += ReportError(error.ErrorDescription, errorGeometry,
                                              error.IssueCode, null,
                                              GetInvolvedRows(polygonFeature, error));
                }
            }

            return(errorCount);
        }
예제 #2
0
        private static IEnumerable <Feature> GetFeatures([CanBeNull] BasicFeatureLayer layer,
                                                         [NotNull] List <long> oids,
                                                         bool recycling = false)
        {
            if (layer == null)
            {
                yield break;
            }

            // TODO: Use layer search (there might habe been an issue with recycling?!)
            var featureClass = layer.GetTable();

            var filter = new QueryFilter
            {
                WhereClause =
                    $"{featureClass.GetDefinition().GetObjectIDField()} IN ({StringUtils.Concatenate(oids, ", ")})"
            };

            filter.OutputSpatialReference = layer.GetSpatialReference();

            foreach (var feature in GdbQueryUtils.GetFeatures(featureClass, filter, recycling))
            {
                yield return(feature);
            }
        }
예제 #3
0
        private int ExecuteGeometry([CanBeNull] IGeometry geometry)
        {
            if (!_canHaveNonLinearSegments)
            {
                return(NoError);
            }

            IQueryFilter filter = TestUtils.CreateFilter(geometry, AreaOfInterest,
                                                         GetConstraint(0),
                                                         (ITable)_featureClass,
                                                         null);

            GdbQueryUtils.SetSubFields(filter,
                                       _featureClass.OIDFieldName,
                                       _featureClass.ShapeFieldName);

            int errorCount = 0;

            const bool recycle = true;

            foreach (IFeature feature in
                     GdbQueryUtils.GetFeatures(_featureClass, filter, recycle))
            {
                errorCount += VerifyFeature(feature);
            }

            return(errorCount);
        }
예제 #4
0
        private static IDictionary <Guid, QualityConditionExceptions> ReadTargetExceptions(
            [NotNull] IList <IObjectClass> targetExceptionClasses,
            [NotNull] IIssueTableFields fields)
        {
            Assert.ArgumentNotNull(targetExceptionClasses, nameof(targetExceptionClasses));
            Assert.ArgumentCondition(targetExceptionClasses.Count > 0, "no exception classes");

            var result = new Dictionary <Guid, QualityConditionExceptions>();

            foreach (ITable targetTable in targetExceptionClasses.Cast <ITable>())
            {
                var factory = new ExceptionObjectFactory(
                    targetTable, fields,
                    defaultStatus: ExceptionObjectStatus.Inactive,
                    includeManagedExceptionAttributes: true);

                foreach (IRow row in GdbQueryUtils.GetRows(targetTable, recycle: true))
                {
                    ExceptionObject exceptionObject = factory.CreateExceptionObject(row);

                    Guid qconVersionUuid = exceptionObject.QualityConditionVersionUuid;

                    QualityConditionExceptions exceptions;
                    if (!result.TryGetValue(qconVersionUuid, out exceptions))
                    {
                        exceptions = new QualityConditionExceptions(qconVersionUuid, null);
                        result.Add(qconVersionUuid, exceptions);
                    }

                    exceptions.Add(exceptionObject);
                }
            }

            return(result);
        }
예제 #5
0
        public void CanGetNullForNonExistingFeatureByGetRow()
        {
            IFeatureWorkspace ws = OpenTestWorkspace();
            IFeatureClass     fc = ws.OpenFeatureClass("TOPGIS_TLM.TLM_STRASSE");

            Assert.Null(GdbQueryUtils.GetRow((ITable)fc, 999999999));
        }
예제 #6
0
        private static IEnumerable <IRow> GetReferencingRows(
            [NotNull] ReferencedTableInfo referencedTableInfo,
            [NotNull] ReferencingTableInfo referencingTableInfo)
        {
            const bool recycle     = true;
            const int  maxKeyCount = 20;

            if (referencedTableInfo.KeySet.Count <= maxKeyCount)
            {
                return(GdbQueryUtils.GetRowsInList(
                           referencingTableInfo.Table,
                           referencingTableInfo.ForeignKeyFieldName,
                           referencedTableInfo.KeySet, recycle,
                           referencingTableInfo.Filter));
            }

            var queryFilter =
                new QueryFilterClass
            {
                WhereClause = string.Format("{0} IS NOT NULL",
                                            referencingTableInfo.ForeignKeyFieldName)
            };

            return(GdbQueryUtils.GetRows(referencingTableInfo.Table, queryFilter,
                                         recycle));
        }
예제 #7
0
        private IQueryFilter CreateFilter([NotNull] IFeatureClass featureClass,
                                          [CanBeNull] string filterExpression)
        {
            IQueryFilter filter =
                new QueryFilterClass
            {
                SubFields   = _shapeFieldName,
                WhereClause =
                    GetWhereClause(featureClass, filterExpression,
                                   _dontFilterPolycurvesByZeroLength)
            };

            var subfields = new List <string> {
                _shapeFieldName
            };

            if (featureClass.HasOID)
            {
                subfields.Add(featureClass.OIDFieldName);
            }

            GdbQueryUtils.SetSubFields(filter, subfields);

            return(filter);
        }
예제 #8
0
        private int ReportErrors([NotNull] ICollection <RowErrorInfo> errorRows)
        {
            Assert.ArgumentNotNull(errorRows);

            var oids        = new List <int>(errorRows.Count);
            var errorsByOid = new Dictionary <int, ErrorInfo>(errorRows.Count);

            foreach (RowErrorInfo errorRow in errorRows)
            {
                oids.Add(errorRow.RowUrl.Oid);
                errorsByOid.Add(errorRow.RowUrl.Oid, errorRow.ErrorInfo);
            }

            if (oids.Count == 0)
            {
                return(NoError);
            }

            var errorCount = 0;

            const bool recycling = false;

            foreach (IRow row in GdbQueryUtils.GetRowsByObjectIds(_table, oids, recycling))
            {
                errorCount += ReportError(errorsByOid[row.OID], row);
            }

            return(errorCount);
        }
예제 #9
0
        private static IEnumerable <IRow> GetJoinedRows(
            [NotNull] IObject obj,
            [NotNull] IList <IRelationshipClass> relationshipChainToFeatureClass)
        {
            string whereClause = string.Format(
                "{0} = {1}",
                DatasetUtils.QualifyFieldName(obj.Class, obj.Class.OIDFieldName),
                obj.OID);

            const IGeometry intersectedGeometry  = null;
            string          postfixClause        = null;
            string          subfields            = null;
            const bool      includeOnlyOIDFields = true;
            const bool      recycle = false;

            foreach (FieldMappingRowProxy rowProxy in GdbQueryUtils.GetRowProxys(
                         obj.Class,
                         intersectedGeometry,
                         whereClause,
                         relationshipChainToFeatureClass,
                         postfixClause,
                         subfields, includeOnlyOIDFields, recycle))
            {
                yield return(rowProxy.BaseRow);
            }
        }
예제 #10
0
        private IQueryFilter GetQueryFilter([NotNull] IFeatureClass featureClass,
                                            int tableIndex,
                                            [CanBeNull] IGeometry geometry)
        {
            Assert.ArgumentNotNull(featureClass, nameof(featureClass));

            string routeIdFieldName = GetRouteIdFieldName(featureClass, tableIndex);

            IQueryFilter result;

            if (geometry == null)
            {
                result = new QueryFilterClass();
            }
            else
            {
                result = new SpatialFilterClass
                {
                    GeometryField = featureClass.ShapeFieldName,
                    SpatialRel    = esriSpatialRelEnum.esriSpatialRelIntersects,
                    Geometry      = geometry
                };
            }

            result.WhereClause = GetWhereClause(tableIndex, routeIdFieldName);

            GdbQueryUtils.SetSubFields(result,
                                       featureClass.OIDFieldName,
                                       featureClass.ShapeFieldName,
                                       routeIdFieldName);

            return(result);
        }
예제 #11
0
        public void CanCreateSpatialFilterWithSubResolutionPolygon()
        {
            IFeatureWorkspace ws = OpenTestWorkspace();
            IFeatureClass     fc = ws.OpenFeatureClass("TOPGIS_TLM.TLM_STRASSE");

            IPolygon subResolutionPoly = GeometryFactory.CreatePolygon(2600000, 1200000,
                                                                       2600000.0001,
                                                                       1200000.0001);

            subResolutionPoly.SpatialReference = ((IGeoDataset)fc).SpatialReference;

            IQueryFilter filter = GdbQueryUtils.CreateSpatialFilter(
                fc, subResolutionPoly, esriSpatialRelEnum.esriSpatialRelIntersects, false,
                null);

            IFeatureCursor cursor = fc.Search(filter, true);

            Marshal.ReleaseComObject(cursor);

            IPolygon linearPoly = GeometryFactory.CreatePolygon(2600000, 1200000,
                                                                2600000.0001, 1200010);

            linearPoly.SpatialReference = ((IGeoDataset)fc).SpatialReference;

            filter = GdbQueryUtils.CreateSpatialFilter(
                fc, linearPoly, esriSpatialRelEnum.esriSpatialRelIntersects, true,
                null);

            cursor = fc.Search(filter, true);
            Marshal.ReleaseComObject(cursor);
        }
예제 #12
0
        public void CanCreateSpatialFilterWithNonZSimpleGeometry()
        {
            IFeatureWorkspace ws = OpenTestWorkspace();
            IFeatureClass     fc = ws.OpenFeatureClass("TOPGIS_TLM.TLM_STRASSE");

            IEnvelope nonZSimpleEnvelope = GeometryFactory.CreateEnvelope(2600000, 1200000,
                                                                          2700000, 1300000);

            GeometryUtils.MakeZAware(nonZSimpleEnvelope);

            Assert.False(((IZAware)nonZSimpleEnvelope).ZSimple, "Must be non-Z-simple");

            ISpatialReference spatialReference =
                Assert.NotNull(DatasetUtils.GetSpatialReference(fc));

            IGeometry validGeometry;
            string    message;

            Assert.False(GdbQueryUtils.IsValidFilterGeometry(
                             nonZSimpleEnvelope,
                             SpatialReferenceUtils.GetXyResolution(spatialReference),
                             out validGeometry, out message),
                         "Search geometry should not be valid");

            Assert.NotNull(validGeometry);

            IQueryFilter filter = GdbQueryUtils.CreateSpatialFilter(fc, nonZSimpleEnvelope);

            Assert.True(GdbQueryUtils.GetFeatures(fc, filter, true).Any(), "No features found");
        }
예제 #13
0
        public void CanGetRowsNotInUUIDList()
        {
            IFeatureWorkspace ws  = OpenTestWorkspace();
            ITable            tbl = ws.OpenTable("TOPGIS_TLM.TLM_STRASSE");

            var          nRows  = 0;
            IQueryFilter filter = new QueryFilterClass();

            foreach (
                // ReSharper disable once UnusedVariable
                IRow row in
                GdbQueryUtils.GetRowsNotInList(tbl, filter, true, "UUID",
                                               new[]
            {
                "{8C5517C9-B19F-4CC1-A6A1-D3DD317BCDD1}"
            }))
            {
                nRows++;
            }

            filter.WhereClause = "UUID not in ('{8C5517C9-B19F-4CC1-A6A1-D3DD317BCDD1}')";
            int n = tbl.RowCount(filter);

            Assert.AreEqual(n, nRows, "");
        }
예제 #14
0
        public void Learning_CanFindFeaturesWithNonZSimpleSearchGeometry()
        {
            // 10.2.1: Test fails (correct) with COM Exception on OpenCursor
            // 10.4.1: Test fails (correct) with COM Exception on OpenCursor
            // 10.6.1: Test passes (incorrectly!), no features found

            IFeatureWorkspace ws = OpenTestWorkspace();
            IFeatureClass     fc = ws.OpenFeatureClass("TOPGIS_TLM.TLM_STRASSE");

            IEnvelope nonZSimpleEnvelope = GeometryFactory.CreateEnvelope(2600000, 1200000,
                                                                          2700000, 1300000);

            GeometryUtils.MakeZAware(nonZSimpleEnvelope);

            Assert.False(((IZAware)nonZSimpleEnvelope).ZSimple, "Must be non-Z-simple");

            ISpatialReference spatialReference = DatasetUtils.GetSpatialReference(fc);

            nonZSimpleEnvelope.SpatialReference = spatialReference;

            ISpatialFilter spatialFilter = new SpatialFilterClass();

            spatialFilter.GeometryField = fc.ShapeFieldName;
            spatialFilter.set_GeometryEx(nonZSimpleEnvelope, true);
            spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;

            Assert.AreEqual(0, GdbQueryUtils.GetFeatures(fc, spatialFilter, true).Count(),
                            "Behaviour changed: Now features are found even with non-Z-simple search geometry.");
        }
예제 #15
0
        public void CanGetRowsInLongList()
        {
            IFeatureWorkspace ws = OpenTestWorkspace();
            IFeatureClass     fc = ws.OpenFeatureClass("TOPGIS_TLM.TLM_STRASSE");

            // fill list
            const int max = 2000;
            Dictionary <int, IRow> dic = GetFirstNRows((ITable)fc, max);

            var selList = new List <int>(max);

            foreach (IRow row in GdbQueryUtils.GetRowsInList((ITable)fc, fc.OIDFieldName,
                                                             dic.Keys, false, null))
            {
                selList.Add(row.OID);
                IRow origRow = dic[row.OID];
                Assert.AreEqual(origRow.OID, row.OID, "");
                //dic[row.OID] = null; REMARK: this changes list dic.Keys and leads to an error in foreach
            }

            Assert.AreEqual(dic.Count, selList.Count, "List counts differ");

            var oidList = new List <int>(dic.Keys);

            oidList.Sort();
            selList.Sort();
            for (var i = 0; i < oidList.Count; i++)
            {
                Assert.AreEqual(oidList[i], selList[i], "{0}th element differs", i);
            }
        }
예제 #16
0
        public void CanGetNullForNonExistingRow()
        {
            IFeatureWorkspace ws    = OpenTestWorkspace();
            ITable            table = ws.OpenTable("TOPGIS_TLM.TLM_WANDERWEG");

            Assert.Null(GdbQueryUtils.GetRow(table, 999999999));
        }
예제 #17
0
        public void CanGetNullForNonExistingFeatureFastEnough()
        {
            IFeatureWorkspace ws = OpenTestWorkspace();
            IFeatureClass     fc = ws.OpenFeatureClass("TOPGIS_TLM.TLM_STRASSE");

            const int iterations = 200;

            var watch = new Stopwatch();

            watch.Start();

            for (var iteration = 0; iteration < iterations; iteration++)
            {
                int oid = 999999999 + iteration;
                Assert.Null(GdbQueryUtils.GetFeature(fc, oid));
            }

            watch.Stop();

            double msPerIteration = watch.ElapsedMilliseconds / (double)iterations;

            _msg.InfoFormat(@"GetFeature() per iteration: {0} ms", msPerIteration);

            const int maxMilliseconds = 35;

            Assert.True(msPerIteration < maxMilliseconds,
                        "GetFeature with non-existing feature takes too long ({0} ms)",
                        msPerIteration);
        }
예제 #18
0
        public void CanConvertMultipatchesSpecialCasesWithInnerRings()
        {
            IWorkspace workspace = TestUtils.OpenSDEWorkspaceOracle();

            IFeatureClass featureClass = DatasetUtils.OpenFeatureClass(
                workspace, "TOPGIS_TLM.TLM_GEBAEUDE");

            const int    rolexLearningCenter      = 321430;
            const int    mediamarktMuriBB         = 565844;
            const int    hintermBahnhofGraenichen = 2269631;
            IQueryFilter qf = new QueryFilterClass()
            {
                WhereClause = "OBJECTID IN (" +
                              $"{hintermBahnhofGraenichen}, " +
                              $"{mediamarktMuriBB}, " +
                              $"{rolexLearningCenter})"
            };
            int count = 0;

            foreach (IFeature feature in GdbQueryUtils.GetFeatures(featureClass, qf, true))
            {
                count++;

                AssertWkbSerialization(feature, false);
                AssertWkbSerialization(feature, true);
            }

            Assert.AreEqual(3, count);
        }
예제 #19
0
        public void CanGetExistingRowsFastEnough()
        {
            IFeatureWorkspace ws = OpenTestWorkspace();
            ITable            fc = ws.OpenTable("TOPGIS_TLM.TLM_WANDERWEG");

            const int max = 100;
            IDictionary <int, IRow> rows = GetFirstNRows(fc, max);

            var watch = new Stopwatch();

            watch.Start();

            foreach (int oid in rows.Keys)
            {
                Assert.NotNull(GdbQueryUtils.GetRow(fc, oid));
                _msg.Info($"Oid {oid} time: {watch.ElapsedMilliseconds}");
            }

            watch.Stop();

            double msPerIteration = watch.ElapsedMilliseconds / (double)rows.Count;

            _msg.InfoFormat(@"GetRow() per iteration: {0} ms", msPerIteration);

            Assert.True(msPerIteration < 50,
                        "GetFeature with existing feature takes too long ({0} ms, {1} rows)",
                        msPerIteration, rows.Count);
        }
예제 #20
0
        public static IGeometry GetShapeCopy([NotNull] IRow row)
        {
            if (row is IFeature)
            {
                var feature = (IFeature)row;

                // TODO optimize
                // - feature.Extent creates a copy (feature.Shape.QueryEnvelope() does not)
                // - the feature may really have no geometry (shapefield was in subfields), in this case the additional get just makes it slow
                if (feature.Extent.IsEmpty)
                {
                    // this may be the case when the ShapeField was not queried (i.e. QueryFilter.SubFields = 'OID, Field')
                    if (row.HasOID && row.Table.HasOID)
                    {
                        feature =
                            GdbQueryUtils.GetFeature((IFeatureClass)row.Table, row.OID);

                        if (feature != null)
                        {
                            return(feature.ShapeCopy);
                        }
                    }
                }
                else
                {
                    return(feature.ShapeCopy);
                }
            }

            return(null);
        }
        private IList <IRow> GetRowsByRelatedGeometry(
            [NotNull] ITable table,
            [NotNull] IObjectDataset objectDataset,
            [NotNull] ITest testWithTable,
            [NotNull] IEnumerable <IList <IRelationshipClass> > relClassChains)
        {
            Assert.ArgumentNotNull(table, nameof(table));
            Assert.ArgumentNotNull(objectDataset, nameof(objectDataset));
            Assert.ArgumentNotNull(testWithTable, nameof(testWithTable));

            HashSet <int> oids = ReferenceGeometryUtils.GetOidsByRelatedGeometry(
                table, relClassChains, Assert.NotNull(_testPerimeter), testWithTable);

            // Add oids of selected rows
            if (ObjectSelection != null)
            {
                oids.UnionWith(ObjectSelection.GetSelectedOIDs(objectDataset));
            }

            if (oids.Count == 0)
            {
                return(new List <IRow>());
            }

            return(new List <IRow>(GdbQueryUtils.GetRowsInList(
                                       table, table.OIDFieldName, oids,
                                       recycle: false)));
        }
예제 #22
0
        public void CanCreateQueryLayerFeatureClassForUnegisteredStGeometryTable()
        {
            IWorkspace workspace = TestUtils.OpenDDxWorkspaceOracle();

            const string periFclass = "UNITTEST_MANAGER.TOPDD_WFL_REVISIONPERI_POLY";
            const string rpView     = "UNITTEST_MANAGER.V_TOPDD_WFL_REVISIONPERIMETER";
            string       periFK     = string.Format("{0}.PERIMETER_OID", rpView);
            string       periPK     = "OBJECTID";

            string tables = string.Format("{0}, {1}", periFclass, rpView);

            string joinExpression = string.Format("{0} = {1}", periFK, periPK);

            string sql = $"SELECT * FROM {tables} WHERE {joinExpression}";

            string queryClassName =
                DatasetUtils.GetQueryLayerClassName((IFeatureWorkspace)workspace,
                                                    "TEST_CLASS");

            // Unqualified Name must start with %, and it is owned by the current user:
            Assert.AreEqual("UNITTEST.%TEST_CLASS", queryClassName);

            double xyTolerance = 0.01;

            IFeatureClass fclass = (IFeatureClass)
                                   DatasetUtils.CreateQueryLayerClass((ISqlWorkspace)workspace, sql, queryClassName,
                                                                      periPK, xyTolerance);

            var filter = new SpatialFilterClass
            {
                Geometry =
                    GeometryFactory.CreateEnvelope(2600000, 1200000, 2700000, 1300000),
                SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
            };

            IFeatureCursor cursor = fclass.Search(filter, true);

            Assert.NotNull(cursor.NextFeature());
            Marshal.ReleaseComObject(cursor);

            int countInBox = GdbQueryUtils.Count(fclass, filter.Geometry);
            int countAll   = GdbQueryUtils.Count(fclass);

            Assert.AreEqual(78, countInBox);
            Assert.AreEqual(260, countAll);

            Assert.AreEqual(countInBox, fclass.FeatureCount(filter));
            Assert.AreEqual(countAll, fclass.FeatureCount(null));

            // solution found elsewhere: only spatial queries work, need to pass spatial filter with geometry
            IFeatureCursor cursorWithNullFilter = fclass.Search(null, true);

            IFeature feature = cursorWithNullFilter.NextFeature();

            Assert.NotNull(feature);
            Assert.AreEqual(xyTolerance, GeometryUtils.GetXyTolerance(feature.Shape));

            Marshal.ReleaseComObject(cursorWithNullFilter);
        }
예제 #23
0
        public IObject GetObject([NotNull] IFeatureWorkspace workspace)
        {
            Assert.ArgumentNotNull(workspace, nameof(workspace));

            IObjectClass objectClass = DatasetUtils.OpenObjectClass(workspace, ClassId);

            return(GdbQueryUtils.GetObject(objectClass, ObjectId));
        }
예제 #24
0
        /// <summary>
        /// Finds the features in the map by the specified criteria, grouped by feature class
        /// </summary>
        /// <param name="mapView">The map view containing the layers to search</param>
        /// <param name="searchGeometry">The search geometry</param>
        /// <param name="spatialRelationship">The spatial relationship between the found features
        /// and the search geometry.</param>
        /// <param name="targetSelectionType">The target selection type that determines which layers
        /// are searched.</param>
        /// <param name="layerPredicate">An extra layer predicate that allows for a more
        /// fine-granular determination of the layers to be searched.</param>
        /// <param name="featurePredicate">An extra feature predicate that allows to determine
        /// criteria on the feature level.</param>
        /// <param name="selectedFeatures">The selected features, relevant only for
        /// <see cref="targetSelectionType"/> with value <see cref="TargetFeatureSelection.SameClass"/>. </param>
        /// <param name="cancelableProgressor"></param>
        /// <returns></returns>
        public static IEnumerable <KeyValuePair <FeatureClass, List <Feature> > > FindFeatures(
            [NotNull] MapView mapView,
            [NotNull] ArcGIS.Core.Geometry.Geometry searchGeometry,
            SpatialRelationship spatialRelationship,
            TargetFeatureSelection targetSelectionType,
            [CanBeNull] Predicate <FeatureLayer> layerPredicate,
            [CanBeNull] Predicate <Feature> featurePredicate,
            List <Feature> selectedFeatures,
            CancelableProgressor cancelableProgressor = null)
        {
            // NOTE: FeatureLayer.Search is quite useless, as we cannot control recyclability and as soon as the cursor
            //       is disposed, the feature's geometry is wrong!

            // -> Get the distinct feature classes (TODO: include layer definition queries)

            IEnumerable <FeatureLayer> featureLayers =
                GetLayers <FeatureLayer>(
                    mapView, fl => IsLayerApplicable(fl, targetSelectionType, layerPredicate,
                                                     selectedFeatures));

            IEnumerable <IGrouping <IntPtr, FeatureLayer> > layersGroupedByClass =
                featureLayers.GroupBy(fl => fl.GetFeatureClass().Handle);

            foreach (var layersInClass in layersGroupedByClass)
            {
                // One query per distinct definition query, then make OIDs distinct

                FeatureClass   featureClass = null;
                List <Feature> features     = new List <Feature>();
                foreach (IGrouping <string, FeatureLayer> layers in layersInClass.GroupBy(
                             fl => fl.DefinitionQuery))
                {
                    if (cancelableProgressor != null &&
                        cancelableProgressor.CancellationToken.IsCancellationRequested)
                    {
                        yield break;
                    }

                    featureClass = layers.First().GetFeatureClass();

                    QueryFilter filter =
                        GdbQueryUtils.CreateSpatialFilter(searchGeometry, spatialRelationship);
                    filter.WhereClause = layers.Key;

                    IEnumerable <Feature> foundFeatures = GdbQueryUtils
                                                          .GetFeatures(featureClass, filter, false)
                                                          .Where(f => featurePredicate == null ||
                                                                 featurePredicate(f));
                    features.AddRange(foundFeatures);
                }

                if (featureClass != null && features.Count > 0)
                {
                    yield return(new KeyValuePair <FeatureClass, List <Feature> >(
                                     featureClass, features.DistinctBy(f => f.GetObjectID()).ToList()));
                }
            }
        }
예제 #25
0
        public void CanGetRasterFileFromMosaicDatasetUsingSpatialQuery()
        {
            IWorkspace workspace = TestUtils.OpenUserWorkspaceOracle();

            IMosaicDataset mosaicDataset = DatasetUtils.OpenMosaicDataset(workspace,
                                                                          "TOPGIS_TLM.TLM_DTM_MOSAIC");

            IFeatureClass rasterCatalog = mosaicDataset.Catalog;

            IEnvelope winterthur = GeometryFactory.CreateEnvelope(
                2690000, 1254000, 2707500, 1266000,
                SpatialReferenceUtils.CreateSpatialReference(WellKnownHorizontalCS.LV95));

            winterthur.Expand(-0.1, -0.1, false);

            IQueryFilter spatialFilter =
                GdbQueryUtils.CreateSpatialFilter(rasterCatalog, winterthur);

            IStringArray stringArray;
            Stopwatch    watch = Stopwatch.StartNew();

            int count = 0;

            foreach (IFeature catalogFeature in GdbQueryUtils.GetFeatures(
                         rasterCatalog, spatialFilter, false))
            {
                // Method 1 (slow):
                var rasterCatalogItem = (IRasterCatalogItem)catalogFeature;

                IRasterDataset rasterDataset = rasterCatalogItem.RasterDataset;
                var            itemPaths     = (IItemPaths)rasterDataset;
                stringArray = itemPaths.GetPaths();
                Marshal.ReleaseComObject(rasterDataset);

                Assert.AreEqual(1, stringArray.Count);

                string resultPathViaRasterDataset = stringArray.Element[0];

                // Method 2 (fast):
                var itemPathsQuery = (IItemPathsQuery)mosaicDataset;

                if (itemPathsQuery.QueryPathsParameters == null)
                {
                    itemPathsQuery.QueryPathsParameters = new QueryPathsParametersClass();
                }

                stringArray = itemPathsQuery.GetItemPaths(catalogFeature);
                Assert.AreEqual(1, stringArray.Count);

                string resultPathViaItemPathsQuery = stringArray.Element[0];
                Assert.AreEqual(resultPathViaRasterDataset, resultPathViaItemPathsQuery);
                count++;
            }

            Console.WriteLine("Successfully extracted {0} raster paths in {1}s", count,
                              watch.Elapsed.TotalSeconds);
        }
예제 #26
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);
            }
        }
예제 #27
0
        public void CanCreateGdbFeatureClass()
        {
            // An in-memory backing dataset is created automatically, if no factory method is provided
            GdbFeatureClass gdbFeatureClass =
                new GdbFeatureClass(41, "TESTABLE", esriGeometryType.esriGeometryPoint,
                                    "Test table");

            IFeatureClass featureClass = gdbFeatureClass;

            Assert.AreEqual(41, featureClass.ObjectClassID);
            Assert.AreEqual("TESTABLE", DatasetUtils.GetName(featureClass));
            Assert.AreEqual("Test table",
                            DatasetUtils.GetAliasName(featureClass));
            Assert.AreEqual(esriGeometryType.esriGeometryPoint,
                            featureClass.ShapeType);

            Assert.False(featureClass.HasOID);
            Assert.Null(featureClass.OIDFieldName);

            Assert.AreEqual(0, GdbQueryUtils.Count(featureClass, ""));

            // Add OID field
            gdbFeatureClass.AddField(FieldUtils.CreateOIDField());

            // Add Shape field
            gdbFeatureClass.AddField(
                FieldUtils.CreateShapeField(
                    esriGeometryType.esriGeometryPoint,
                    SpatialReferenceUtils.CreateSpatialReference(WellKnownHorizontalCS.LV95)));

            Assert.True(featureClass.HasOID);
            Assert.AreEqual("OBJECTID", featureClass.OIDFieldName);
            Assert.AreEqual("SHAPE", featureClass.ShapeFieldName);

            IQueryFilter queryFilter = GdbQueryUtils.CreateQueryFilter("OBJECTID");

            queryFilter.WhereClause = "OBJECTID < 0";

            Assert.AreEqual(0,
                            GdbQueryUtils.Count(featureClass, queryFilter));

            var backingDataset = gdbFeatureClass.BackingDataset as InMemoryDataset;

            Assert.NotNull(backingDataset);

            backingDataset.AllRows.Add(new GdbRow(1, gdbFeatureClass));

            Assert.AreEqual(0,
                            GdbQueryUtils.Count(featureClass, queryFilter));

            queryFilter.WhereClause = "OBJECTID > 0";

            Assert.AreEqual(1,
                            GdbQueryUtils.Count(featureClass, queryFilter));
        }
        public IObject GetObject([NotNull] IFeatureWorkspace workspace)
        {
            Assert.ArgumentNotNull(workspace, nameof(workspace));

            IObjectClass objectClass = DatasetUtils.OpenObjectClass(workspace,
                                                                    RelationshipClassId);

            // TODO consider using ITable.GetRow(oid) and handling exception if not found
            // faster?
            return(GdbQueryUtils.GetObject(objectClass, ObjectId));
        }
예제 #29
0
        private static IQueryFilter GetQueryFilter([NotNull] IEnumerable <string> keyFields,
                                                   [CanBeNull] string whereClause)
        {
            var result = new QueryFilterClass {
                WhereClause = whereClause
            };

            GdbQueryUtils.SetSubFields(result, keyFields);

            return(result);
        }
예제 #30
0
        private static IEnumerable <IGeometry> GetReferenceGeometries(
            [NotNull] IObject obj,
            [NotNull] IList <IRelationshipClass> relationshipChainToFeatureClass)
        {
            if (relationshipChainToFeatureClass.Count == 0)
            {
                yield break;
            }

            if (relationshipChainToFeatureClass.Count == 1)
            {
                foreach (IObject relatedObject in
                         GdbQueryUtils.GetRelatedObjects(obj, relationshipChainToFeatureClass))
                {
                    var relatedFeature = relatedObject as IFeature;

                    if (relatedFeature != null)
                    {
                        yield return(relatedFeature.Shape);
                    }
                    else
                    {
                        _msg.DebugFormat("Related object in spatial relation is not a feature: {0}",
                                         GdbObjectUtils.ToString(relatedObject));
                    }
                }
            }
            else
            {
                int?shapeFieldIndex = null;

                foreach (IRow joinedRow in GetJoinedRows(obj, relationshipChainToFeatureClass))
                {
                    // determine shape field index based on the first row
                    if (shapeFieldIndex == null)
                    {
                        int index;
                        if (TryGetShapeFieldIndex(joinedRow.Fields, out index))
                        {
                            shapeFieldIndex = index;
                        }
                        else
                        {
                            _msg.WarnFormat(
                                "Shape field not found in joined table for getting reference geometry for {0}",
                                DatasetUtils.GetName(obj.Class));
                            yield break;
                        }
                    }

                    yield return(joinedRow.Value[shapeFieldIndex.Value] as IGeometry);
                }
            }
        }