void SetMosaicRule(MosaicLayer mosaicLayer, FeatureLayer footprintLayer, List <long> selectedItems)
 {
     ArcGIS.Desktop.Framework.Threading.Tasks.QueuedTask.Run(() =>
     {
         // Check if overviews are supposed to be excluded from the selection.
         string objectIDs = null;
         if (excludeOverviews)
         {
             // Get the selected rows from the feature layer.
             RowCursor selectedRows = footprintLayer.GetSelection().Search();
             if (selectedRows.MoveNext())
             {
                 using (var selectedRow = selectedRows.Current)
                 {
                     // Get the value for the Category field.
                     int tag = Convert.ToInt32(selectedRow.GetOriginalValue(selectedRows.FindField("Category")));
                     // For each row, if Category is not 2 (2 = overview), then add the object id to the list of items to lock to.
                     if (tag != 2)
                     {
                         objectIDs = selectedRow.GetOriginalValue(selectedRows.FindField("OBJECTID")).ToString();
                     }
                     while (selectedRows.MoveNext())
                     {
                         tag = Convert.ToInt32(selectedRow.GetOriginalValue(selectedRows.FindField("Category")));
                         if (tag != 2)
                         {
                             objectIDs += "," + selectedRow.GetOriginalValue(selectedRows.FindField("OBJECTID")).ToString();
                         }
                     }
                 }
             }
         }
         // Get the mosaic rule of the image sub-layer of the mosaic layer.
         ImageServiceLayer imageLayer = mosaicLayer.GetImageLayer() as ImageServiceLayer;
         CIMMosaicRule newMosaicRule  = imageLayer.GetMosaicRule();
         // If there is no saved mosaic rule, then save the original mosaic rule of the mosaic layer.
         if (mosaicRule == null)
         {
             mosaicRule = newMosaicRule;
             // Then create a new mosaic rule.
             newMosaicRule = new CIMMosaicRule();
         }
         // Set the Mosaic Method to 'Lock Raster'
         newMosaicRule.MosaicMethod = RasterMosaicMethod.LockRaster;
         // Set the object id's to lock to.
         if (excludeOverviews)
         {
             newMosaicRule.LockRasterID = objectIDs;
         }
         else
         {
             newMosaicRule.LockRasterID = string.Join(",", selectedItems);
         }
         // Update the mosaic layer with the changed mosaic rule.
         imageLayer.SetMosaicRule(newMosaicRule);
     });
 }
        private async Task QueryRows(object query)
        {
            string where = "";
            if (query != null)
            {
                where = query.ToString();
            }
            IsLoading = true;
            lock (_theLock) {
                ListOfRows.Clear();
            }
            if (_layerSource == null)
            {
                _layerSource = await _selectedLayer.getFeatureClass();
            }
            if (_layerSource != null)
            {
                var data = new List <DynamicDataRow>();
                await QueuingTaskFactory.StartNew(() => {
                    var queryFilter = new ArcGIS.Core.Data.QueryFilter {
                        WhereClause = where
                    };
                    int maxcols      = 6;
                    RowCursor cursor = _layerSource.Search(queryFilter);
                    if (cursor.MoveNext())
                    {
                        ExtendListView.Columns = new List <ArcGIS.Core.Data.Field>();
                        maxcols = cursor.Current.Fields.Count() > 6 ? 6 : cursor.Current.Fields.Count();

                        for (int c = 0; c < maxcols; c++)
                        {
                            ExtendListView.Columns.Add(cursor.Current.Fields[c]);
                        }
                        do
                        {
                            var row = new DynamicDataRow();
                            for (int v = 0; v < maxcols; v++)
                            {
                                row[GetName(cursor.Fields[v])] = cursor.Current[v].ToString();
                            }
                            data.Add(row);
                        } while (cursor.MoveNext());
                    }
                });

                lock (_theLock) {
                    ListOfRows = null;
                    ListOfRows = data;
                }
            }
            RaisePropertyChanged("ListOfRows");
            Status    = string.Format("{0} rows loaded", ListOfRows.Count());
            IsLoading = false;
        }
Exemplo n.º 3
0
            public override bool MoveNext()
            {
                if (_copy > 0)
                {
                    --_copy;
                    return(true);
                }

                bool r = _inputCursor.MoveNext();

                if (!r)
                {
                    return(r);
                }

                if (_cache != null)
                {
                    _idGetter(ref _currentId);
                    _copy = _cache[_currentId];
                }
                else
                {
                    _copy = NextPoisson(_lambda, _rand);
                    _copy = Math.Min(_copy, _maxReplica);
                }

                while (_copy <= 0)
                {
                    r = _inputCursor.MoveNext();
                    if (!r)
                    {
                        return(r);
                    }
                    if (_cache != null)
                    {
                        _idGetter(ref _currentId);
                        _copy = _cache[_currentId];
                    }
                    else if (_classGetter == null)
                    {
                        _copy = NextPoisson(_lambda, _rand);
                        _copy = Math.Min(_copy, _maxReplica);
                    }
                    else
                    {
                        _classGetter(ref _currentCl);
                        _copy = _currentCl.Equals(_classValue) ? NextPoisson(_lambda, _rand) : 1;
                        _copy = Math.Min(_copy, _maxReplica);
                    }
                }
                --_copy;
                return(true);
            }
