コード例 #1
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();
                }
        }
コード例 #2
0
        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 (FeatureClassDefinition featureClassDefinition = geodatabase.GetDefinition <FeatureClassDefinition>("LocalGovernment.GDB.ServiceRequestComment"))
                {
                    int   rankIndex = featureClassDefinition.FindField("RANK");
                    Field field     = featureClassDefinition.GetFields()[rankIndex];

                    Domain domain = field.GetDomain();

                    RangeDomain rangeDomain = (RangeDomain)domain;

                    // Will be "ServiceRequestRanking".
                    string name = rangeDomain.GetName();

                    // Will be FieldType.Integer.
                    FieldType fieldType = rangeDomain.GetFieldType();

                    // Will be "A factor assigned to unassigned service requests indicating importance".
                    string description = rangeDomain.GetDescription();

                    // Will be 1.
                    int minValue = Convert.ToInt32(rangeDomain.GetMinValue());

                    // Will be 5.
                    int maxValue = Convert.ToInt32(rangeDomain.GetMaxValue());
                }
        }
コード例 #3
0
        protected override WorkListStatusSchema CreateStatusSchemaCore(FeatureClassDefinition definition)
        {
            int fieldIndex;

            try
            {
                fieldIndex = definition.FindField(_statusFieldName);

                if (fieldIndex < 0)
                {
                    throw new ArgumentException($"No field {_statusFieldName}");
                }
            }
            catch (Exception e)
            {
                _msg.Error($"Error find field {_statusFieldName} in {definition.GetName()}", e);
                throw;
            }

            return(new WorkListStatusSchema(_statusFieldName, fieldIndex,
                                            (int)IssueCorrectionStatus.NotCorrected,
                                            (int)IssueCorrectionStatus.Corrected));
        }
コード例 #4
0
        private async Task <string> AddFeatureToLayer(Geometry geom, EllipseAttributes attributes)
        {
            string message = String.Empty;

            if (attributes == null)
            {
                message = "Attributes are Empty"; // For debug does not need to be resource
                return(message);
            }

            FeatureClass ellipseFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true);

            if (ellipseFeatureClass == null)
            {
                message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName();
                return(message);
            }

            bool creationResult = false;

            FeatureClassDefinition ellipseDefinition = ellipseFeatureClass.GetDefinition();

            EditOperation editOperation = new EditOperation();

            editOperation.Name = "Ellipse Feature Insert";
            editOperation.Callback(context =>
            {
                try
                {
                    RowBuffer rowBuffer = ellipseFeatureClass.CreateRowBuffer();

                    if (ellipseDefinition.FindField("Major") >= 0)
                    {
                        rowBuffer["Major"] = attributes.majorAxis;       // Text
                    }
                    if (ellipseDefinition.FindField("Minor") >= 0)
                    {
                        rowBuffer["Minor"] = attributes.minorAxis;       // Double
                    }
                    if (ellipseDefinition.FindField("DistUnit") >= 0)
                    {
                        rowBuffer["DistUnit"] = attributes.distanceunit; // Text
                    }
                    if (ellipseDefinition.FindField("Angle") >= 0)
                    {
                        rowBuffer["Angle"] = attributes.angle;           // Double
                    }
                    if (ellipseDefinition.FindField("AngleUnit") >= 0)
                    {
                        rowBuffer["AngleUnit"] = attributes.angleunit;   // Text
                    }
                    if (ellipseDefinition.FindField("CenterX") >= 0)
                    {
                        rowBuffer["CenterX"] = attributes.centerx;       // Double
                    }
                    if (ellipseDefinition.FindField("CenterY") >= 0)
                    {
                        rowBuffer["CenterY"] = attributes.centery;       // Double
                    }
                    rowBuffer["Shape"] = GeometryEngine.Instance.Project(geom, ellipseDefinition.GetSpatialReference());

                    Feature feature = ellipseFeatureClass.CreateRow(rowBuffer);
                    feature.Store();

                    //To indicate that the attribute table has to be updated
                    context.Invalidate(feature);
                }
                catch (GeodatabaseException geodatabaseException)
                {
                    message = geodatabaseException.Message;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }, ellipseFeatureClass);

            await QueuedTask.Run(async() =>
            {
                creationResult = await editOperation.ExecuteAsync();
            });

            if (!creationResult)
            {
                message = editOperation.ErrorMessage;
            }

            return(message);
        }
