Exemplo n.º 1
0
        private void IterateFeatures(RecyclingPolicy policy)
        {
            var features          = _featureClass.GetFeatures(policy);
            int consecutiveNumber = 1;

            foreach (var feature in features)
            {
                Assert.That(feature.OID, Is.EqualTo(consecutiveNumber));
                consecutiveNumber++;
            }
        }
Exemplo n.º 2
0
        /// <summary>
        ///测试getFeature与getFeatures
        /// </summary>
        /// <param name="featureCls"></param>
        /// <param name="oids"></param>
        /// <param name="fieldIndex"></param>
        public void SearchById(IFeatureClass featureCls, int[] oids, int fieldIndex)
        {
            foreach (var oid in oids)
            {
                var feature = featureCls.GetFeature(oid);
                Console.WriteLine("oid:" + feature.get_Value(fieldIndex));
            }



            using (var comReleaser = new ComReleaser())
            {
                IFeatureCursor featureCursor = featureCls.GetFeatures(oids, true);;
                IFeature       feature       = featureCursor.NextFeature();
                while (feature != null)
                {
                    Console.WriteLine("oid:" + feature.get_Value(fieldIndex));
                    feature = featureCursor.NextFeature();
                }
            }

            using (var comReleaser = new ComReleaser())
            {
                IGeoDatabaseBridge geodatabaseBridge = new GeoDatabaseHelperClass();
                IFeatureCursor     featureCursor     = geodatabaseBridge.GetFeatures(featureCls, oids, true);;
                IFeature           feature           = featureCursor.NextFeature();
                while (feature != null)
                {
                    Console.WriteLine("oid:" + feature.get_Value(fieldIndex));
                    feature = featureCursor.NextFeature();
                }
            }
        }
Exemplo n.º 3
0
 public IFeatureCursor GetNodeFeatures(IQueryFilter filter)
 {
     if (_nodeFc != null)
     {
         return(_nodeFc.GetFeatures(filter));
     }
     return(null);
 }
Exemplo n.º 4
0
 async public Task <IFeatureCursor> GetNodeFeatures(IQueryFilter filter)
 {
     if (_nodeFc != null)
     {
         return(await _nodeFc.GetFeatures(filter));
     }
     return(null);
 }
Exemplo n.º 5
0
 public IFeatureCursor Query(IFeatureClass fc, IQueryFilter filter)
 {
     if (fc == null)
     {
         return(null);
     }
     return(fc.GetFeatures(filter));
 }
 public IFeatureCursor GetFeatures(IQueryFilter filter)
 {
     if (_fc == null)
     {
         return(null);
     }
     return(_fc.GetFeatures(filter));
 }
Exemplo n.º 7
0
        async public Task <IFeatureCursor> Query(IFeatureClass fc, IQueryFilter filter)
        {
            if (fc == null)
            {
                return(null);
            }

            return(await fc.GetFeatures(filter));
        }
Exemplo n.º 8
0
        async public Task <IFeatureCursor> GetFeatures(IQueryFilter filter)
        {
            if (_fc == null)
            {
                return(null);
            }

            return(await _fc.GetFeatures(filter));
        }
Exemplo n.º 9
0
            async public Task <IFeature> NextFeature()
            {
                if (_edgeCursor == null && _edgeFcs != null && _edgeFcIndex < _edgeFcs.Count)
                {
                    IFeatureClass fc = _edgeFcs[_edgeFcIndex++];
                    _fcid = await _fdb.FeatureClassID(await _fdb.DatasetID(fc.Dataset.DatasetName), fc.Name);

                    if (_fcid < 0)
                    {
                        return(await NextFeature());
                    }
                    if (fc.Name == _networkName + "_ComplexEdges")
                    {
                        _fcid = -1;
                    }

                    IQueryFilter f = (IQueryFilter)_filter.Clone();
                    if (f.SubFields != "*")
                    {
                        f.AddField(fc.IDFieldName);
                        f.AddField(fc.ShapeFieldName);
                    }

                    _edgeCursor = await fc.GetFeatures(f);

                    if (_edgeCursor == null)
                    {
                        return(await NextFeature());
                    }
                }
                if (_edgeCursor != null)
                {
                    IFeature feature = await _edgeCursor.NextFeature();

                    if (feature != null)
                    {
                        feature.Fields.Add(new FieldValue("NETWORK#FCID", _fcid));
                        return(feature);
                    }

                    _edgeCursor.Dispose();
                    _edgeCursor = null;
                    return(await NextFeature());
                }
                if (_nodeCursor == null && _nodeFc != null)
                {
                    _nodeCursor = await _nodeFc.GetFeatures(_filter);
                }
                if (_nodeCursor != null)
                {
                    return(await _nodeCursor.NextFeature());
                }

                return(null);
            }
Exemplo n.º 10
0
        async private Task <bool> CopyFeatures2(IFeatureClass source, IFeatureUpdater fdb, IFeatureClass dest, FieldTranslation fTrans, BinaryTree2Builder treeBuilder)
        {
            List <BinaryTree2BuilderNode> nodes;

            if (treeBuilder == null || (nodes = treeBuilder.Nodes) == null)
            {
                _errMsg = "Spatial Index is not defined...";
                return(false);
            }

            if (ReportAction != null)
            {
                ReportAction(this, "Copy Features (" + dest.Name + ")");
            }
            int featcounter = 0;

            foreach (BinaryTree2BuilderNode node in nodes)
            {
                if (!_cancelTracker.Continue)
                {
                    break;
                }

                RowIDFilter filter = new RowIDFilter(source.IDFieldName);
                filter.IDs       = node.OIDs;
                filter.SubFields = "*";

                using (IFeatureCursor fCursor = await source.GetFeatures(filter))
                {
                    if (fCursor == null)
                    {
                        _errMsg = "Fatal error: sourcedb query failed...";
                        return(false);
                    }

                    int copycounter = await CopyFeatures(fCursor, node.Number, fdb, dest, fTrans, featcounter);

                    if (copycounter < 0)
                    {
                        fCursor.Dispose();
                        return(false);
                    }
                    featcounter = copycounter;

                    fCursor.Dispose();
                }
            }
            if (ReportProgress != null)
            {
                ReportProgress(this, featcounter);
            }
            return(true);
        }
Exemplo n.º 11
0
        public IFeatureCursor GetFeatures(string appendToClause)
        {
            if (_data == null ||
                !(_data.Class is IFeatureClass))
            {
                return(null);
            }

            IFeatureClass fc = (IFeatureClass)_data.Class;

            switch (_queryMethod)
            {
            case QueryMethod.All:
            case QueryMethod.Filter:
                QueryFilter filter = new QueryFilter();
                filter.AddField("*");
                filter.WhereClause = (_queryMethod == QueryMethod.Filter) ? _filterClause : String.Empty;
                if (!String.IsNullOrEmpty(appendToClause))
                {
                    if (String.IsNullOrEmpty(filter.WhereClause))
                    {
                        filter.WhereClause = appendToClause;
                    }
                    else
                    {
                        filter.WhereClause += " AND " + appendToClause;
                    }
                }
                return(fc.GetFeatures(filter));

            case QueryMethod.Selected:
                IFeatureSelection featSelection = _data as IFeatureSelection;
                if (featSelection == null)
                {
                    throw new ArgumentException("Data is not as FeatureSelection...");
                }

                if (featSelection.SelectionSet is IIDSelectionSet)
                {
                    return(new SelectionCursor(_data.Class as IFeatureClass, featSelection.SelectionSet as IIDSelectionSet, appendToClause));
                }
                else if (featSelection.SelectionSet is IGlobalIDSelectionSet)
                {
                    return(new GlobalSelectionCursor(_data.Class as IFeatureClass, featSelection.SelectionSet as IGlobalIDSelectionSet, appendToClause));
                }
                break;
            }

            return(null);
        }
Exemplo n.º 12
0
        private bool CopyFeatures(IFeatureClass source, IFeatureUpdater fdb, IFeatureClass dest, FieldTranslation fTrans, DualTree tree)
        {
            if (tree == null || tree.Nodes == null)
            {
                _errMsg = "Spatial Index is not defined...";
                return(false);
            }

            if (ReportAction != null)
            {
                ReportAction(this, "Copy Features (" + dest.Name + ")");
            }
            int featcounter = 0;

            foreach (SpatialIndexNode node in tree.Nodes)
            {
                if (!_cancelTracker.Continue)
                {
                    break;
                }

                RowIDFilter filter = new RowIDFilter(source.IDFieldName);
                filter.IDs       = node.IDs;
                filter.SubFields = "*";

                using (IFeatureCursor fCursor = source.GetFeatures(filter))
                {
                    if (fCursor == null)
                    {
                        _errMsg = "Fatal error: sourcedb query failed...";
                        return(false);
                    }
                    if (!CopyFeatures(fCursor, node.NID, fdb, dest, fTrans, ref featcounter))
                    {
                        fCursor.Dispose();
                        return(false);
                    }
                    fCursor.Dispose();
                }
            }
            if (ReportProgress != null)
            {
                ReportProgress(this, featcounter);
            }
            return(true);
        }