Exemplo n.º 4
0
            protected override bool MoveNextCore()
            {
                // If leading cursor is not started, start it.
                // But, if in moving it we find we've reached the end, we have the degenerate case where
                // there are no rows, in which case we ourselves should return false immedaitely.

                if (_leadingCursor.Position < 0 && !_leadingCursor.MoveNext())
                {
                    return(false);
                }
                Ch.Assert(_leadingCursor.Position >= 0);

                // We are now in a "valid" place. Advance the leading cursor until it hits
                // the end of the group (or the end of the data).
                int groupSize = 0;

                while (_leadingCursor.Position >= 0 && IsSameGroup())
                {
                    groupSize++;
                    if (!_leadingCursor.MoveNext())
                    {
                        break;
                    }
                }

                // The group can only be empty if the leading cursor immediately reaches the end of the data.
                // This is handled by the check above.
                Ch.Assert(groupSize > 0);

                // Catch up with the trailing cursor and populate all the aggregates.
                // REVIEW: this could be done lazily, but still all aggregators together.
                foreach (var agg in _aggregators.Where(x => x != null))
                {
                    agg.SetSize(groupSize);
                }

                for (int i = 0; i < groupSize; i++)
                {
                    var res = _trailingCursor.MoveNext();
                    Ch.Assert(res);

                    foreach (var agg in _aggregators.Where(x => x != null))
                    {
                        agg.ReadValue(i);
                    }
                }

                return(true);
            }
        /// <summary>
        /// Create a unique value renderer based on the weather
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        private static CIMUniqueValueRenderer CreateRedenderer(Table table)
        {
            List <string> uniqueIconUrls = new List <string>();

            using (RowCursor cursor = table.Search())
            {
                do
                {
                    if (cursor.Current != null)
                    {
                        string url = cursor.Current["Iconurl"].ToString();
                        if (!uniqueIconUrls.Contains(url))
                        {
                            uniqueIconUrls.Add(url);
                        }
                    }
                }while (cursor.MoveNext());
            }

            CIMUniqueValueGroup uniqueValueGroup = new CIMUniqueValueGroup
            {
                Heading = "Weer type",
                Classes = CreateUniqueValueClasses(uniqueIconUrls)
            };

            CIMUniqueValueRenderer uniqueValueRenderer = new CIMUniqueValueRenderer
            {
                Groups = new CIMUniqueValueGroup[] { uniqueValueGroup },
                Fields = new string[] { "Iconurl" }
            };

            return(uniqueValueRenderer);
        }
Exemplo n.º 6
0
        public Task UpdateUicFacility(string facilityId)
        {
            return(QueuedTask.Run(() =>
            {
                var map = MapView.Active.Map;
                FeatureLayer uicFacilities = (FeatureLayer)map.FindLayers("UICFacility").First();
                QueryFilter qf = new QueryFilter()
                {
                    WhereClause = string.Format("FacilityID = '{0}'", facilityId)
                };
                using (RowCursor cursor = uicFacilities.Search(qf))
                {
                    bool hasRow = cursor.MoveNext();
                    using (Row row = cursor.Current)
                    {
                        System.Diagnostics.Debug.WriteLine(string.Format("UpdateUicFacility: facId: {0} county: {1}",
                                                                         row["FacilityID"],
                                                                         row["CountyFIPS"]));

                        this.UicFacilityId = Convert.ToString(row["FacilityID"]);
                        this.CountyFips = Convert.ToString(row["CountyFIPS"]);
                        this.NaicsPrimary = Convert.ToString(row["NAICSPrimary"]);
                        this.FacilityName = Convert.ToString(row["FacilityName"]);
                        this.FacilityAddress = Convert.ToString(row["FacilityAddress"]);
                        this.FacilityCity = Convert.ToString(row["FacilityCity"]);
                        this.FacilityState = Convert.ToString(row["FacilityState"]);
                        this.FacilityMilePost = Convert.ToString(row["FacilityMilePost"]);
                        this.Comments = Convert.ToString(row["Comments"]);
                    }
                }
            }));
        }
