Пример #1
0
        public static async Task KeyPointsIntegration()
        {
            await QueuedTask.Run(() =>
            {
                using (Geodatabase gdb1 = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb1.ApplyEdits(() =>
                    {
                        FeatureClass voyageRiskKeyPoint = gdb1.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_VoyageRiskKeyPoint);
                        FeatureClassDefinition voyageRiskKeyPointDefinition = gdb1.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_VoyageRiskKeyPoint);
                        voyageRiskKeyPoint.DeleteRows(new QueryFilter()
                        {
                            WhereClause = "OBJECTID >= 1"
                        });
                        string shapeFieldName = voyageRiskKeyPointDefinition.GetShapeField();

                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskInternalPoint, 1);
                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskOutlinePoint, 0);
                        double midLocaRisk = Math.Pow(0.5, 3.03);
                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskLocaMidPoint, midLocaRisk);
                        RiskAssessment(gdb1, voyageRiskKeyPoint, ConstDefintion.ConstFeatureClass_VoyageMaskRiskMidPoint, 0.5);
                    });
                }
            });
        }
Пример #2
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();
                }
        }
        public void MainMethodCode()
        {
            Uri serviceUrl = new Uri("https://arcgis.server.example.com:6443/arcgis/rest/services/FeatureServiceName/FeatureServer");

            ServiceConnectionProperties arcGisServer = new ServiceConnectionProperties(serviceUrl)
            {
                User     = "******",
                Password = "******"
            };

            using (Geodatabase serverFeatureService = new Geodatabase(arcGisServer))
            {
                FeatureClassDefinition featureClassDefinition = serverFeatureService.GetDefinition <FeatureClassDefinition>("0");
                string shapeField            = featureClassDefinition.GetShapeField();
                IReadOnlyList <Field> fields = featureClassDefinition.GetFields();

                TableDefinition tableDefinition = serverFeatureService.GetDefinition <TableDefinition>("4");
                string          objectIDField   = tableDefinition.GetObjectIDField();
            }
        }
        private static void ExploreTopologyValidation(Geodatabase geodatabase, Topology topology)
        {
            // If the topology currently does not have dirty areas, calling Validate() returns an empty envelope.

            Console.WriteLine("***************************************************************************");
            ValidationResult result = topology.Validate(new ValidationDescription(topology.GetExtent()));

            Console.WriteLine($"'AffectedArea' after validating a topology that has not been edited => {result.AffectedArea.ToJson()}");

            // Now create a feature that purposely violates the "PointProperlyInsideArea" topology rule.  This action will
            // create dirty areas.

            Feature newFeature = null;

            try
            {
                // Fetch the feature in the Campsites feature class whose objectID is 2.  Then create a new geometry slightly
                // altered from this and use it to create a new feature.

                using (Feature featureViaCampsites2 = GetFeature(geodatabase, "Campsites", 2))
                {
                    Geometry currentGeometry = featureViaCampsites2.GetShape();
                    Geometry newGeometry     = GeometryEngine.Instance.Move(currentGeometry, (currentGeometry.Extent.XMax / 8),
                                                                            (currentGeometry.Extent.YMax / 8));

                    using (FeatureClass campsitesFeatureClass = featureViaCampsites2.GetTable())
                        using (FeatureClassDefinition definition = campsitesFeatureClass.GetDefinition())
                            using (RowBuffer rowBuffer = campsitesFeatureClass.CreateRowBuffer())
                            {
                                rowBuffer[definition.GetShapeField()] = newGeometry;

                                geodatabase.ApplyEdits(() =>
                                {
                                    newFeature = campsitesFeatureClass.CreateRow(rowBuffer);
                                });
                            }
                }

                // After creating a new feature in the 'Campsites' participating feature class, the topology's state should be
                // "Unanalyzed" because it has not been validated.

                Console.WriteLine($"The topology state after an edit has been applied => {topology.GetState()}");

                // Now validate the topology.  The result envelope corresponds to the dirty areas.

                result = topology.Validate(new ValidationDescription(topology.GetExtent()));
                Console.WriteLine($"'AffectedArea' after validating a topology that has just been edited => {result.AffectedArea.ToJson()}");

                // After Validate(), the topology's state should be "AnalyzedWithErrors" because the topology currently has errors.

                Console.WriteLine($"The topology state after validate topology => {topology.GetState()}");

                // If there are no dirty areas, the result envelope should be empty.

                result = topology.Validate(new ValidationDescription(topology.GetExtent()));
                Console.WriteLine($"'AffectedArea' after validating a topology that has just been validated => {result.AffectedArea.ToJson()}");
            }
            finally
            {
                if (newFeature != null)
                {
                    geodatabase.ApplyEdits(() =>
                    {
                        newFeature.Delete();
                    });

                    newFeature.Dispose();
                }
            }

            // Validate again after deleting the newly-created feature.

            topology.Validate(new ValidationDescription(topology.GetExtent()));
        }