コード例 #5
0
        private async Task <string> AddFeatureToLayer(Geometry geom, RangeAttributes attributes)
        {
            string message = String.Empty;

            if (attributes == null)
            {
                message = "Attributes are Empty"; // For debug does not need to be resource
                return(message);
            }

            FeatureClass ringFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true);

            if (ringFeatureClass == null)
            {
                message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName();
                return(message);
            }

            bool creationResult = false;

            FeatureClassDefinition ringDefinition = ringFeatureClass.GetDefinition();

            EditOperation editOperation = new EditOperation();

            editOperation.Name = "Ring Feature Insert";
            editOperation.Callback(context =>
            {
                try
                {
                    RowBuffer rowBuffer = ringFeatureClass.CreateRowBuffer();

                    if (ringDefinition.FindField("Distance") >= 0)
                    {
                        rowBuffer["Distance"] = attributes.distance;     // Double
                    }
                    if (ringDefinition.FindField("DistUnit") >= 0)
                    {
                        rowBuffer["DistUnit"] = attributes.distanceunit; // Text
                    }
                    if (ringDefinition.FindField("Rings") >= 0)
                    {
                        rowBuffer["Rings"] = attributes.numRings;        // Double
                    }
                    if (ringDefinition.FindField("CenterX") >= 0)
                    {
                        rowBuffer["CenterX"] = attributes.centerx;       // Double
                    }
                    if (ringDefinition.FindField("CenterY") >= 0)
                    {
                        rowBuffer["CenterY"] = attributes.centery;       // Double
                    }
                    if (ringDefinition.FindField("RRType") >= 0)
                    {
                        rowBuffer["RRType"] = attributes.ringorradial;   // Double
                    }
                    // Ensure Z removed (this feature class does not have Z)
                    var geoNoZ = geom;
                    if (geom.HasZ)
                    {
                        PolylineBuilder pb = new PolylineBuilder((Polyline)geom);
                        pb.HasZ            = false;
                        geoNoZ             = pb.ToGeometry();
                    }

                    rowBuffer["Shape"] = GeometryEngine.Instance.Project(geoNoZ, ringDefinition.GetSpatialReference());

                    Feature feature = ringFeatureClass.CreateRow(rowBuffer);
                    feature.Store();

                    //To Indicate that the attribute table has to be updated
                    context.Invalidate(feature);
                }
                catch (GeodatabaseException geodatabaseException)
                {
                    message = geodatabaseException.Message;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }, ringFeatureClass);

            await QueuedTask.Run(async() =>
            {
                creationResult = await editOperation.ExecuteAsync();
            });

            if (!creationResult)
            {
                message = editOperation.ErrorMessage;
            }

            return(message);
        }
コード例 #6
0
        private async Task <string> AddFeatureToLayer(Geometry geom, CircleAttributes attributes)
        {
            string message = String.Empty;

            if (attributes == null)
            {
                message = "Attributes are Empty"; // For debug does not need to be resource
                return(message);
            }

            FeatureClass circleFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true);

            if (circleFeatureClass == null)
            {
                message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName();
                return(message);
            }

            bool creationResult = false;

            FeatureClassDefinition circleDefinition = circleFeatureClass.GetDefinition();

            EditOperation editOperation = new EditOperation();

            editOperation.Name = "Circular Feature Insert";
            editOperation.Callback(context =>
            {
                try
                {
                    RowBuffer rowBuffer = circleFeatureClass.CreateRowBuffer();

                    double distance = attributes.distance;
                    if (IsDistanceCalcExpanded && (CircleType == CircleFromTypes.Diameter))
                    {
                        distance *= 2.0;
                    }

                    if (circleDefinition.FindField("Distance") >= 0)
                    {
                        rowBuffer["Distance"] = distance;     // Double
                    }
                    if (circleDefinition.FindField("DistUnit") >= 0)
                    {
                        rowBuffer["DistUnit"] = attributes.distanceunit; // Text
                    }
                    if (circleDefinition.FindField("DistType") >= 0)
                    {
                        rowBuffer["DistType"] = attributes.circletype;   // Text
                    }
                    if (circleDefinition.FindField("CenterX") >= 0)
                    {
                        rowBuffer["CenterX"] = attributes.centerx;       // Double
                    }
                    if (circleDefinition.FindField("CenterY") >= 0)
                    {
                        rowBuffer["CenterY"] = attributes.centery;       // Double
                    }
                    rowBuffer["Shape"] = GeometryEngine.Instance.Project(geom, circleDefinition.GetSpatialReference());

                    Feature feature = circleFeatureClass.CreateRow(rowBuffer);
                    feature.Store();

                    //To Indicate that the attribute table has to be updated
                    context.Invalidate(feature);
                }
                catch (GeodatabaseException geodatabaseException)
                {
                    message = geodatabaseException.Message;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }, circleFeatureClass);

            await QueuedTask.Run(async() =>
            {
                creationResult = await editOperation.ExecuteAsync();
            });

            if (!creationResult)
            {
                message = editOperation.ErrorMessage;
                await Project.Current.DiscardEditsAsync();
            }
            else
            {
                await Project.Current.SaveEditsAsync();
            }

            return(message);
        }
コード例 #7
0
        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 (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite"))
                {
                    EditOperation editOperation = new EditOperation();
                    editOperation.Callback(context =>
                    {
                        RowBuffer rowBuffer = null;
                        Feature feature     = null;

                        try
                        {
                            FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

                            int facilityIdIndex = facilitySiteDefinition.FindField("FACILITYID");
                            rowBuffer           = enterpriseFeatureClass.CreateRowBuffer();

                            // Either the field index or the field name can be used in the indexer.
                            rowBuffer[facilityIdIndex] = "FAC-400";
                            rowBuffer["NAME"]          = "Griffith Park";
                            rowBuffer["OWNTYPE"]       = "Municipal";
                            rowBuffer["FCODE"]         = "Park";
                            // Add it to Public Attractions Subtype.
                            rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 820;

                            List <Coordinate2D> newCoordinates = new List <Coordinate2D>
                            {
                                new Coordinate2D(1021570, 1880583),
                                new Coordinate2D(1028730, 1880994),
                                new Coordinate2D(1029718, 1875644),
                                new Coordinate2D(1021405, 1875397)
                            };

                            rowBuffer[facilitySiteDefinition.GetShapeField()] = new PolygonBuilder(newCoordinates).ToGeometry();

                            feature = enterpriseFeatureClass.CreateRow(rowBuffer);

                            //To Indicate that the Map has to draw this feature and/or the attribute table to be updated
                            context.Invalidate(feature);

                            long objectID   = feature.GetObjectID();
                            Polygon polygon = feature.GetShape() as Polygon;

                            // Do some other processing with the newly-created feature.
                        }
                        catch (GeodatabaseException exObj)
                        {
                            Console.WriteLine(exObj);
                        }
                        finally
                        {
                            if (rowBuffer != null)
                            {
                                rowBuffer.Dispose();
                            }

                            if (feature != null)
                            {
                                feature.Dispose();
                            }
                        }
                    }, enterpriseFeatureClass);

                    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();
                }
        }