Exemplo n.º 13
0
        /// <summary>
        ///     Queries for the features that have the specified object ids.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="oids">The list of object ids.</param>
        /// <returns>
        ///     Returns a <see cref="List{IFeature}" /> representing the features returned from the query.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">oids</exception>
        public static IList <IFeature> Fetch(this IFeatureClass source, params int[] oids)
        {
            if (source == null)
            {
                return(null);
            }
            if (oids == null)
            {
                throw new ArgumentNullException("oids");
            }

            using (ComReleaser cr = new ComReleaser())
            {
                IFeatureCursor cursor = source.GetFeatures(oids, false);
                cr.ManageLifetime(cursor);

                return(cursor.AsEnumerable().ToList());
            }
        }
Exemplo n.º 14
0
        async public Task <IFeature> GetEdgeFeature(int eid)
        {
            RowIDFilter filter = new RowIDFilter(String.Empty);

            filter.IDs.Add(eid);
            filter.AddField("*");

            IFeatureCursor cursor = await GetEdgeFeatures(filter);

            if (cursor == null)
            {
                return(null);
            }

            IFeature feature = await cursor.NextFeature();

            cursor.Dispose();

            if (feature != null && feature.FindField("FCID") != null && feature.FindField("OID") != null &&
                _edgeFcs.ContainsKey((int)feature["FCID"]))
            {
                IGraphEdge edge = _pageManager.GetEdge(eid);
                try
                {
                    if (edge != null && edge.FcId == -1) // Complex Edge
                    {
                        filter = new RowIDFilter("FDB_OID");
                        filter.IDs.Add((int)feature["OID"]);
                        filter.AddField("*");
                        IFeatureClass fc = _edgeFcs[(int)feature["FCID"]];
                        using (IFeatureCursor c = await fc.GetFeatures(filter))
                        {
                            return(await c.NextFeature());
                        }
                    }
                }
                catch { }
            }
            return(feature);
        }
Exemplo n.º 15
0
        void FillValueList()
        {
            lstValues.Items.Clear();

            if (_fc == null ||
                _merger == null ||
                _merger.Sources.Count != 1 ||
                ((FieldItem)cmbField.SelectedItem).Field == null)
            {
                return;
            }

            this.Cursor = Cursors.WaitCursor;
            IActivityData aData = _merger.Sources[0];

            if (aData.QueryMethod == QueryMethod.All ||
                aData.QueryMethod == QueryMethod.Filter)
            {
                DistinctFilter filter = new DistinctFilter(((FieldItem)cmbField.SelectedItem).Field.name);
                if (aData.QueryMethod == QueryMethod.Filter)
                {
                    filter.WhereClause = aData.FilterClause;
                }
                filter.OrderBy = ((FieldItem)cmbField.SelectedItem).Field.name;

                using (IFeatureCursor cursor = _fc.GetFeatures(filter))
                {
                    IFeature feature;
                    while ((feature = cursor.NextFeature) != null)
                    {
                        ListViewItem item = new ListViewItem(feature[0].ToString(), 0);
                        item.Checked = true;
                        lstValues.Items.Add(item);
                    }
                }
            }
            this.Cursor = Cursors.Default;
        }
Exemplo n.º 16
0
        public IFeature GetEdgeFeature(int eid)
        {
            RowIDFilter filter = new RowIDFilter(String.Empty);

            filter.IDs.Add(eid);
            filter.AddField("*");

            IFeature feature = null;

            using (IFeatureCursor cursor = GetEdgeFeatures(filter))
            {
                feature = cursor.NextFeature;
            }

            if (feature != null && feature.FindField("FCID") != null && feature.FindField("OID") != null &&
                _edgeFcs.ContainsKey(Convert.ToInt32(feature["FCID"])))
            {
                IGraphEdge edge = _pageManager.GetEdge(eid);
                try
                {
                    if (edge != null && edge.FcId == -1) // Complex Edge
                    {
                        filter = new RowIDFilter("FDB_OID");
                        filter.IDs.Add(Convert.ToInt32(feature["OID"]));
                        filter.AddField("*");
                        IFeatureClass fc = _edgeFcs[Convert.ToInt32(feature["FCID"])];
                        using (IFeatureCursor c = fc.GetFeatures(filter))
                        {
                            return(c.NextFeature);
                        }
                    }
                }
                catch { }
            }

            return(feature);
        }
Exemplo n.º 17
0
        async private Task <bool> CopyFeatures(IFeatureClass source, IFeatureUpdater fdb, IFeatureClass dest, FieldTranslation fTrans, List <IQueryFilter> filters)
        {
            if (ReportAction != null)
            {
                ReportAction(this, "Copy Features (" + dest.Name + ")");
            }
            int featcounter = 0;

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

            if (filters == null || filters.Count == 0)
            {
                QueryFilter filter = new QueryFilter();
                filter.SubFields = "*";
                filters          = new List <IQueryFilter>();
                filters.Add(filter);
            }
            foreach (IQueryFilter filter in filters)
            {
                using (IFeatureCursor fCursor = await source.GetFeatures(filter))
                {
                    IFeature feature;
                    while ((feature = await fCursor.NextFeature()) != null)
                    {
                        if (!_cancelTracker.Continue)
                        {
                            break;
                        }

                        if (_transformer != null)
                        {
                            feature.Shape = _transformer.Transform2D(feature.Shape) as IGeometry;
                        }

                        if (fTrans != null)
                        {
                            fTrans.RenameFields(feature);
                        }
                        features.Add(feature);
                        if (features.Count >= this.FeatureBufferSize)
                        {
                            if (!await fdb.Insert(dest, features))
                            {
                                _errMsg = "Fatal error: destdb insert failed...\n" + fdb.LastErrorMessage;
                                return(false);
                            }
                            features.Clear();
                        }
                        featcounter++;
                        if ((featcounter % this.FeatureBufferSize) == 0 && ReportProgress != null)
                        {
                            ReportProgress(this, featcounter);
                        }
                    }
                    if (features.Count > 0 && _cancelTracker.Continue)
                    {
                        if (!await fdb.Insert(dest, features))
                        {
                            _errMsg = "Fatal error: destdb insert failed...\n" + fdb.LastErrorMessage;
                            return(false);
                        }
                        features.Clear();
                    }
                }
            }

            return(true);
        }
 public void EmptyGeometries(IFeatureClass inFeatureClass, IFIDSet pFIDSet)
 {
     try
       {
     if (pFIDSet.Count() < 1)
       return;
     pFIDSet.Reset();
     int[] iID = { };
     iID = RedimPreserveInt(ref iID, pFIDSet.Count());
     for (int iCount = 0; iCount <= pFIDSet.Count() - 1; iCount++)
       pFIDSet.Next(out iID[iCount]);
     IFeatureCursor pFeatCursor = inFeatureClass.GetFeatures(iID, false);
     IFeature pFeat = pFeatCursor.NextFeature();
     while (pFeat != null)
     {
       IGeometry pGeo = pFeat.ShapeCopy;
       pGeo.SetEmpty();
       pFeat.Shape = pGeo;
       pFeat.Store();
       Marshal.ReleaseComObject(pFeat);
       pFeat = pFeatCursor.NextFeature();
     }
     Marshal.ReleaseComObject(pFeatCursor);
     iID = null;
     return;
       }
       catch (Exception ex)
       {
     MessageBox.Show(ex.Message);
     return;
       }
 }
