public TileCacheLayerExplorerObject(TileCacheDatasetExplorerObject parent, IDatasetElement element) : base(parent, typeof(FeatureClass), 1) { if (element == null) { return; } _parent = parent; _fcname = element.Title; if (element.Class is IRasterClass) { _rc = (IRasterClass)element.Class; } }
async public Task <IDatasetElement> Element(string title) { if (_fdb == null) { return(null); } IDatasetElement element = await _fdb.DatasetElement(this, title); if (element != null && element.Class is pgFeatureClass) { ((pgFeatureClass)element.Class).SpatialReference = _sRef; } return(element); }
private void cmbRightTable_SelectedIndexChanged(object sender, EventArgs e) { cmbRightTableField.Items.Clear(); if (cmbRightTable.SelectedItem == null) { return; } IDatasetElement element = ((DatasetElementItem)cmbRightTable.SelectedItem).DatasetElement; foreach (IField field in ((ITableClass)element.Class).Fields) { cmbRightTableField.Items.Add(field.name); } ValidateOk(); }
async public Task <IExplorerObject> CreateExplorerObject(IExplorerObject parentExObject) { if (!(parentExObject is SQLiteFDBDatasetExplorerObject)) { return(null); } SQLiteFDBDatasetExplorerObject parent = (SQLiteFDBDatasetExplorerObject)parentExObject; IFeatureDataset dataset = await((SQLiteFDBDatasetExplorerObject)parentExObject).GetInstanceAsync() as IFeatureDataset; if (dataset == null || !(dataset.Database is SQLiteFDB)) { return(null); } FormNewNetworkclass dlg = new FormNewNetworkclass(dataset, typeof(CreateFDBNetworkFeatureclass)); if (dlg.ShowDialog() != DialogResult.OK) { return(null); } CreateFDBNetworkFeatureclass creator = new CreateFDBNetworkFeatureclass( dataset, dlg.NetworkName, dlg.EdgeFeatureclasses, dlg.NodeFeatureclasses); creator.SnapTolerance = dlg.SnapTolerance; creator.ComplexEdgeFcIds = await dlg.ComplexEdgeFcIds(); creator.GraphWeights = dlg.GraphWeights; creator.SwitchNodeFcIdAndFieldnames = dlg.SwitchNodeFcIds; creator.NodeTypeFcIds = dlg.NetworkNodeTypeFcIds; FormTaskProgress progress = new FormTaskProgress(); progress.ShowProgressDialog(creator, creator.Run()); IDatasetElement element = await dataset.Element(dlg.NetworkName); return(new SQLiteFDBFeatureClassExplorerObject( parent, parent.FileName, parent.Name, element)); }
async private void btnOK_Click(object sender, EventArgs e) { if (_dataset != null && _dataset.ConnectionString != _dsConnectionString) { await _dataset.SetConnectionString(_dsConnectionString); await _dataset.Open(); int dsIndex = 0; IDataset ds; while ((ds = _map[dsIndex]) != null) { if (ds == _dataset) { break; } dsIndex++; } if (ds == null) { return; } foreach (IDatasetElement element in _map.MapElements) { if (!(element is DatasetElement)) { continue; } if (element.DatasetID == dsIndex) { IDatasetElement el = await _dataset.Element(element.Title); if (el == null) { ((DatasetElement)element).Class2 = null; } else { ((DatasetElement)element).Class2 = el.Class; } } } } }
public IExplorerObject CreateExplorerObject(IExplorerObject parentExObject) { if (!CanCreate(parentExObject)) { return(null); } if (!(parentExObject.Object is IFeatureDataset) || !(((IDataset)parentExObject.Object).Database is AccessFDB)) { return(null); } AccessFDB fdb = ((IDataset)parentExObject.Object).Database as AccessFDB; FormNewFeatureclass dlg = new FormNewFeatureclass(parentExObject.Object as IFeatureDataset); if (dlg.ShowDialog() != DialogResult.OK) { return(null); } IGeometryDef gDef = dlg.GeometryDef; int FCID = fdb.CreateFeatureClass( parentExObject.Name, dlg.FeatureclassName, gDef, dlg.Fields); if (FCID < 0) { MessageBox.Show("ERROR: " + fdb.lastErrorMsg); return(null); } ISpatialIndexDef sIndexDef = fdb.SpatialIndexDef(parentExObject.Name); fdb.SetSpatialIndexBounds(dlg.FeatureclassName, "BinaryTree2", dlg.SpatialIndexExtents, 0.55, 200, dlg.SpatialIndexLevels); IDatasetElement element = ((IFeatureDataset)parentExObject.Object)[dlg.FeatureclassName]; return(new AccessFDBFeatureClassExplorerObject( parentExObject as AccessFDBDatasetExplorerObject, _filename, parentExObject.Name, element)); }
public IDatasetElement this[string DatasetElementTitle] { get { if (_fdb == null) { return(null); } IDatasetElement element = _fdb.DatasetElement(this, DatasetElementTitle); if (element != null && element.Class is AccessFDBFeatureClass) { ((AccessFDBFeatureClass)element.Class).SpatialReference = _sRef; } return(element); } }
public override bool ProcessAble(IDatasetElement data) { if (data == null || data.Class == null) { return(false); } if (data.Class is IFeatureClass) { if (_geomType == geometryType.Unknown) { return(true); } return(((IFeatureClass)data.Class).GeometryType == _geomType); } return(false); }
async public Task <object> GetInstanceAsync() { if (_fc != null) { return(_fc); } var datdaset = await this.Dataset(); if (this.Dataset() != null) { IDatasetElement element = await datdaset.Element(_fcName); if (element != null) { _fc = element.Class as IFeatureClass; } } return(_fc); }
public IMap this[IDatasetElement layer] { get { foreach(IMap map in _maps) { if (layer is IGroupLayer) { foreach (IDatasetElement element in map.MapElements) { if (layer == element) return map; } } else { if (map[layer] != null) return map; } } return null; } }
public OgrLayerExplorerObject(OgrDatasetExplorerObject parent, IDatasetElement element) : base(parent, typeof(FeatureClass)) { if (element == null) { return; } _parent = parent; _fcname = element.Title; if (element.Class is IFeatureClass) { _fc = (IFeatureClass)element.Class; switch (_fc.GeometryType) { case geometryType.Envelope: case geometryType.Polygon: _icon = new AccessFDBPolygonIcon(); _type = "Polygon Featureclass"; break; case geometryType.Multipoint: case geometryType.Point: _icon = new AccessFDBPointIcon(); _type = "Point Featureclass"; break; case geometryType.Polyline: _icon = new AccessFDBLineIcon(); _type = "Polyline Featureclass"; break; default: _icon = new AccessFDBLineIcon(); _type = "Featureclass"; break; } } }
private static IFeatureClass GetFeatureclass(IFeatureDataset ds, string name) { IDatasetElement element = ds[name]; if (element != null && element.Class is IFeatureClass) { return(element.Class as IFeatureClass); } foreach (IDatasetElement element2 in ds.Elements) { if (element2.Class is IFeatureClass) { if (element2.Class.Name == name) { return(element2.Class as IFeatureClass); } } } return(null); }
public void AppendElement(string elementName) { if (_elements == null) { _elements = new List <IDatasetElement>(); } foreach (IDatasetElement e in _elements) { if (e.Title == elementName) { return; } } IDatasetElement element = this[elementName]; if (element != null) { _elements.Add(element); } }
async public Task AppendElement(string elementName) { if (_layers == null) { _layers = new List <IDatasetElement>(); } foreach (IDatasetElement e in _layers) { if (e.Title == elementName) { return; } } IDatasetElement element = await _fdb.DatasetElement(this, elementName); if (element != null) { _layers.Add(element); } }
public void AppendElement(string elementName) { if (_layers == null) { _layers = new List <IDatasetElement>(); } foreach (IDatasetElement e in _layers) { if (e.Title == elementName) { return; } } //IDatasetElement element = _fdb.DatasetElement(this, elementName); IDatasetElement element = this[elementName]; if (element != null) { _layers.Add(element); } }
private void MigrateMapToFeatureDatabaseDialog_Shown(object sender, EventArgs e) { #region Featureklassen mit gleichen Namen suchen List <IDatasetElement> elements = _map.MapElements; for (int i = 0; i < elements.Count; i++) { IDatasetElement elementI = elements[i]; if (!(elementI.Class is IFeatureClass)) { continue; } for (int j = i + 1; j < elements.Count; j++) { IDatasetElement elementJ = elements[j]; if (!(elementJ.Class is IFeatureClass)) { continue; } if (elementI.Class.Name == elementJ.Class.Name) { IFeatureClass fcI = (IFeatureClass)elementI.Class, fcJ = (IFeatureClass)elementJ.Class; if (fcI.Dataset.ConnectionString.ToLower() == fcJ.Dataset.ConnectionString.ToLower()) { continue; } MessageBox.Show("There is more than one featureclass with the name '" + elementI.Class.Name + "'!\nEvery featureclass must have different name to run this function...", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); this.Close(); return; } } } #endregion }
public FormDataTable2(IDatasetElement dsElement) { InitializeComponent(); _tableClass = null; if (dsElement is IFeatureLayer) { _tableClass = ((IFeatureLayer)dsElement).FeatureClass; } else if (dsElement is ITableLayer) { _tableClass = ((ITableLayer)dsElement).TableClass; } _dsElement = dsElement; cmbShow.SelectedIndex = 0; if (_dsElement is IFeatureSelection) { ((IFeatureSelection)_dsElement).FeatureSelectionChanged -= new FeatureSelectionChangedEvent(FeatureSelectionChanged); ((IFeatureSelection)_dsElement).FeatureSelectionChanged += new FeatureSelectionChangedEvent(FeatureSelectionChanged); } }
async public Task <bool> ImportToNewFeatureclass(IFeatureDatabase fdb, string dsname, string fcname, IFeatureClass sourceFC, FieldTranslation fieldTranslation, bool project, List <IQueryFilter> filters, ISpatialIndexDef sIndexDef, geometryType?sourceGeometryType = null) { if (!_cancelTracker.Continue) { return(true); } if (fdb is AccessFDB) { ISpatialIndexDef dsSpatialIndexDef = await((AccessFDB)fdb).SpatialIndexDef(dsname); if (sIndexDef == null) { sIndexDef = dsSpatialIndexDef; } else if (sIndexDef.GeometryType != dsSpatialIndexDef.GeometryType) { _errMsg = "Spatial-Index-Definition-GeometryTypes are not compatible!"; return(false); } } if (sIndexDef == null) { sIndexDef = new gViewSpatialIndexDef(); } bool msSpatial = false; if (fdb is SqlFDB && (sIndexDef.GeometryType == GeometryFieldType.MsGeography || sIndexDef.GeometryType == GeometryFieldType.MsGeometry)) { msSpatial = true; } else { int maxAllowedLevel = ((fdb is SqlFDB || fdb is pgFDB) ? 62 : 30); if (sIndexDef.Levels > maxAllowedLevel) { ISpatialReference defSRef = sIndexDef.SpatialReference; sIndexDef = new gViewSpatialIndexDef( sIndexDef.SpatialIndexBounds, Math.Min(sIndexDef.Levels, maxAllowedLevel), sIndexDef.MaxPerNode, sIndexDef.SplitRatio); ((gViewSpatialIndexDef)sIndexDef).SpatialReference = defSRef; } } try { fcname = fcname.Replace(".", "_"); IFeatureDataset destDS = await fdb.GetDataset(dsname); if (destDS == null) { _errMsg = fdb.LastErrorMessage; return(false); } IDatasetElement destLayer = await destDS.Element(fcname); if (destLayer != null) { if (ReportRequest != null) { RequestArgs args = new RequestArgs( "Featureclass " + fcname + " already exists in " + dsname + "\nDo want to replace it?", MessageBoxButtons.YesNoCancel, DialogResult.Cancel); ReportRequest(this, args); switch (args.Result) { case DialogResult.No: return(true); case DialogResult.Cancel: _errMsg = "Import is canceled by the user..."; return(false); } } } GeometryDef geomDef = new GeometryDef(sourceFC); if (geomDef.GeometryType == geometryType.Unknown && sourceGeometryType != null) { geomDef.GeometryType = sourceGeometryType.Value; } int fcID = -1; if (destLayer != null) { if (fdb is AccessFDB) { fcID = await((AccessFDB)fdb).ReplaceFeatureClass(destDS.DatasetName, fcname, geomDef, (fieldTranslation == null) ? ((sourceFC.Fields != null) ? (IFields)sourceFC.Fields.Clone() : new Fields()) : fieldTranslation.DestinationFields); if (fcID < 0) { _errMsg = "Can't replace featureclass " + fcname + "...\r\n" + fdb.LastErrorMessage; destDS.Dispose(); return(false); } } else { await fdb.DeleteFeatureClass(fcname); } } if (fcID < 0) { fcID = await fdb.CreateFeatureClass(destDS.DatasetName, fcname, geomDef, (fieldTranslation == null)? ((sourceFC.Fields != null) ? (IFields)sourceFC.Fields.Clone() : new Fields()) : fieldTranslation.DestinationFields); } if (fcID < 0) { _errMsg = "Can't create featureclass " + fcname + "...\r\n" + fdb.LastErrorMessage; destDS.Dispose(); return(false); } destLayer = await destDS.Element(fcname); if (destLayer == null || !(destLayer.Class is IFeatureClass)) { _errMsg = "Can't load featureclass " + fcname + "...\r\n" + destDS.LastErrorMessage; destDS.Dispose(); return(false); } IFeatureClass destFC = destLayer.Class as IFeatureClass; if (project && destFC.SpatialReference != null && !destFC.SpatialReference.Equals(sourceFC.SpatialReference)) { _transformer = GeometricTransformerFactory.Create(); //_transformer.FromSpatialReference = sourceFC.SpatialReference; //_transformer.ToSpatialReference = destFC.SpatialReference; _transformer.SetSpatialReferences(sourceFC.SpatialReference, destFC.SpatialReference); } if (!Envelope.IsNull(sIndexDef.SpatialIndexBounds) && sIndexDef.SpatialReference != null && !sIndexDef.SpatialReference.Equals(destFC.SpatialReference)) { if (!sIndexDef.ProjectTo(destFC.SpatialReference)) { _errMsg = "Can't project SpatialIndex Boundaries..."; destDS.Dispose(); return(false); } } DualTree tree = null; BinaryTree2Builder tree2 = null; if (msSpatial) { ((SqlFDB)fdb).SetMSSpatialIndex((MSSpatialIndex)sIndexDef, destFC.Name); await((SqlFDB)fdb).SetFeatureclassExtent(destFC.Name, sIndexDef.SpatialIndexBounds); } else { if (_treeVersion == TreeVersion.BinaryTree) { tree = await SpatialIndex(sourceFC, sIndexDef.MaxPerNode, filters); if (tree == null) { return(false); } } else if (_treeVersion == TreeVersion.BinaryTree2) { if (_schemaOnly && sourceFC.Dataset.Database is IImplementsBinarayTreeDef) { BinaryTreeDef tDef = await((IImplementsBinarayTreeDef)sourceFC.Dataset.Database).BinaryTreeDef(sourceFC.Name); tree2 = new BinaryTree2Builder(tDef.Bounds, tDef.MaxLevel, tDef.MaxPerNode, tDef.SplitRatio); } else { tree2 = await SpatialIndex2(fdb, sourceFC, sIndexDef, filters); if (tree2 == null) { return(false); } } } // Vorab einmal alle "Bounds" festlegen, damit auch // ein aufzubauender Layer geviewt werden kann if (_treeVersion == TreeVersion.BinaryTree2 && fdb is AccessFDB) { if (ReportAction != null) { ReportAction(this, "Insert spatial index nodes"); } List <long> nids = new List <long>(); foreach (BinaryTree2BuilderNode node in tree2.Nodes) { nids.Add(node.Number); } await((AccessFDB)fdb).ShrinkSpatialIndex(fcname, nids); if (ReportAction != null) { ReportAction(this, "Set spatial index bounds"); } //((AccessFDB)fdb).SetSpatialIndexBounds(fcname, "BinaryTree2", tree2.Bounds, sIndexDef.SplitRatio, sIndexDef.MaxPerNode, tree2.maxLevels); await((AccessFDB)fdb).SetSpatialIndexBounds(fcname, "BinaryTree2", tree2.Bounds, tree2.SplitRatio, tree2.MaxPerNode, tree2.maxLevels); await((AccessFDB)fdb).SetFeatureclassExtent(fcname, tree2.Bounds); } } if (_cancelTracker.Continue) { bool result = true; if (!_schemaOnly) { if (msSpatial) { result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters); } else if (_treeVersion == TreeVersion.BinaryTree) { if (String.IsNullOrEmpty(sourceFC.IDFieldName)) // SDE Views haben keine ID -> Tree enthält keine Features { result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters); } else { result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, tree); } } else if (_treeVersion == TreeVersion.BinaryTree2) { if (String.IsNullOrEmpty(sourceFC.IDFieldName)) // SDE Views haben keine ID -> Tree enthält keine Features { result = await CopyFeatures(sourceFC, fdb, destFC, fieldTranslation, filters); } else { result = await CopyFeatures2(sourceFC, fdb, destFC, fieldTranslation, tree2); } } if (!result) { await fdb.DeleteFeatureClass(fcname); destDS.Dispose(); return(false); } } } destDS.Dispose(); if (_cancelTracker.Continue && fdb is AccessFDB) { if (ReportAction != null) { ReportAction(this, "Calculate extent"); } await((AccessFDB)fdb).CalculateExtent(destFC); if (msSpatial == false) { if (_treeVersion == TreeVersion.BinaryTree) { if (ReportAction != null) { ReportAction(this, "Set spatial index bounds"); } await((AccessFDB)fdb).SetSpatialIndexBounds(fcname, "BinaryTree", tree.Bounds, sIndexDef.SplitRatio, sIndexDef.MaxPerNode, 0); if (ReportAction != null) { ReportAction(this, "Insert spatial index nodes"); } await((AccessFDB)fdb).__intInsertSpatialIndexNodes2(fcname, tree.Nodes); } } return(true); } else { await fdb.DeleteFeatureClass(fcname); _errMsg = "Import is canceled by the user..."; return(false); } } finally { if (_transformer != null) { _transformer.Release(); _transformer = null; } } }
public LayerTreeNode(IDatasetElement layer) { base.ImageIndex = base.SelectedImageIndex = 1; this.Layer = layer; base.Text = this.ToString(); }
public MsSql2008SpatialSdeFeatureClassExplorerObject(MsSql2008SpatialSdeExplorerObject parent, IDatasetElement element) : base(parent, typeof(IFeatureClass), 1) { if (element == null || !(element.Class is IFeatureClass)) { return; } _parent = parent; _fcname = element.Title; if (element.Class is IFeatureClass) { _fc = (IFeatureClass)element.Class; switch (_fc.GeometryType) { case geometryType.Envelope: case geometryType.Polygon: _icon = new MsSql2008SpatialSdePolygonIcon(); _type = "Polygon Featureclass"; break; case geometryType.Multipoint: case geometryType.Point: _icon = new MsSql2008SpatialSdePointIcon(); _type = "Point Featureclass"; break; case geometryType.Polyline: _icon = new MsSql2008SpatialSdeLineIcon(); _type = "Polyline Featureclass"; break; default: _icon = new MsSql2008SpatialSdeLineIcon(); _type = "Featureclass"; break; } } }
override public List <IActivityData> Process() { IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; GeometryDef geomDef = new GeometryDef( geometryType.Polygon, null, false); IFeatureClass tFc = base.CreateTargetFeatureclass(geomDef, sFc.Fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); Report.featureMax = sFc.CountFeatures; Report.featurePos = 0; ReportProgess("Query Filter: " + SourceData.FilterClause); using (IFeatureCursor cursor = SourceData.GetFeatures(String.Empty)) { IFeature feature; List <IFeature> features = new List <IFeature>(); ReportProgess("Read/Write Features..."); while ((feature = cursor.NextFeature) != null) { if (feature.Shape is ITopologicalOperation) { feature.Shape = ((ITopologicalOperation)feature.Shape).Buffer(_bufferDistance); } else { continue; } if (feature.Shape == null) { continue; } features.Add(feature); Report.featurePos++; ReportProgess(); if (!CancelTracker.Continue) { break; } if (features.Count > 100) { if (!tDatabase.Insert(tFc, features)) { throw new Exception(tDatabase.lastErrorMsg); } features.Clear(); } } if (features.Count > 0) { ReportProgess(); if (!tDatabase.Insert(tFc, features)) { throw new Exception(tDatabase.lastErrorMsg); } } ReportProgess("Flush Features"); base.FlushFeatureClass(tFc); return(base.ToProcessResult(tFc)); } }
public override List <IActivityData> Process() { IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; IFeatureClass tFc = base.CreateTargetFeatureclass(sFc, sFc.Fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); Report.featureMax = sFc.CountFeatures; Report.featurePos = 0; ReportProgess("Query Filter: " + SourceData.FilterClause); using (IFeatureCursor cursor = SourceData.GetFeatures(String.Empty)) { IFeature feature; List <IFeature> features = new List <IFeature>(); ReportProgess("Read/Write Features..."); while ((feature = cursor.NextFeature) != null) { if (feature.Shape == null) { continue; } List <IGeometry> geometries = new List <IGeometry>(); #region Dissolve if (feature.Shape is IPolygon) { foreach (IPolygon polygon in Algorithm.SplitPolygonToDonutsAndPolygons((IPolygon)feature.Shape)) { geometries.Add(polygon); } } else if (feature.Shape is IPolyline) { foreach (IPath path in Algorithm.GeometryPaths((IPolyline)feature.Shape)) { Polyline pLine = new Polyline(); pLine.AddPath(path); geometries.Add(pLine); } } else if (feature.Shape is IMultiPoint) { for (int i = 0; i < ((IMultiPoint)feature.Shape).PointCount; i++) { IPoint p = ((IMultiPoint)feature.Shape)[i]; if (p != null) { geometries.Add(p); } } } #endregion if (geometries.Count > 0) { foreach (IGeometry geometry in geometries) { Feature f = new Feature(feature); f.Shape = geometry; if (!tDatabase.Insert(tFc, f)) { throw new Exception(tDatabase.lastErrorMsg); } } } } } ReportProgess("Flush Features"); base.FlushFeatureClass(tFc); return(base.ToProcessResult(tFc)); }
override public List <IActivityData> Process() { #region Where Clauses List <string> whereClauses = new List <string>(); if (_mergeField == null) { whereClauses.Add(String.Empty); } else { foreach (object val in _values) { if (val == null) { continue; } switch (_mergeField.type) { case FieldType.smallinteger: case FieldType.integer: case FieldType.biginteger: whereClauses.Add(_mergeField.name + "=" + val.ToString()); break; case FieldType.Float: case FieldType.Double: whereClauses.Add(_mergeField.name + "=" + Convert.ToDouble(val).ToString(_nhi)); break; case FieldType.boolean: whereClauses.Add(_mergeField.name + "=" + val.ToString()); break; case FieldType.String: whereClauses.Add(_mergeField.name + "='" + val.ToString() + "'"); break; default: throw new Exception("Can't merge this fieldtype: " + _mergeField.type.ToString()); } } } #endregion IDatasetElement sElement = base.SourceDatasetElement; IFeatureClass sFc = base.SourceFeatureClass; TargetDatasetElement tElement = base.TargetDatasetElement; IDataset tDs = base.TargetDataset; //IFeatureDatabase tDatabase = base.TargetFeatureDatabase; Fields fields = new Fields(); if (_mergeField != null) { fields.Add(_mergeField); } IFeatureClass tFc = base.CreateTargetFeatureclass(sFc, fields); IFeatureDatabase tDatabase = FeatureDatabase(tFc); Report.featureMax = sFc.CountFeatures; Report.featurePos = 0; bool isPolygonFc = (sFc.GeometryType == geometryType.Polygon); foreach (string whereClause in whereClauses) { ReportProgess("Query Filter: " + SourceData.FilterClause + (String.IsNullOrEmpty(whereClause) ? " AND " + whereClause : String.Empty)); Feature mergeFeature = null;; bool attributeAdded = false; using (IFeatureCursor cursor = SourceData.GetFeatures(whereClause)) { IFeature feature; List <IPolygon> polygons = new List <IPolygon>(); while ((feature = cursor.NextFeature) != null) { if (mergeFeature == null) { mergeFeature = new Feature(); } Report.featurePos++; if (!CancelTracker.Continue) { break; } if (_mergeField != null && attributeAdded == false) { mergeFeature.Fields.Add(new FieldValue(_mergeField.name, feature[_mergeField.name])); attributeAdded = true; } if (isPolygonFc) { if (feature.Shape != null) { if (!(feature.Shape is IPolygon)) { throw new Exception("Wrong argument type :" + feature.Shape.GeometryType.ToString()); } polygons.Add(feature.Shape as IPolygon); } } else { if (mergeFeature.Shape == null) { mergeFeature.Shape = feature.Shape; } else { mergeFeature.Shape = Algorithm.Merge(mergeFeature.Shape, feature.Shape, false); } } ReportProgess(); } if (isPolygonFc && mergeFeature != null) { ProgressReporterEvent r = new ProgressReporterEvent(MergePolygonReport); mergeFeature.Shape = Algorithm.FastMergePolygon(polygons, CancelTracker, r); } } if (mergeFeature != null) { if (!tDatabase.Insert(tFc, mergeFeature)) { throw new Exception(tDatabase.lastErrorMsg); } } if (!CancelTracker.Continue) { break; } } ReportProgess("Flush Features"); base.FlushFeatureClass(tFc); return(base.ToProcessResult(tFc)); }
public void Run() { if (_dataset == null || !(_fdb is IFeatureDatabaseReplication) || _edgeFcs == null) { return; } IFeatureDatabaseReplication db = (IFeatureDatabaseReplication)_fdb; if (_dataset[_networkName] != null) { MessageBox.Show("Featureclass '" + _networkName + "' already exists!"); return; } bool succeeded = false; List <int> FcIds = new List <int>(); try { ProgressReport report = new ProgressReport(); int datasetId = _fdb.DatasetID(_dataset.DatasetName); if (datasetId == -1) { return; } NetworkBuilder networkBuilder = new NetworkBuilder(_dataset.Envelope, _tolerance); if (ReportProgress != null) { networkBuilder.reportProgress += new ProgressReporterEvent(networkBuilder_reportProgress); } #region Spatial Index BinaryTreeDef edgeTreeDef = null, nodeTreeDef = null; foreach (IFeatureClass fc in _edgeFcs) { BinaryTreeDef treeDef = _fdb.BinaryTreeDef(fc.Name); if (treeDef == null) { IEnvelope bounds = fc.Envelope; if (Envelope.IsNull(bounds)) { continue; } treeDef = new BinaryTreeDef(fc.Envelope, 10); } if (edgeTreeDef == null) { edgeTreeDef = new BinaryTreeDef(treeDef.Bounds, Math.Min(treeDef.MaxLevel, 10)); } else { Envelope bounds = edgeTreeDef.Bounds; bounds.Union(treeDef.Bounds); edgeTreeDef = new BinaryTreeDef(bounds, Math.Min(Math.Max(edgeTreeDef.MaxLevel, treeDef.MaxLevel), 10)); } } foreach (IFeatureClass fc in _nodeFcs) { BinaryTreeDef treeDef = _fdb.BinaryTreeDef(fc.Name); if (treeDef == null) { IEnvelope bounds = fc.Envelope; if (Envelope.IsNull(bounds)) { continue; } treeDef = new BinaryTreeDef(fc.Envelope, 10); } if (nodeTreeDef == null) { nodeTreeDef = new BinaryTreeDef(treeDef.Bounds, Math.Min(treeDef.MaxLevel, 10)); } else { Envelope bounds = nodeTreeDef.Bounds; bounds.Union(treeDef.Bounds); nodeTreeDef = new BinaryTreeDef(bounds, Math.Min(Math.Max(nodeTreeDef.MaxLevel, treeDef.MaxLevel), 10)); } } #endregion #region Add Edges foreach (IFeatureClass fc in _edgeFcs) { int fcId = _fdb.FeatureClassID(datasetId, fc.Name); if (fcId == -1) { continue; } FcIds.Add(fcId); bool useOneway = false; QueryFilter filter = new QueryFilter(); filter.AddField(fc.IDFieldName); filter.AddField(fc.ShapeFieldName); if (!String.IsNullOrEmpty(_onewayFieldName) && fc.FindField(_onewayFieldName) != null) { filter.AddField(_onewayFieldName); useOneway = true; } Dictionary <Guid, IGraphWeightFeatureClass> gwfcs = new Dictionary <Guid, IGraphWeightFeatureClass>(); if (_graphWeights != null) { foreach (IGraphWeight weight in _graphWeights) { foreach (IGraphWeightFeatureClass gwfc in weight.FeatureClasses) { if (gwfc.FcId == fcId && !String.IsNullOrEmpty(gwfc.FieldName)) { gwfcs.Add(weight.Guid, gwfc); filter.AddField(gwfc.FieldName); } } } } if (gwfcs.Keys.Count == 0) { gwfcs = null; } bool useWithComplexEdges = false; if (_complexEdgeFcs != null && (_complexEdgeFcs.Contains(fcId) || _complexEdgeFcs.Contains(-1))) { useWithComplexEdges = true; } using (IFeatureCursor cursor = fc.GetFeatures(filter)) { #region Report report.Message = "Analize Edges: " + fc.Name; report.featureMax = fc.CountFeatures; report.featurePos = 0; if (ReportProgress != null) { ReportProgress(report); } #endregion IFeature feature; while ((feature = cursor.NextFeature) != null) { bool oneway = false; if (useOneway) { int ow = Convert.ToInt32(feature[_onewayFieldName]); oneway = (ow != 0); } Hashtable gw = null; if (gwfcs != null) { foreach (Guid weightGuid in gwfcs.Keys) { IGraphWeightFeatureClass gwfc = gwfcs[weightGuid]; object objVal = feature[gwfc.FieldName]; double val = (objVal == DBNull.Value) ? 0.0 : Convert.ToDouble(feature[gwfc.FieldName]); if (gwfc.SimpleNumberCalculation != null) { val = gwfc.SimpleNumberCalculation.Calculate(val); } if (gw == null) { gw = new Hashtable(); } gw.Add(weightGuid, val); } } networkBuilder.AddEdgeFeature(fcId, feature, oneway, gw, useWithComplexEdges); #region Report report.featurePos++; if (report.featurePos % 1000 == 0) { if (ReportProgress != null) { ReportProgress(report); } } #endregion } } } #endregion #region Calculate ComplexEdges if (_complexEdgeFcs != null && _complexEdgeFcs.Count > 0) { List <NetworkNode> networkNodes = networkBuilder.NetworkNodes.ToList(); #region Report report.Message = "Create Complex Edges..."; report.featureMax = networkNodes.Count; report.featurePos = 0; if (ReportProgress != null) { ReportProgress(report); } #endregion foreach (NetworkNode node in networkNodes) { networkBuilder.SplitToComplexEdges(node); #region Report report.featurePos++; if (report.featurePos % 1000 == 0) { if (ReportProgress != null) { ReportProgress(report); } } #endregion } } #endregion #region Add Nodes if (_nodeFcs != null) { foreach (IFeatureClass fc in _nodeFcs) { int fcId = _fdb.FeatureClassID(datasetId, fc.Name); if (fcId == -1) { continue; } FcIds.Add(fcId); bool isSwitchable = false; string switchStateFieldname = String.Empty; if (_switchNodeFcs != null && _switchNodeFcs.ContainsKey(fcId)) { isSwitchable = true; switchStateFieldname = _switchNodeFcs[fcId]; } NetworkNodeType nodeType = NetworkNodeType.Unknown; if (_nodeTypeFcs != null && _nodeTypeFcs.ContainsKey(fcId)) { nodeType = _nodeTypeFcs[fcId]; } QueryFilter filter = new QueryFilter(); filter.AddField(fc.IDFieldName); filter.AddField(fc.ShapeFieldName); filter.AddField(switchStateFieldname); using (IFeatureCursor cursor = fc.GetFeatures(filter)) { #region Report report.Message = "Analize Nodes: " + fc.Name; report.featureMax = fc.CountFeatures; report.featurePos = 0; if (ReportProgress != null) { ReportProgress(report); } #endregion IFeature feature; while ((feature = cursor.NextFeature) != null) { bool switchState = isSwitchable; if (isSwitchable && !String.IsNullOrEmpty(switchStateFieldname)) { object so = feature[switchStateFieldname]; if (so != null) { if (so is bool) { switchState = (bool)so; } else { try { switchState = Convert.ToInt32(so) > 0; } catch { switchState = false; } } } } networkBuilder.AddNodeFeature(fcId, feature, isSwitchable, switchState, nodeType); #region Report report.featurePos++; if (report.featurePos % 1000 == 0) { if (ReportProgress != null) { ReportProgress(report); } } #endregion } } } } #endregion #region CreateGraph #region Report report.Message = "Create Graph"; report.featurePos = 0; if (ReportProgress != null) { ReportProgress(report); } #endregion networkBuilder.CreateGraph(); #endregion #region Create Edge Featureclass #region Simple Edges Table Fields fields = new Fields(); fields.Add(new Field("Page", FieldType.integer)); fields.Add(new Field("Data", FieldType.binary)); db.CreateIfNotExists(_networkName + "_Edges", fields); #endregion #region Edge Index Table fields = new Fields(); fields.Add(new Field("EID", FieldType.integer)); fields.Add(new Field("FCID", FieldType.integer)); fields.Add(new Field("OID", FieldType.integer)); fields.Add(new Field("ISCOMPLEX", FieldType.boolean)); db.CreateIfNotExists(_networkName + "_EdgeIndex", fields); #endregion #region Complex Edges FeatureClass fields = new Fields(); fields.Add(new Field("EID", FieldType.integer)); fields.Add(new Field("N1", FieldType.integer)); fields.Add(new Field("N2", FieldType.integer)); fields.Add(new Field("FCID", FieldType.integer)); fields.Add(new Field("OID", FieldType.integer)); //fields.Add(new Field("Length", FieldType.integer)); //fields.Add(new Field("GeoLength", FieldType.integer)); _fdb.ReplaceFeatureClass(_dataset.DatasetName, _networkName + "_ComplexEdges", new GeometryDef(geometryType.Polyline), fields); IDatasetElement element = _dataset[_networkName + "_ComplexEdges"]; if (element == null || !(element.Class is IFeatureClass)) { return; } if (edgeTreeDef != null) { _fdb.SetSpatialIndexBounds(_networkName + "_ComplexEdges", "BinaryTree2", edgeTreeDef.Bounds, edgeTreeDef.SplitRatio, edgeTreeDef.MaxPerNode, edgeTreeDef.MaxLevel); } #endregion int edge_page = 0; List <IFeature> features = new List <IFeature>(), features2 = new List <IFeature>(); List <IRow> rows = new List <IRow>(); IFeatureClass edgeFc = (IFeatureClass)element.Class; IFeatureCursor c = networkBuilder.Edges; IFeature f; #region Report report.Message = "Create Edges"; if (c is ICount) { report.featureMax = ((ICount)c).Count; } report.featurePos = 0; if (ReportProgress != null) { ReportProgress(report); } #endregion string tabEdgesName = _fdb.TableName(_networkName + "_Edges"); string tabEdgeIndexName = _fdb.TableName(_networkName + "_EdgeIndex"); while ((f = c.NextFeature) != null) { int eid = (int)f["EID"]; if ((bool)f["ISCOMPLEX"] == true) { #region Complex Edges features.Add(f); report.featurePos++; if (features.Count > 0 && features.Count % 1000 == 0) { if (ReportProgress != null) { ReportProgress(report); } _fdb.Insert(edgeFc, features); features.Clear(); } #endregion } #region Edges Table features2.Add(f); if (NetworkObjectSerializer.Page(eid + 1) > edge_page) { IRow row = new Row(); row.Fields.Add(new FieldValue("Page", edge_page++)); row.Fields.Add(new FieldValue("Data", NetworkObjectSerializer.SerializeEdges(features2))); db.InsertRow(tabEdgesName, row, null); features2.Clear(); } #endregion #region Edge Index IRow eir = new Row(); eir.Fields.Add(new FieldValue("EID", (int)f["EID"])); eir.Fields.Add(new FieldValue("FCID", (int)f["FCID"])); eir.Fields.Add(new FieldValue("OID", (int)f["OID"])); eir.Fields.Add(new FieldValue("ISCOMPLEX", (bool)f["ISCOMPLEX"])); rows.Add(eir); if (rows.Count > 0 && rows.Count % 1000 == 0) { _fdb.InsertRows(tabEdgeIndexName, rows, null); rows.Clear(); } #endregion } if (rows.Count > 0) { _fdb.InsertRows(tabEdgeIndexName, rows, null); rows.Clear(); } if (features2.Count > 0) { IRow row = new Row(); row.Fields.Add(new FieldValue("Page", edge_page)); row.Fields.Add(new FieldValue("Data", NetworkObjectSerializer.SerializeEdges(features2))); db.InsertRow(tabEdgesName, row, null); features2.Clear(); } if (features.Count > 0) { if (ReportProgress != null) { ReportProgress(report); } _fdb.Insert(edgeFc, features); } _fdb.CalculateExtent(edgeFc); #endregion #region Create Weights if (_graphWeights != null) { foreach (IGraphWeight weight in _graphWeights) { fields = new Fields(); fields.Add(new Field("Page", FieldType.integer)); fields.Add(new Field("Data", FieldType.binary)); db.CreateIfNotExists(_networkName + "_Weights_" + weight.Guid.ToString("N").ToLower(), fields); string tabWeightName = _fdb.TableName(_networkName + "_Weights_" + weight.Guid.ToString("N").ToLower()); NetworkEdges edges = networkBuilder.NetworkEdges; int weight_page = 0; int counter = 0; BinaryWriter bw = NetworkObjectSerializer.GetBinaryWriter(); foreach (NetworkEdge edge in edges) { counter++; if (NetworkObjectSerializer.Page(counter) > weight_page) { IRow row = new Row(); row.Fields.Add(new FieldValue("Page", weight_page++)); row.Fields.Add(new FieldValue("Data", NetworkObjectSerializer.GetBuffer(bw))); db.InsertRow(tabWeightName, row, null); bw = NetworkObjectSerializer.GetBinaryWriter(); } if (edge.Weights != null && edge.Weights.ContainsKey(weight.Guid)) { NetworkObjectSerializer.WriteWeight(bw, weight, (double)edge.Weights[weight.Guid]); } else { NetworkObjectSerializer.WriteWeight(bw, weight, (double)0.0); } } if (bw.BaseStream.Position > 0) { IRow row = new Row(); row.Fields.Add(new FieldValue("Page", weight_page++)); row.Fields.Add(new FieldValue("Data", NetworkObjectSerializer.GetBuffer(bw))); db.InsertRow(tabWeightName, row, null); } } } #endregion #region Create Node Featureclass fields = new Fields(); //fields.Add(new Field("NID", FieldType.integer)); //fields.Add(new Field("G1", FieldType.integer)); //fields.Add(new Field("G2", FieldType.integer)); fields.Add(new Field("SWITCH", FieldType.boolean)); fields.Add(new Field("STATE", FieldType.boolean)); fields.Add(new Field("FCID", FieldType.integer)); fields.Add(new Field("OID", FieldType.integer)); fields.Add(new Field("NODETYPE", FieldType.integer)); _fdb.ReplaceFeatureClass(_dataset.DatasetName, _networkName + "_Nodes", new GeometryDef(geometryType.Point), fields); element = _dataset[_networkName + "_Nodes"]; if (element == null || !(element.Class is IFeatureClass)) { return; } if (nodeTreeDef != null) { _fdb.SetSpatialIndexBounds(_networkName + "_Nodes", "BinaryTree2", nodeTreeDef.Bounds, nodeTreeDef.SplitRatio, nodeTreeDef.MaxPerNode, nodeTreeDef.MaxLevel); } else if (edgeTreeDef != null) { _fdb.SetSpatialIndexBounds(_networkName + "_Nodes", "BinaryTree2", edgeTreeDef.Bounds, edgeTreeDef.SplitRatio, edgeTreeDef.MaxPerNode, edgeTreeDef.MaxLevel); } features.Clear(); IFeatureClass nodeFc = (IFeatureClass)element.Class; c = networkBuilder.Nodes; #region Report report.Message = "Create Nodes"; if (c is ICount) { report.featureMax = ((ICount)c).Count; } report.featurePos = 0; if (ReportProgress != null) { ReportProgress(report); } #endregion while ((f = c.NextFeature) != null) { features.Add(f); report.featurePos++; if (features.Count > 0 && features.Count % 1000 == 0) { if (ReportProgress != null) { ReportProgress(report); } _fdb.Insert(nodeFc, features); features.Clear(); } } if (features.Count > 0) { if (ReportProgress != null) { ReportProgress(report); } _fdb.Insert(nodeFc, features); } _fdb.CalculateExtent(nodeFc); #endregion #region Create Graph Class int graph_page = 0; fields = new Fields(); fields.Add(new Field("Page", FieldType.integer)); fields.Add(new Field("Data", FieldType.binary)); //fields.Add(new Field("N1", FieldType.integer)); //fields.Add(new Field("N2", FieldType.integer)); //fields.Add(new Field("EID", FieldType.integer)); //fields.Add(new Field("LENGTH", FieldType.Double)); //fields.Add(new Field("GEOLENGTH", FieldType.Double)); _fdb.ReplaceFeatureClass(_dataset.DatasetName, _networkName, new GeometryDef(geometryType.Network), fields); element = _dataset[_networkName]; if (element == null || !(element.Class is IFeatureClass)) { return; } features.Clear(); IFeatureClass networkFc = (IFeatureClass)element.Class; c = networkBuilder.Graph; #region Report report.Message = "Create Network"; if (c is ICount) { report.featureMax = ((ICount)c).Count; } report.featurePos = 0; if (ReportProgress != null) { ReportProgress(report); } #endregion string fcNetworkName = _fdb.TableName("FC_" + _networkName); while ((f = c.NextFeature) != null) { report.featurePos++; // Wenn aktuelles Feature in neue Page gehört -> // bestehende, vor neuem Einfügen speichern und pageIndex erhöhen (graph_page++) if (NetworkObjectSerializer.Page((int)f["N1"]) > graph_page) { if (ReportProgress != null) { ReportProgress(report); } IRow row = new Row(); row.Fields.Add(new FieldValue("Page", graph_page++)); row.Fields.Add(new FieldValue("Data", NetworkObjectSerializer.SerializeGraph(features))); db.InsertRow(fcNetworkName, row, null); features.Clear(); } features.Add(f); } if (features.Count > 0) { IRow row = new Row(); row.Fields.Add(new FieldValue("Page", graph_page)); row.Fields.Add(new FieldValue("Data", NetworkObjectSerializer.SerializeGraph(features))); db.InsertRow(fcNetworkName, row, null); features.Clear(); } #endregion #region Create FDB_Networks int netId = _fdb.GetFeatureClassID(_networkName); fields = new Fields(); fields.Add(new Field("ID", FieldType.integer)); fields.Add(new Field("Properties", FieldType.binary)); db.CreateIfNotExists("FDB_Networks", fields); NetworkObjectSerializer.NetworkProperties networkProps = new NetworkObjectSerializer.NetworkProperties( NetworkObjectSerializer.PageSize, _tolerance); IRow row2 = new Row(); row2.Fields.Add(new FieldValue("ID", netId)); row2.Fields.Add(new FieldValue("Properties", networkProps.Serialize())); db.InsertRow(_fdb.TableName("FDB_Networks"), row2, null); #endregion #region Create FDB_NetworkClasses fields = new Fields(); fields.Add(new Field("NetworkId", FieldType.integer)); fields.Add(new Field("FCID", FieldType.integer)); fields.Add(new Field("Properties", FieldType.binary)); db.CreateIfNotExists("FDB_NetworkClasses", fields); foreach (int fcId in FcIds) { bool isSwitchable = (_switchNodeFcs != null && _switchNodeFcs.ContainsKey(fcId)); string switchStateFieldname = (isSwitchable ? _switchNodeFcs[fcId] : String.Empty); NetworkObjectSerializer.NetworkClassProperties nwclsProps = new NetworkObjectSerializer.NetworkClassProperties( _complexEdgeFcs.Contains(fcId), isSwitchable, switchStateFieldname); IRow row = new Row(); row.Fields.Add(new FieldValue("NetworkId", netId)); row.Fields.Add(new FieldValue("FCID", fcId)); row.Fields.Add(new FieldValue("Properties", nwclsProps.Serialize())); db.InsertRow(_fdb.TableName("FDB_NetworkClasses"), row, null); } #endregion #region FDB_NetworkWeighs fields = new Fields(); fields.Add(new Field("NetworkId", FieldType.integer)); fields.Add(new Field("Name", FieldType.String)); fields.Add(new Field("WeightGuid", FieldType.guid)); fields.Add(new Field("Properties", FieldType.binary)); db.CreateIfNotExists("FDB_NetworkWeights", fields); if (_graphWeights != null) { foreach (IGraphWeight weight in _graphWeights) { IRow row = new Row(); row.Fields.Add(new FieldValue("NetworkId", netId)); row.Fields.Add(new FieldValue("Name", weight.Name)); row.Fields.Add(new FieldValue("WeightGuid", weight.Guid)); row.Fields.Add(new FieldValue("Properties", NetworkObjectSerializer.SerializeWeight(weight))); db.InsertRow(_fdb.TableName("FDB_NetworkWeights"), row, null); } } #endregion succeeded = true; } catch (Exception ex) { MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error); } finally { if (!succeeded) { if (_fdb is IAlterDatabase) { ((IAlterDatabase)_fdb).DropTable(_networkName + "_Edges"); } _fdb.DeleteFeatureClass(_networkName + "_ComplexEdges"); _fdb.DeleteFeatureClass(_networkName + "_Nodes"); _fdb.DeleteFeatureClass(_networkName); } } }
public AccessFDBFeatureClassExplorerObject(AccessFDBDatasetExplorerObject parent, string filename, string dsname, IDatasetElement element) : base(parent, typeof(FeatureClass)) { if (element == null) { return; } _parent = parent; _filename = filename; _dsname = dsname; _fcname = element.Title; string typePrefix = String.Empty; bool isLinked = false; if (element.Class is LinkedFeatureClass) { typePrefix = "Linked "; isLinked = true; } if (element.Class is IRasterCatalogClass) { _icon = new AccessFDBRasterIcon(); _type = typePrefix + "Raster Catalog Layer"; _rc = (IRasterClass)element.Class; } else if (element.Class is IRasterClass) { _icon = new AccessFDBRasterIcon(); _type = typePrefix + "Raster Layer"; _rc = (IRasterClass)element.Class; } else if (element.Class is IFeatureClass) { _fc = (IFeatureClass)element.Class; switch (_fc.GeometryType) { case geometryType.Envelope: case geometryType.Polygon: if (isLinked) { _icon = new AccessFDBLinkedPolygonIcon(); } else { _icon = new AccessFDBPolygonIcon(); } _type = typePrefix + "Polygon Featureclass"; break; case geometryType.Multipoint: case geometryType.Point: if (isLinked) { _icon = new AccessFDBLinkedPointIcon(); } else { _icon = new AccessFDBPointIcon(); } _type = typePrefix + "Point Featureclass"; break; case geometryType.Polyline: if (isLinked) { _icon = new AccessFDBLinkedLineIcon(); } else { _icon = new AccessFDBLineIcon(); } _type = typePrefix + "Polyline Featureclass"; break; } } _contextItems = new ToolStripItem[1]; _contextItems[0] = new ToolStripMenuItem("Tasks"); //_contextItems = new ToolStripItem[1]; //_contextItems[0] = new ToolStripMenuItem("Rebuild Spatial Index..."); //_contextItems[0].Click += new EventHandler(RebuildSpatialIndex_Click); ToolStripMenuItem item = new ToolStripMenuItem("Shrink Spatial Index..."); item.Click += new EventHandler(ShrinkSpatialIndex_Click); ((ToolStripMenuItem)_contextItems[0]).DropDownItems.Add(item); item = new ToolStripMenuItem("Spatial Index Definition..."); item.Click += new EventHandler(SpatialIndexDef_Click); ((ToolStripMenuItem)_contextItems[0]).DropDownItems.Add(item); item = new ToolStripMenuItem("Repair Spatial Index..."); item.Click += new EventHandler(RepairSpatialIndex_Click); ((ToolStripMenuItem)_contextItems[0]).DropDownItems.Add(item); ((ToolStripMenuItem)_contextItems[0]).DropDownItems.Add(new ToolStripSeparator()); item = new ToolStripMenuItem("Truncate"); item.Click += new EventHandler(Truncate_Click); ((ToolStripMenuItem)_contextItems[0]).DropDownItems.Add(item); }
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); } } }
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); }
internal void Init(string CapabilitiesString, WFSDataset wfsDataset) { try { _themes = new List <IWebServiceTheme>(); XmlDocument doc = new XmlDocument(); doc.LoadXml(CapabilitiesString); XmlNode CapabilitiesNode = doc.SelectSingleNode("WMT_MS_Capabilities/Capability"); _getCapabilities = new GetCapabilities(CapabilitiesNode.SelectSingleNode("Request/GetCapabilities")); _getMap = new GetMap(CapabilitiesNode.SelectSingleNode("Request/GetMap")); _getFeatureInfo = new GetFeatureInfo(CapabilitiesNode.SelectSingleNode("Request/GetFeatureInfo")); _describeLayer = new DescribeLayer(CapabilitiesNode.SelectSingleNode("Request/DescribeLayer")); _getLegendGraphic = new GetLegendGraphic(CapabilitiesNode.SelectSingleNode("Request/GetLegendGraphic")); _getStyles = new GetStyles(CapabilitiesNode.SelectSingleNode("Request/GetStyles")); _exceptions = new WMSExceptions(CapabilitiesNode.SelectSingleNode("Exception")); _userDefinedSymbolization = new UserDefinedSymbolization(CapabilitiesNode.SelectSingleNode("UserDefinedSymbolization")); XmlNode service = CapabilitiesNode.SelectSingleNode("Layer"); XmlNode title = service.SelectSingleNode("Title"); if (title != null) { _name = title.InnerText; } _srs = new SRS(service); this.SRSCode = _srs.Srs[_srs.SRSIndex]; foreach (XmlNode layer in service.SelectNodes("Layer")) { string name = "", Title = ""; XmlNode nameNode = layer.SelectSingleNode("Name"); XmlNode titleNode = layer.SelectSingleNode("Title"); if (nameNode == null) { continue; } name = Title = nameNode.InnerText; if (titleNode != null) { Title = titleNode.InnerText; } XmlNodeList styles = layer.SelectNodes("Style"); WFSFeatureClass wfsFc = null; if (wfsDataset != null) { IDatasetElement wfsElement = wfsDataset[name]; if (wfsElement != null && wfsElement.Class is WFSFeatureClass) { wfsFc = wfsElement.Class as WFSFeatureClass; } } if (styles.Count == 0) { IClass wClass = null; if (wfsFc != null) { wClass = wfsFc; } else if (layer.Attributes["queryable"] != null && layer.Attributes["queryable"].Value == "1") { wClass = new WMSQueryableThemeClass(_dataset, name, String.Empty, layer, _getFeatureInfo, _srs, _exceptions); } else { wClass = new WMSThemeClass(_dataset, name, String.Empty, layer); } IWebServiceTheme theme; if (wClass is WFSFeatureClass) { theme = new WebServiceTheme2( wClass, Title, name, true, this); } else { theme = new WebServiceTheme( wClass, Title, name, true, this ); } _themes.Add(theme); } else { foreach (XmlNode style in styles) { string sName = "", sTitle = ""; XmlNode sNameNode = style.SelectSingleNode("Name"); XmlNode sTitleNode = style.SelectSingleNode("Title"); if (sNameNode == null) { continue; } sName = sTitle = sNameNode.InnerText; if (sTitleNode != null) { sTitle = sTitleNode.InnerText; } IClass wClass = null; if (wfsFc is WFSFeatureClass) { wClass = wfsFc; ((WFSFeatureClass)wClass).Style = sName; } else if (layer.Attributes["queryable"] != null && layer.Attributes["queryable"].Value == "1") { wClass = new WMSQueryableThemeClass(_dataset, name, sName, layer, _getFeatureInfo, _srs, _exceptions); } else { wClass = new WMSThemeClass(_dataset, name, sName, layer); } IWebServiceTheme theme; if (wClass is WFSFeatureClass) { theme = new WebServiceTheme2( wClass, Title + " (Style=" + sTitle + ")", name, true, this); } else { theme = new WebServiceTheme( wClass, Title + " (Style=" + sTitle + ")", name, true, this ); } _themes.Add(theme); } } } doc = null; } catch (Exception ex) { string errMsg = ex.Message; } }
public RelationTreeNode(IMapDocument mapDocument, ITableRelation tableRelation, IDatasetElement element) { _mapDocument = mapDocument; this.TableRelation = tableRelation; this.DatasetElement = element; IDatasetElement target = (tableRelation.LeftTable == element) ? tableRelation.RightTable : tableRelation.LeftTable; base.Text = tableRelation.RelationName + " (" + target.Title + ")"; base.Click += new EventHandler(RelationTreeNode_Click); }
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); } }