コード例 #8
0
        // Illustrates creating 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"))
                {
                    RowBuffer rowBuffer = null;
                    Feature   feature   = null;

                    try
                    {
                        EditOperation editOperation = new EditOperation();
                        editOperation.Callback(context =>
                        {
                            FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();

                            int nameIndex = featureClassDefinition.FindField("NAME");
                            rowBuffer     = featureClass.CreateRowBuffer();

                            // Either the field index or the field name can be used in the indexer.
                            rowBuffer[nameIndex]   = "New School";
                            rowBuffer["POLLINGID"] = "260";
                            rowBuffer["FULLADD"]   = "100 New Street";
                            rowBuffer["CITY"]      = "Naperville";
                            rowBuffer["STATE"]     = "IL";
                            rowBuffer["OPERHOURS"] = "Yes";
                            rowBuffer["HANDICAP"]  = "6.00am=7.00pm";
                            rowBuffer["NEXTELECT"] = "11/6/2012";
                            rowBuffer["REGDATE"]   = "8/6/2012";
                            rowBuffer["PHONE"]     = "815-740-4782";
                            rowBuffer["EMAIL"]     = "*****@*****.**";

                            rowBuffer[featureClassDefinition.GetShapeField()] = new MapPointBuilder(1028367, 1809789).ToGeometry();

                            feature = featureClass.CreateRow(rowBuffer);

                            //To Indicate that the Map has to draw this feature and/or the attribute table to be updated
                            context.Invalidate(feature);

                            // Do some other processing with the newly-created feature.
                        }, featureClass);

                        bool editResult = editOperation.Execute();

                        // At this point the changes are visible in the process, but not persisted/visible outside.
                        long     objectID = feature.GetObjectID();
                        MapPoint mapPoint = feature.GetShape() as MapPoint;

                        // 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();
                    }
                    catch (GeodatabaseException exObj)
                    {
                        Console.WriteLine(exObj);
                        throw;
                    }
                    finally
                    {
                        if (rowBuffer != null)
                        {
                            rowBuffer.Dispose();
                        }

                        if (feature != null)
                        {
                            feature.Dispose();
                        }
                    }
                }
        }
コード例 #9
0
        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 (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite"))
                {
                    FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();

                    int    facilityCodeIndex = featureClassDefinition.FindField("FCODE");
                    Field  field             = featureClassDefinition.GetFields()[facilityCodeIndex];
                    Domain domain            = field.GetDomain(featureClassDefinition.GetSubtypes().FirstOrDefault(
                                                                   subtype => subtype.GetName().ToLowerInvariant().Contains("agriculture")));

                    CodedValueDomain codedValueDomain = (CodedValueDomain)domain;

                    // Will be "Agriculture Food and Livestock FCode"'.
                    string name = codedValueDomain.GetName();

                    // Will be FieldType.String'.
                    FieldType fieldType = codedValueDomain.GetFieldType();

                    // Will be "The type of agriculture, food and livestock facility"'.
                    string description = codedValueDomain.GetDescription();

                    // Will be 13 since there are 13 code value pairs in this domain'.
                    int numberOfcodedValues = codedValueDomain.GetCount();

                    // This will be a the code value pairs sorted (in this case) by the codes' increasing integer value.
                    SortedList <object, string> codedValuePairs = codedValueDomain.GetCodedValuePairs();

                    FeatureClassDefinition siteAddressPointDefinition = geodatabase.GetDefinition <FeatureClassDefinition>("LocalGovernment.GDB.SiteAddressPoint");
                    int    unitTypeIndex         = siteAddressPointDefinition.FindField("UNITTYPE");
                    Field  unitTypeField         = siteAddressPointDefinition.GetFields()[unitTypeIndex];
                    Domain addressUnitTypeDomain = unitTypeField.GetDomain();

                    CodedValueDomain valueDomain = (CodedValueDomain)addressUnitTypeDomain;

                    // Will be Apartment.
                    string aptCodeDescription = valueDomain.GetName("APT");

                    // Will be Basement.
                    string bsmtCodeDescription = valueDomain.GetName("BSMT");

                    // Will be DEPT. Make sure you know the domain's FieldType is String before cast.
                    string departmentCode = valueDomain.GetCodedValue("Department") as string;

                    // Will be FL.
                    string floorCode = valueDomain.GetCodedValue("Floor") as string;
                }
        }
