private async void SelectCourse()
        {
            string fieldName = string.Empty;
            var    oidField  = QueuedTask.Run(() =>
            {
                string name;
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    FeatureClassDefinition fcd = geodatabase.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_Course);
                    name = fcd.GetObjectIDField();
                }
                return(name);
            }).Result;
            string path        = ConstDefintion.ConstFeatureClass_Course;
            string whereClause = $"{oidField} = {CourseListSelectedItem}";

            ProgressDialog progressDialogDomain = new ProgressDialog($"切换选择中", ConstDefintion.ConstStr_GeoprocessCancling, false);
            var            arg  = Geoprocessing.MakeValueArray(path, "NEW_SELECTION", whereClause);
            var            task = await Geoprocessing.ExecuteToolAsync("SelectLayerByAttribute_management", arg, null, new CancelableProgressorSource(progressDialogDomain).Progressor);

            if (!task.IsFailed)
            {
                if (!(MapView.Active == null))
                {
                    await MapView.Active.ZoomToSelectedAsync();
                }
            }
        }
예제 #2
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);
                    });
                }
            });
        }
        public async Task UpdateFeatureAsync(long uid, Geometry geometry)
        {
            await QueuedTask.Run(() =>
            {
                using (FeatureClass featureClass = Layer.GetFeatureClass())
                {
                    FeatureClassDefinition definition = featureClass?.GetDefinition();
                    string objectIdField = definition?.GetObjectIDField();
                    QueryFilter filter   = new QueryFilter {
                        WhereClause = $"{objectIdField} = {uid}"
                    };

                    using (RowCursor existsResult = featureClass?.Search(filter, false))
                    {
                        while (existsResult?.MoveNext() ?? false)
                        {
                            using (Row row = existsResult.Current)
                            {
                                Feature feature = row as Feature;
                                feature?.SetShape(geometry);
                                feature?.Store();
                            }
                        }
                    }
                }
            });
        }