Пример #5
0
 public async static void CreatePolygonExpantion()
 {
     await QueuedTask.Run(() =>
     {
         using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
         {
             gdb.ApplyEdits(() =>
             {
                 using (FeatureClass fcStaticObstructPolygon = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_StaticObstructPolygon))
                 {
                     FeatureClassDefinition fcdStaticObstructPoint = gdb.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_StaticObstructPolygon);
                     FeatureClass fcSOPBuffer    = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPBuffer);
                     FeatureClass fc_SOPIDEPoint = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPIDEPoint);
                     fc_SOPIDEPoint.DeleteRows(new QueryFilter()
                     {
                         WhereClause = "OBJECTID >= 1"
                     });
                     using (RowCursor rc = fcStaticObstructPolygon.Search(null, false))
                     {
                         while (rc.MoveNext())
                         {
                             using (Feature f = rc.Current as Feature)
                             {
                                 int affectDis       = Convert.ToInt32(f[ConstDefintion.ConstFieldName_AffectDis]);
                                 double affectDegree = (double)f[ConstDefintion.ConstFieldName_AffectDegree];
                                 MapPoint p          = f[fcdStaticObstructPoint.GetShapeField()] as MapPoint;
                                 GeodesicEllipseParameter geodesic = new GeodesicEllipseParameter()
                                 {
                                     Center          = p.Coordinate2D,
                                     SemiAxis1Length = affectDis,
                                     SemiAxis2Length = affectDis,
                                     LinearUnit      = LinearUnit.Meters,
                                     OutGeometryType = GeometryType.Polygon,
                                     AxisDirection   = 0,
                                     VertexCount     = 800
                                 };
                                 Geometry circle = GeometryEngine.Instance.GeodesicEllipse(geodesic, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                 using (RowBuffer rowBuffer = fcSOPBuffer.CreateRowBuffer())
                                 {
                                     // Either the field index or the field name can be used in the indexer.
                                     rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = 0;
                                     rowBuffer["Shape"] = circle;
                                     using (Feature feature = fcSOPBuffer.CreateRow(rowBuffer))
                                     {
                                         feature.Store();
                                     }
                                 }
                                 using (RowBuffer rowBuffer = fc_SOPIDEPoint.CreateRowBuffer())
                                 {
                                     // Either the field index or the field name can be used in the indexer.
                                     rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = affectDegree;
                                     rowBuffer["Shape"] = p;
                                     using (Feature feature = fc_SOPIDEPoint.CreateRow(rowBuffer))
                                     {
                                         feature.Store();
                                     }
                                 }
                             }
                         }
                     }
                 }
             });
         }
     });
 }
        private async Task SetupDefinitionDetailsAsync()
        {
            DefinitionDetails.Clear();
            try
            {
                var lstDefs = await QueuedTask.Run <List <string> >(() =>
                {
                    Definition datasetDefinition = Dataset.DatasetDefinition;
                    List <string> lstDefDetails  = new List <string>();
                    if (datasetDefinition is TableDefinition)
                    {
                        TableDefinition tableDefinition = datasetDefinition as TableDefinition;
                        lstDefDetails.Add($"Object ID Field: {tableDefinition.GetObjectIDField()}");
                        StringBuilder stringBuilder = new StringBuilder();

                        if (!(_datastore is FileSystemDatastore))
                        {
                            lstDefDetails.Add($"Alias Name: {tableDefinition.GetAliasName()}");
                            lstDefDetails.Add($"CreatedAt Field: {tableDefinition.GetCreatedAtField()}");
                            lstDefDetails.Add($"Creator Field: {tableDefinition.GetCreatorField()}");
                            lstDefDetails.Add($"Subtype Field: {tableDefinition.GetSubtypeField()}");
                            lstDefDetails.Add($"Default Subtype Code: {tableDefinition.GetDefaultSubtypeCode()}");
                            lstDefDetails.Add($"EditedAt Field: {tableDefinition.GetEditedAtField()}");
                            lstDefDetails.Add($"Editor Field: {tableDefinition.GetEditorField()}");
                            lstDefDetails.Add($"Global ID Field: {tableDefinition.GetGlobalIDField()}");
                            lstDefDetails.Add($"Model Name: {tableDefinition.GetModelName()}");
                            foreach (var subtype in tableDefinition.GetSubtypes())
                            {
                                stringBuilder.Append(subtype.GetCode()).Append(": ").Append(subtype.GetName()).Append(Environment.NewLine);
                            }
                            lstDefDetails.Add($"Subtypes: {stringBuilder}");
                        }
                        stringBuilder = new StringBuilder();
                        foreach (Index index in tableDefinition.GetIndexes())
                        {
                            stringBuilder.Append(index.GetName()).Append(",");
                            string order = index.IsAscending() ? "Ascending" : "Descending";
                            stringBuilder.Append(order).Append(", ");
                            string unique = index.IsUnique() ? "Unique" : "Not Unique";
                            stringBuilder.Append(unique);
                        }
                        lstDefDetails.Add($"Indexes: {stringBuilder}");
                    }

                    if (datasetDefinition is FeatureClassDefinition)
                    {
                        FeatureClassDefinition featureClassDefinition = datasetDefinition as FeatureClassDefinition;
                        if (!(_datastore is FileSystemDatastore))
                        {
                            lstDefDetails.Add($"Area Field: {featureClassDefinition.GetAreaField()}");
                            lstDefDetails.Add($"Length Field: {featureClassDefinition.GetLengthField()}");
                        }
                        lstDefDetails.Add($"Shape Field: {featureClassDefinition.GetShapeField()}");
                        lstDefDetails.Add($"Shape Type: {featureClassDefinition.GetShapeType()}");
                        lstDefDetails.Add($"Spatial Reference Name: {featureClassDefinition.GetSpatialReference().Name}");
                        Envelope extent = featureClassDefinition.GetExtent();
                        lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}");
                    }

                    if (datasetDefinition is FeatureDatasetDefinition)
                    {
                        FeatureDatasetDefinition featureDatasetDefinition = datasetDefinition as FeatureDatasetDefinition;
                        lstDefDetails.Add($"Spatial Reference Name: {featureDatasetDefinition.GetSpatialReference().Name}");
                        try
                        {
                            Envelope extent = featureDatasetDefinition.GetExtent();
                            lstDefDetails.Add($"Extent Details: XMin-{extent.XMin} XMax-{extent.XMax} YMin-{extent.YMin} YMax-{extent.YMax}");
                        }
                        catch (Exception)
                        {
                            lstDefDetails.Add("Could not get extent");
                        }
                    }

                    if (datasetDefinition is RelationshipClassDefinition)
                    {
                        RelationshipClassDefinition relationshipClassDefinition = datasetDefinition as RelationshipClassDefinition;
                        lstDefDetails.Add($"Alias Name: {relationshipClassDefinition.GetAliasName()}");
                        lstDefDetails.Add($"Cardinality: {relationshipClassDefinition.GetCardinality()}");
                        lstDefDetails.Add($"Origin Class: {relationshipClassDefinition.GetOriginClass()}");
                        lstDefDetails.Add($"Destination Class: {relationshipClassDefinition.GetDestinationClass()}");
                        lstDefDetails.Add($"Origin Primary Key: {relationshipClassDefinition.GetOriginKeyField()}");
                        lstDefDetails.Add($"Origin Foreign Key: {relationshipClassDefinition.GetOriginForeignKeyField()}");
                        lstDefDetails.Add($"Is Attachement?: {relationshipClassDefinition.IsAttachmentRelationship()}");
                        lstDefDetails.Add($"Is Composite Relationship?: {relationshipClassDefinition.IsComposite()}");
                    }

                    if (datasetDefinition is AttributedRelationshipClassDefinition)
                    {
                        AttributedRelationshipClassDefinition relationshipClassDefinition = datasetDefinition as AttributedRelationshipClassDefinition;
                        lstDefDetails.Add($"Destination Key: {relationshipClassDefinition.GetDestinationKeyField()}");
                        lstDefDetails.Add($"Destination Foreign Key: {relationshipClassDefinition.GetDestinationForeignKeyField()}");
                        lstDefDetails.Add($"Object ID Field: {relationshipClassDefinition.GetObjectIDField()}");
                    }
                    return(lstDefDetails);
                });

                DefinitionDetails.AddRange(lstDefs);
            }
            catch (Exception exObj)
            {
                MessageBox.Show(exObj.Message, "Error");
            }
        }
        /// <summary>
        /// Method used to create a mask for geoprocessing environment
        /// Will buffer around each observer at the max distance to create mask
        /// </summary>
        /// <param name="maskFeatureClassName"></param>
        /// <param name="bufferDistance"></param>
        /// <returns>Task</returns>
        private async Task CreateMask(string maskFeatureClassName, double bufferDistance, SpatialReference surfaceSR)
        {
            // create new
            await FeatureClassHelper.CreateLayer(maskFeatureClassName, "POLYGON", false, false);

            try
            {
                string message        = String.Empty;
                bool   creationResult = false;
                await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(async() =>
                {
                    using (Geodatabase geodatabase = new Geodatabase(CoreModule.CurrentProject.DefaultGeodatabasePath))
                        using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>(maskFeatureClassName))
                            using (FeatureClassDefinition fcDefinition = enterpriseFeatureClass.GetDefinition())
                            {
                                EditOperation editOperation = new EditOperation();
                                editOperation.Callback(context =>
                                {
                                    try
                                    {
                                        var shapeFieldName = fcDefinition.GetShapeField();

                                        foreach (var observer in ObserverAddInPoints)
                                        {
                                            using (var rowBuffer = enterpriseFeatureClass.CreateRowBuffer())
                                            {
                                                // Either the field index or the field name can be used in the indexer.
                                                // project the point here or the buffer tool may use an angular unit and run forever
                                                var point   = GeometryEngine.Project(observer.Point, surfaceSR);
                                                var polygon = GeometryEngine.Buffer(point, bufferDistance);
                                                rowBuffer[shapeFieldName] = polygon;

                                                using (var feature = enterpriseFeatureClass.CreateRow(rowBuffer))
                                                {
                                                    //To Indicate that the attribute table has to be updated
                                                    context.Invalidate(feature);
                                                }
                                            }
                                        }
                                    }
                                    catch (GeodatabaseException exObj)
                                    {
                                        message = exObj.Message;
                                    }
                                }, enterpriseFeatureClass);

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

                                await Project.Current.SaveEditsAsync();
                            }
                });

                if (!creationResult)
                {
                    MessageBox.Show(message);
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }
        }
