Пример #1
0
        public override void LoadChildren()
        {
            var addChildrenTask = QueuedTask.Run(() =>
            {
                var lstChildren = new List <GdbItem>();
                // use the geodatabase to get all layers
                var fGdbPath = new FileGeodatabaseConnectionPath(new Uri(Folder, UriKind.Absolute));
                using (var gdb = new Geodatabase(fGdbPath))
                {
                    IReadOnlyList <Definition> fcList = gdb.GetDefinitions <FeatureClassDefinition>();
                    //Feature class
                    foreach (FeatureClassDefinition fcDef in fcList)
                    {
                        GdbItem gdbItem = new GdbItem(this, fcDef.GetName());
                        lstChildren.Add(gdbItem);
                    }
                }
                return(lstChildren);
            });

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

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

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

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

            return(gdbItems);
        }
        /// <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);
            }
        }
        private Task ChangeUSHighwaysLayerDataConnectionAsync(FeatureLayer featureLayer, string catalogPath)
        {
            return(QueuedTask.Run(() => {
                CIMDataConnection currentDataConnection = featureLayer.GetDataConnection();

                string connection = System.IO.Path.GetDirectoryName(catalogPath);
                string suffix = System.IO.Path.GetExtension(connection).ToLower();

                var workspaceConnectionString = string.Empty;
                WorkspaceFactory wf = WorkspaceFactory.FileGDB;
                if (suffix == ".sde")
                {
                    wf = WorkspaceFactory.SDE;
                    var dbGdbConnection = new DatabaseConnectionFile(new Uri(connection, UriKind.Absolute));
                    workspaceConnectionString = new Geodatabase(dbGdbConnection).GetConnectionString();
                }
                else
                {
                    var dbGdbConnectionFile = new FileGeodatabaseConnectionPath(new Uri(connection, UriKind.Absolute));
                    workspaceConnectionString = new Geodatabase(dbGdbConnectionFile).GetConnectionString();
                }

                string dataset = System.IO.Path.GetFileName(catalogPath);
                // provide a replace data connection method
                CIMStandardDataConnection updatedDataConnection = new CIMStandardDataConnection()
                {
                    WorkspaceConnectionString = workspaceConnectionString,
                    WorkspaceFactory = wf,
                    Dataset = dataset,
                    DatasetType = esriDatasetType.esriDTFeatureClass
                };

                featureLayer.SetDataConnection(updatedDataConnection);

                //For a RDBMS, it might look like this:
                //string connection = "C:\\Work\\temp.sde";
                //Geodatabase sde = new Geodatabase(connection);

                //// provide a replace data connection method
                //CIMStandardDataConnection updatedDataConnection = new CIMStandardDataConnection();
                //updatedDataConnection.WorkspaceConnectionString = sde.GetConnectionString();
                //updatedDataConnection.WorkspaceFactory = WorkspaceFactory.SDE;
                //updatedDataConnection.Dataset = "vtest.usa.states";
                //updatedDataConnection.DatasetType = esriDatasetType.esriDTFeatureClass;



                //// Alternatively, use Layer.FindAndReplaceWorkspacePath()
                ////Note: this will not allow changing the dataset name or workspace type
                ////
                ////string connection = "C:\\Work\\temp.sde";
                ////Geodatabase sde = new Geodatabase(connection);
                ////featureLayer.FindAndReplaceWorkspacePath(((CIMStandardDataConnection)currentDataConnection).WorkspaceConnectionString,
                ////                        sde.GetConnectionString(), true);


                //////////////////////////////////////////////
                ////Please Read
                ////
                //ok, so at this point we have a couple of bugs at 1.1 AND 1.2.....
                //
                //#1: if you switched to a Datasource that invalidates the Renderer, the Renderer does
                //not get invalidated in the UI
                //(eg You had a UniqueValueRenderer on a Field called "CATEGORY", the new datasource
                //does NOT have that field and so the renderer is invalid).
                //
                //#2: By default, Layers are added with a permanent cache. The cache is NOT automatically
                //invalidated so data (eg in the Attribute table, on the screen for draws) does NOT get
                //Refreshed so you have to invalidate the cache manually...

                //So, Bug #1 - we arbitrarily switch the Renderer to a simple renderer as a work around for that...
                featureLayer.SetRenderer(featureLayer.CreateRenderer(new SimpleRendererDefinition()));

                //Bug #2, we manually invalidate the cache
                featureLayer.ClearDisplayCache();
            }));
        }