예제 #4
0
        public static async Task <bool> ZoomToExtentAsync(Uri aoiUri, double bufferFactor = 1)
        {
            //Get the active map view.
            var mapView = MapView.Active;

            if (mapView == null)
            {
                return(false);
            }
            string strFileName   = null;
            string strFolderPath = null;

            if (aoiUri.IsFile)
            {
                strFileName   = System.IO.Path.GetFileName(aoiUri.LocalPath);
                strFolderPath = System.IO.Path.GetDirectoryName(aoiUri.LocalPath);
            }

            Envelope zoomEnv = null;
            await QueuedTask.Run(() => {
                // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase.
                using (
                    Geodatabase geodatabase =
                        new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath))))
                {
                    // Use the geodatabase.
                    FeatureClassDefinition fcDefinition = geodatabase.GetDefinition <FeatureClassDefinition>(strFileName);
                    zoomEnv = fcDefinition.GetExtent().Expand(bufferFactor, bufferFactor, true);
                }
            });

            //Zoom the view to a given extent.
            return(await mapView.ZoomToAsync(zoomEnv, null));
        }
        protected override async void OnClick()
        {
            var selectedLayer = MapView.Active.GetSelectedLayers().FirstOrDefault();

            if (selectedLayer == null || !(selectedLayer is FeatureLayer))
            {
                MessageBox.Show("You have to select a feature layer.  The selected layer's database connection is then used to create the new FeatureClass.");
                return;
            }
            var selectedFeatureLayer = selectedLayer as FeatureLayer;

            await QueuedTask.Run(() =>
            {
                var selectedLayerTable     = selectedFeatureLayer.GetTable();
                var stringFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheString", FieldType.String);
                var intFieldDescription    = new ArcGIS.Core.Data.DDL.FieldDescription("TheInteger", FieldType.Integer);
                var dblFieldDescription    = new ArcGIS.Core.Data.DDL.FieldDescription("TheDouble", FieldType.Double)
                {
                    Precision = 9,
                    Scale     = 5
                };
                var dateFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheDate", FieldType.Date);

                using (var geoDb = selectedLayerTable.GetDatastore() as Geodatabase)
                {
                    var fcName = selectedLayerTable.GetName();
                    try
                    {
                        FeatureClassDefinition originalFeatureClassDefinition   = geoDb.GetDefinition <FeatureClassDefinition>(fcName);
                        FeatureClassDescription originalFeatureClassDescription = new FeatureClassDescription(originalFeatureClassDefinition);

                        // Assemble a list of all of new field descriptions
                        var fieldDescriptions = new List <ArcGIS.Core.Data.DDL.FieldDescription>()
                        {
                            stringFieldDescription,
                            intFieldDescription,
                            dblFieldDescription,
                            dateFieldDescription
                        };
                        // Create a FeatureClassDescription object to describe the feature class to create
                        var fcDescription =
                            new FeatureClassDescription(fcName, fieldDescriptions, originalFeatureClassDescription.ShapeDescription);

                        // Create a SchemaBuilder object
                        SchemaBuilder schemaBuilder = new SchemaBuilder(geoDb);

                        // Add the modification to the feature class to our list of DDL tasks
                        schemaBuilder.Modify(fcDescription);

                        // Execute the DDL
                        bool success = schemaBuilder.Build();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show($@"Exception: {ex}");
                    }
                }
            });
        }
        private async Task <IGPResult> ExtraObstacle(double distance)
        {
            string fieldName = string.Empty;
            var    oidField  = QueuedTask.Run(() =>
            {
                string name;
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    FeatureClassDefinition fcd = geodatabase.GetDefinition <FeatureClassDefinition>(ConstDefintion.ConstFeatureClass_Course);
                    name = fcd.GetObjectIDField();
                }
                return(name);
            }).Result;
            string         path                 = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_Course;
            string         outpath              = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_SelectedCourse;
            string         whereClause          = $"{oidField} = {CourseListSelectedItem}";
            ProgressDialog progressDialogDomain = new ProgressDialog($"正在创建被选择航线图层", ConstDefintion.ConstStr_GeoprocessCancling, false);
            var            arg = Geoprocessing.MakeValueArray(path, outpath, whereClause);
            var            gp  = await Geoprocessing.ExecuteToolAsync("Select_analysis", arg, null, new CancelableProgressorSource(progressDialogDomain).Progressor);

            if (!gp.IsFailed)
            {
                ProgressDialog progressDialog1 = new ProgressDialog($"正在构造缓冲区", ConstDefintion.ConstStr_GeoprocessCancling, false);
                string         outBufferpath   = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseBuffer;
                string         str_distance    = $"{distance} NauticalMiles";
                var            arg1            = Geoprocessing.MakeValueArray(outpath, outBufferpath, str_distance);
                var            gp1             = await Geoprocessing.ExecuteToolAsync("Buffer_analysis", arg1, null, new CancelableProgressorSource(progressDialog1).Progressor);

                if (!gp1.IsFailed)
                {
                    ProgressDialog progressDialog2   = new ProgressDialog($"正在提取碍航物", ConstDefintion.ConstStr_GeoprocessCancling, false);
                    string         insArgs           = $"{ObstaclePath} 1;{outBufferpath} 2";
                    string         outcourseObstacle = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseObstacle;
                    var            arg2 = Geoprocessing.MakeValueArray(insArgs, outcourseObstacle);
                    var            gp2  = await Geoprocessing.ExecuteToolAsync("Intersect_analysis", arg2, null, new CancelableProgressorSource(progressDialog2).Progressor);

                    if (!gp2.IsFailed)
                    {
                        ProgressDialog progressDialog3            = new ProgressDialog($"正在创建泰森多边形", ConstDefintion.ConstStr_GeoprocessCancling, false);
                        string         outCourseObstacle_Thiessen = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseObstacleThiessen;
                        var            arg3 = Geoprocessing.MakeValueArray(outcourseObstacle, outCourseObstacle_Thiessen);
                        var            gp3  = await Geoprocessing.ExecuteToolAsync("CreateThiessenPolygons_analysis", arg3, null, new CancelableProgressorSource(progressDialog3).Progressor);

                        if (!gp3.IsFailed)
                        {
                            ProgressDialog progressDialog4           = new ProgressDialog($"正在裁剪", ConstDefintion.ConstStr_GeoprocessCancling, false);
                            string         inCourseObstacle_Thiessen = outCourseObstacle_Thiessen;
                            string         inBuffer        = outBufferpath;
                            string         outClipThiessen = GeoDataTool.DefaultProject.DefaultGeodatabasePath + "\\" + ConstDefintion.ConstFeatureClass_CourseObstacleThiessenClip;
                            var            arg4            = Geoprocessing.MakeValueArray(inCourseObstacle_Thiessen, inBuffer, outClipThiessen);
                            var            gp4             = await Geoprocessing.ExecuteToolAsync("Clip_analysis", arg4, null, new CancelableProgressorSource(progressDialog4).Progressor);

                            return(gp4);
                        }
                    }
                }
            }
            return(null);
        }
        /// <summary>
        /// Check to make sure the enviornment is set up correctly before processing the users request
        ///
        /// </summary>
        /// <returns></returns>
        private async Task <bool> CheckRequirements()
        {
            if (_selectedMap == null)
            {
                MessageBox.Show("Select A Map In Domain Appointer Settings");
                return(false);
            }

            if (_selectedLayer == null)
            {
                MessageBox.Show("Select A Layer in Domain Appointer Settings");
                return(false);
            }

            if (_selectedField == null)
            {
                MessageBox.Show("Select a Field in Domain Appointer Settings");
            }

            bool canEditData = false;

            await QueuedTask.Run(() =>
            {
                canEditData = _selectedLayer.CanEditData();
            });

            if (!canEditData)
            {
                MessageBox.Show("Feature Layer '" + _selectedLayer.Name + "' Is not Editable");
                return(false);
            }

            IEnumerable <Field> fields = null;

            await QueuedTask.Run(() =>
            {
                Table table = _selectedLayer.GetTable();
                if (table is FeatureClass)
                {
                    FeatureClass featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }
                }
            });

            var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(_selectedField.ToLower()));

            if (match == null)
            {
                MessageBox.Show("The field '" + _selectedField + "' is Missing From '" + _selectedLayer.Name + "' Feature Layer");
                return(false);
            }


            return(true);
        }