Пример #8
0
        /// <summary>
        /// Method used to create a mask for geoprocessing environment
        /// Will buffer around each observer at the max distance to create mask
        /// </summary>
        /// <param name="maskFeatureClassName"></param>
        /// <param name="bufferDistance"></param>
        /// <returns>Task</returns>
        private async Task CreateMask(string maskFeatureClassName,
                                      double minDistanceInMapUnits, double maxDistanceInMapUnits,
                                      double horizontalStartAngleInDegrees, double horizontalEndAngleInDegrees,
                                      SpatialReference surfaceSR, ObservableCollection <AddInPoint> observerPoints,
                                      bool constructRangeFans = false)
        {
            // create new
            await FeatureClassHelper.CreateLayer(FeatureDatasetName, maskFeatureClassName, "POLYGON", false, false);

            try
            {
                string message        = String.Empty;
                bool   creationResult = false;
                await ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(async() =>
                {
                    using (Geodatabase geodatabase = new Geodatabase(FeatureClassHelper.FgdbFileToConnectionPath(CoreModule.CurrentProject.DefaultGeodatabasePath)))
                        using (FeatureClass enterpriseFeatureClass = geodatabase.OpenDataset <FeatureClass>(maskFeatureClassName))
                            using (FeatureClassDefinition fcDefinition = enterpriseFeatureClass.GetDefinition())
                            {
                                EditOperation editOperation = new EditOperation();
                                editOperation.Callback(context =>
                                {
                                    try
                                    {
                                        var shapeFieldName = fcDefinition.GetShapeField();

                                        foreach (var observer in observerPoints)
                                        {
                                            using (var rowBuffer = enterpriseFeatureClass.CreateRowBuffer())
                                            {
                                                // Either the field index or the field name can be used in the indexer.
                                                // project the point here or the buffer tool may use an angular unit and run forever
                                                var point        = GeometryEngine.Instance.Project(observer.Point, surfaceSR);
                                                Geometry polygon = null;

                                                if (constructRangeFans)
                                                {
                                                    polygon = GeometryHelper.ConstructRangeFan(point as MapPoint,
                                                                                               minDistanceInMapUnits, maxDistanceInMapUnits, horizontalStartAngleInDegrees,
                                                                                               horizontalEndAngleInDegrees, surfaceSR);
                                                }
                                                else
                                                {
                                                    polygon = GeometryEngine.Instance.Buffer(point, maxDistanceInMapUnits);
                                                }

                                                rowBuffer[shapeFieldName] = polygon;

                                                Feature feature = enterpriseFeatureClass.CreateRow(rowBuffer);
                                                feature.Store();
                                                context.Invalidate(feature);
                                            } // using
                                        }     // for each
                                    }
                                    catch (GeodatabaseException exObj)
                                    {
                                        message = exObj.Message;
                                    }
                                }, enterpriseFeatureClass);

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

                                await Project.Current.SaveEditsAsync();
                            }
                });

                if (!creationResult)
                {
                    MessageBox.Show(message);
                }
            }
            catch (Exception ex)
            {
                Debug.Print(ex.Message);
            }
        }
        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();
                }
        }
        // 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();
                        }
                    }
                }
        }