コード例 #10
0
        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 (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite"))
                {
                    FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

                    int ownTypeIndex = facilitySiteDefinition.FindField("OWNTYPE");
                    int areaIndex    = facilitySiteDefinition.FindField(facilitySiteDefinition.GetAreaField());

                    EditOperation editOperation = new EditOperation();
                    editOperation.Callback(context =>
                    {
                        QueryFilter queryFilter = new QueryFilter {
                            WhereClause = "FCODE = 'Hazardous Materials Facility' AND OWNTYPE = 'Private'"
                        };

                        using (RowCursor rowCursor = enterpriseFeatureClass.Search(queryFilter, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Feature feature = (Feature)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(feature);

                                    // Transfer all Hazardous Material Facilities to the City.
                                    feature[ownTypeIndex] = "Municipal";

                                    if (Convert.ToDouble(feature[areaIndex]) > 50000)
                                    {
                                        // Set the Shape of the feature to whatever you need.

                                        List <Coordinate2D> newCoordinates = new List <Coordinate2D>
                                        {
                                            new Coordinate2D(1021570, 1880583),
                                            new Coordinate2D(1028730, 1880994),
                                            new Coordinate2D(1029718, 1875644),
                                            new Coordinate2D(1021405, 1875397)
                                        };

                                        feature.SetShape(new PolygonBuilder(newCoordinates).ToGeometry());
                                    }

                                    feature.Store();

                                    // Has to be called after the store too
                                    context.Invalidate(feature);
                                }
                            }
                        }
                    }, enterpriseFeatureClass);

                    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();
                }
        }
コード例 #11
0
        private async Task <string> AddFeatureToLayer(Geometry geom, LineAttributes attributes)
        {
            string message = String.Empty;

            if (attributes == null)
            {
                message = "Attributes are Empty"; // For debug does not need to be resource
                return(message);
            }

            FeatureClass lineFeatureClass = await GetFeatureClass(addToMapIfNotPresent : true);

            if (lineFeatureClass == null)
            {
                message = DistanceAndDirectionLibrary.Properties.Resources.ErrorFeatureClassNotFound + this.GetLayerName();
                return(message);
            }

            bool creationResult = false;

            FeatureClassDefinition lineDefinition = lineFeatureClass.GetDefinition();

            EditOperation editOperation = new EditOperation();

            editOperation.Name = "Line Feature Insert";
            editOperation.Callback(context =>
            {
                try
                {
                    RowBuffer rowBuffer = lineFeatureClass.CreateRowBuffer();

                    if (lineDefinition.FindField("Distance") >= 0)
                    {
                        rowBuffer["Distance"] = attributes.distance;     // Double
                    }
                    if (lineDefinition.FindField("DistUnit") >= 0)
                    {
                        rowBuffer["DistUnit"] = attributes.distanceunit; // Text
                    }
                    if (lineDefinition.FindField("Angle") >= 0)
                    {
                        rowBuffer["Angle"] = attributes.angle;       // Double
                    }
                    if (lineDefinition.FindField("AngleUnit") >= 0)
                    {
                        rowBuffer["AngleUnit"] = attributes.angleunit;   // Text
                    }
                    if (lineDefinition.FindField("OriginX") >= 0)
                    {
                        rowBuffer["OriginX"] = attributes.originx;   // Double
                    }
                    if (lineDefinition.FindField("OriginY") >= 0)
                    {
                        rowBuffer["OriginY"] = attributes.originy;   // Double
                    }
                    if (lineDefinition.FindField("DestX") >= 0)
                    {
                        rowBuffer["DestX"] = attributes.destinationx;   // Double
                    }
                    if (lineDefinition.FindField("DestY") >= 0)
                    {
                        rowBuffer["DestY"] = attributes.destinationy;   // Double
                    }
                    // Ensure Geometry Has Z
                    var geomZ = geom;
                    if (!geom.HasZ)
                    {
                        PolylineBuilder pb = new PolylineBuilder((Polyline)geom);
                        pb.HasZ            = true;
                        geomZ = pb.ToGeometry();
                    }

                    rowBuffer["Shape"] = GeometryEngine.Instance.Project(geomZ, lineDefinition.GetSpatialReference());

                    Feature feature = lineFeatureClass.CreateRow(rowBuffer);
                    feature.Store();

                    //To Indicate that the attribute table has to be updated
                    context.Invalidate(feature);
                }
                catch (GeodatabaseException geodatabaseException)
                {
                    message = geodatabaseException.Message;
                }
                catch (Exception ex)
                {
                    message = ex.Message;
                }
            }, lineFeatureClass);

            await QueuedTask.Run(async() =>
            {
                creationResult = await editOperation.ExecuteAsync();
            });

            if (!creationResult)
            {
                message = editOperation.ErrorMessage;
            }

            return(message);
        }