예제 #8
0
 protected override IAttributeReader CreateAttributeReaderCore(FeatureClassDefinition definition)
 {
     return(new AttributeReader(definition,
                                Attributes.QualityConditionName,
                                Attributes.IssueCodeDescription,
                                Attributes.InvolvedObjects,
                                Attributes.IssueSeverity,
                                Attributes.IssueCode));
 }
        private async Task <Boolean> CheckRequirements()
        {
            if (_selectedMap == null)
            {
                MessageBox.Show("Select A Map In File Tile Opener Settings");
                return(false);
            }

            if (_selectedFeatureLayer == null)
            {
                MessageBox.Show("Select A Layer in File Tile Opener Settings");
                return(false);
            }

            if (_selectedField == null)
            {
                MessageBox.Show("Select a Field in File Tile Opener Settings");
            }

            IEnumerable <Field> fields = null;

            await QueuedTask.Run(() =>
            {
                Table table = _selectedFeatureLayer.GetTable();
                if (table is FeatureClass)
                {
                    FeatureClass featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }
                }
            });

            var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(_selectedField.ToLower()));

            if (match == null)
            {
                MessageBox.Show("This field '" + _selectedField + "' is Missing From '" + _selectedFeatureLayer.Name + "' Feature Layer", "Oops");
                return(false);
            }

            // No need to check for whitespace. I disallow this in the 'view'.
            if (String.IsNullOrEmpty(_fileExtension))
            {
                MessageBox.Show("Type or Choose a File Extension in File Tile Opener Settings");
                return(false);
            }

            if (String.IsNullOrWhiteSpace(_fileWorkspace))
            {
                MessageBox.Show("Type or Choose a File Workspace in File Tile Opener Settings");
                return(false);
            }

            return(true);
        }