Пример #5
0
        public async void RasterDatasetSnippets()
        {
            try
            {
                #region Open raster dataset in a folder.
                // Create a FileSystemConnectionPath using the folder path.
                FileSystemConnectionPath connectionPath = new FileSystemConnectionPath(new System.Uri(@"C:\Temp"), FileSystemDatastoreType.Raster);
                // Create a new FileSystemDatastore using the FileSystemConnectionPath.
                FileSystemDatastore dataStore = new FileSystemDatastore(connectionPath);
                // Open the raster dataset.
                RasterDataset fileRasterDataset = dataStore.OpenDataset <RasterDataset>("Sample.tif");
                #endregion

                #region Open raster dataset in a geodatabase.
                // Create a FileGeodatabaseConnectionPath using the path to the gdb. Note: This can be a path to a .sde file.
                FileGeodatabaseConnectionPath geodatabaseConnectionPath = new FileGeodatabaseConnectionPath(new Uri(@"C:\Temp\rasters.gdb"));
                // Create a new Geodatabase object using the FileGeodatabaseConnectionPath.
                Geodatabase geodatabase = new Geodatabase(geodatabaseConnectionPath);
                // Open the raster dataset.
                RasterDataset gdbRasterDataset = geodatabase.OpenDataset <RasterDataset>("sample");
                #endregion

                RasterDataset rasterDataset = fileRasterDataset;
                #region Get the raster dataset definition from a raster dataset.
                await QueuedTask.Run(() =>
                {
                    RasterDatasetDefinition rasterDatasetDefinition = rasterDataset.GetDefinition();
                    rasterDatasetDefinition.GetBandCount();
                });

                #endregion

                {
                    #region Access rows in a raster attribute table.
                    var raster = MapView.Active.Map.GetLayersAsFlattenedList().OfType <RasterLayer>().FirstOrDefault();
                    if (raster != null)
                    {
                        await QueuedTask.Run(() =>
                        {
                            var rasterTbl = raster.GetRaster().GetAttributeTable();
                            var cursor    = rasterTbl.Search();
                            while (cursor.MoveNext())
                            {
                                var row = cursor.Current;
                            }
                        });
                    }
                    #endregion
                }

                {
                    #region Create a raster cursor to iterate through the raster data.
                    await QueuedTask.Run(() =>
                    {
                        // Create a full raster from the raster dataset.
                        ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster();

                        // Calculate size of pixel blocks to process. Use 1000 or height/width of the raster, whichever is smaller.
                        int pixelBlockHeight = raster.GetHeight() > 1000 ? 1000 : raster.GetHeight();
                        int pixelBlockWidth  = raster.GetWidth() > 1000 ? 1000 : raster.GetWidth();

                        // Create the raster cursor using the height and width calculated.
                        RasterCursor rasterCursor = raster.CreateCursor(pixelBlockWidth, pixelBlockHeight);

                        // Use a do-while loop to iterate through the pixel blocks of the raster using the raster cursor.
                        do
                        {
                            // Get the current pixel block from the cursor.
                            using (PixelBlock currentPixelBlock = rasterCursor.Current)
                            {
                                // Do something with the pixel block...
                            }

                            // Once you are done, move to the next pixel block.
                        }         while (rasterCursor.MoveNext());
                    });

                    #endregion
                }

                {
                    #region Read and Write pixels from and to a raster dataset using pixel blocks.
                    await QueuedTask.Run(() =>
                    {
                        // Create a full raster from the raster dataset.
                        ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster();

                        // Calculate size of pixel block to create. Use 128 or height/width of the raster, whichever is smaller.
                        int pixelBlockHeight = raster.GetHeight() > 128 ? 128 : raster.GetHeight();
                        int pixelBlockWidth  = raster.GetWidth() > 128 ? 128 : raster.GetWidth();

                        // Create a new (blank) pixel block.
                        PixelBlock currentPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight);

                        // Read pixel values from the raster dataset into the pixel block starting from the given top left corner.
                        raster.Read(0, 0, currentPixelBlock);

                        // Do something with the pixel block...

                        // Write the pixel block to the raster dataset starting from the given top left corner.
                        raster.Write(0, 0, currentPixelBlock);
                    });

                    #endregion
                }

                {
                    // Create a full raster from the raster dataset.
                    ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster();

                    // Calculate size of pixel block to create. Use 128 or height/width of the raster, whichever is smaller.
                    int pixelBlockHeight = raster.GetHeight() > 128 ? 128 : raster.GetHeight();
                    int pixelBlockWidth  = raster.GetWidth() > 128 ? 128 : raster.GetWidth();

                    // Create a new (blank) pixel block.
                    PixelBlock currentPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight);

                    #region Process pixels using a pixel block
                    await QueuedTask.Run(() =>
                    {
                        // Read pixel values from the raster dataset into the pixel block starting from the given top left corner.
                        raster.Read(0, 0, currentPixelBlock);

                        // For each plane (band) in the pixel block
                        for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++)
                        {
                            // Get a copy of the array of pixels from the pixel block corresponding to the current plane.
                            Array sourcePixels = currentPixelBlock.GetPixelData(plane, true);
                            // Get the height and width of the pixel block.
                            int pBHeight = currentPixelBlock.GetHeight();
                            int pBWidth  = currentPixelBlock.GetWidth();

                            // Iterate through the pixels in the array.
                            for (int i = 0; i < pBHeight; i++)
                            {
                                for (int j = 0; j < pBWidth; j++)
                                {
                                    // Get the NoData mask value to see if the pixel is a valid pixel.
                                    if (Convert.ToByte(currentPixelBlock.GetNoDataMaskValue(plane, j, i)) == 1)
                                    {
                                        // Get the pixel value from the array and process it (add 5 to the value).
                                        // Note: This is assuming the pixel type is Unisigned 8bit.
                                        int pixelValue = Convert.ToInt16(sourcePixels.GetValue(j, i)) + 5;
                                        // Make sure the pixel value does not go above the range of the pixel type.
                                        pixelValue = pixelValue > 254 ? 254 : pixelValue;
                                        // Set the new pixel value to the array.
                                        // Note: This is assuming the pixel type is Unisigned 8bit.
                                        sourcePixels.SetValue(Convert.ToByte(pixelValue), j, i);
                                    }
                                }
                            }
                            // Set the modified array of pixels back to the pixel block.
                            currentPixelBlock.SetPixelData(plane, sourcePixels);
                        }
                        // Write the pixel block to the raster dataset starting from the given top left corner.
                        raster.Write(0, 0, currentPixelBlock);
                    });

                    #endregion
                    #region Calculate Raster statistics
                    //If a raster dataset has statistics, you can create a raster layer and get these statistics by accessing the colorizer.
                    await QueuedTask.Run(() =>
                    {
                        //Accessing the raster layer
                        var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType <BasicRasterLayer>().FirstOrDefault();
                        //Getting the colorizer
                        var colorizer = lyr.GetColorizer() as CIMRasterStretchColorizer;
                        //Accessing the statistics
                        var stats = colorizer.StretchStats;
                        var max   = stats.max;
                        var min   = stats.min;
                    });

                    #endregion
                }
            }
            catch (Exception)
            {
            }
        }
        /// <summary>
        /// テキスト ボックスに格納される
        /// </summary>
        private void ManipulateGeometry(FeatureLayer manipulatedlayer)
        {
            QueuedTask.Run(() =>
            {
                var fileGDBpath = new FileGeodatabaseConnectionPath(new Uri(_gdbPath));
                using (Geodatabase geodatabase = new Geodatabase(fileGDBpath))
                {
                    // フィーチャクラスを取得する
                    using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(_featureClassName))
                    {
                        using (var rowCursor = manipulatedlayer.Search(null))
                        {
                            var editOperation = new EditOperation();

                            if (manipulatedlayer.GetFeatureClass().GetDefinition().GetShapeType().ToString() == "Polygon")
                            {
                                while (rowCursor.MoveNext())
                                {
                                    using (var row = rowCursor.Current)
                                    {
                                        Feature feature = row as Feature;
                                        Geometry shape  = feature.GetShape();

                                        MapPoint mapPoint = GeometryEngine.Instance.Centroid(shape);

                                        //レイヤーのフィーチャクラスの Shape フィールドを取得
                                        string shapeField = featureClass.GetDefinition().GetShapeField();

                                        var attributes = new Dictionary <string, object>();
                                        attributes.Add(shapeField, mapPoint);

                                        //ジオメトリの属性値設定
                                        foreach (var fld in row.GetFields().Where(fld => fld.FieldType != FieldType.Geometry && fld.FieldType != FieldType.OID && fld.Name != "Shape_Length" && fld.Name != "Shape_Area"))
                                        {
                                            attributes.Add(fld.Name, row[fld.Name]);
                                        }

                                        //フィーチャの作成と編集実行
                                        editOperation.Create(featureClass, attributes);
                                    }
                                }
                            }
                            else if (manipulatedlayer.GetFeatureClass().GetDefinition().GetShapeType().ToString() == "Polyline")
                            {
                                while (rowCursor.MoveNext())
                                {
                                    using (var row = rowCursor.Current)
                                    {
                                        Feature feature             = row as Feature;
                                        Polyline polyline           = feature.GetShape() as Polyline;
                                        ReadOnlyPointCollection pts = polyline.Points;

                                        var mapPointBuilder    = new MapPointBuilder(manipulatedlayer.GetSpatialReference());
                                        mapPointBuilder.X      = pts.First().X;
                                        mapPointBuilder.Y      = pts.First().Y;
                                        MapPoint firstMapPoint = mapPointBuilder.ToGeometry();

                                        mapPointBuilder.X     = pts.Last().X;
                                        mapPointBuilder.Y     = pts.Last().Y;
                                        MapPoint lastMapPoint = mapPointBuilder.ToGeometry();

                                        //レイヤーのフィーチャクラスの Shape フィールドを取得
                                        string shapeField = featureClass.GetDefinition().GetShapeField();

                                        var firstAttributes = new Dictionary <string, object>();
                                        firstAttributes.Add(shapeField, firstMapPoint);

                                        var lastAttributes = new Dictionary <string, object>();
                                        lastAttributes.Add(shapeField, lastMapPoint);

                                        //ジオメトリの属性値設定
                                        foreach (var fld in row.GetFields().Where(fld => fld.FieldType != FieldType.Geometry && fld.FieldType != FieldType.OID && fld.Name != "Shape_Length" && fld.Name != "Shape_Area"))
                                        {
                                            firstAttributes.Add(fld.Name, row[fld.Name]);
                                            lastAttributes.Add(fld.Name, row[fld.Name]);
                                        }

                                        editOperation.Create(featureClass, firstAttributes);
                                        editOperation.Create(featureClass, lastAttributes);
                                    }
                                }
                            }

                            editOperation.Execute();
                        }
                    }
                }
            });
        }