Exemplo n.º 19
0
        async private Task <BinaryTree2Builder> SpatialIndex2(IFeatureDatabase fdb, IFeatureClass fc, ISpatialIndexDef def, List <IQueryFilter> filters)
        {
            if (fc == null)
            {
                return(null);
            }

            IEnvelope bounds = null;

            if (fc.Envelope != null)
            {
                bounds = fc.Envelope;
            }
            else if (fc.Dataset is IFeatureDataset && await((IFeatureDataset)fc.Dataset).Envelope() != null)
            {
                bounds = await((IFeatureDataset)fc.Dataset).Envelope();
            }
            if (bounds == null)
            {
                return(null);
            }
            if (_transformer != null)
            {
                IGeometry transBounds = _transformer.Transform2D(bounds) as IGeometry;
                if (transBounds != null)
                {
                    bounds = transBounds.Envelope;
                }
            }
            int maxAllowedLevel            = ((fdb is SqlFDB) ? 62 : 30);
            BinaryTree2Builder treeBuilder =
                ((Envelope.IsNull(def.SpatialIndexBounds)) ?
                 new BinaryTree2Builder(bounds,
                                        ((def.Levels != 0) ? def.Levels : maxAllowedLevel),
                                        ((def.MaxPerNode != 0) ? def.MaxPerNode : 500),
                                        ((def.SplitRatio != 0.0) ? def.SplitRatio : 0.55)) :
                 new BinaryTree2Builder2(def.SpatialIndexBounds, def.Levels, def.MaxPerNode, def.SplitRatio));

            if (filters == null)
            {
                QueryFilter filter = new QueryFilter();
                filter.AddField(fc.ShapeFieldName);
                filters = new List <IQueryFilter>();
                filters.Add(filter);
            }
            foreach (IQueryFilter filter in filters)
            {
                using (IFeatureCursor fCursor = await fc.GetFeatures(filter))
                {
                    if (fCursor == null)
                    {
                        _errMsg = "Fatal error: sourcedb query failed...";
                        return(null);
                    }

                    if (ReportAction != null)
                    {
                        ReportAction(this, "Calculate spatial index");
                    }

                    IEnvelope fcEnvelope = bounds;
                    if (_transformer != null)
                    {
                        IGeometry geom = _transformer.Transform2D(fcEnvelope) as IGeometry;
                        if (geom == null)
                        {
                            _errMsg = "SpatialIndex: Can't project featureclass extent!";
                            return(null);
                        }
                        fcEnvelope = geom.Envelope;
                    }
                    //treeBuilder = new BinaryTree2Builder(fcEnvelope, maxLevels, maxPerNode);

                    int      counter = 0;
                    IFeature feat;
                    while ((feat = await fCursor.NextFeature()) != null)
                    {
                        if (!_cancelTracker.Continue)
                        {
                            break;
                        }

                        IGeometry shape = feat.Shape;
                        if (_transformer != null)
                        {
                            shape = _transformer.Transform2D(shape) as IGeometry;
                        }

                        feat.Shape = shape;
                        treeBuilder.AddFeature(feat);

                        if ((counter % 1000) == 0 && ReportProgress != null)
                        {
                            ReportProgress(this, counter);
                        }
                        counter++;
                    }
                    fCursor.Dispose();
                }
            }

            treeBuilder.Trim();
            return(treeBuilder);
        }
Exemplo n.º 20
0
        async private Task <DualTree> SpatialIndex(IFeatureClass fc, int maxPerNode, List <IQueryFilter> filters)
        {
            if (fc == null || fc.Envelope == null)
            {
                return(null);
            }

            if (filters == null)
            {
                QueryFilter filter = new QueryFilter();
                filter.AddField(fc.ShapeFieldName);
                filters = new List <IQueryFilter>();
                filters.Add(filter);
            }

            DualTree dualTree = new DualTree(maxPerNode);

            foreach (IQueryFilter filter in filters)
            {
                IFeatureCursor fCursor = await fc.GetFeatures(filter);

                if (fCursor == null)
                {
                    _errMsg = "Fatal error: sourcedb query failed...";
                    return(null);
                }

                if (ReportAction != null)
                {
                    ReportAction(this, "Calculate spatial index");
                }
                IEnvelope fcEnvelope = fc.Envelope;
                if (_transformer != null)
                {
                    IGeometry geom = _transformer.Transform2D(fcEnvelope) as IGeometry;
                    if (geom == null)
                    {
                        _errMsg = "SpatialIndex: Can't project featureclass extent!";
                        return(null);
                    }
                    fcEnvelope = geom.Envelope;
                }
                dualTree.CreateTree(fcEnvelope);  // hier projezieren

                int      counter = 0;
                IFeature feat;
                while ((feat = await fCursor.NextFeature()) != null)
                {
                    if (!_cancelTracker.Continue)
                    {
                        break;
                    }

                    SHPObject shpObj;

                    IGeometry shape = feat.Shape;
                    if (_transformer != null)
                    {
                        shape = _transformer.Transform2D(shape) as IGeometry;
                    }

                    if (shape != null)
                    {
                        shpObj = new SHPObject((int)((uint)feat.OID), shape.Envelope);
                    }
                    else
                    {
                        shpObj = new SHPObject((int)((uint)feat.OID), null);
                    }

                    dualTree.AddShape(shpObj);
                    if ((counter % 1000) == 0 && ReportProgress != null)
                    {
                        ReportProgress(this, counter);
                    }
                    counter++;
                }
                dualTree.FinishIt();
                fCursor.Dispose();

                if (ReportProgress != null)
                {
                    ReportProgress(this, counter);
                }
            }
            return(dualTree);
        }