예제 #10
0
        //[CanBeNull]
        //protected Table OpenFeatureClass2([NotNull] ISourceClass sourceClass)
        //{
        //	return GeodatabaseBySourceClasses.TryGetValue(sourceClass, out Geodatabase gdb)
        //		       ? sourceClass.OpenFeatureClass(gdb)
        //		       : null;
        //}

        private ISourceClass CreateSourceClass(GdbTableIdentity identity, FeatureClassDefinition definition)
        {
            IAttributeReader attributeReader = CreateAttributeReaderCore(definition);

            WorkListStatusSchema statusSchema = CreateStatusSchemaCore(definition);

            ISourceClass sourceClass = CreateSourceClassCore(identity, attributeReader, statusSchema);

            return(sourceClass);
        }
예제 #11
0
        /// <summary>
        /// Create sample polygon feature using the point geometries from the multi-point feature using the
        /// ConvexHull method provided by the GeometryEngine.
        /// </summary>
        /// <param name="polygonLayer">Polygon geometry feature layer used to add the new feature.</param>
        /// <param name="lineLayer">The polyline feature layer containing the features used to construct the polygon.</param>
        /// <returns></returns>
        private void constructSamplePolygon(FeatureLayer polygonLayer, FeatureLayer lineLayer)
        {
            // execute the fine grained API calls on the CIM main thread
            //return QueuingTaskFactory.StartNew(() =>
            //{
            // get the feature classes and their definitions
            // get the underlying feature class for each layer
            var polygonFeatureClass = polygonLayer.GetTableAsync().Result as FeatureClass;
            var lineFeatureClass    = lineLayer.GetTableAsync().Result as FeatureClass;
            FeatureClassDefinition polygonDefinition  = null;
            FeatureClassDefinition polylineDefinition = null;

            // construct a cursor to retrieve the line features
            var lineCursor = lineFeatureClass.Search(null, false);

            // set up the edit operation for the feature creation
            var createOperation = EditingModule.CreateEditOperation();

            createOperation.Name = "Create polygons";

            // construct the polygon geometry from the convex hull of the combined polyline features
            // by contructing a convex hull
            // HINT:  GeometryEngine.ConvexHull
            List <CoordinateCollection> combinedCoordinates = new List <CoordinateCollection>();

            while (lineCursor.MoveNext())
            {
                // TODO
                // add the feature geometry into the overall list of coordinate collections
                // retrieve the first feature
                //var lineFeature = ... use the current property of the cursor

                // add the coordinate collection of the current geometry into our overall list of collections
                //var polylineGeometry = lineFeature.Shape as Polyline;
                //combinedCoordinates.AddRange ... Hint: we want the part collection of the polyline
            }

            // TODO
            //construct a polygon geometry from the convex hull of the polyline
            //constructed from the list of coordinate collections combined from all the polylines
            //var polyLine = new Polyline(..., lineFeatureClass.SpatialReference)
            //var geom = GeometryEngine.ConvexHull(...
            //var newPolygon = Polygon.Clone(...

            // TODO
            // specify the create edit operation

            // TODO
            // execute the operation

            // TODO
            // save the edits
            //return EditingModule.SaveEditsAsync();
            //});
        }