Exemplo n.º 7
0
        public Task UpdateUicWell(string wellId)
        {
            return(QueuedTask.Run(() =>
            {
                var map = MapView.Active.Map;
                FeatureLayer uicWells = (FeatureLayer)map.FindLayers("UICWell").First();
                QueryFilter qf = new QueryFilter()
                {
                    WhereClause = string.Format("FacilityID = '{0}'", wellId)
                };
                using (RowCursor cursor = uicWells.Search(qf))
                {
                    bool hasRow = cursor.MoveNext();
                    using (Row row = cursor.Current)
                    {
                        //System.Diagnostics.Debug.WriteLine(string.Format("UpdateUicFacility: facId: {0} county: {1}",
                        //                                    row["FacilityID"],
                        //                                    row["CountyFIPS"]));

                        this.UicFacilityId = Convert.ToString(row["WellID"]);
                        this.CountyFips = Convert.ToString(row["WellName"]);
                        this.NaicsPrimary = Convert.ToString(row["WellClass"]);
                        this.FacilityName = Convert.ToString(row["WellSubClass"]);
                        this.FacilityAddress = Convert.ToString(row["HighPriority"]);
                        this.FacilityCity = Convert.ToString(row["WellSWPZ"]);
                    }
                }
            }));
        }
Exemplo n.º 8
0
        /// <summary>
        /// Copy selected GIS features into Rhino; assign objects to corresponding layers, and apply attribute values as user text
        /// </summary>
        /// <param name="rhinoDoc">Active Rhino Doc</param>
        internal static void copySelectedObjects(RhinoDoc rhinoDoc)
        {
            if (rhinoDoc == null)
            {
                return;
            }
            var origin = RhinoUtil.getOrigin(rhinoDoc);
            // System.Windows.MessageBox.Show($"Origin {origin.ToString()}");
            var layers = MapView.Active.Map.GetLayersAsFlattenedList().OfType <FeatureLayer>().ToList();

            foreach (var layer in layers)
            {
                var t = QueuedTask.Run(() =>
                {
                    var selectionfromMap = layer.GetSelection();
                    var count            = selectionfromMap.GetCount();
                    // MessageBox.Show($"Got layer {firstLayer.Name} with {count} selected features");
                    var filter = new QueryFilter {
                        ObjectIDs = selectionfromMap.GetObjectIDs()
                    };
                    if (count > 0)
                    {
                        using (RowCursor rowCursor = layer.Search(filter))
                        {
                            while (rowCursor.MoveNext())
                            {
                                long oid = rowCursor.Current.GetObjectID();
                                // get the shape from the row
                                Feature feature = rowCursor.Current as Feature;
                                if (feature.GetShape() is Polygon polygon)
                                {
                                    convertPolygon(layer, feature, polygon, rhinoDoc, origin);
                                }
                                else if (feature.GetShape() is Polyline polyline)
                                {
                                    convertPolyline(layer, feature, polyline, rhinoDoc, origin);
                                }
                                else if (feature.GetShape() is MapPoint point)
                                {
                                    convertPoint(layer, feature, point, rhinoDoc, origin);
                                }
                                else if (feature.GetShape() is Multipoint multiPoint)
                                {
                                    // TODO: treat multipoint as a group of points
                                }
                                else if (feature.GetShape() is Multipatch multiPatch)
                                {
                                    // TODO: treat multipoint as a group of patches
                                }
                                else
                                {
                                    // TODO: figure out other possible types inherited from ArcGIS.Core.Geometry
                                }
                                // MessageBox.Show("Found feature with attributes:\n" + string.Join("\n", feature.GetFields().Select(f => f.Name).ToList()));
                            }
                        }
                    }
                });
            }
        }
        private ObservableCollection <string> GetAllCourse()
        {
            var task = QueuedTask.Run(() =>
            {
                ObservableCollection <string> result = new ObservableCollection <string>();
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(GeoDataTool.DefaultProject.DefaultGeodatabasePath))))
                {
                    using (FeatureClass course = geodatabase.OpenDataset <FeatureClass>(ConstDefintion.ConstFeatureClass_Course))
                    {
                        using (RowCursor rowCursor = course.Search(null, false))
                        {
                            while (rowCursor.MoveNext())
                            {
                                using (Row row = rowCursor.Current)
                                {
                                    result.Add(row.GetObjectID().ToString());
                                }
                            }
                        }
                    }
                }
                return(result);
            });

            return(task.Result);
        }
Exemplo n.º 10
0
        private static List <Guid> GetSelectionGlobalIds(Map activeMap, List <string> layerNames)
        {
            List <Guid> globalIds = new List <Guid>();

            Dictionary <MapMember, List <long> > mapSelection = activeMap.GetSelection();
            IEnumerable <MapMember> desiredMapMembers         = mapSelection.Keys.Where(mm => layerNames.Contains(mm.Name));

            foreach (MapMember mapMember in desiredMapMembers)
            {
                List <long>  objectIds    = mapSelection[mapMember];
                FeatureLayer featureLayer = mapMember as FeatureLayer;

                QueryFilter queryFilter = new QueryFilter
                {
                    ObjectIDs = objectIds
                };

                using (RowCursor rowCursor = featureLayer.Search(queryFilter))
                {
                    while (rowCursor.MoveNext())
                    {
                        Row row = rowCursor.Current;
                        globalIds.Add(new Guid(row["GLOBALID"].ToString()));
                    }
                }
            }
            return(globalIds);
        }