Exemplo n.º 21
0
        static void Main(string[] args)
        {
            string cmd = "fill", jsonFile = (args.Length == 1 && args[0] != "fill" ? args[0] : String.Empty), indexUrl = String.Empty, indexName = String.Empty, category = String.Empty;
            bool   replace = false;

            for (int i = 0; i < args.Length; i++)
            {
                if (args[i] == "fill" && i < args.Length - 1)
                {
                    cmd      = "fill";
                    jsonFile = args[i + 1];
                    i++;
                }
                if (args[i] == "remove-category")
                {
                    cmd = "remove-category";
                }
                if (args[i] == "-s" && i < args.Length - 1)
                {
                    indexUrl = args[i + 1];
                }
                if (args[i] == "-i" && i < args.Length - 1)
                {
                    indexName = args[i + 1];
                }
                if (args[i] == "-c" && i < args.Length - 1)
                {
                    category = args[i + 1];
                }
                if (args[i] == "-r")
                {
                    replace = true;
                }
            }

            if (args.Length == 0)
            {
                Console.WriteLine("Usage: gView.Cmd.ElasticSearch fill|remove-catetory [Options]");
                return;
            }

            if (cmd == "fill" && String.IsNullOrEmpty(jsonFile))
            {
                Console.WriteLine("Usage: gView.Cmd.ElasticSearch fill {json-file}");
                return;
            }
            else if (cmd == "remove-category" && (String.IsNullOrWhiteSpace(indexUrl) || String.IsNullOrWhiteSpace(category)))
            {
                Console.WriteLine("Usage: gView.cmd.ElasticSearch remove-category -s {index-url} -i {index-name} -c {category} [-r]");
                Console.WriteLine("  -r ... raplace german Umlaute:");
                Console.WriteLine("            _ae_, _oe_, _ue_   =>  ä, ö, ü");
                Console.WriteLine("            _Ae_, _Oe_, _Ue_   =>  Ä, Ö, Ü");
                Console.WriteLine("            _sz_               =>  ß");
                return;
            }

            try
            {
                //gView.Framework.system.SystemVariables.CustomApplicationDirectory =
                //    System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

                Console.WriteLine("Environment");

                Console.WriteLine("Working Directory: " + gView.Framework.system.SystemVariables.StartupDirectory);
                Console.WriteLine("64Bit=" + gView.Framework.system.Wow.Is64BitProcess);

                if (cmd == "fill")
                {
                    #region Fill Index (with Json File)

                    var importConfig = JsonConvert.DeserializeObject <ImportConfig>(File.ReadAllText(jsonFile));

                    var searchContext = new ElasticSearchContext(importConfig.Connection.Url, importConfig.Connection.DefaultIndex);

                    if (importConfig.Connection.DeleteIndex)
                    {
                        searchContext.DeleteIndex();
                    }

                    searchContext.CreateIndex();
                    searchContext.Map <Item>();
                    searchContext.Map <Meta>();

                    ISpatialReference sRefTarget = SpatialReference.FromID("epsg:4326");

                    Console.WriteLine("Target Spatial Reference: " + sRefTarget.Name + " " + String.Join(" ", sRefTarget.Parameters));

                    foreach (var datasetConfig in importConfig.Datasets)
                    {
                        if (datasetConfig.FeatureClasses == null)
                        {
                            continue;
                        }

                        IDataset dataset = new PlugInManager().CreateInstance(datasetConfig.DatasetGuid) as IDataset;
                        if (dataset == null)
                        {
                            throw new ArgumentException("Can't load dataset with guid " + datasetConfig.DatasetGuid.ToString());
                        }

                        dataset.ConnectionString = datasetConfig.ConnectionString;
                        dataset.Open();

                        foreach (var featureClassConfig in datasetConfig.FeatureClasses)
                        {
                            var itemProto = featureClassConfig.IndexItemProto;
                            if (itemProto == null)
                            {
                                continue;
                            }

                            string metaId = Guid.NewGuid().ToString("N").ToLower();
                            category = featureClassConfig.Category;
                            if (!String.IsNullOrWhiteSpace(category))
                            {
                                var meta = new Meta()
                                {
                                    Id         = metaId,
                                    Category   = category,
                                    Descrption = featureClassConfig.Meta?.Descrption,
                                    Sample     = featureClassConfig?.Meta.Sample,
                                    Service    = featureClassConfig?.Meta.Service,
                                    Query      = featureClassConfig?.Meta.Query
                                };
                                searchContext.Index <Meta>(meta);
                            }

                            bool useGeometry = featureClassConfig.UserGeometry;

                            IDatasetElement dsElement = dataset[featureClassConfig.Name];
                            if (dsElement == null)
                            {
                                throw new ArgumentException("Unknown dataset element " + featureClassConfig.Name);
                            }
                            IFeatureClass fc = dsElement.Class as IFeatureClass;
                            if (fc == null)
                            {
                                throw new ArgumentException("Dataobject is not a featureclass " + featureClassConfig.Name);
                            }

                            Console.WriteLine("Index " + fc.Name);
                            Console.WriteLine("=====================================================================");

                            QueryFilter filter = new QueryFilter();
                            filter.SubFields = "*";
                            if (!String.IsNullOrWhiteSpace(featureClassConfig.Filter))
                            {
                                filter.WhereClause = featureClassConfig.Filter;
                                Console.WriteLine("Filter: " + featureClassConfig.Filter);
                            }

                            List <Item> items = new List <Item>();
                            int         count = 0;

                            ISpatialReference sRef = fc.SpatialReference ?? SpatialReference.FromID("epsg:" + featureClassConfig.SRefId);
                            Console.WriteLine("Source Spatial Reference: " + sRef.Name + " " + String.Join(" ", sRef.Parameters));
                            Console.WriteLine("IDField: " + fc.IDFieldName);

                            using (GeometricTransformer transformer = new GeometricTransformer())
                            {
                                if (useGeometry)
                                {
                                    transformer.SetSpatialReferences(sRef, sRefTarget);
                                }

                                IFeatureCursor cursor = (IFeatureCursor)fc.GetFeatures(filter);
                                IFeature       feature;
                                while ((feature = cursor.NextFeature) != null)
                                {
                                    var indexItem = ParseFeature(metaId, category, feature, itemProto, useGeometry, transformer, featureClassConfig);
                                    items.Add(indexItem);
                                    count++;

                                    if (items.Count >= 500)
                                    {
                                        searchContext.IndexMany <Item>(items.ToArray());
                                        items.Clear();

                                        Console.Write(count + "...");
                                    }
                                }

                                if (items.Count > 0)
                                {
                                    searchContext.IndexMany <Item>(items.ToArray());
                                    Console.WriteLine(count + "...finish");
                                }
                            }
                        }
                    }

                    #endregion
                }
                else if (cmd == "remove-category")
                {
                    #region Remove Category

                    RemoveCategory(indexUrl, indexName, replace ? Replace(category) : category);

                    #endregion
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
        }
Exemplo n.º 22
0
 public static IEnumerable <IFeature> GetFeatures(this IFeatureClass featureClass, RecyclingPolicy policy)
 {
     return(featureClass.GetFeatures(null, policy));
 }
Exemplo n.º 23
0
        async public Task Render()
        {
            if (_layer == null)
            {
                return;
            }

            if (_layer.SelectionRenderer == null)
            {
                return;
            }

            if (!(_layer is IFeatureSelection))
            {
                return;
            }

            IFeatureClass fClass = _layer.FeatureClass;

            if (fClass == null)
            {
                return;
            }

            ISelectionSet selectionSet = ((IFeatureSelection)_layer).SelectionSet;

            if (selectionSet == null)
            {
                return;
            }

            IDataset dataset = _map[_layer];

            if (dataset == null)
            {
                return;
            }

            if (!(dataset is IFeatureDataset))
            {
                return;
            }

            IGeometry filterGeom = _map.Display.Envelope;

            if (_map.Display.GeometricTransformer != null)
            {
                filterGeom = MapHelper.Project(fClass, _map.Display);
                //filterGeom = (IGeometry)_map.Display.GeometricTransformer.InvTransform2D(filterGeom);
            }

            IQueryFilter filter = null;

            //List<int> IDs=new List<int>();  // Sollte nicht null sein...
            if (selectionSet is ISpatialIndexedIDSelectionSet)
            {
                List <int> IDs = ((ISpatialIndexedIDSelectionSet)selectionSet).IDsInEnvelope(filterGeom.Envelope);
                filter = new RowIDFilter(fClass.IDFieldName, IDs);
            }
            else if (selectionSet is IIDSelectionSet)
            {
                List <int> IDs = ((IIDSelectionSet)selectionSet).IDs;
                filter = new RowIDFilter(fClass.IDFieldName, IDs);
            }
            else if (selectionSet is ISpatialIndexedGlobalIDSelectionSet)
            {
                List <long> IDs = ((ISpatialIndexedGlobalIDSelectionSet)selectionSet).IDsInEnvelope(filterGeom.Envelope);
                filter = new GlobalRowIDFilter(fClass.IDFieldName, IDs);
            }
            else if (selectionSet is IGlobalIDSelectionSet)
            {
                List <long> IDs = ((IGlobalIDSelectionSet)selectionSet).IDs;
                filter = new GlobalRowIDFilter(fClass.IDFieldName, IDs);
            }
            else if (selectionSet is IQueryFilteredSelectionSet)
            {
                filter = ((IQueryFilteredSelectionSet)selectionSet).QueryFilter.Clone() as IQueryFilter;
            }

            if (filter == null)
            {
                return;
            }

            filter.AddField(fClass.ShapeFieldName);

            #region Clone Layer

            IFeatureRenderer selectionRenderer = null;

            lock (lockThis)
            {
                // Beim Clonen sprerren...
                // Da sonst bei der Servicemap bei gleichzeitigen Requests
                // Exception "Objekt wird bereits an anderer Stelle verwendet" auftreten kann!
                selectionRenderer = (IFeatureRenderer)_layer.SelectionRenderer.Clone(new CloneOptions(_map,
                                                                                                      false,
                                                                                                      maxLabelRefscaleFactor: _layer.MaxRefScaleFactor));
            }

            #endregion

            selectionRenderer.PrepareQueryFilter(_layer, filter);

            using (IFeatureCursor fCursor = (fClass is ISelectionCache) ? ((ISelectionCache)fClass).GetSelectedFeatures(_map.Display) : await fClass.GetFeatures(filter))
            {
                if (fCursor != null)
                {
                    //_layer.SelectionRenderer.Draw(_map, fCursor, DrawPhase.Geography, _cancelTracker);
                    IFeature feature;
                    while ((feature = await fCursor.NextFeature()) != null)
                    {
                        if (_cancelTracker != null)
                        {
                            if (!_cancelTracker.Continue)
                            {
                                break;
                            }
                        }

                        selectionRenderer.Draw(_map, feature);
                    }
                    fCursor.Dispose();
                }
            }
        }
Exemplo n.º 24
0
        async public Task <IGraphEdge> GetGraphEdge(IPoint point, double tolerance)
        {
            if (point == null)
            {
                return(null);
            }
            SpatialFilter filter = new SpatialFilter();

            filter.Geometry = new Envelope(point.X - tolerance, point.Y - tolerance,
                                           point.X + tolerance, point.Y + tolerance);
            filter.AddField("FDB_SHAPE");
            filter.AddField("FDB_OID");

            using (IFeatureCursor cursor = await GetEdgeFeatures(filter))
            {
                IFeature feature, selected = null;
                double   selectedDist = double.MaxValue;
                int      selectedFcId = int.MinValue;
                IPoint   snappedPoint = null;
                while ((feature = await cursor.NextFeature()) != null)
                {
                    if (!(feature.Shape is IPolyline) ||
                        feature.FindField("NETWORK#FCID") == null)
                    {
                        continue;
                    }

                    int fcid = (int)feature["NETWORK#FCID"];

                    double dist, stat;
                    IPoint spoint = gView.Framework.SpatialAlgorithms.Algorithm.Point2PolylineDistance((IPolyline)feature.Shape, point, out dist, out stat);
                    if (spoint == null)
                    {
                        continue;
                    }

                    if (selected == null || dist <= selectedDist)
                    {
                        if (fcid != -1)
                        {
                            #region Do complex Edge exists
                            IFeatureClass complexEdgeFc = _edgeFcs[-1];
                            if (complexEdgeFc != null)
                            {
                                QueryFilter complexEdgeFilter = new QueryFilter();
                                complexEdgeFilter.WhereClause = "FCID=" + fcid + " AND OID=" + feature.OID;
                                complexEdgeFilter.AddField("FDB_OID");
                                using (IFeatureCursor complexEdgeCursor = await complexEdgeFc.GetFeatures(complexEdgeFilter))
                                {
                                    if (await complexEdgeCursor.NextFeature() != null)
                                    {
                                        continue;
                                    }
                                }
                            }
                            #endregion
                        }
                        selected     = feature;
                        selectedDist = dist;
                        selectedFcId = fcid;
                        snappedPoint = spoint;
                    }
                }
                if (selected == null)
                {
                    return(null);
                }

                int eid = -1;
                if (selectedFcId == -1)
                {
                    #region Complex Edge
                    object eidObj = await _fdb._conn.QuerySingleField("SELECT EID FROM " + _fdb.TableName("FC_" + _name + "_ComplexEdges") + " WHERE FDB_OID=" + selected.OID, "EID");

                    if (eidObj != null)
                    {
                        eid = (int)eidObj;
                    }
                    #endregion
                }
                else
                {
                    object eidObj = await _fdb._conn.QuerySingleField("SELECT EID FROM " + _fdb.TableName(_name + "_EdgeIndex") + " WHERE FCID=" + selectedFcId + " AND OID=" + selected.OID, "EID");

                    if (eidObj != null)
                    {
                        eid = (int)eidObj;
                    }
                }

                if (eid != -1)
                {
                    point.X = snappedPoint.X;
                    point.Y = snappedPoint.Y;

                    IGraphTableAdapter gt = this.GraphTableAdapter();
                    return(gt.QueryEdge(eid));
                }
                return(null);
            }
        }
Exemplo n.º 25
0
        async static private Task <BinaryTree2Builder> SpatialIndex2(IFeatureDatabase fdb, IFeatureClass fc, ISpatialIndexDef def, List <IQueryFilter> filters = null)
        {
            if (fc == null)
            {
                return(null);
            }

            IEnvelope bounds = null;

            if (fc.Envelope != null)
            {
                bounds = fc.Envelope;
            }
            else if (fc.Dataset is IFeatureDataset && await((IFeatureDataset)fc.Dataset).Envelope() != null)
            {
                bounds = await((IFeatureDataset)fc.Dataset).Envelope();
            }

            if (bounds == null)
            {
                return(null);
            }
            //if (_transformer != null)
            //{
            //    IGeometry transBounds = _transformer.Transform2D(bounds) as IGeometry;
            //    if (transBounds != null)
            //        bounds = transBounds.Envelope;
            //}
            int maxAllowedLevel            = ((fdb is SqlFDB) ? 62 : 30);
            BinaryTree2Builder treeBuilder =
                ((Envelope.IsNull(def.SpatialIndexBounds)) ?
                 new BinaryTree2Builder(bounds,
                                        ((def.Levels != 0) ? def.Levels : maxAllowedLevel),
                                        ((def.MaxPerNode != 0) ? def.MaxPerNode : 500),
                                        ((def.SplitRatio != 0.0) ? def.SplitRatio : 0.55),
                                        maxVerticesPerNode: 500 * 50) :
                 new BinaryTree2Builder2(def.SpatialIndexBounds, def.Levels, def.MaxPerNode, def.SplitRatio));

            if (filters == null)
            {
                QueryFilter filter = new QueryFilter()
                {
                    WhereClause = "1=1"
                };
                filter.AddField(fc.ShapeFieldName);
                filters = new List <IQueryFilter>();
                filters.Add(filter);
            }
            foreach (IQueryFilter filter in filters)
            {
                using (IFeatureCursor fCursor = await fc.GetFeatures(filter))
                {
                    if (fCursor == null)
                    {
                        throw new Exception("Fatal error: sourcedb query failed...");
                    }

                    Console.WriteLine("Calculate spatial index:");

                    IEnvelope fcEnvelope = bounds;
                    //if (_transformer != null)
                    //{
                    //    IGeometry geom = _transformer.Transform2D(fcEnvelope) as IGeometry;
                    //    if (geom == null)
                    //    {
                    //        _errMsg = "SpatialIndex: Can't project featureclass extent!";
                    //        return null;
                    //    }
                    //    fcEnvelope = geom.Envelope;
                    //}

                    int      counter = 0;
                    IFeature feat;
                    while ((feat = await fCursor.NextFeature()) != null)
                    {
                        IGeometry shape = feat.Shape;
                        //if (_transformer != null)
                        //{
                        //    shape = _transformer.Transform2D(shape) as IGeometry;
                        //}

                        feat.Shape = shape;
                        treeBuilder.AddFeature(feat);

                        counter++;
                        if (counter % 10000 == 0)
                        {
                            Console.Write($"...{ counter }");
                        }
                    }
                    Console.Write($"...{ counter }");
                }
            }

            treeBuilder.Trim();
            Console.WriteLine();

            return(treeBuilder);
        }
Exemplo n.º 26
0
        private bool CopyFeatures(IFeatureClass source, IFeatureUpdater fdb, IFeatureClass dest, FieldTranslation fTrans, List <IQueryFilter> filters)
        {
            if (filters == null)
            {
                QueryFilter filter = new QueryFilter();
                filter.SubFields = "*";

                filters = new List <IQueryFilter>();
                filters.Add(filter);
            }

            int             counter  = 0;
            List <IFeature> features = new List <IFeature>();

            foreach (IQueryFilter filter in filters)
            {
                using (IFeatureCursor cursor = source.GetFeatures(filter))
                {
                    IFeature feature;
                    while ((feature = cursor.NextFeature) != null)
                    {
                        if (fTrans != null)
                        {
                            fTrans.RenameFields(feature);
                        }
                        if (_transformer != null)
                        {
                            feature.Shape = _transformer.Transform2D(feature.Shape) as IGeometry;
                        }
                        features.Add(feature);
                        counter++;
                        if ((counter % this.FeatureBufferSize) == 0)
                        {
                            if (!fdb.Insert(dest, features))
                            {
                                _errMsg = "Fatal error: destdb insert failed...\n" + fdb.lastErrorMsg;
                                return(false);
                            }
                            features.Clear();
                            if (ReportProgress != null)
                            {
                                ReportProgress(this, counter);
                            }
                        }
                    }
                }
            }
            if (features.Count > 0)
            {
                if (!fdb.Insert(dest, features))
                {
                    _errMsg = "Fatal error: destdb insert failed...";
                    return(false);
                }
                features.Clear();
                if (ReportProgress != null)
                {
                    ReportProgress(this, counter);
                }
            }
            return(true);
        }
Exemplo n.º 27
0
        private bool InsertImage(IFeatureUpdater fdb, IFeatureClass rasterFC, FileInfo fi, Dictionary <string, Guid> providers)
        {
            if (!_cancelTracker.Continue)
            {
                _errMsg = "Canceled by user...";
                return(false);
            }

            if (ReportAction != null)
            {
                ReportAction(this, "Insert Image: " + fi.FullName);
            }
            if (ReportProgress != null)
            {
                ReportProgress(this, 1);
            }

            System.Drawing.Imaging.ImageFormat format = System.Drawing.Imaging.ImageFormat.Jpeg;
            switch (fi.Extension.ToLower())
            {
            case ".png":
                format = System.Drawing.Imaging.ImageFormat.Png;
                break;

            case ".tif":
            case ".tiff":
                format = System.Drawing.Imaging.ImageFormat.Tiff;
                break;
            }

            #region RasterFileDataset bestimmen
            List <IRasterFileDataset> rFileDatasets = new List <IRasterFileDataset>();
            IRasterFileDataset        rFileDataset  = null;
            IRasterLayer  rasterLayer = null;
            PlugInManager compMan     = new PlugInManager();
            foreach (XmlNode ds in compMan.GetPluginNodes(Plugins.Type.IDataset))
            {
                IRasterFileDataset rds = compMan.CreateInstance(ds) as IRasterFileDataset;
                if (rds == null)
                {
                    continue;
                }

                if (rds.SupportsFormat(fi.Extension) < 0)
                {
                    continue;
                }
                if (providers != null && providers.ContainsKey(fi.Extension.ToLower()))
                {
                    if (!providers[fi.Extension.ToLower()].Equals(PlugInManager.PlugInID(rds)))
                    {
                        continue;
                    }
                }
                rFileDatasets.Add(rds);
            }
            if (rFileDatasets.Count == 0)
            {
                _errMsg = "No Rasterfile Provider for " + fi.Extension;
                return(false);
            }

            // RasterFileDataset nach priorität sortieren
            rFileDatasets.Sort(new RasterFileDatasetComparer(fi.Extension));

            // RasterFileDataset suchen, mit dem sich Bild öffnen läßt
            foreach (IRasterFileDataset rfd in rFileDatasets)
            {
                rfd.AddRasterFile(fi.FullName);

                if (rfd.Elements.Count == 0)
                {
                    //Console.WriteLine(_errMsg = fi.FullName + " is not a valid Raster File...");
                    continue;
                }
                IDatasetElement element = rfd.Elements[0];
                if (!(element is IRasterLayer))
                {
                    //Console.WriteLine(_errMsg = fi.FullName + " is not a valid Raster Layer...");
                    rFileDataset.Dispose();
                    continue;
                }

                // gefunden...
                rasterLayer  = (IRasterLayer)element;
                rFileDataset = rfd;
                break;
            }
            if (rasterLayer == null || rFileDataset == null)
            {
                Console.WriteLine(_errMsg = fi.FullName + " is not a valid Raster Layer...");
                return(false);
            }
            #endregion

            FileInfo fiWorld = null;
            double   cellX   = 1;
            double   cellY   = 1;

            IRasterFile rasterFile = null;
            if (rasterLayer is IRasterFile)
            {
                rasterFile = (IRasterFile)rasterLayer;
            }
            if (rasterLayer.RasterClass != null)
            {
                if (rasterLayer.RasterClass is IRasterFile &&
                    ((IRasterFile)rasterLayer.RasterClass).WorldFile != null)
                {
                    rasterFile = (IRasterFile)rasterLayer.RasterClass;
                }
                else
                {
                    IRasterClass c = (IRasterClass)rasterLayer.RasterClass;
                    cellX = Math.Sqrt(c.dx1 * c.dx1 + c.dx2 * c.dx2);
                    cellY = Math.Sqrt(c.dy1 * c.dy1 + c.dy2 * c.dy2);
                }
            }
            if (rasterFile != null)
            {
                try
                {
                    IRasterWorldFile world = rasterFile.WorldFile;
                    if (world != null)
                    {
                        if (!world.isGeoReferenced)
                        {
                            if (handleNonGeorefAsError)
                            {
                                _errMsg = "Can't add non georeferenced images: " + fi.FullName;
                                return(false);
                            }
                            else
                            {
                                return(true);
                            }
                        }

                        cellX = Math.Sqrt(world.dx_X * world.dx_X + world.dx_Y * world.dx_Y);
                        cellY = Math.Sqrt(world.dy_X * world.dy_X + world.dy_Y * world.dy_Y);

                        fiWorld = new FileInfo(rasterFile.WorldFile.Filename);
                        if (!fiWorld.Exists)
                        {
                            fiWorld = null;
                        }
                    }
                }
                catch
                {
                    fiWorld = null;
                }
            }

            #region Check if already Exits
            //
            // Suchen, ob Image mit gleichen Pfad schon vorhanden ist, wenn ja
            // nur weitermachen, wenn sich das änderungsdatum unterscheidet...
            //

            QueryFilter filter = new QueryFilter();
            filter.AddField("FDB_OID");
            filter.AddField("PATH");
            filter.AddField("LAST_MODIFIED");
            filter.AddField("PATH2");
            filter.AddField("LAST_MODIFIED2");

            string fullName = fi.FullName.Replace(@"\", @"\\");
            if (_fdb is AccessFDB)
            {
                filter.WhereClause = ((AccessFDB)_fdb).DbColName("PATH") + "='" + fullName + "'";
            }
            else
            {
                filter.WhereClause = "PATH='" + fullName + "'";
            }
            int deleteOID = -1;
            using (IFeatureCursor cursor = rasterFC.GetFeatures(filter))
            {
                IFeature existingFeature = cursor.NextFeature;
                if (existingFeature != null)
                {
                    DateTime dt1 = (DateTime)existingFeature["LAST_MODIFIED"];
                    if (Math.Abs(((TimeSpan)(dt1 - fi.LastWriteTimeUtc)).TotalSeconds) > 1.0)
                    {
                        deleteOID = existingFeature.OID;
                    }
                    else if (fiWorld != null &&
                             existingFeature["PATH2"] != System.DBNull.Value &&
                             existingFeature["PATH2"].ToString() != String.Empty)
                    {
                        DateTime dt2 = (DateTime)existingFeature["LAST_MODIFIED2"];
                        if (existingFeature["PATH2"].ToString().ToLower() != fiWorld.FullName.ToLower() ||
                            Math.Abs(((TimeSpan)(dt2 - fiWorld.LastWriteTimeUtc)).TotalSeconds) > 1.0)
                        {
                            deleteOID = existingFeature.OID;
                        }
                    }

                    if (deleteOID == -1)
                    {
                        Console.Write(".");
                        //Console.WriteLine(fi.FullName + " already exists...");
                        return(true);
                    }
                }
            }
            if (deleteOID != -1)
            {
                if (!fdb.Delete(rasterFC, deleteOID))
                {
                    Console.WriteLine(_errMsg = "Can't delete old record " + fi.FullName + "\n" + fdb.lastErrorMsg);
                    return(false);
                }
            }
            //
            ///////////////////////////////////////////////////////////////////
            //
            #endregion

            Feature feature = new Feature();
            feature.Shape = rasterLayer.RasterClass.Polygon;
            feature.Fields.Add(new FieldValue("PATH", fi.FullName));
            feature.Fields.Add(new FieldValue("LAST_MODIFIED", fi.LastWriteTimeUtc));
            if (fiWorld != null)
            {
                feature.Fields.Add(new FieldValue("PATH2", fiWorld.FullName));
                feature.Fields.Add(new FieldValue("LAST_MODIFIED2", fiWorld.LastWriteTimeUtc));
            }
            else
            {
                feature.Fields.Add(new FieldValue("PATH2", ""));
            }
            feature.Fields.Add(new FieldValue("RF_PROVIDER", PlugInManager.PlugInID(rFileDataset).ToString()));
            feature.Fields.Add(new FieldValue("MANAGED", _managed && (rasterLayer is IBitmap)));
            feature.Fields.Add(new FieldValue("FORMAT", fi.Extension.Replace(".", "")));
            feature.Fields.Add(new FieldValue("CELLX", cellX));
            feature.Fields.Add(new FieldValue("CELLY", cellY));
            feature.Fields.Add(new FieldValue("LEVELS", (_managed) ? Math.Max(_levels, 1) : 0));

            if (!fdb.Insert(rasterFC, feature))
            {
                Console.WriteLine("\nERROR@" + fi.FullName + ": " + fdb.lastErrorMsg);
            }
            else
            {
                if (_managed && (rasterLayer is IBitmap) && (fdb is SqlFDB))
                {
                    QueryFilter qfilter = new QueryFilter();
                    qfilter.SubFields = "FDB_OID";
                    if (_fdb is AccessFDB)
                    {
                        filter.WhereClause = ((AccessFDB)_fdb).DbColName("PATH") + "='" + fi.FullName + "'";
                    }
                    else
                    {
                        qfilter.WhereClause = "PATH='" + fi.FullName + "'";
                    }
                    IFeatureCursor cursor = ((SqlFDB)fdb).Query(rasterFC, qfilter);
                    if (cursor != null)
                    {
                        IFeature feat = cursor.NextFeature;
                        if (feat != null)
                        {
                            InsertImageDatasetBitmap(feat.OID, rasterLayer, _levels, format);
                        }
                        cursor.Dispose();
                    }
                }

                Console.WriteLine(">" + fi.FullName + " added...");
            }

            rFileDataset.Dispose();
            return(true);
        }
Exemplo n.º 28
0
        public bool RemoveUnexisting()
        {
            if (!(_fdb is AccessFDB))
            {
                return(false);
            }
            IFeatureClass rasterFC = ((AccessFDB)_fdb).GetFeatureclass(_dsname, _dsname + "_IMAGE_POLYGONS");

            if (rasterFC == null)
            {
                if (rasterFC == null)
                {
                    Console.WriteLine("\n\nERROR: Open Featureclass - Can't init featureclass " + _dsname + "_IMAGE_POLYGONS");
                    return(false);
                }
            }

            if (ReportAction != null)
            {
                ReportAction(this, "Remove unexisting");
            }
            if (ReportProgress != null)
            {
                ReportProgress(this, 1);
            }

            QueryFilter filter = new QueryFilter();

            filter.AddField("FDB_OID");
            filter.AddField("PATH");
            filter.AddField("LAST_MODIFIED");
            filter.AddField("PATH2");
            filter.AddField("LAST_MODIFIED2");

            List <int> Oids = new List <int>();

            using (IFeatureCursor cursor = rasterFC.GetFeatures(filter))
            {
                IFeature feature;
                while ((feature = cursor.NextFeature) != null)
                {
                    string path  = (string)feature["PATH"];
                    string path2 = (string)feature["PATH2"];
                    try
                    {
                        if (!String.IsNullOrEmpty(path))
                        {
                            FileInfo fi = new FileInfo(path);
                            if (!fi.Exists)
                            {
                                Console.Write("*");
                                Oids.Add(feature.OID);
                                continue;
                            }
                        }
                        if (!String.IsNullOrEmpty(path2))
                        {
                            FileInfo fi = new FileInfo(path2);
                            if (!fi.Exists)
                            {
                                Console.Write("*");
                                Oids.Add(feature.OID);
                                continue;
                            }
                        }
                        Console.Write(".");
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(_errMsg = "Exception: " + ex.Message);
                    }
                }

                foreach (int oid in Oids)
                {
                    if (!((AccessFDB)_fdb).Delete(rasterFC, oid))
                    {
                        Console.WriteLine(_errMsg = "Can't delete record OID=" + oid);
                        return(false);
                    }
                }

                return(true);
            }
        }
Exemplo n.º 29
0
        private void Run()
        {
            if (_targetDataset == null || _fdb == null || _sourceDataset == null)
            {
                return;
            }

            //if (_targetDataset[_name] != null)
            //{
            //    MessageBox.Show("Featureclass '" + _name + "' already exists!");
            //    return;
            //}
            bool succeeded = false;

            try
            {
                Envelope bounds  = new Envelope(_spatialIndexDef.SpatialIndexBounds);
                Envelope iBounds = new Envelope(bounds.minx - _tileSizeX, bounds.miny - _tileSizeY,
                                                bounds.maxx + _tileSizeX, bounds.maxy + _tileSizeY);

                _cacheDirectory += @"\" + _name;
                if (!String.IsNullOrEmpty(_cacheDirectory))
                {
                    DirectoryInfo di = new DirectoryInfo(_cacheDirectory);
                    if (!di.Exists)
                    {
                        di.Create();
                    }

                    StringBuilder sb = new StringBuilder();
                    sb.Append("<TileCacheDefinition>\r\n");
                    sb.Append(" <General levels='" + _levels + "' origin='lowerleft' />\r\n");
                    sb.Append(" <Envelope minx='" + bounds.minx.ToString(_nhi) + "' miny='" + bounds.miny.ToString(_nhi) + "' maxx='" + bounds.maxx.ToString(_nhi) + "' maxy='" + bounds.maxy.ToString(_nhi) + "' />\r\n");
                    sb.Append(" <TileSize x='" + _tileSizeX.ToString(_nhi) + "' y='" + _tileSizeY.ToString(_nhi) + "' />\r\n");
                    sb.Append(" <TileResolution x='" + _resX.ToString(_nhi) + "' y='" + _resY.ToString(_nhi) + "' />\r\n");
                    sb.Append("</TileCacheDefinition>");

                    StreamWriter sw = new StreamWriter(di.FullName + @"\tilecache.xml");
                    sw.WriteLine(sb.ToString());
                    sw.Close();
                }
                ProgressReport report = new ProgressReport();

                int datasetId = _fdb.DatasetID(_targetDataset.DatasetName);
                if (datasetId == -1)
                {
                    return;
                }

                IClass cls = null;
                try
                {
                    cls = _sourceDataset.Elements[0].Class;
                }
                catch { cls = null; }
                IMultiGridIdentify gridClass = cls as IMultiGridIdentify;
                if (_gridType == TileGridType.binary_float && gridClass == null)
                {
                    return;
                }
                IFeatureClass sourceFc = cls as IFeatureClass;

                Map map = null;
                if (_gridType == TileGridType.image_jpg || _gridType == TileGridType.image_png)
                {
                    map = new Map();
                    ILayer layer = LayerFactory.Create(cls);
                    map.AddLayer(layer);
                    //map.iWidth = (int)(_tileSizeX / _resX);
                    //map.iHeight = (int)(_tileSizeY / _resY);
                }


                #region Create Featureclass
                IFeatureClass   fc      = null;
                IDatasetElement element = _targetDataset[_name];
                if (element != null && element.Class is IFeatureClass)
                {
                    fc = (IFeatureClass)element.Class;
                    if (fc.GeometryType == geometryType.Polygon &&
                        fc.FindField("GRID_LEVEL") != null &&
                        fc.FindField("GRID_ROW") != null &&
                        fc.FindField("GRID_COLUMN") != null &&
                        fc.FindField("FILE") != null)
                    {
                        if (MessageBox.Show("TileGridClass already exists. Do you wan't to append to this Grid?",
                                            "Warning",
                                            MessageBoxButtons.YesNo,
                                            MessageBoxIcon.Question, MessageBoxDefaultButton.Button1) != DialogResult.Yes)
                        {
                            return;
                        }
                    }
                    else
                    {
                        _fdb.DeleteFeatureClass(_name);
                        fc = null;
                    }
                }
                if (fc == null)
                {
                    Fields fields = new Fields();

                    fields.Add(new Field("GRID_LEVEL", FieldType.integer));
                    fields.Add(new Field("GRID_ROW", FieldType.integer));
                    fields.Add(new Field("GRID_COLUMN", FieldType.integer));
                    fields.Add(new Field("FILE", FieldType.String, 512));

                    _fdb.CreateFeatureClass(_targetDataset.DatasetName, _name,
                                            new GeometryDef(geometryType.Polygon),
                                            fields);
                    element = _targetDataset[_name];
                    if (element == null || !(element.Class is IFeatureClass))
                    {
                        return;
                    }
                    _fdb.SetSpatialIndexBounds(_name, "BinaryTree2", iBounds, _spatialIndexDef.SplitRatio, _spatialIndexDef.MaxPerNode, _spatialIndexDef.Levels);
                    fc = (IFeatureClass)element.Class;
                }
                #endregion

                #region Create Tiles

                #region Report
                double tx = _tileSizeX, ty = _tileSizeY;
                if (ReportProgress != null)
                {
                    report.featureMax = 0;
                    for (int i = 0; i < _levels; i++)
                    {
                        if (_createLevels.Contains(i))
                        {
                            for (double y = bounds.miny; y < bounds.maxy; y += ty)
                            {
                                for (double x = bounds.minx; x < bounds.maxx; x += tx)
                                {
                                    report.featureMax++;
                                }
                            }
                        }
                        if (_levelType == TileLevelType.ConstantImagesize)
                        {
                            tx *= 2;
                            ty *= 2;
                        }
                    }
                    report.Message    = "Create Tiles";
                    report.featurePos = 0;
                    ReportProgress(report);
                }
                int reportInterval = (_createTiles ? 10 : 1000);
                #endregion

                List <IFeature> features = new List <IFeature>();
                for (int level = 0; level < _levels; level++)
                {
                    if (map != null)
                    {
                        map.iWidth  = (int)(_tileSizeX / _resX);
                        map.iHeight = (int)(_tileSizeY / _resY);
                    }
                    if (_createLevels.Contains(level))
                    {
                        int row = 0;
                        for (double y = bounds.miny; y < bounds.maxy; y += _tileSizeY)
                        {
                            DirectoryInfo di = new DirectoryInfo(_cacheDirectory + @"\" + level + @"\" + row);
                            if (!di.Exists)
                            {
                                di.Create();
                            }

                            int column = 0;
                            for (double x = bounds.minx; x < bounds.maxx; x += _tileSizeX)
                            {
                                #region Polygon
                                Polygon polygon = new Polygon();
                                Ring    ring    = new Ring();
                                ring.AddPoint(new Point(x, y));
                                ring.AddPoint(new Point(Math.Min(x + _tileSizeX, bounds.maxx), y));
                                ring.AddPoint(new Point(Math.Min(x + _tileSizeX, bounds.maxx), Math.Min(y + _tileSizeY, bounds.maxy)));
                                ring.AddPoint(new Point(x, Math.Min(y + _tileSizeY, bounds.maxy)));
                                ring.Close();
                                polygon.AddRing(ring);
                                #endregion

                                if (sourceFc != null)
                                {
                                    SpatialFilter filter = new SpatialFilter();
                                    filter.AddField(sourceFc.IDFieldName);
                                    filter.Geometry = polygon;
                                    filter.FilterSpatialReference = fc.SpatialReference;
                                    using (IFeatureCursor cursor = sourceFc.GetFeatures(filter))
                                    {
                                        if (cursor.NextFeature == null)
                                        {
                                            column++;
                                            report.featurePos++;
                                            if (ReportProgress != null && report.featurePos % reportInterval == 0)
                                            {
                                                ReportProgress(report);
                                            }
                                            continue;
                                        }
                                    }
                                }

                                string relFilename = level + "/" + row + "/" + column + ".bin";

                                if (_createTiles)
                                {
                                    string filename = di.FullName + @"\" + column;
                                    if (_gridType == TileGridType.binary_float)
                                    {
                                        float[] vals = gridClass.MultiGridQuery(
                                            null,
                                            new IPoint[] { ring[0], ring[1], ring[3] },
                                            _resX, _resY,
                                            fc.SpatialReference, null);
                                        if (!HasFloatArrayData(vals))
                                        {
                                            column++;
                                            report.featurePos++;
                                            if (ReportProgress != null && report.featurePos % reportInterval == 0)
                                            {
                                                ReportProgress(report);
                                            }
                                            continue;
                                        }
                                        StoreFloatArray(filename + ".bin", x, y, _resX, _resY, vals);
                                    }
                                    else if (map != null)
                                    {
                                        map.ZoomTo(new Envelope(x, y, x + _tileSizeX, y + _tileSizeY));
                                        map.RefreshMap(DrawPhase.All, _cancelTracker);
                                        if (_gridType == TileGridType.image_png)
                                        {
                                            map.Bitmap.Save(filename + ".png", System.Drawing.Imaging.ImageFormat.Png);
                                        }
                                        else if (_gridType == TileGridType.image_jpg)
                                        {
                                            map.Bitmap.Save(filename + ".jpg", System.Drawing.Imaging.ImageFormat.Jpeg);
                                        }
                                    }
                                }

                                Feature feature = new Feature();
                                feature.Shape = polygon;
                                feature.Fields.Add(new FieldValue("GRID_LEVEL", level));
                                feature.Fields.Add(new FieldValue("GRID_ROW", row));
                                feature.Fields.Add(new FieldValue("GRID_COLUMN", column));
                                feature.Fields.Add(new FieldValue("FILE", relFilename));

                                features.Add(feature);
                                column++;
                                report.featurePos++;
                                if (features.Count >= reportInterval)
                                {
                                    if (ReportProgress != null)
                                    {
                                        ReportProgress(report);
                                    }
                                    if (!_fdb.Insert(fc, features))
                                    {
                                        MessageBox.Show(_fdb.lastErrorMsg, "DB Insert Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                                        return;
                                    }
                                    features.Clear();

                                    if (!_cancelTracker.Continue)
                                    {
                                        succeeded = true;
                                        return;
                                    }
                                }
                            }
                            row++;
                        }
                    }
                    if (_levelType == TileLevelType.ConstantImagesize)
                    {
                        _tileSizeX *= 2;
                        _tileSizeY *= 2;
                    }
                    _resX *= 2;
                    _resY *= 2;
                }
                if (features.Count > 0)
                {
                    if (ReportProgress != null)
                    {
                        ReportProgress(report);
                    }
                    _fdb.Insert(fc, features);
                }
                _fdb.CalculateExtent(fc);
                #endregion

                succeeded = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            finally
            {
                if (!succeeded)
                {
                    _fdb.DeleteFeatureClass(_name);
                }
            }
        }
Exemplo n.º 30
0
        async public Task <IFeature> GetNodeFeatureAttributes(int nodeId, string[] attributes)
        {
            try
            {
                QueryFilter filter = new QueryFilter();
                filter.WhereClause = "FDB_OID=" + nodeId;
                filter.AddField("FCID");
                filter.AddField("OID");

                IFeature feature;
                using (IFeatureCursor cursor = await GetNodeFeatures(filter))
                    feature = await cursor.NextFeature();
                if (feature == null)
                {
                    return(null);
                }

                string fcName = await _fdb.GetFeatureClassName((int)feature["FCID"]);

                IDatasetElement element = await _dataset.Element(fcName);

                if (element == null)
                {
                    return(null);
                }
                IFeatureClass fc = element.Class as IFeatureClass;
                if (fc == null)
                {
                    return(null);
                }

                filter = new QueryFilter();
                if (fc is IDatabaseNames)
                {
                    filter.WhereClause = ((IDatabaseNames)fc).DbColName(fc.IDFieldName) + "=" + Convert.ToInt32(feature["OID"]);
                }
                else
                {
                    filter.WhereClause = _fdb.DbColName(fc.IDFieldName) + "=" + Convert.ToInt32(feature["OID"]);
                }

                if (attributes == null)
                {
                    filter.AddField("*");
                }
                else
                {
                    foreach (string attribute in attributes)
                    {
                        if (attribute == "*")
                        {
                            filter.AddField(attribute);
                        }
                        else if (fc.FindField(attribute) != null)
                        {
                            filter.AddField(attribute);
                        }
                    }
                }

                using (IFeatureCursor cursor = await fc.GetFeatures(filter))
                    feature = await cursor.NextFeature();

                if (feature != null)
                {
                    feature.Fields.Add(new FieldValue("_classname", fc.Name));
                }

                return(feature);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 31
0
        private ArrayList CheckValue(string featAnnotName, string FeatName, string CheckRule, string otherString, string Tolerance, string errorMsg, int[] idValues)
        {
            double        tol          = 0;
            ArrayList     errorMsgList = new ArrayList(); //定义错误信息
            IFeatureClass AnnoFC       = CheckerUtil.GetFeatureClassFromWorkspace(featAnnotName);
            IFeatureClass FeatFC       = CheckerUtil.GetFeatureClassFromWorkspace(FeatName);

            if (AnnoFC == null || FeatFC == null)
            {
                string strMsg = "没能在数据库中找到对应的注记图层,请检查输入的图层名称是否正确";
                errorMsgList.Add(new CheckError {
                    Description = strMsg, Locations = null
                });
                return(null);
            }
            try
            {
                tol = double.Parse(Tolerance);
            }
            catch
            {
                string strMsg = "输入的容差为非数值型,请检查输入的容差值是否正确";
                errorMsgList.Add(new CheckError {
                    Description = strMsg, Locations = null
                });
                return(errorMsgList);
            }

            string[] fieldsParm = CheckRule.Split(',');

            for (int i = 0; i < fieldsParm.Length; i++)
            {
                int fieldIndex = FeatFC.Fields.FindField(fieldsParm[i].ToString());
                if (fieldIndex == -1)
                {
                    string strMsg = "没能找到" + InputFCName + "图层中的 " + fieldsParm[i].ToString() + " 字段,请检查输入的字段名称是否正确";
                    errorMsgList.Add(new CheckError {
                        Description = strMsg, Locations = null
                    });
                    return(errorMsgList);
                }
            }
            //开始检索所有的注记
            bool           hasErr = false;
            IFeatureCursor pAnnoCursor;

            if (idValues == null)
            {
                pAnnoCursor = AnnoFC.Search(null, false);
            }
            else
            {
                pAnnoCursor = AnnoFC.GetFeatures(idValues, false);
            }
            IFeature pAnnoFeat = pAnnoCursor.NextFeature();

            while (pAnnoFeat != null)
            {
                string annoStr = pAnnoFeat.get_Value(pAnnoFeat.Fields.FindField("TextString")).ToString();  //Annotation的值
                //查找与之对应的所有相交的建筑物
                ISpatialFilter       spFilter = new SpatialFilterClass();
                ITopologicalOperator topo     = pAnnoFeat.Shape as ITopologicalOperator;
                topo.Buffer(tol);
                spFilter.Geometry   = topo as IPolygon;
                spFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                IFeatureCursor featCursor = FeatFC.Search(spFilter, false);
                IFeature       bFeat      = featCursor.NextFeature();
                while (bFeat != null)
                {
                    string fieldsStr = "";
                    //ArrayList fieldsValue = new ArrayList();
                    for (int i = 0; i < fieldsParm.Length; i++)
                    {
                        string fStr = bFeat.get_Value(bFeat.Fields.FindField(fieldsParm[i])).ToString();
                        fieldsStr = fieldsStr + fStr;
                    }
                    string whole        = fieldsStr + otherString;
                    string notFoundChar = "";
                    for (int i = 0; i < annoStr.Length; i++)
                    {
                        //假如没找到对应的字符,则写入错误
                        if (whole.IndexOf(annoStr[i]) == -1)
                        {
                            hasErr       = true;
                            notFoundChar = notFoundChar + "'" + annoStr[i].ToString() + "' ";
                        }
                    }
                    if (hasErr)
                    {
                        List <IGeometry> pGeoList = new List <IGeometry>();
                        pGeoList.Add(pAnnoFeat.Shape);
                        pGeoList.Add(bFeat.Shape);

                        string strMsg = "注记层:" + featAnnotName + ",要素ID号为: '" + pAnnoFeat.OID.ToString() + "' 与 对应要素层:" + FeatName + ", 要素ID号为: '" + bFeat.OID.ToString() + "'的属性不一致,没找到  " + notFoundChar + "关键字   " + errorMsg;
                        errorMsgList.Add(new CheckError {
                            Description = strMsg, Locations = pGeoList
                        });
                    }
                    bFeat = featCursor.NextFeature();
                }
                pAnnoFeat = pAnnoCursor.NextFeature();
            }
            if (hasErr == false)
            {
                string strMsg = "没发现任何不符合的要素";
                errorMsgList.Add(new CheckError {
                    Description = strMsg, Locations = null
                });
            }
            return(errorMsgList);
        }