예제 #12
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();
                }
        }
        /// <summary>
        /// Validates Conditions for user before attempting to edit the data
        /// </summary>
        /// <returns></returns>
        private async Task <bool> PrepStatus()
        {
            if (_selectedMap == null)
            {
                MessageBox.Show("Select A Map In Inspector Settings");
                return(false);
            }

            if (_selectedLayer == null)
            {
                MessageBox.Show("Select A Layer in Inspector Settings");
                return(false);
            }

            IEnumerable <Field> fields       = null;
            FeatureClass        featureclass = null;

            await QueuedTask.Run(() =>
            {
                // Get the fields
                Table table = (_selectedLayer as FeatureLayer).GetTable();

                if (table is FeatureClass)
                {
                    featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }
                }
            });


            var match = fields.FirstOrDefault(field => field.Name.ToLower().Contains(InpsectorFieldName.ToLower()));

            if (match == null)
            {
                MessageBox.Show("Add field named '" + InpsectorFieldName + "' to '" + _selectedLayer.Name + "' layer of type Integer");
                return(false);
            }
            match = fields.FirstOrDefault(field => (field.FieldType == FieldType.SmallInteger || field.FieldType == FieldType.Integer));
            if (match == null)
            {
                MessageBox.Show("Add field named '" + InpsectorFieldName + "' to '" + _selectedLayer.Name + "' layer of type Integer");
                return(false);
            }


            return(true);
        }
        double GetLength(FeatureClass fc, EnterpriseDatabaseType enterpriseDbType)
        {
            try
            {
                using (FeatureClassDefinition fcd = fc.GetDefinition())
                {
                    // the name of the length field changes depending on what enterprise geodatabase is used
                    var areaFieldName = "Shape_Length";
                    switch (enterpriseDbType)
                    {
                    case EnterpriseDatabaseType.SQLServer:
                        areaFieldName = "STLength";
                        break;
                    }
                    Field lengthField = fcd.GetFields().FirstOrDefault(x => x.Name.Contains(areaFieldName));
                    if (lengthField == null)
                    {
                        return(0);
                    }
                    System.Diagnostics.Debug.WriteLine(lengthField.Name);

                    StatisticsDescription SumDesc = new StatisticsDescription(lengthField, new List <StatisticsFunction>()
                    {
                        StatisticsFunction.Sum
                    });
                    TableStatisticsDescription tsd = new TableStatisticsDescription(new List <StatisticsDescription>()
                    {
                        SumDesc
                    });
                    double sum = 0;
                    try
                    {
                        sum = fc.CalculateStatistics(tsd).FirstOrDefault().StatisticsResults.FirstOrDefault().Sum; // exception is thrown on this line
                    }
                    catch
                    {
                        sum = Utilities.GetSumWorkAround(fc, lengthField.Name);
                    }
                    return(sum);
                }
            }
            catch (Exception ex)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(ex.ToString(), "Error");
                return(0);
            }
        }
예제 #15
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());
                }
        }
        /// <summary>
        /// 指定されたファイルジオデータベースに同名称既存のレイヤーの存在を検査する
        /// </summary>
        public bool FeatureClassExists(string geodatabase, string featureClassName)
        {
            try
            {
                var fileGDBpath = new FileGeodatabaseConnectionPath(new Uri(geodatabase));

                using (Geodatabase gdb = new Geodatabase(fileGDBpath))
                {
                    FeatureClassDefinition featureClassDefinition = gdb.GetDefinition <FeatureClassDefinition>(featureClassName);
                    featureClassDefinition.Dispose();
                    return(true);
                }
            }
            catch
            {
                return(false);
            }
        }
예제 #17
0
        private void RegisterDatasets(Dictionary <Geodatabase, List <Table> > tablesByGeodatabase)
        {
            foreach (var pair in tablesByGeodatabase)
            {
                Geodatabase geodatabase = pair.Key;
                var         definitions = geodatabase.GetDefinitions <FeatureClassDefinition>().ToLookup(d => d.GetName());

                foreach (Table table in pair.Value)
                {
                    var identity = new GdbTableIdentity(table);

                    FeatureClassDefinition definition = definitions[identity.Name].FirstOrDefault();

                    ISourceClass sourceClass = CreateSourceClass(identity, definition);

                    GeodatabaseBySourceClasses.Add(sourceClass, geodatabase);
                }
            }
        }
 public bool FeatureClassExists(string fileGDBPath, string featureClassName)
 {
     try
     {
         using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(fileGDBPath))))
         {
             FeatureClassDefinition featureClassDefinition = geodatabase.GetDefinition <FeatureClassDefinition>(featureClassName);
             featureClassDefinition.Dispose();
             System.Diagnostics.Debug.WriteLine($"Feature class exists");
             return(true);
         }
     }
     catch
     {
         // GetDefinition throws an exception if the definition doesn't exist
         System.Diagnostics.Debug.WriteLine($"Feature class does not exist");
         return(false);
     }
 }