Exemplo n.º 11
0
        /// <summary>
        /// Retrieves a specific row/feature for given ObjectID.
        /// </summary>
        /// <param name="table">Table of Feature class containing the row/feature.</param>
        /// <param name="oid">The ObjectID of the row/feature to be returned.</param>
        /// <returns>The row/feature specified by the ObjectID. If entity with the ObjectID exists, a null reference is returned.</returns>
        public static async Task <Row> GetRowByIDAsync(this Table table, long oid)
        {
            Row foundRow = null;

            if (table == null)
            {
                return(foundRow);
            }

            await QueuingTaskFactory.StartNew(() =>
            {
                if (table.Definition is TableDefinition)
                {
                    var tableDefinition = table.Definition as TableDefinition;

                    var queryFilter = new QueryFilter {
                        WhereClause = tableDefinition.ObjectIDField + " = " + oid.ToString()
                    };

                    RowCursor rc = table.Search(queryFilter, false);

                    if (rc.MoveNext())
                    {
                        foundRow = rc.Current;
                    }
                }
            });

            return(foundRow);
        }
Exemplo n.º 12
0
        public static async Task <string[]> QueryAoiEnvelopeAsync(Uri clipFileGdbUri, string clipName)
        {
            string[] arrRetValues = new string[2];
            Geometry aoiGeo       = null;
            int      intCount     = 0;
            await QueuedTask.Run(() =>
            {
                using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(clipFileGdbUri)))
                    using (Table table = geodatabase.OpenDataset <Table>(clipName))
                    {
                        //check for multiple buffer polygons and buffer AOI if we need to
                        QueryFilter queryFilter = new QueryFilter();
                        using (RowCursor cursor = table.Search(queryFilter, false))
                        {
                            while (cursor.MoveNext())
                            {
                                using (Feature feature = (Feature)cursor.Current)
                                {
                                    aoiGeo = feature.GetShape();
                                }
                                intCount++;
                            }
                        }
                    }
            });

            if (intCount > 1)
            {
                string        tmpClipBuffer = "tmpClipBuffer";
                BA_ReturnCode success       = await GeoprocessingTools.BufferAsync(clipFileGdbUri.LocalPath + "\\" + clipName, clipFileGdbUri.LocalPath + "\\" + tmpClipBuffer,
                                                                                   "0.5 Meters", "ALL");

                if (success == BA_ReturnCode.Success)
                {
                    await QueuedTask.Run(() =>
                    {
                        using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(clipFileGdbUri)))
                            using (Table table = geodatabase.OpenDataset <Table>(tmpClipBuffer))
                            {
                                //check for multiple buffer polygons and buffer AOI if we need to
                                QueryFilter queryFilter = new QueryFilter();
                                using (RowCursor cursor = table.Search(queryFilter, false))
                                {
                                    while (cursor.MoveNext())
                                    {
                                        using (Feature feature = (Feature)cursor.Current)
                                        {
                                            aoiGeo   = feature.GetShape(); // Replace unbuffered geometry with buffered
                                            clipName = tmpClipBuffer;
                                        }
                                    }
                                }
                            }
                    });
                }
            }
            arrRetValues[0] = aoiGeo.Extent.XMin + " " + aoiGeo.Extent.YMin + " " + aoiGeo.Extent.XMax + " " + aoiGeo.Extent.YMax;
            arrRetValues[1] = clipFileGdbUri.LocalPath + "\\" + clipName;
            return(arrRetValues);
        }
Exemplo n.º 13
0
 public string[] prepareData(FeatureLayer data)
 {
     try
     {
         string[] columns = null;
         if (data != null)
         {
             Task t = QueuedTask.Run(() =>
             {
                 Table table      = data.GetTable();
                 RowCursor cursor = table.Search();
                 cursor.MoveNext();
                 var fields = cursor.GetFields();
                 columns    = new string[fields.Count];
                 int i      = 0;
                 foreach (Field field in fields)
                 {
                     columns[i] = field.Name;
                     i++;
                 }
             });
             t.Wait();
         }
         return(columns);
     }
     catch (Exception e)
     {
         return(null);
     }
 }
Exemplo n.º 14
0
        /// <summary>
        /// Retrieves a specific row/feature for given ObjectID.
        /// </summary>
        /// <param name="table">Table of Feature class containing the row/feature.</param>
        /// <param name="oid">The ObjectID of the row/feature to be returned.</param>
        /// <returns>The row/feature specified by the ObjectID. If entity with the ObjectID exists, a null reference is returned.</returns>
        public static async Task <Row> GetRowByIDAsync(this Table table, long oid)
        {
            Row foundRow = null;

            if (table == null)
            {
                return(foundRow);
            }

            await QueuingTaskFactory.StartNew(() =>
            {
                if (table.Definition is TableDefinition)
                {
                    var tableDefinition = table.Definition as TableDefinition;

                    // TODO
                    // specify query filter to return only the row with the specified identifier
                    QueryFilter queryFilter = new QueryFilter();

                    RowCursor rc = table.Search(queryFilter, false);

                    if (rc.MoveNext())
                    {
                        foundRow = rc.Current;
                    }
                }
            });

            return(foundRow);
        }