Пример #11
0
        public void MainMethodCode()
        {
            using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
                using (Table table = fileGeodatabase.OpenDataset <Table>("luCodeInspection"))
                {
                    QueryFilter queryFilter = new QueryFilter {
                        WhereClause = "ACTION = '1st Notice'"
                    };

                    using (RowCursor cursor = table.Search(queryFilter)) // Using Recycling.
                    {
                        bool hasRow = cursor.MoveNext();

                        using (Row currentRow = cursor.Current)
                        {
                            TableDefinition tableDefinition = table.GetDefinition();

                            int trivialFindField   = currentRow.FindField(currentRow.GetFields()[0].Name); // This will (obviously) give 0.
                            int inspectIDIndex     = currentRow.FindField("INSPECTID");
                            int violateKeyIndex    = currentRow.FindField("violatekey");
                            int workKeyIndex       = currentRow.FindField("WorkKey");
                            int subtypeFieldIndex  = currentRow.FindField(tableDefinition.GetSubtypeField()); // Will be -1 since there are no subtypes.
                            int objectIdFieldIndex = currentRow.FindField(tableDefinition.GetObjectIDField());
                            int minusOne           = currentRow.FindField("Gibberish");                       // This will be -1.
                        }
                    }
                }

            // 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 landUseCaseFeatureClass = geodatabase.OpenDataset <FeatureClass>("LocalGovernment.GDB.LandUseCase"))
                {
                    QueryFilter filter = new QueryFilter {
                        WhereClause = "CASETYPE = 'Rezoning'"
                    };

                    using (RowCursor landUseCursor = landUseCaseFeatureClass.Search(filter, false))
                    {
                        FeatureClassDefinition featureClassDefinition = landUseCaseFeatureClass.GetDefinition();

                        while (landUseCursor.MoveNext())
                        {
                            Feature rezoningUseCase = (Feature)landUseCursor.Current;

                            int caseIdIndex     = rezoningUseCase.FindField("CASEID");
                            int caseNameIndex   = rezoningUseCase.FindField("casename");
                            int applicantIndex  = rezoningUseCase.FindField("Applicant");
                            int shapeFieldIndex = rezoningUseCase.FindField(featureClassDefinition.GetShapeField());
                            int subtypeIndex    = rezoningUseCase.FindField(featureClassDefinition.GetSubtypeField()); // Will be -1 since there are no subtypes.
                            int objectIdIndex   = rezoningUseCase.FindField(featureClassDefinition.GetObjectIDField());

                            break;
                        }
                    }
                }
        }
        public static async Task GenerateIDEKeyPointAsync(string fcName)
        {
            //1.
            await QueuedTask.Run(() =>
            {
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        using (FeatureClass fcStaticObstructPoint = gdb.OpenDataset <FeatureClass>(fcName))
                        {
                            FeatureClassDefinition fcdStaticObstructPoint = gdb.GetDefinition <FeatureClassDefinition>(fcName);
                            FeatureClass fcSOPBuffer    = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPBuffer);
                            FeatureClass fc_SOPIDEPoint = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPIDEPoint);
                            fc_SOPIDEPoint.DeleteRows(new QueryFilter()
                            {
                                WhereClause = "OBJECTID >= 1"
                            });
                            using (RowCursor rc = fcStaticObstructPoint.Search(null, false))
                            {
                                while (rc.MoveNext())
                                {
                                    using (Feature f = rc.Current as Feature)
                                    {
                                        int affectDis       = Convert.ToInt32(f[ConstDefintion.ConstFieldName_AffectDis]);
                                        double affectDegree = (double)f[ConstDefintion.ConstFieldName_AffectDegree];
                                        MapPoint p          = f[fcdStaticObstructPoint.GetShapeField()] as MapPoint;
                                        GeodesicEllipseParameter geodesic = new GeodesicEllipseParameter()
                                        {
                                            Center          = p.Coordinate2D,
                                            SemiAxis1Length = affectDis,
                                            SemiAxis2Length = affectDis,
                                            LinearUnit      = LinearUnit.Meters,
                                            OutGeometryType = GeometryType.Polygon,
                                            AxisDirection   = 0,
                                            VertexCount     = 800
                                        };
                                        Geometry circle = GeometryEngine.Instance.GeodesicEllipse(geodesic, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                        using (RowBuffer rowBuffer = fcSOPBuffer.CreateRowBuffer())
                                        {
                                            // Either the field index or the field name can be used in the indexer.
                                            rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = 0;
                                            rowBuffer["Shape"] = circle;
                                            using (Feature feature = fcSOPBuffer.CreateRow(rowBuffer))
                                            {
                                                feature.Store();
                                            }
                                        }
                                        using (RowBuffer rowBuffer = fc_SOPIDEPoint.CreateRowBuffer())
                                        {
                                            // Either the field index or the field name can be used in the indexer.
                                            rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = affectDegree;
                                            rowBuffer["Shape"] = p;
                                            using (Feature feature = fc_SOPIDEPoint.CreateRow(rowBuffer))
                                            {
                                                feature.Store();
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });

            //2.运行要素边缘转点
            string inpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SOPBufferPoint;
            var    args   = Geoprocessing.MakeValueArray(inpath);
            var    result = await Geoprocessing.ExecuteToolAsync("Delete_management", args, null, null, null);

            string inpath1 = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SOPBuffer;
            string outpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SOPBufferPoint;
            var    args1   = Geoprocessing.MakeValueArray(inpath1, outpath, "ALL");
            var    result1 = await Geoprocessing.ExecuteToolAsync("FeatureVerticesToPoints_management", args1, null, null, null);

            //3.
            await QueuedTask.Run(() =>
            {
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        FeatureClass SOPIDEPoint    = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPIDEPoint);
                        FeatureClass SOPBufferPoint = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_SOPBufferPoint);
                        FeatureClassDefinition SOPIDEPointDefinition = gdb.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_SOPIDEPoint);
                        using (RowCursor rowCursor = SOPBufferPoint.Search(null, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Feature f = rowCursor.Current as Feature)
                                {
                                    using (RowBuffer rowBuffer = SOPIDEPoint.CreateRowBuffer())
                                    {
                                        rowBuffer[ConstDefintion.ConstFieldName_AffectDegree] = 0;
                                        rowBuffer[SOPIDEPointDefinition.GetShapeField()]      = f.GetShape();
                                        using (Feature feature = SOPIDEPoint.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });
        }
Пример #13
0
        private static void CreateAllDomain(FeatureClass fc_targetShip)
        {
            //创建船周围的船舶领域
            using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
            {
                gdb.ApplyEdits(() =>
                {
                    //置空原船舶领域图层
                    FeatureClass shipDomain = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_ShipDomianEllipse);
                    FeatureClassDefinition shipDomainDefinition = gdb.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_ShipDomianEllipse);
                    shipDomain.DeleteRows(new QueryFilter()
                    {
                        WhereClause = "OBJECTID >= 1"
                    });

                    using (RowCursor rowCursor = fc_targetShip.Search(null, false))
                    {
                        while (rowCursor.MoveNext())
                        {
                            using (Row row = rowCursor.Current)
                            {
                                Feature ship    = row as Feature;
                                MapPoint p_ship = ship.GetShape() as MapPoint;

                                double asemi               = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_asemi]) / 2;
                                double bsemi               = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_bsemi]) / 2;
                                double aoffset             = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_aoffset]) / 2;
                                double boffset             = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_boffset]) / 2;
                                double DDV                 = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_CollisionRisk]);
                                double cog                 = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_cog]);
                                cog                        = CommonMethod.GIScoord2ShipCoord(cog);
                                Coordinate2D ellipseCenter = new Coordinate2D()
                                {
                                    X = p_ship.X,
                                    Y = p_ship.Y
                                };
                                GeodesicEllipseParameter geodesic = new GeodesicEllipseParameter()
                                {
                                    Center          = ellipseCenter,
                                    SemiAxis1Length = asemi,
                                    SemiAxis2Length = bsemi,
                                    LinearUnit      = LinearUnit.Meters,
                                    OutGeometryType = GeometryType.Polygon,
                                    AxisDirection   = AngularUnit.Degrees.ConvertToRadians(cog),
                                    VertexCount     = 800
                                };
                                Geometry ellipse       = GeometryEngine.Instance.GeodesicEllipse(geodesic, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                double moveX           = (aoffset * Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog)) + boffset * Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog)));
                                double moveY           = (aoffset * Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog)) - boffset * Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog)));
                                Geometry moved_ellipse = GeometryEngine.Instance.Move(ellipse, moveX, moveY);
                                using (RowBuffer rowBuffer = shipDomain.CreateRowBuffer())
                                {
                                    // Either the field index or the field name can be used in the indexer.
                                    rowBuffer[ConstDefintion.ConstFieldName_asemi]         = asemi;
                                    rowBuffer[ConstDefintion.ConstFieldName_bsemi]         = bsemi;
                                    rowBuffer[ConstDefintion.ConstFieldName_aoffset]       = aoffset;
                                    rowBuffer[ConstDefintion.ConstFieldName_CollisionRisk] = DDV;
                                    rowBuffer[shipDomainDefinition.GetShapeField()]        = moved_ellipse;
                                    using (Feature feature = shipDomain.CreateRow(rowBuffer))
                                    {
                                        feature.Store();
                                    }
                                }
                            }
                        }
                    }
                });
            }
        }