コード例 #12
0
        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 (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite"))
                {
                    FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

                    int facilityCodeIndex = facilitySiteDefinition.FindField("FCODE");
                    int subtypeFieldIndex = facilitySiteDefinition.FindField(facilitySiteDefinition.GetSubtypeField());

                    // Agriculture, Food and Livestock subtype.
                    Subtype agricultureSubtype = facilitySiteDefinition.GetSubtypes().First(subtype => subtype.GetCode() == 701);

                    // Industry Subtype.
                    Subtype industrySubtype = facilitySiteDefinition.GetSubtypes().First(subtype => subtype.GetName().Equals("Industry"));

                    Field faclilityCodeField = facilitySiteDefinition.GetFields()[facilityCodeIndex];

                    // This will be true since FCODE is a Text field.
                    if (faclilityCodeField.FieldType.Equals(FieldType.String))
                    {
                        // This will be null since at the field level there is no default value.
                        string fieldLevelDefaultValue = faclilityCodeField.GetDefaultValue() as String;

                        // This will be "Agriculture or Livestock Structure".
                        string defaultValueForAgricultureSubtype = faclilityCodeField.GetDefaultValue(agricultureSubtype) as String;

                        // This will be "Industrial Facility".
                        string defaultValueForIndustrySubtype = faclilityCodeField.GetDefaultValue(industrySubtype) as String;
                    }

                    Field subtypeField = facilitySiteDefinition.GetFields()[subtypeFieldIndex];

                    // This will be true since SUBTYPEFIELD is a Long Integer field.
                    if (subtypeField.FieldType.Equals(FieldType.Integer))
                    {
                        // This will be 701 since at the field level the default value is set.
                        int fieldLevelDefaultValue = Convert.ToInt32(subtypeField.GetDefaultValue());

                        // This will give you 701 since it is Agriculture, Food and Livestock subtype subtype.
                        int defaultValueForAgricultureSubtype = Convert.ToInt32(subtypeField.GetDefaultValue(agricultureSubtype));

                        // This will give you 710 since it is Industry subtype.
                        int defaultValueForIndustrySubtype = Convert.ToInt32(subtypeField.GetDefaultValue(industrySubtype));
                    }
                }
        }