Exemplo n.º 15
0
        /// <summary>
        /// Searches a given Table to return the content of the complete row.  Note that this method is not using Recycling
        /// </summary>
        /// <remarks>using ArcGIS.Core.Data expected </remarks>
        /// <note>ReturnValue is typeof List&lt;Row&gt; </note>
        private List <Row> GetRowListFor(Table table, QueryFilter queryFilter)
        {
            List <Row> rows = new List <Row>();

            try
            {
                using (RowCursor rowCursor = table.Search(queryFilter, false))
                {
                    while (rowCursor.MoveNext())
                    {
                        rows.Add(rowCursor.Current);
                    }
                }
            }
            catch (GeodatabaseFieldException fieldException)
            {
                // One of the fields in the where clause might not exist. There are multiple ways this can be handled:
                // 1. You could rethrow the exception to bubble up to the caller after some debug or info logging
                // 2. You could return null to signify that something went wrong. The logs added before return could tell you what went wrong.
                // 3. You could return empty list of rows. This might not be advisable because if there was no exception thrown and the
                //    query returned no results, you would also get an empty list of rows. This might cause problems when
                //    differentiating between a failed Search attempt and a successful search attempt which gave no result.

                // logger.Error(fieldException.Message);
                return(null);
            }
            catch (Exception exception)
            {
                // logger.Error(exception.Message);
                return(null);
            }

            return(rows);
        }
Exemplo n.º 16
0
        public static Row FetchRowFromElement(UtilityNetwork utilityNetwork, Element element)
        {
            // Get the table from the element
            using (Table table = utilityNetwork.GetTable(element.NetworkSource))
            {
                // Create a query filter to fetch the appropriate row
                QueryFilter queryFilter = new QueryFilter()
                {
                    ObjectIDs = new List <long>()
                    {
                        element.ObjectID
                    }
                };

                // Fetch and return the row
                using (RowCursor rowCursor = table.Search(queryFilter))
                {
                    if (rowCursor.MoveNext())
                    {
                        return(rowCursor.Current);
                    }
                    return(null);
                }
            }
        }
        protected static List <object> PopulateResultData(Table table, QueryFilter queryFilter)
        {
            var list = new List <object>();
            IReadOnlyList <Subtype> subtypes = table.GetDefinition().GetSubtypes();

            using (RowCursor rowCursor = table.Search(queryFilter, false))
            {
                while (rowCursor.MoveNext())
                {
                    using (Row current = rowCursor.Current)
                    {
                        var subtypeValue      = Convert.ToInt32(current["Offense_Type"]);
                        var sMayorOffenseType = Convert.ToString(current["Major_Offense_Type"]);
                        var sAddress          = Convert.ToString(current["Address"]);
                        var theSubtype        = subtypes.First(subtype => (subtype.GetCode() == subtypeValue));
                        var sOffenseType      = theSubtype.GetName();
                        list.Add(new CrimeData
                        {
                            MajorOffenseType = sMayorOffenseType,
                            Address          = sAddress,
                            OffenseType      = sOffenseType
                        });
                    }
                }
            }
            return(list);
        }
Exemplo n.º 18
0
        internal Task EnsureIDsForSelectedAsync(EditOperation operation)
        {
            return(QueuedTask.Run(() =>
            {
                using (var segmentsCursor = SegmentsLayer.GetSelection().Search(null, false))
                {
                    while (segmentsCursor.MoveNext())
                    {
                        var row = segmentsCursor.Current;
                        EnsureIDForSegment(row, operation);
                    }
                }

                using (RowCursor headsCursor = HeadsLayer.GetSelection().Search(null, false))
                {
                    while (headsCursor.MoveNext())
                    {
                        var row = headsCursor.Current;
                        if (row[USNG_TH] == null || (string)row[USNG_TH] == "" || (string)row[USNG_TH] == "<Null>")
                        {
                            operation.Modify(HeadsLayer, row.GetObjectID(), new Dictionary <string, object> {
                                [USNG_TH] = GetUSNGID_Point((MapPoint)row["Shape"])
                            });
                        }
                    }
                }
            }));
        }
        /// <summary>
        /// Get the list of selected features GUID from the layer
        /// </summary>
        /// <param name="fl">Layer</param>
        /// <param name="selectedFeatures">Selected features</param>
        /// <returns>List of GUID</returns>
        private static List <Guid> GetGuidFromLayer(BasicFeatureLayer fl, Selection selectedFeatures)
        {
            List <Guid> listIds = new List <Guid>();

            // some data have restriction of element number in a clause IN, so we cut the in smaller list
            List <string> lEid = FormatOidToString(selectedFeatures.GetObjectIDs().ToList());

            TableDefinition tbl       = fl.GetTable().GetDefinition();
            string          FieldName = tbl.GetObjectIDField();

            QueryFilter qf = new QueryFilter
            {
                SubFields = "*"
            };

            foreach (string se in lEid)
            {
                qf.WhereClause = String.Format("{0} IN ({1})", FieldName, se);

                try
                {
                    RowCursor rc = fl.Search(qf);

                    while (rc.MoveNext())
                    {
                        listIds.Add(rc.Current.GetGlobalID());
                    }
                }
                catch { }
            }

            return(listIds);
        }