예제 #19
0
        private void OutputDefinition(Geodatabase geodatabase, TopologyDefinition topologyDefinition)
        {
            Console.WriteLine($"Topology cluster tolerance => {topologyDefinition.GetClusterTolerance()}");
            Console.WriteLine($"Topology Z cluster tolerance => {topologyDefinition.GetZClusterTolerance()}");

            IReadOnlyList <string> featureClassNames = topologyDefinition.GetFeatureClassNames();

            Console.WriteLine($"There are {featureClassNames.Count} feature classes that are participating in the topology:");

            foreach (string name in featureClassNames)
            {
                // Open each feature class that participates in the topology.

                using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(name))
                    using (FeatureClassDefinition featureClassDefinition = featureClass.GetDefinition())
                    {
                        Console.WriteLine($"\t{featureClass.GetName()} ({featureClassDefinition.GetShapeType()})");
                    }
            }
        }
        public void MainMethodCode()
        {
            Uri serviceUrl = new Uri("https://arcgis.server.example.com:6443/arcgis/rest/services/FeatureServiceName/FeatureServer");

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

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

                TableDefinition tableDefinition = serverFeatureService.GetDefinition <TableDefinition>("4");
                string          objectIDField   = tableDefinition.GetObjectIDField();
            }
        }
예제 #21
0
        double GetArea(FeatureClass fc)
        {
            try
            {
                using (FeatureClassDefinition fcd = fc.GetDefinition())
                {
                    // the name of the area field changes depending on what enterprise geodatabase is used
                    var   areaFieldName = "Shape_Area";
                    Field areaField     = fcd.GetFields().FirstOrDefault(x => x.Name.Contains(areaFieldName));
                    if (areaField == null)
                    {
                        return(0);
                    }
                    System.Diagnostics.Debug.WriteLine(areaField.Name); // Output is "Shape.STArea()" as expected

                    StatisticsDescription SumDesc = new StatisticsDescription(areaField, new List <StatisticsFunction>()
                    {
                        StatisticsFunction.Sum
                    });
                    TableStatisticsDescription tsd = new TableStatisticsDescription(new List <StatisticsDescription>()
                    {
                        SumDesc
                    });
                    double sum = 0;
                    try
                    {
                        sum = fc.CalculateStatistics(tsd).FirstOrDefault().StatisticsResults.FirstOrDefault().Sum; // exception is thrown on this line
                    }
                    catch
                    {
                        sum = Utilities.GetSumWorkAround(fc, areaField.Name);
                    }
                    return(sum);
                }
            }
            catch (Exception ex)
            {
                ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show(ex.ToString(), "Error");
                return(0);
            }
        }
예제 #22
0
 /// <summary>
 /// workaround to get sum from enterprise gdb lenght/area fields
 /// see https://community.esri.com/message/889796-problem-using-shapestlength-field-in-the-calculatestatistics-method
 /// </summary>
 /// <param name="fc">feature class to get sum from</param>
 /// <param name="fieldName">fieldname to sum up</param>
 /// <returns>sum</returns>
 public static double GetSumWorkAround(FeatureClass fc, string fieldName)
 {
     try
     {
         using (FeatureClassDefinition fcd = fc.GetDefinition())
         {
             double totalLen = 0.0;
             var    cur      = fc.Search();
             while (cur.MoveNext())
             {
                 var feat = cur.Current;
                 totalLen += Convert.ToDouble(feat[fieldName]);
             }
             return(totalLen);
         }
     }
     catch (Exception)
     {
         throw;
     }
 }
        /// <summary>
        /// Gets all the field in the selected layer that meets requirement and adds them to the drop down list
        /// </summary>
        private async void PopulateLayerFields()
        {
            _fields.Clear();
            IEnumerable <Field> fields       = null;
            FeatureClass        featureclass = null;

            await QueuedTask.Run(() =>
            {
                Table table = _selectedLayer.GetTable();

                if (table is FeatureClass)
                {
                    featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }

                    foreach (Field field in fields)
                    {
                        Domain domain = field.GetDomain();

                        if (domain != null)
                        {
                            FieldType fieldType = domain.GetFieldType();
                            if (fieldType == FieldType.SmallInteger || fieldType == FieldType.Integer)
                            {
                                _fields.Add(field.Name);
                            }
                            ;
                        }
                    }
                }
            });

            if (_fields.Count <= 0)
            {
                MessageBox.Show("No Valid Fields in '" + _selectedLayer.Name + "'  Feature Layer");
            }
        }