コード例 #13
0
        public async Task MainMethodCode()
        {
            // Opening a Non-Versioned SQL Server instance.

            DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
            {
                AuthenticationMode = AuthenticationMode.DBMS,

                // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
                Instance = @"testMachine\testInstance",

                // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
                Database = "LocalGovernment",

                // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
                User     = "******",
                Password = "******",
                Version  = "dbo.DEFAULT"
            };

            using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
                using (RelationshipClass relationshipClass = geodatabase.OpenDataset <RelationshipClass>("LocalGovernment.GDB.OverviewToProject"))
                    using (FeatureClass projectsFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.CIPProjects"))
                        using (FeatureClass overviewFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.CIPProjectsOverview"))
                        {
                            FeatureClassDefinition overviewDefinition = overviewFeatureClass.GetDefinition();
                            // Because the following fields are used in 2 places, it is more inefficient to get their respective indexes so that they can be resued.
                            int projectManagerIndex = overviewDefinition.FindField("PROJECTMAN");
                            int fundSourceIndex     = overviewDefinition.FindField("FUNDSOUR");

                            RelationshipClassDefinition relationshipClassDefinition = relationshipClass.GetDefinition();
                            // This will be PROJNAME. This can be used to get the field index or used directly as the field name.
                            string originKeyField = relationshipClassDefinition.GetOriginKeyField();

                            EditOperation editOperation = new EditOperation();
                            editOperation.Callback(context =>
                            {
                                // The rows are being added to illustrate adding relationships. If one has existing rows, those can be used to add a relationship.
                                RowBuffer projectsRowBuffer  = projectsFeatureClass.CreateRowBuffer();
                                projectsRowBuffer["TOTCOST"] = 500000;

                                RowBuffer overviewRowBufferWithoutPKValue            = overviewFeatureClass.CreateRowBuffer();
                                overviewRowBufferWithoutPKValue[projectManagerIndex] = "John Doe";
                                overviewRowBufferWithoutPKValue[fundSourceIndex]     = "Public";

                                RowBuffer overviewRowBuffer            = overviewFeatureClass.CreateRowBuffer();
                                overviewRowBuffer["PROJNAME"]          = "LibraryConstruction";
                                overviewRowBuffer[projectManagerIndex] = "John Doe";
                                overviewRowBuffer[fundSourceIndex]     = "Public";

                                using (Row projectsRow = projectsFeatureClass.CreateRow(projectsRowBuffer))
                                    using (Row overviewRowWithoutPKValue = overviewFeatureClass.CreateRow(overviewRowBufferWithoutPKValue))
                                        using (Row overviewRow = overviewFeatureClass.CreateRow(overviewRowBuffer))
                                        {
                                            try
                                            {
                                                Relationship failingRelationship = relationshipClass.CreateRelationship(overviewRowWithoutPKValue, projectsRow);
                                            }
                                            catch (GeodatabaseRelationshipClassException exception)
                                            {
                                                // This will have a message "Unable to obtain origin primary key value.". So, the origin row needs to have the origin *primary*
                                                // key value referenced by the origin *foreign* key value in the RelationshipClass.
                                                Console.WriteLine(exception);
                                            }

                                            Relationship relationship = relationshipClass.CreateRelationship(overviewRow, projectsRow);

                                            //To Indicate that the Map has to draw this feature/row and/or the attribute table has to be updated
                                            context.Invalidate(projectsRow);
                                            context.Invalidate(overviewRow);
                                            context.Invalidate(relationshipClass);
                                        }
                            }, projectsFeatureClass, overviewFeatureClass);

                            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();
                        }
        }
コード例 #14
0
        public void MainMethodCode()
        {
            using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
                using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("PollingPlace"))
                {
                    FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();

                    int areaFieldIndex = featureClassDefinition.FindField(featureClassDefinition.GetAreaField());

                    // ******************** WITHOUT USING RECYCLING ********************

                    QueryFilter queryFilter = new QueryFilter {
                        WhereClause = "CITY = 'Plainfield'"
                    };

                    List <Feature> features = new List <Feature>();

                    // Searching is similar to that of Table when using Queryfilter.
                    using (RowCursor cursor = featureClass.Search(queryFilter, false))
                    {
                        while (cursor.MoveNext())
                        {
                            // Each object returned by RowCursor.Current can be cast to a Feature object if the Search was performed on a FeatureClass.
                            features.Add(cursor.Current as Feature);
                        }
                    }

                    IEnumerable <Feature> featuresHavingShapePopulated = features.Where(feature => !feature.GetShape().IsEmpty);

                    // Since Feature encapsulates unmanaged resources, it is important to remember to call Dispose() on every entry in the list when
                    // the list is no longer in use.  Alternatively, do not add the features to the list.  Instead, process each of them inside the cursor.

                    Dispose(features);

                    // ******************** USING RECYCLING ********************

                    using (RowCursor recyclingCursor = featureClass.Search(queryFilter))
                    {
                        while (recyclingCursor.MoveNext())
                        {
                            // Similar to a RowCursor on a Table, when a MoveNext is executed, the same feature object is populated with the next feature's details
                            // So any processing should be done on the Current Feature before the MoveNext is called again.

                            Feature feature = (Feature)recyclingCursor.Current;

                            if (Convert.ToDouble(feature[areaFieldIndex]) > 500)
                            {
                                Console.WriteLine(feature.GetShape().ToXML());
                            }
                        }
                    }
                }

            // Opening a Non-Versioned SQL Server instance.

            DatabaseConnectionProperties connectionProperties = new DatabaseConnectionProperties(EnterpriseDatabaseType.SQLServer)
            {
                AuthenticationMode = AuthenticationMode.DBMS,

                // Where testMachine is the machine where the instance is running and testInstance is the name of the SqlServer instance.
                Instance = @"testMachine\testInstance",

                // Provided that a database called LocalGovernment has been created on the testInstance and geodatabase has been enabled on the database.
                Database = "LocalGovernment",

                // Provided that a login called gdb has been created and corresponding schema has been created with the required permissions.
                User     = "******",
                Password = "******",
                Version  = "dbo.DEFAULT"
            };

            using (Geodatabase geodatabase = new Geodatabase(connectionProperties))
                using (FeatureClass schoolBoundaryFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.SchoolBoundary"))
                {
                    // Using a spatial query filter to find all features which have a certain district name and lying within a given Polygon.
                    SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
                    {
                        WhereClause    = "DISTRCTNAME = 'Indian Prairie School District 204'",
                        FilterGeometry = new PolygonBuilder(new List <Coordinate2D>
                        {
                            new Coordinate2D(1021880, 1867396),
                            new Coordinate2D(1028223, 1870705),
                            new Coordinate2D(1031165, 1866844),
                            new Coordinate2D(1025373, 1860501),
                            new Coordinate2D(1021788, 1863810)
                        }).ToGeometry(),

                        SpatialRelationship = SpatialRelationship.Within
                    };

                    using (RowCursor indianPrairieCursor = schoolBoundaryFeatureClass.Search(spatialQueryFilter, false))
                    {
                        while (indianPrairieCursor.MoveNext())
                        {
                            using (Feature feature = (Feature)indianPrairieCursor.Current)
                            {
                                // Process the feature.
                                Console.WriteLine(feature.GetObjectID());
                            }
                        }
                    }
                }
        }
コード例 #15
0
        public static async Task <BA_ReturnCode> UpdateFeatureAttributesAsync(Uri gdbUri, string featureClassName, QueryFilter oQueryFilter, IDictionary <string, string> dictEdits)
        {
            bool   modificationResult = false;
            string errorMsg           = "";
            await QueuedTask.Run(() =>
            {
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri)))
                    using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName))
                    {
                        FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition();

                        EditOperation editOperation = new EditOperation();
                        editOperation.Callback(context => {
                            using (RowCursor rowCursor = featureClass.Search(oQueryFilter, false))
                            {
                                while (rowCursor.MoveNext())
                                {
                                    using (Feature feature = (Feature)rowCursor.Current)
                                    {
                                        // In order to update the the attribute table has to be called before any changes are made to the row
                                        context.Invalidate(feature);
                                        // Loop through fields to update
                                        foreach (string strKey in dictEdits.Keys)
                                        {
                                            int idxRow = featureClassDefinition.FindField(strKey);
                                            if (idxRow > -1)
                                            {
                                                feature[idxRow] = dictEdits[strKey];
                                            }
                                        }
                                        feature.Store();
                                        // Has to be called after the store too
                                        context.Invalidate(feature);
                                    }
                                }
                            }
                        }, featureClass);

                        try
                        {
                            modificationResult = editOperation.Execute();
                            if (!modificationResult)
                            {
                                errorMsg = editOperation.ErrorMessage;
                            }
                        }
                        catch (GeodatabaseException exObj)
                        {
                            errorMsg = exObj.Message;
                        }
                    }
            });

            if (String.IsNullOrEmpty(errorMsg))
            {
                await Project.Current.SaveEditsAsync();

                return(BA_ReturnCode.Success);
            }
            else
            {
                if (Project.Current.HasEdits)
                {
                    await Project.Current.DiscardEditsAsync();
                }
                Module1.Current.ModuleLogManager.LogError(nameof(UpdateFeatureAttributesAsync),
                                                          "Exception: " + errorMsg);
                return(BA_ReturnCode.UnknownError);
            }
        }