Exemplo n.º 20
0
        public static IEnumerable <Feature> GetSelectedFeatures([CanBeNull] BasicFeatureLayer layer)
        {
            Selection selection = layer?.GetSelection();

            if (selection == null)
            {
                yield break;
            }

            RowCursor cursor = selection.Search(null, false);

            try
            {
                while (cursor.MoveNext())
                {
                    var feature = (Feature)cursor.Current;

                    yield return(feature);
                }
            }
            finally
            {
                cursor.Dispose();
            }
        }
        private void GetFeaturesAndAddAttachment()
        {
            // TODO
            // open the file geodatabase c:\ProSDKWorkshop\data\generic.gdb
            using (Geodatabase geodatabase = new Geodatabase(@"c:\ProSDKWorkshop\data\generic.gdb"))
            {
                using (FeatureClass pointFeatureClass = geodatabase.OpenDataset <FeatureClass>("SamplePoints"))
                {
                    using (RowCursor features = pointFeatureClass.Search())
                    {
                        while (features.MoveNext())
                        {
                            Feature currentFeature = features.Current as Feature;
                            currentFeature.AddAttachment(new Attachment("SamplePicture", "image/png",
                                                                        CreateMemoryStreamFromContentsOf(@"C:\ProSDKWorkshop\data\redlands.png")));
                        }
                    }
                }
            }

            // TODO
            // open the SamplePoints feature class

            // TODO
            // retrieve all features by searching the feature class

            // TODO
            // for each feature add the attachment

            // TODO
            // add the sample picture as an attachment

            // add the feature class as a layer to the active map
            LayerFactory.CreateFeatureLayer(new Uri(@"c:\ProSDKWorkshop\data\generic.gdb\SamplePoints"), MapView.Active.Map);
        }
        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();
                            }
                        }
                    }
                }
            });
        }
Exemplo n.º 23
0
        protected override bool CanUseSelection(IEnumerable <Feature> selectedFeatures)
        {
            var found = false;

            if (WorkListLayer == null)
            {
                return(false);
            }

            //check if a selected feature is part of the worklist layer
            foreach (Feature selectedFeature in selectedFeatures)
            {
                var filter = new SpatialQueryFilter();
                filter.FilterGeometry      = selectedFeature.GetShape();
                filter.SpatialRelationship = SpatialRelationship.Intersects;
                using (RowCursor cursor = WorkListLayer.Search(filter))
                {
                    while (cursor.MoveNext())
                    {
                        var feature = cursor.Current as Feature;

                        //if selected feature is a feature of the worklist layer
                        if (feature.GetShape().ToJson() == selectedFeature.GetShape().ToJson())
                        {
                            found = true;
                        }
                    }
                }
            }

            return(found);
        }
        /// <summary>
        /// Get GUID from Layer
        /// </summary>
        /// <param name="Fl">BasicFeatureLayer</param>
        /// <param name="SelectedFeatures">Selection</param>
        /// <returns></returns>
        private static List <Guid> GetGuidFromLayer(BasicFeatureLayer Fl, Selection SelectedFeatures)
        {
            List <Guid> listIds = new List <Guid>();

            // Some SGDB having limitations on the list size when using WHERE IN clauses, the list is cut in smaller lists
            List <string> lEid = FormatOidToString(SelectedFeatures.GetObjectIDs().ToList());

            TableDefinition tbl       = Fl.GetTable().GetDefinition();
            string          FieldName = tbl.GetObjectIDField();

            QueryFilter qf = new QueryFilter
            {
                SubFields = "*"
            };

            //List<long> lselected = new List<long>();

            foreach (string se in lEid)
            {
                qf.WhereClause = String.Format("{0} IN ({1})", FieldName, se);

                try
                {
                    RowCursor rc = Fl.Search(qf);

                    while (rc.MoveNext())
                    {
                        listIds.Add(rc.Current.GetGlobalID());
                    }
                }
                catch { }
            }

            return(listIds);
        }