Пример #14
0
        public static async Task CreateKeyPoints(string maskName, string unionMaskName, string keyPointName, double factor)
        {
            await QueuedTask.Run(() =>
            {
                StreamReader sr = new StreamReader(System.Environment.CurrentDirectory + ConstDefintion.ConstPath_TimeFilterConfig, Encoding.Default);
                String line;
                //读取状态
                line = sr.ReadLine();
                string filterStatus = line;
                line            = sr.ReadLine();
                int filterValue = Convert.ToInt32(line);
                sr.Close();
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        //置空原船舶领域图层
                        FeatureClass fc_targetShip = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_TargetShip);
                        FeatureClass voyageMask    = gdb.OpenDataset <FeatureClass>(maskName);
                        FeatureClassDefinition voyageMaskDefinition = gdb.GetDefinition <FeatureClassDefinition>(maskName);
                        FeatureClass fc_ownShip             = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_OwnShip);
                        FeatureClass TargetShipObstacleLine = gdb.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_TargetShipObstacleLine);
                        TargetShipObstacleLine.DeleteRows(new QueryFilter()
                        {
                            WhereClause = "OBJECTID >= 1"
                        });
                        double own_x;
                        double own_y;
                        double own_cog;
                        using (RowCursor rowCursor = fc_ownShip.Search(null, false))
                        {
                            rowCursor.MoveNext();
                            using (Feature row = rowCursor.Current as Feature)
                            {
                                own_x   = (row.GetShape() as MapPoint).X;
                                own_y   = (row.GetShape() as MapPoint).Y;
                                own_cog = Convert.ToDouble(row[ConstDefintion.ConstFieldName_cog]);
                            }
                        }

                        voyageMask.DeleteRows(new QueryFilter()
                        {
                            WhereClause = "OBJECTID >= 1"
                        });
                        using (RowCursor rowCursor = fc_targetShip.Search(null, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Row row = rowCursor.Current)
                                {
                                    Feature ship         = row as Feature;
                                    MapPoint p_ship      = ship.GetShape() as MapPoint;
                                    double CollisionRisk = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_CollisionRisk]);
                                    double asemi         = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_asemi]) * factor * 0.78;
                                    double bsemi         = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_bsemi]) * factor * 0.78;
                                    double aoffset       = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_aoffset]) * factor;
                                    double boffset       = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_boffset]) * factor;
                                    double cog           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_cog]);
                                    double sog           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_sog]);
                                    double tdv1          = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tdv1]);
                                    double tdv2          = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tdv2]);
                                    double ddv           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_ddv]);
                                    double tcr           = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tcr]);
                                    double tmin          = Convert.ToDouble(ship[ConstDefintion.ConstFieldName_tmin]);
                                    long objectID        = Convert.ToInt64(ship[voyageMaskDefinition.GetObjectIDField()]);
                                    cog = CommonMethod.GIScoord2ShipCoord(cog);
                                    Coordinate2D ellipseCenter = new Coordinate2D()
                                    {
                                        X = p_ship.X,
                                        Y = p_ship.Y
                                    };
                                    if (!(CollisionRisk > 0))
                                    {
                                        continue;
                                    }
                                    //根据时间过滤器
                                    if (filterStatus != ConstDefintion.ConstStr_TimeFilterStatusOFF)
                                    {
                                        int time = filterValue * 60;
                                        if (tdv1 > time)
                                        {
                                            continue;
                                        }
                                        else
                                        {
                                            if (tdv2 > time)
                                            {
                                                tdv2 = time;
                                            }
                                        }
                                    }
                                    //if (CommonMethod.JungeLeft(own_x - ellipseCenter.X, own_y - ellipseCenter.Y, own_cog) && CollisionRisk != 1) continue;
                                    GeodesicEllipseParameter geodesic = new GeodesicEllipseParameter()
                                    {
                                        Center          = ellipseCenter,
                                        SemiAxis1Length = asemi,
                                        SemiAxis2Length = bsemi,
                                        LinearUnit      = LinearUnit.Meters,
                                        OutGeometryType = GeometryType.Polygon,
                                        AxisDirection   = AngularUnit.Degrees.ConvertToRadians(cog),
                                        VertexCount     = 800
                                    };
                                    //创建原始位置的椭圆
                                    Geometry ellipse          = GeometryEngine.Instance.GeodesicEllipse(geodesic, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                    double moveX              = (aoffset *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) + boffset *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog));
                                    double moveY              = (aoffset *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) - boffset *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog));
                                    Geometry moved_ellipse    = GeometryEngine.Instance.Move(ellipse, moveX, moveY);
                                    Coordinate2D centerRevise = new Coordinate2D()
                                    {
                                        X = p_ship.X + moveX,
                                        Y = p_ship.Y + moveY
                                    };
                                    //基于TDV创建船舶领域与动界
                                    double moveXs = (tdv1 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    double moveYs = (tdv1 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    Geometry moved_start_ellipse = GeometryEngine.Instance.Move(moved_ellipse, moveXs, moveYs);
                                    Coordinate2D centerTs        = new Coordinate2D()
                                    {
                                        X = centerRevise.X + moveXs,
                                        Y = centerRevise.Y + moveYs
                                    };
                                    double moveXe = (tdv2 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    double moveYe = (tdv2 *sog *ConstDefintion.ConstDouble_mpersTOkn *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog)));
                                    Geometry moved_end_ellipse = GeometryEngine.Instance.Move(moved_ellipse, moveXe, moveYe);
                                    Coordinate2D centerTe      = new Coordinate2D()
                                    {
                                        X = centerRevise.X + moveXe,
                                        Y = centerRevise.Y + moveYe
                                    };

                                    //最终图形由两个椭圆和连接椭圆的长方形组成
                                    Geometry e_s_start    = GeometryEngine.Instance.SimplifyAsFeature(moved_start_ellipse, false);
                                    Geometry e_s_end      = GeometryEngine.Instance.SimplifyAsFeature(moved_end_ellipse, false);
                                    MapPoint p_1          = MapPointBuilder.CreateMapPoint(centerTs.X - (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTs.Y + (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    MapPoint p_2          = MapPointBuilder.CreateMapPoint(centerTs.X + (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTs.Y - (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    MapPoint p_3          = MapPointBuilder.CreateMapPoint(centerTe.X + (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTe.Y - (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    MapPoint p_4          = MapPointBuilder.CreateMapPoint(centerTe.X - (bsemi *Math.Sin(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29, centerTe.Y + (bsemi *Math.Cos(AngularUnit.Degrees.ConvertToRadians(cog))) * 1.29);
                                    IList <MapPoint> p1_4 = GetInternPoints(p_1, p_4);
                                    IList <MapPoint> p2_3 = GetInternPoints(p_2, p_3);
                                    p2_3 = p2_3.Reverse <MapPoint>().ToList();
                                    List <MapPoint> list2D = new List <MapPoint>();
                                    list2D.Add(p_1);
                                    foreach (MapPoint p in p1_4)
                                    {
                                        list2D.Add(p);
                                    }
                                    list2D.Add(p_4);
                                    list2D.Add(p_3);
                                    foreach (MapPoint p in p2_3)
                                    {
                                        list2D.Add(p);
                                    }
                                    list2D.Add(p_2);
                                    Polygon connect_R = PolygonBuilder.CreatePolygon(list2D, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                    Geometry simple_r = GeometryEngine.Instance.SimplifyAsFeature(connect_R, false);
                                    //融合图形
                                    IList <Geometry> g_List = new List <Geometry>()
                                    {
                                        e_s_start, simple_r, e_s_end
                                    };
                                    Geometry ellInstance = GeometryEngine.Instance.Union(g_List);
                                    using (RowBuffer rowBuffer = voyageMask.CreateRowBuffer())
                                    {
                                        // Either the field index or the field name can be used in the indexer.
                                        rowBuffer[ConstDefintion.ConstFieldName_ddv]      = CollisionRisk;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv1]     = tdv1;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv2]     = tdv2;
                                        rowBuffer[ConstDefintion.ConstFieldName_asemi]    = asemi;
                                        rowBuffer[ConstDefintion.ConstFieldName_bsemi]    = bsemi;
                                        rowBuffer[ConstDefintion.ConstFieldName_cog]      = cog;
                                        rowBuffer[ConstDefintion.ConstFieldName_sog]      = sog;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerX1] = centerTs.X;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerY1] = centerTs.Y;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerX2] = centerTe.X;
                                        rowBuffer[ConstDefintion.ConstFieldName_centerY2] = centerTe.Y;
                                        rowBuffer[voyageMaskDefinition.GetShapeField()]   = ellInstance;

                                        using (Feature feature = voyageMask.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                    //创建本船与他船的冲突路径
                                    Coordinate2D ts_location = ellipseCenter;
                                    Coordinate2D ts_Ts       = new Coordinate2D()//目标船冲突起点
                                    {
                                        X = ts_location.X + moveXs,
                                        Y = ts_location.Y + moveYs
                                    };
                                    Coordinate2D ts_Te = new Coordinate2D()//目标船冲突终点
                                    {
                                        X = ts_location.X + moveXe,
                                        Y = ts_location.Y + moveYe
                                    };
                                    List <Coordinate2D> ts_obstaclePointList = new List <Coordinate2D>()
                                    {
                                        ts_Ts, ts_Te
                                    };
                                    Polyline ts_obstacleLine = PolylineBuilder.CreatePolyline(ts_obstaclePointList, SpatialReferenceBuilder.CreateSpatialReference(3857));
                                    double kj_risk           = 0;
                                    if (ddv > 1)
                                    {
                                        kj_risk = 0;
                                    }
                                    else if (ddv < 0.5)
                                    {
                                        kj_risk = 1;
                                    }
                                    else
                                    {
                                        kj_risk = Math.Pow(2 - 2 * ddv, 3.03);
                                    }
                                    using (RowBuffer rowBuffer = TargetShipObstacleLine.CreateRowBuffer())
                                    {
                                        // Either the field index or the field name can be used in the indexer.
                                        rowBuffer[ConstDefintion.ConstFieldName_dcr]   = kj_risk;
                                        rowBuffer[ConstDefintion.ConstFieldName_tcr]   = tcr;
                                        rowBuffer[ConstDefintion.ConstFieldName_risk]  = CollisionRisk;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv1]  = tdv1;
                                        rowBuffer[ConstDefintion.ConstFieldName_tdv2]  = tdv2;
                                        rowBuffer[ConstDefintion.ConstFieldName_tmin]  = tmin;
                                        rowBuffer[ConstDefintion.ConstFieldName_Shape] = ts_obstacleLine;

                                        using (Feature feature = TargetShipObstacleLine.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
            });

            //创建航行位置Mask

            await QueuedTask.Run(async() =>
            {
                //Mask边缘
                //合并要素
                using (Geodatabase gdb = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    gdb.ApplyEdits(() =>
                    {
                        using (FeatureClass u_VoyageMask = gdb.OpenDataset <FeatureClass>(unionMaskName))
                        {
                            u_VoyageMask.DeleteRows(new QueryFilter()
                            {
                                WhereClause = "OBJECTID >= 1"
                            });
                            using (FeatureClass voyageMask = gdb.OpenDataset <FeatureClass>(maskName))
                            {
                                IList <Geometry> u_list = new List <Geometry>();
                                FeatureClassDefinition u_voyageMaskDefinition = gdb.GetDefinition <FeatureClassDefinition>(unionMaskName);
                                using (RowCursor rowCursor = voyageMask.Search(null, false))
                                {
                                    while (rowCursor.MoveNext())
                                    {
                                        using (Feature f = rowCursor.Current as Feature)
                                        {
                                            u_list.Add(f.GetShape());
                                        }
                                    }
                                    //赋值
                                    using (RowBuffer rowBuffer = u_VoyageMask.CreateRowBuffer())
                                    {
                                        Geometry geometry = GeometryEngine.Instance.Union(u_list);
                                        rowBuffer[u_voyageMaskDefinition.GetShapeField()] = geometry;
                                        using (Feature feature = u_VoyageMask.CreateRow(rowBuffer))
                                        {
                                            feature.Store();
                                        }
                                    }
                                }
                            }
                        }
                    });
                }
                //运行要素边缘转点
                string inpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + keyPointName;
                var args      = Geoprocessing.MakeValueArray(inpath);
                var result    = await Geoprocessing.ExecuteToolAsync("Delete_management", args, null, null, null);

                string inpath1 = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + unionMaskName;
                string outpath = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + keyPointName;
                var args1      = Geoprocessing.MakeValueArray(inpath1, outpath, "ALL");
                var result1    = await Geoprocessing.ExecuteToolAsync("FeatureVerticesToPoints_management", args1, null, null, null);
            });
        }
Пример #15
0
        static void Main(string[] args)
        {
            //Call Host.Initialize before constructing any objects from ArcGIS.Core
            Host.Initialize();

            Console.WriteLine("CoreHost - Initilized");

            try
            {
                // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase.
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"D:\Projecten\GisTech\Git\Pro SDK\CoreHost\Nederland.gdb"))))
                {
                    Console.WriteLine("CoreHost - File Geodatebase found");

                    FeatureClass countryFeatureClass = geodatabase.OpenDataset <FeatureClass>("Landsgrens");
                    FeatureClass slicesFeatureClass  = geodatabase.OpenDataset <FeatureClass>("Slices");

                    FeatureClassDefinition countryFeatureClassDefinition = countryFeatureClass.GetDefinition();
                    FeatureClassDefinition slicesFeatureClassDefinition  = slicesFeatureClass.GetDefinition();

                    Console.WriteLine("CoreHost - FeatureClasses found");

                    // Create new slices based on the poligon of the Netherlands
                    IReadOnlyList <Polygon> slices = null;
                    using (RowCursor curs = countryFeatureClass.Search())
                    {
                        Console.WriteLine("CoreHost - GeometryEngine slicing features");

                        while (curs.MoveNext())
                        {
                            if (curs.Current != null)
                            {
                                using (Feature feature = (Feature)curs.Current)
                                {
                                    var polygon = curs.Current[countryFeatureClassDefinition.GetShapeField()] as Polygon;
                                    slices = GeometryEngine.Instance.SlicePolygonIntoEqualParts(polygon, 20, new Random().Next(0, 360), SliceType.Blocks);
                                }
                            }
                        }
                    }

                    Console.WriteLine("CoreHost - Deleting old slices");
                    // Delete all existing items.
                    geodatabase.ApplyEdits(() =>
                    {
                        slicesFeatureClass.DeleteRows(new QueryFilter()
                        {
                            WhereClause = "42 = 42"
                        });
                    });

                    Console.WriteLine("CoreHost - Saving features");

                    // Store new slices.
                    geodatabase.ApplyEdits(() =>
                    {
                        if (slices != null)
                        {
                            for (int i = 0; i < slices.Count; i++)
                            {
                                using (RowBuffer rowBuffer = slicesFeatureClass.CreateRowBuffer())
                                {
                                    // Either the field index or the field name can be used in the indexer.
                                    rowBuffer["Code"]      = i.ToString();
                                    rowBuffer["Landsnaam"] = "Nederland";
                                    rowBuffer[slicesFeatureClassDefinition.GetShapeField()] = slices[i];

                                    using (Feature feature = slicesFeatureClass.CreateRow(rowBuffer))
                                    {
                                        feature.Store();
                                    }
                                }
                            }
                        }
                    });

                    Console.WriteLine("CoreHost - Data saved");
                }
            }
            catch (GeodatabaseNotFoundOrOpenedException)
            {
                Console.WriteLine("File GeoDataBase niet gevonden");
            }
            catch (GeodatabaseEditingException)
            {
                Console.WriteLine("Kan niet schrijven naar de File GeoDataBase");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Fout {ex}");
            }

            Console.WriteLine("Press any key to continue...");
            Console.ReadLine();
        }
        public void MainMethodCode()
        {
            using (Geodatabase fileGeodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(@"C:\Data\LocalGovernment.gdb"))))
                using (FeatureClass featureClass = fileGeodatabase.OpenDataset <FeatureClass>("PollingPlace"))
                {
                    QueryFilter queryFilter = new QueryFilter {
                        WhereClause = "CITY = 'Plainfield'"
                    };
                    Selection selection = featureClass.Select(queryFilter, SelectionType.ObjectID, SelectionOption.Normal);

                    // The result is a mapping between those object ids which failed validation and the reason why the validation failed (a string message).
                    IReadOnlyDictionary <long, string> validationResult = featureClass.Validate(selection);

                    RowCursor      rowCursor = featureClass.Search(queryFilter, false);
                    List <Feature> features  = new List <Feature>();

                    try
                    {
                        while (rowCursor.MoveNext())
                        {
                            features.Add(rowCursor.Current as Feature);
                        }

                        // This is equivalent to the validation performed using the selection.
                        IReadOnlyDictionary <long, string> equivalentValidationResult = featureClass.Validate(features);

                        // Again this is equivalent to both the above results.
                        IReadOnlyDictionary <long, string> anotherEquivalentResult = featureClass.Validate(queryFilter);

                        SpatialQueryFilter spatialQueryFilter = new SpatialQueryFilter
                        {
                            FilterGeometry = new EnvelopeBuilder(
                                new MapPointBuilder(1052803, 1812751).ToGeometry(),
                                new MapPointBuilder(1034600, 1821320).ToGeometry()).ToGeometry(),

                            SpatialRelationship = SpatialRelationship.Within
                        };

                        IReadOnlyDictionary <long, string> spatialFilterBasedValidationResult = featureClass.Validate(spatialQueryFilter);
                    }
                    finally
                    {
                        rowCursor.Dispose();
                        Dispose(features);
                    }
                }

            // 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"))
                {
                    QueryFilter parkFilter = new QueryFilter {
                        WhereClause = "FCODE = 'Park'"
                    };
                    Selection parkSelection = enterpriseFeatureClass.Select(parkFilter, SelectionType.ObjectID, SelectionOption.Normal);

                    // Remember that validation cost is directly proprtional to the number of Features validated. So, select the set of features to be
                    // validated judiciously.  This will be empty because all the Park Features are valid.
                    IReadOnlyDictionary <long, string> emptyDictionary = enterpriseFeatureClass.Validate(parkSelection);

                    // We are adding an invalid feature to illustrate a case where the validation result is not empty.

                    long invalidFeatureObjectID = -1;

                    EditOperation editOperation = new EditOperation();
                    editOperation.Callback(context =>
                    {
                        RowBuffer rowBuffer = null;
                        Feature feature     = null;

                        try
                        {
                            FeatureClassDefinition facilitySiteDefinition = enterpriseFeatureClass.GetDefinition();

                            rowBuffer = enterpriseFeatureClass.CreateRowBuffer();

                            rowBuffer["FACILITYID"] = "FAC-400";
                            rowBuffer["NAME"]       = "Griffith Park";
                            rowBuffer["OWNTYPE"]    = "Municipal";
                            rowBuffer["FCODE"]      = "Park";
                            // Note that this is an invalid subtype value.
                            rowBuffer[facilitySiteDefinition.GetSubtypeField()] = 890;
                            rowBuffer[facilitySiteDefinition.GetShapeField()]   = new PolygonBuilder(new List <Coordinate2D>
                            {
                                new Coordinate2D(1021570, 1880583),
                                new Coordinate2D(1028730, 1880994),
                                new Coordinate2D(1029718, 1875644),
                                new Coordinate2D(1021405, 1875397)
                            }).ToGeometry();

                            feature = enterpriseFeatureClass.CreateRow(rowBuffer);

                            invalidFeatureObjectID = feature.GetObjectID();
                        }
                        catch (GeodatabaseException exObj)
                        {
                            Console.WriteLine(exObj);
                        }
                        finally
                        {
                            if (rowBuffer != null)
                            {
                                rowBuffer.Dispose();
                            }

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

                    editOperation.Execute();

                    // This will have one keypair value for the invalid row that was added.
                    IReadOnlyDictionary <long, string> result = enterpriseFeatureClass.Validate(parkFilter);

                    // This will say "invalid subtype code".
                    string errorMessage = result[invalidFeatureObjectID];
                }
        }