예제 #24
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));
        }
예제 #25
0
        public async static Task <bool> AddAndFlashGeometryAsync(this FeatureLayer targetFeatureLayer, Geometry GeometryToAdd)
        {
            var targetFeatureClass = await targetFeatureLayer.GetTableAsync() as FeatureClass;

            FeatureClassDefinition targetClassDefinition = null;
            Feature newFeature = null;

            var editOperation = EditingModule.CreateEditOperation();

            editOperation.Name = "Flash closest geometry";

            editOperation.Callback(context =>
            {
                targetClassDefinition = targetFeatureClass.Definition as FeatureClassDefinition;

                var targetGeometry = GeometryEngine.Project(GeometryToAdd, targetClassDefinition.SpatialReference);

                if (GeometryToAdd.GeometryType != targetClassDefinition.ShapeType)
                {
                    return;
                }

                var featureBuffer = targetFeatureClass.CreateRowBuffer();
                newFeature        = targetFeatureClass.CreateRow(featureBuffer) as Feature;

                newFeature.Shape = targetGeometry;
                newFeature.Store();

                context.invalidate(newFeature);
            }, targetFeatureClass);



            MappingModule.ActiveMapView.FlashFeature(targetFeatureLayer, Convert.ToInt32(newFeature.ObjectID));

            return(true);
        }
예제 #26
0
        private async void cboLayerList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            string       lname = cboLayerList.SelectedItem.ToString();
            var          mv    = MapView.Active;
            FeatureLayer fl    = mv.Map.FindLayers(lname).FirstOrDefault() as FeatureLayer;

            var fields = await QueuedTask.Run(() =>
            {
                FeatureClass fc = fl.GetFeatureClass();
                FeatureClassDefinition fcdef = fc.GetDefinition();
                return(fcdef.GetFields());
            });

            lstFields.Items.Clear();
            for (int i = 0; i < fields.Count; i++)
            {
                Field fld = fields[i];
                if (fld.FieldType == FieldType.String)
                {
                    lstFields.Items.Add(fld.Name);
                }
            }
            lstFields.SelectAll();
        }
        /// <summary>
        ///  Adds the selected feature layer's field to the '_fields' collection
        /// </summary>
        private async void PopulateFeatureLayerFields()
        {
            _fields.Clear();
            IEnumerable <Field> fields       = null;
            FeatureClass        featureclass = null;

            await QueuedTask.Run(() =>
            {
                Table table = _selectedFeatureLayer.GetTable();

                if (table is FeatureClass)
                {
                    featureclass = table as FeatureClass;
                    using (FeatureClassDefinition def = featureclass.GetDefinition())
                    {
                        fields = def.GetFields();
                    }

                    foreach (Field field in fields)
                    {
                        FieldType fieldType = field.FieldType;
                        // Change field type acceptance here
                        if (fieldType == FieldType.SmallInteger || fieldType == FieldType.Integer || fieldType == FieldType.String || fieldType == FieldType.Double || fieldType == FieldType.Single || fieldType == FieldType.GUID)
                        {
                            _fields.Add(field.Name);
                        }
                        ;
                    }
                }
            });

            if (_fields.Count <= 0)
            {
                MessageBox.Show("No Valid Fields in '" + _selectedFeatureLayer.Name + "'  Feature Layer");
            }
        }
예제 #28
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);
        }
예제 #29
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);
            }
        }
예제 #30
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);
        }