Exemplo n.º 25
0
            protected override bool MoveNextCore()
            {
                // If leading cursor is not started, start it.
                if (_leadingCursor.State == CursorState.NotStarted)
                {
                    _leadingCursor.MoveNext();
                }

                if (_leadingCursor.State == CursorState.Done)
                {
                    // Leading cursor reached the end of the input on the previous MoveNext.
                    return(false);
                }

                // Then, advance the leading cursor until it hits the end of the group (or the end of the data).
                int groupSize = 0;

                while (_leadingCursor.State == CursorState.Good && IsSameGroup())
                {
                    groupSize++;
                    _leadingCursor.MoveNext();
                }

                // The group can only be empty if the leading cursor immediately reaches the end of the data.
                // This is handled by the check above.
                Ch.Assert(groupSize > 0);

                // Catch up with the trailing cursor and populate all the aggregates.
                // REVIEW: this could be done lazily, but still all aggregators together.
                foreach (var agg in _aggregators.Where(x => x != null))
                {
                    agg.SetSize(groupSize);
                }

                for (int i = 0; i < groupSize; i++)
                {
                    var res = _trailingCursor.MoveNext();
                    Ch.Assert(res);

                    foreach (var agg in _aggregators.Where(x => x != null))
                    {
                        agg.ReadValue(i);
                    }
                }

                return(true);
            }
Exemplo n.º 26
0
        /// <summary>
        /// Calculate viewpoints along a vector line, e.g. road, path.
        /// </summary>
        /// <param name="gdbPath">Path to GDB</param>
        /// <param name="featureClassName">Feature class</param>
        /// <returns>Viewpoints</returns>
        private HashSet <SpatialUtils.ViewpointProps> GetLine(String gdbPath, String featureClassName)
        {
            HashSet <SpatialUtils.ViewpointProps> result = new HashSet <SpatialUtils.ViewpointProps>(); //using hash set to prevent duplicates, possible speed up with array

            using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(gdbPath))))
                using (FeatureClass featureClass = geodatabase.OpenDataset <FeatureClass>(featureClassName)) {
                    QueryFilter queryFilter = new QueryFilter {
                        SubFields     = "POINT_X, POINT_Y, ORIG_FID",
                        PostfixClause = "ORDER BY ORIG_FID"
                    };

                    using (RowCursor rowCursor = featureClass.Search(queryFilter, false)) {
                        double previousX   = Double.NaN;
                        double previousY   = Double.NaN;
                        int    previousFid = Int32.MinValue;

                        while (rowCursor.MoveNext())
                        {
                            using (Row row = rowCursor.Current) {
                                double pointX = Convert.ToDouble(row["POINT_X"]);
                                double pointY = Convert.ToDouble(row["POINT_Y"]);
                                int    fid    = Convert.ToInt32(row["ORIG_FID"]);

                                if (fid == previousFid)
                                {
                                    double length = Math.Sqrt(Math.Pow(pointX - previousX, 2) + Math.Pow(pointY - previousY, 2));
                                    int    steps  = (int)Math.Floor(length / stepLength);
                                    double xStep  = (pointX - previousX) / steps;
                                    double yStep  = (pointY - previousY) / steps;
                                    for (int i = 0; i <= steps; i++)
                                    {
                                        Tuple <int, int> point = inputRaster.MapToPixel(previousX + xStep * i, previousY + yStep * i);
                                        result.Add(new SpatialUtils.ViewpointProps()
                                        {
                                            X = point.Item1,
                                            Y = point.Item2
                                        });
                                    }
                                }
                                else if (previousFid != Int32.MinValue) //endpoint
                                {
                                    Tuple <int, int> point = inputRaster.MapToPixel(previousX, previousY);
                                    result.Add(new SpatialUtils.ViewpointProps()
                                    {
                                        X = point.Item1,
                                        Y = point.Item2
                                    });
                                }

                                previousX   = pointX;
                                previousY   = pointY;
                                previousFid = fid;
                            }
                        }
                    }
                }

            return(result);
        }
        private Task LoadToService(Element element, CancelableProgressorSource status, int chunksize)
        {
            return(QueuedTask.Run(() => {
                var featuresList = new List <Object>();
                using (RowCursor rowCursor = element.Cursor)
                {
                    while (rowCursor.MoveNext())
                    {
                        using (Row row = rowCursor.Current)
                        {
                            Object feat;

                            // Read attributes
                            var _attributes = element.FormatAttributes(row);

                            // Read and convert geometry
                            if (element.Item.Type == "File Geodatabase Feature Class" || element.Item.Type == "Shapefile")
                            {
                                var feature = row as Feature;
                                var shape = feature.GetShape();
                                var shape_prj = GeometryEngine.Instance.Project(shape, webMercator);
                                var json_geom = GeometryEngine.Instance.ExportToJSON(JSONExportFlags.jsonExportSkipCRS, shape_prj);
                                var geom = element.Serialize(json_geom);
                                feat = new { attributes = _attributes, geometry = geom };
                            }
                            else if (element.Item.Type == "File Geodatabase Table" || element.Item.Type == "Excel Table" || element.Item.Type == "Text File")
                            {
                                feat = new { attributes = _attributes }
                            }
                            ;
                            else
                            {
                                feat = new { }
                            };                  // Maybe Throw a exception?

                            // Add feature
                            featuresList.Add(feat);

                            // Evaluate size
                            if (featuresList.Count == chunksize)
                            {
                                var _result = AddFeatures(featuresList, element);
                                featuresList.Clear();
                                status.Progressor.Value += 1;
                                status.Progressor.Status = String.Format("{0} de {1}", status.Progressor.Value * chunksize, element.Count);
                                status.Progressor.Message = String.Format("Registros cargados {0}", status.Progressor.Value * chunksize);
                            }
                        }
                    }
                }

                if (featuresList.Count > 0)
                {
                    AddFeatures(featuresList, element);
                    status.Progressor.Value += 1;
                    status.Progressor.Message = String.Format("Registros cargados {0}", status.Progressor.Value * chunksize);
                }
            }, status.Progressor));
        }