コード例 #16
0
        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 (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.FacilitySite"))
                {
                    FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

                    int facilityCodeIndex = facilitySiteDefinition.FindField("FCODE");
                    int ownerTypeIndex    = facilitySiteDefinition.FindField("OWNTYPE");
                    int subtypeFieldIndex = facilitySiteDefinition.FindField(facilitySiteDefinition.GetSubtypeField());

                    // Agriculture, Food and Livestock subtype.
                    Subtype agricultureSubtype = facilitySiteDefinition.GetSubtypes().First(subtype => subtype.GetCode() == 701);

                    // Industry Subtype.
                    Subtype industrySubtype = facilitySiteDefinition.GetSubtypes().First(subtype => subtype.GetName().Equals("Industry"));

                    Field faclilityCodeField = facilitySiteDefinition.GetFields()[facilityCodeIndex];

                    // This will be null since there is not domain assigned at the field level.
                    Domain facilityCodeFieldLevelDomain         = faclilityCodeField.GetDomain();
                    Domain facilityCodeAgricultureSubtypeDomain = faclilityCodeField.GetDomain(agricultureSubtype);

                    // This will be "Agriculture Food and Livestock FCode".
                    string facilityCodeAgricultureSubtypeDomainName = facilityCodeAgricultureSubtypeDomain.GetName();
                    Domain facilityCodeIndustrySubtypeDomain        = faclilityCodeField.GetDomain(industrySubtype);

                    // This will be "Industry FCode"
                    string facilityCodeIndustrySubtypeDomainName = facilityCodeIndustrySubtypeDomain.GetName();

                    Field  ownerTypeField            = facilitySiteDefinition.GetFields()[ownerTypeIndex];
                    Domain ownerTypeFieldLevelDomain = ownerTypeField.GetDomain();

                    // This will be "OwnerType".
                    string ownerTypeFieldLevelDomainName     = ownerTypeFieldLevelDomain.GetName();
                    Domain ownerTypeAgricultureSubtypeDomain = ownerTypeField.GetDomain(agricultureSubtype);

                    // This will be "OwnerType" because the same domain has been set at the subtype level.
                    string ownerTypeAgricultureSubtypeDomainName = ownerTypeAgricultureSubtypeDomain.GetName();
                    Domain ownerTypeIndustrySubtypeDomain        = ownerTypeField.GetDomain(industrySubtype);

                    // This will be "OwnerType" because the same domain has been set at the subtype level.
                    string ownerTypeIndustrySubtypeDomainName = ownerTypeIndustrySubtypeDomain.GetName();

                    Field subtypeField = facilitySiteDefinition.GetFields()[subtypeFieldIndex];

                    // This will be null.
                    Domain subtypeField_FieldLevelDomain = subtypeField.GetDomain();

                    // This will be null.
                    Domain subtypeField_AgricultureSubtypeDomain = subtypeField.GetDomain(agricultureSubtype);

                    // This will be null.
                    Domain subtypeField_IndustrySubtypeDomain = subtypeField.GetDomain(industrySubtype);
                }
        }