Exemplo n.º 28
0
        public void ActivateRecord(Geometry geometry)
        {
            QueuedTask.Run(() =>
            {
                try
                {
                    var layers = MapView.Active.Map.GetLayersAsFlattenedList();
                    var pfL    = layers.FirstOrDefault(l => l is ParcelLayer) as ParcelLayer;
                    // if there is no fabric in the map then exit
                    if (pfL == null)
                    {
                        return;
                    }

                    var recordsLayer = MapView.Active.Map.FindLayers("Records").FirstOrDefault() as BasicFeatureLayer;
                    if (recordsLayer == null)
                    {
                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Records Layer is not found.", "Error", System.Windows.MessageBoxButton.OK, MessageBoxImage.Exclamation);
                        return;
                    }
                    RowCursor rowCursor = null;
                    // define a spatial query filter
                    var spatialQueryFilter = new SpatialQueryFilter
                    {
                        // passing the search geometry to the spatial filter
                        FilterGeometry = geometry,
                        // define the spatial relationship between search geometry and feature class
                        SpatialRelationship = SpatialRelationship.Intersects
                    };
                    // apply the spatial filter to the feature layer in question
                    rowCursor = recordsLayer.Search(spatialQueryFilter);

                    RowHandle rowHandle = null;
                    var featName        = string.Empty;
                    if (rowCursor.MoveNext())
                    {
                        var row   = rowCursor.Current;
                        rowHandle = new RowHandle(row);
                        featName  = Convert.ToString(row["NAME"]);
                    }

                    if (rowHandle != null)
                    {
                        // Reference the parcel record and set it as the active record
                        var parcelRecord = new ParcelRecord(rowHandle.Token);
                        pfL.SetActiveRecord(parcelRecord);

                        ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Record activated:  " + featName, "Info", System.Windows.MessageBoxButton.OK, MessageBoxImage.Information);
                    }
                }
                catch (Exception exc)
                {
                    // Catch any exception found and display in a message box
                    ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("Exception caught: " + exc.Message);
                    return;
                }
            });
        }
Exemplo n.º 29
0
        internal static List <ConfusionMatrix> Create(IHostEnvironment env, IDataView confusionMatrix)
        {
            Contracts.AssertValue(env);
            env.AssertValue(confusionMatrix);

            if (!confusionMatrix.Schema.TryGetColumnIndex(MetricKinds.ColumnNames.Count, out int countColumn))
            {
                throw env.Except($"ConfusionMatrix data view did not contain a {nameof(MetricKinds.ColumnNames.Count)} column.");
            }

            RowCursor cursor = confusionMatrix.GetRowCursor(col => col == countColumn);
            var       slots  = default(VBuffer <ReadOnlyMemory <char> >);

            confusionMatrix.Schema[countColumn].Metadata.GetValue(MetadataUtils.Kinds.SlotNames, ref slots);
            var slotsValues = slots.GetValues();

            string[] classNames = new string[slotsValues.Length];
            for (int i = 0; i < slotsValues.Length; i++)
            {
                classNames[i] = slotsValues[i].ToString();
            }

            ColumnType type = confusionMatrix.Schema[countColumn].Type;

            env.Assert(type.IsVector);
            ValueGetter <VBuffer <double> > countGetter = cursor.GetGetter <VBuffer <double> >(countColumn);
            VBuffer <double>       countValues          = default;
            List <ConfusionMatrix> confusionMatrices    = new List <ConfusionMatrix>();

            int valuesRowIndex = 0;

            double[,] elements = null;
            while (cursor.MoveNext())
            {
                if (valuesRowIndex == 0)
                {
                    elements = new double[type.VectorSize, type.VectorSize];
                }

                countGetter(ref countValues);
                ReadOnlySpan <double> values = countValues.GetValues();
                for (int i = 0; i < values.Length; i++)
                {
                    elements[valuesRowIndex, i] = values[i];
                }

                valuesRowIndex++;

                if (valuesRowIndex == type.VectorSize)
                {
                    valuesRowIndex = 0;
                    confusionMatrices.Add(new ConfusionMatrix(elements, classNames));
                }
            }

            return(confusionMatrices);
        }
Exemplo n.º 30
0
        public void CacheWithCursor()
        {
            int val = 0;

            while (_cursor.MoveNext())
            {
                _getter(ref val);
            }
        }