コード例 #17
0
        public static async Task <IList <BA_Objects.Interval> > GetUniqueSortedValuesAsync(Uri gdbUri, string featClassName,
                                                                                           string valueFieldName, string nameFieldName, double upperBound, double lowerBound)
        {
            IList <BA_Objects.Interval> lstInterval = new List <BA_Objects.Interval>();

            if (gdbUri.IsFile)
            {
                string strFolderPath = System.IO.Path.GetDirectoryName(gdbUri.LocalPath);
                if (System.IO.Directory.Exists(strFolderPath))
                {
                    await QueuedTask.Run(() =>
                    {
                        //get Dictionary of unique elevations from the vector att
                        IDictionary <String, String> dictElev = new Dictionary <String, String>();

                        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri)))
                            using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featClassName))
                            {
                                FeatureClassDefinition def = featureClass.GetDefinition();
                                int idxElev = def.FindField(valueFieldName);
                                int idxName = def.FindField(nameFieldName);
                                if (idxElev < 0 || idxName < 0)
                                {
                                    Module1.Current.ModuleLogManager.LogError(nameof(GetUniqueSortedValuesAsync),
                                                                              "A required field was missing from " + featClassName + ". Process failed!");
                                    return;
                                }
                                using (RowCursor rowCursor = featureClass.Search(new QueryFilter(), false))
                                {
                                    while (rowCursor.MoveNext())
                                    {
                                        using (Feature feature = (Feature)rowCursor.Current)
                                        {
                                            string strElev = Convert.ToString(feature[idxElev]);
                                            string strName = "";
                                            if (feature[idxName] == null)
                                            {
                                                strName = "Name missing";
                                            }
                                            else
                                            {
                                                strName = Convert.ToString(feature[idxName]);
                                                if (String.IsNullOrEmpty(strName))
                                                {
                                                    strName = "Name missing";
                                                }
                                            }
                                            if (dictElev.ContainsKey(strElev))
                                            {
                                                strName           = dictElev[strElev] + ", " + strName;
                                                dictElev[strElev] = strName;
                                            }
                                            else
                                            {
                                                dictElev.Add(strElev, strName);
                                            }
                                        }
                                    }
                                }
                            }
                        List <double> lstValidValues = new List <double>();
                        int nuniquevalue             = dictElev.Keys.Count;
                        double value  = -1.0F;
                        bool bSuccess = false;
                        foreach (var strElev in dictElev.Keys)
                        {
                            bSuccess = Double.TryParse(strElev, out value);
                            if ((int)(value - 0.5) < (int)upperBound && (int)value + 0.5 > (int)lowerBound)
                            {
                                lstValidValues.Add(value);
                            }
                            else if (value > upperBound || value < lowerBound)      //invalid data in the attribute field, out of bound
                            {
                                Module1.Current.ModuleLogManager.LogError(nameof(GetUniqueSortedValuesAsync),
                                                                          "WARNING!! A monitoring site is ignored in the analysis! The site's elevation (" +
                                                                          value + ") is outside the DEM range (" + lowerBound + ", " + upperBound + ")!");
                            }
                        }
                        //add upper and lower bnds to the dictionary
                        if (!dictElev.ContainsKey(Convert.ToString(upperBound)))
                        {
                            dictElev.Add(Convert.ToString(upperBound), "Not represented");
                            lstValidValues.Add(upperBound);
                        }
                        if (!dictElev.ContainsKey(Convert.ToString(lowerBound)))
                        {
                            dictElev.Add(Convert.ToString(lowerBound), "Min Value");
                            lstValidValues.Add(lowerBound);
                        }

                        // Sort the list
                        lstValidValues.Sort();
                        // Add lower bound to interval list
                        for (int i = 0; i < lstValidValues.Count - 1; i++)
                        {
                            BA_Objects.Interval interval = new BA_Objects.Interval();
                            interval.Value      = i + 1;
                            interval.LowerBound = lstValidValues[i];
                            double nextItem     = lstValidValues[i + 1];
                            interval.UpperBound = nextItem;
                            interval.Name       = dictElev[Convert.ToString(nextItem)]; // use the upperbnd name to represent the interval
                            lstInterval.Add(interval);
                        }
                    });
                }
            }
            return(lstInterval);
        }
コード例 #18
0
        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 (RelationshipClass relationshipClass = geodatabase.OpenDataset <RelationshipClass>("LocalGovernment.GDB.luCodeViolationHasInspections"))
                    using (FeatureClass violationsFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.luCodeViolation"))
                        using (Table inspectionTable = geodatabase.OpenDataset <Table>("LocalGovernment.GDB.luCodeInspection"))
                        {
                            List <Row>  jeffersonAveViolations = new List <Row>();
                            QueryFilter queryFilter            = new QueryFilter {
                                WhereClause = "LOCDESC LIKE '///%Jefferson///%'"
                            };

                            // If you need to *cache* the rows retrieved from the cursor for processing later, it is important that you don't use recycling in
                            // the Search() method (i.e., useRecyclingCursor must be set to *false*).  Also, the returned rows/features cached in the list
                            // should be disposed when no longer in use so that unmanaged resources are not held on to longer than necessary.

                            using (RowCursor rowCursor = violationsFeatureClass.Search(queryFilter, false))
                            {
                                while (rowCursor.MoveNext())
                                {
                                    jeffersonAveViolations.Add(rowCursor.Current);
                                }
                            }

                            IReadOnlyList <Row> relatedOriginRows      = null;
                            IReadOnlyList <Row> relatedDestinationRows = null;

                            try
                            {
                                QueryFilter filter = new QueryFilter {
                                    WhereClause = "ACTION = '1st Notice'"
                                };
                                Selection selection = inspectionTable.Select(filter, SelectionType.ObjectID, SelectionOption.Normal);

                                relatedOriginRows = relationshipClass.GetRowsRelatedToDestinationRows(selection.GetObjectIDs());

                                // Find out if any of 1st Notice inspections were from Jefferson Avenue.
                                FeatureClassDefinition featureClassDefinition = violationsFeatureClass.GetDefinition();
                                int  locationDescriptionIndex = featureClassDefinition.FindField("LOCDESC");
                                bool containsJeffersonAve     = relatedOriginRows.Any(row => Convert.ToString(row[locationDescriptionIndex]).Contains("Jefferson"));

                                List <long> jeffersonAveViolationObjectIds = jeffersonAveViolations.Select(row => row.GetObjectID()).ToList();

                                relatedDestinationRows = relationshipClass.GetRowsRelatedToOriginRows(jeffersonAveViolationObjectIds);

                                //Find out if any Jefferson Ave Violations have 1st Notice Inspections
                                TableDefinition tableDefinition           = inspectionTable.GetDefinition();
                                int             actionFieldIndex          = tableDefinition.FindField("ACTION");
                                bool            hasFirstNoticeInspections = relatedDestinationRows.Any(row => Convert.ToString(row[actionFieldIndex]).Contains("1st Notice"));
                            }
                            finally
                            {
                                Dispose(jeffersonAveViolations);
                                Dispose(relatedOriginRows);
                                Dispose(relatedDestinationRows);
                            }
                        }
        }