protected override void OnClick()
        {
            //
            //  TODO: Sample code showing how to access button host
            //
            ArcMap.Application.CurrentTool = null;

            IMap map = ArcMap.Document.ActivatedView.FocusMap;

            //Check to make sure the map contains a layer
            if (map.LayerCount < 1)
            {
                MessageBox.Show("Must have a layer in your map...");
                return;
            }

            //Get the selected layer
            ILayer selectedLayer = ArcMap.Document.SelectedLayer;
            //Checl that there is a selected layer in the table of contents
            if (selectedLayer == null)
            {
                MessageBox.Show("You must have a layer highlighted in the table of contents.");
                return;
            }
            //Check that the selected layer is a featuer layer
            if (!(selectedLayer is IFeatureLayer))
            {
                MessageBox.Show("The highlighted layer in the TOC must be a feature layer.");
                return;
            }

            IFeatureLayer featureLayer = selectedLayer as IFeatureLayer;
            IFeatureClass featureClass = featureLayer.FeatureClass;
            //Check that the features shape is a line
            if (featureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
            {
                MessageBox.Show("The highlighted layer in the TOC must be a polyline.");
                return;
            }
            //Check that features are selected in the table of contents
            IFeatureSelection featureSelection = featureLayer as IFeatureSelection;
            if (featureSelection.SelectionSet.Count < 1)
            {
                MessageBox.Show("The highlighted layer in the TOC must have some features selected.");
                return;
            }

            ISelectionSet2 selectionSet = featureSelection.SelectionSet as ISelectionSet2;

            int streetFieldIndex = featureClass.FindField(sStreetFldName);
            //Check that the street name exists in the table.
            if (streetFieldIndex < 0)
            {
                MessageBox.Show(sStreetFldName + " was not found in highlighted layer.");
                return;
            }

            int crossA = featureClass.FindField(sCrossAFldName);
            //Check that the cross from field was found in the table
            if (crossA < 1)
            {
                MessageBox.Show(sCrossAFldName + " was not found in highlighted layer.");
                return;
            }
            //Check that the cross to field was found in the table
            int crossB = featureClass.FindField(sCrossBFldName);
            if (crossB < 1)
            {
                MessageBox.Show(sCrossBFldName + " was not found in highlighted layer.");
                return;
            }
            //Find the editor
            UID id = new UID();
            id.Value = "esriEditor.Editor";

            IApplication application = ArcMap.Application;
            IEditor3 editorExtension = application.FindExtensionByCLSID(id) as IEditor3;
            //Make sure that an active edit session is happening
            if (!(editorExtension.EditState == esriEditState.esriStateEditing))
            {
                MessageBox.Show("Must be in an edit session");
                return;
            }
            //Update the status bar
            application.StatusBar.Message[0] = "Populating Cross Streets...";
            editorExtension.StartOperation();
            IQueryFilter queryFilter = new QueryFilter();
            queryFilter.AddField(sCrossAFldName);
            queryFilter.AddField(sCrossBFldName);
            ICursor featureCursor;
            selectionSet.Update(null, false, out featureCursor);
            IFeature feature = featureCursor.NextRow() as IFeature;
            string total = selectionSet.Count.ToString();
            int count = 0;
            //Iterate through the features until all of the selected ones have been tested
            do
            {
                count++;
                application.StatusBar.Message[0] = "Populating cross streets... " + count.ToString() + " of " + total;
                string street = feature.Value[streetFieldIndex] as string;
                IGeometry geometry = feature.Shape;
                ICurve curve = geometry as ICurve;
                IPoint point = curve.FromPoint;
                string sCrossA = FindStreets(point, featureClass, streetFieldIndex, street, sJoin);
                point = curve.ToPoint;
                string sCrossB = FindStreets(point, featureClass, streetFieldIndex, street, sJoin);

                feature.Value[crossA] = sCrossA;
                feature.Value[crossB] = sCrossB;
                IRow row = feature;

                featureCursor.UpdateRow(feature);

                feature = featureCursor.NextRow() as IFeature;
            } while (!(feature == null));
            editorExtension.StopOperation("Populate Cross Streets");
        }
Example #2
0
        private 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 = 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 = 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);
        }
        protected override void OnClick()
        {
            try
            {
                if (_wkspHelper.CurrentWorkspace == null)
                {
                    MessageBox.Show("You must select and open a telecom workspace before running this tool");
                    return;
                }

                DialogResult res = MessageBox.Show(null, "This test may run for a considerable time (15+ minutes) and may make modifications to the database to resolve issues. \n\nConsider taking a backup before doing this. \n\nDo you wish to proceed?", "DB Integrity Check", MessageBoxButtons.OKCancel);
                if (res != DialogResult.OK)
                    return;

                IFeatureClass cableFc = _wkspHelper.FindFeatureClass(ConfigUtil.FiberCableFtClassName);
                if (cableFc == null) { return; }

                IFeatureWorkspace fworkspace =_wkspHelper.CurrentWorkspace;
                if (fworkspace == null) { return; }

                // --------------------------------------------
                // Check the integrity of the cable feature class
                // --------------------------------------------
                IRelationshipClass fiberCableToFiberRc = fworkspace.OpenRelationshipClass(ConfigUtil.FiberCableToFiberRelClassName);
                IRelationshipClass fiberCableToBufferRc = fworkspace.OpenRelationshipClass(ConfigUtil.FiberCableToBufferRelClassName);
                IFeature feature;
                bool badCable = false;
                bool badBuffers = false;
                bool badFibers = false;
                bool conversionRequired = false;
                IWorkspaceEdit2 edit = fworkspace as IWorkspaceEdit2;
                ITransactions transaction = edit as ITransactions;

                edit.StartEditing(true);
                edit.StartEditOperation();

                IQueryFilter qf = new QueryFilter();
                qf.AddField(ConfigUtil.NumberOfBuffersFieldName);
                qf.AddField(ConfigUtil.NumberOfFibersFieldName);
                qf.AddField(ConfigUtil.IpidFieldName);

                using (ComReleaser comReleaser = new ComReleaser())
                {
                    IFeatureCursor fCursor = (IFeatureCursor)cableFc.Update(qf, false);
                    ICursor pCursor = fCursor as ICursor;
                    comReleaser.ManageLifetime(fCursor);

                    int buffersFieldIdx = cableFc.FindField(ConfigUtil.NumberOfBuffersFieldName);
                    int fibersFieldIdx = cableFc.FindField(ConfigUtil.NumberOfFibersFieldName);
                    int ipidFieldIdx = cableFc.FindField(ConfigUtil.IpidFieldName);

                    int count = 0;
                    while ((feature = fCursor.NextFeature()) != null)
                    {
                        // Cables should have non null field values
                        if (feature.get_Value(ipidFieldIdx) == DBNull.Value)
                        {
                            badCable = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with NULL IPID value");
                            continue;
                        }
                        if (feature.get_Value(buffersFieldIdx) == DBNull.Value)
                        {
                            badBuffers = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with NULL buffer field value", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            continue;
                        }
                        if (feature.get_Value(fibersFieldIdx) == DBNull.Value)
                        {
                            badFibers = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with NULL fiber field value", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            continue;
                        }

                        int bufferCount = (int)feature.get_Value(buffersFieldIdx);
                        int fiberCount = (int)feature.get_Value(fibersFieldIdx);

                        // Cables should have non zero values
                        if (bufferCount == 0)
                        {
                            badBuffers = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with 0 buffer field value", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            continue;
                        }
                        if (fiberCount == 0)
                        {
                            badFibers = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with 0 strand field value", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            continue;
                        }

                        // Cables should have relationships
                        int rcBufferCount = fiberCableToBufferRc.GetObjectsRelatedToObject(feature).Count;
                        if (rcBufferCount == 0)
                        {
                            badBuffers = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with 0 related buffers", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            continue;
                        }
                        int rcFiberCount = fiberCableToFiberRc.GetObjectsRelatedToObject(feature).Count;
                        if (rcFiberCount == 0)
                        {
                            badFibers = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with 0 related fibers", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            continue;
                        }

                        // Buffer field count & relationships to buffers not matching
                        if (bufferCount != rcBufferCount)
                        {
                            badBuffers = true;
                            String output = "Expected: " + bufferCount + " Found: " + rcBufferCount + " Cable ID: " + feature.get_Value(ipidFieldIdx).ToString();
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Found Fiber Cable with buffer count->relationship mismatch", output);
                            continue;
                        }

                        // other checks
                        if (rcFiberCount % rcBufferCount != 0)
                        {
                            badFibers = true;
                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Fiber Cable with invalid strand count - (relationships % buffercount) is non zero", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            continue;
                        }

                        // we must be dealing with a total count (convert to per buffer tube value)
                        if (fiberCount == rcFiberCount && bufferCount > 1)
                        {
                            count++;
                            Debug.Write(count + " Strand Total to Strands Per Buffer conversion", " Cable ID: " + feature.get_Value(ipidFieldIdx).ToString() + "\n");
                            conversionRequired = true;
                            //                            _logHelper.addLogEntry(DateTime.Now.ToString(), "INTEGRITY", "Strand Total to Strands Per Buffer conversion", "Cable ID: " + feature.get_Value(ipidFieldIdx).ToString());
                            feature.set_Value(fibersFieldIdx, rcFiberCount / rcBufferCount);
                            feature.Store();
                        }
                    }
                }
                edit.StopEditOperation();
                edit.StopEditing(true);

                if (badCable)
                    MessageBox.Show("Database integrity issues were detected. Found invalid Fiber Cable. Please see the log file for more details");
                if (badBuffers)
                    MessageBox.Show("Database integrity issues were detected. Found Fiber Cable with buffer count issues. Please see the log file for more details");
                if (badFibers)
                    MessageBox.Show("Database integrity issues were detected. Found Fiber Cable with strands count issues. Please see the log file for more details");
                if (conversionRequired)
                    MessageBox.Show("Database integrity issues were detected. Strand Total to Strands Per Buffer conversion was done.");
            }
            catch (Exception e)
            {
                _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Integrity Check Error", e.Message);
            }

            MessageBox.Show("The results of the DB checks are listed in the tools Log window");
        }
Example #4
0
        async void worker2_DoWork(object sender, DoWorkEventArgs e)
        {
            if (_theme == null || _theme.Nodes == null || _theme.Nodes.Count == 0 || _userdefValues == null)
            {
                return;
            }

            if (_parent == null || _parent.MapDocument == null ||
                _parent.MapDocument.FocusMap == null ||
                _parent.MapDocument.FocusMap.Display == null)
            {
                return;
            }

            ISpatialReference sRef =
                (_parent.MapDocument.FocusMap.Display.SpatialReference != null) ?
                _parent.MapDocument.FocusMap.Display.SpatialReference.Clone() as ISpatialReference :
                null;

            try
            {
                StartProgress();

                foreach (QueryThemeTable table in _theme.Nodes)
                {
                    if (table.QueryFieldDef == null)
                    {
                        continue;
                    }

                    IFeatureLayer layer = table.GetLayer(_parent._doc) as IFeatureLayer;
                    if (layer == null || !(layer.Class is IFeatureClass))
                    {
                        continue;
                    }

                    IFeatureClass fc = layer.Class as IFeatureClass;

                    #region SQL
                    StringBuilder sql         = new StringBuilder();
                    int           actPromptID = -99;
                    foreach (DataRow fieldDef in table.QueryFieldDef.Select("", "Prompt"))
                    {
                        string logic = " OR ";
                        if ((int)fieldDef["Prompt"] != actPromptID)
                        {
                            actPromptID = (int)fieldDef["Prompt"];
                            logic       = ") AND (";
                        }

                        string val = "";
                        if (!_userdefValues.TryGetValue((int)fieldDef["Prompt"], out val))
                        {
                            continue;
                        }

                        if (val == "")
                        {
                            continue;
                        }

                        val = val.Replace("*", "%");

                        IField field = fc.FindField(fieldDef["Field"].ToString());
                        if (field == null)
                        {
                            continue;
                        }

                        switch (field.type)
                        {
                        case FieldType.biginteger:
                        case FieldType.Double:
                        case FieldType.Float:
                        case FieldType.smallinteger:
                        case FieldType.integer:
                            if (IsNumeric(val))
                            {
                                if (sql.Length > 0)
                                {
                                    sql.Append(logic);
                                }

                                sql.Append(field.name + fieldDef["Operator"] + val);
                            }
                            break;

                        case FieldType.String:
                            string op = fieldDef["Operator"].ToString();
                            string v  = val;
                            if (v.IndexOf("%") != -1)
                            {
                                op = " like ";
                            }
                            else if (op.ToLower() == " like ")
                            {
                                v += "%";
                            }
                            if (sql.Length > 0)
                            {
                                sql.Append(logic);
                            }

                            sql.Append(field.name + op + "'" + v + "'");
                            break;
                        }
                    }
                    if (sql.Length == 0)
                    {
                        continue;
                    }

                    sql.Insert(0, "(");
                    sql.Append(")");
                    #endregion

                    if (!_cancelTracker.Continue)
                    {
                        return;
                    }

                    #region Layer Title
                    string title = fc.Name;
                    if (_focusMap != null && _focusMap.TOC != null)
                    {
                        ITOCElement tocElement = _focusMap.TOC.GetTOCElement(layer);
                        if (tocElement != null)
                        {
                            title = tocElement.Name;
                        }
                    }
                    #endregion

                    #region Fields
                    Fields fields = null;
                    IField primaryDisplayField = null;

                    if (layer != null && layer.Fields != null && table.VisibleFieldDef != null && table.VisibleFieldDef.UseDefault == false)
                    {
                        fields = new Fields();

                        foreach (IField field in layer.Fields.ToEnumerable())
                        {
                            if (table.VisibleFieldDef.PrimaryDisplayField == field.name)
                            {
                                primaryDisplayField = field;
                            }

                            DataRow[] r = table.VisibleFieldDef.Select("Visible=true AND Name='" + field.name + "'");
                            if (r.Length == 0)
                            {
                                continue;
                            }

                            Field f = new Field(field);
                            f.visible   = true;
                            f.aliasname = (string)r[0]["Alias"];
                            fields.Add(f);
                        }
                    }
                    #endregion

                    #region QueryFilter
                    QueryFilter filter = new QueryFilter();
                    if (fields == null)
                    {
                        filter.SubFields = "*";
                    }
                    else
                    {
                        foreach (IField field in fields.ToEnumerable())
                        {
                            if (!field.visible)
                            {
                                continue;
                            }

                            filter.AddField(field.name);
                        }
                        if (primaryDisplayField != null)
                        {
                            filter.AddField(primaryDisplayField.name);
                        }

                        if (layer is IFeatureLayer && ((IFeatureLayer)layer).FeatureClass != null)
                        {
                            filter.AddField(((IFeatureLayer)layer).FeatureClass.ShapeFieldName);
                        }
                    }

                    filter.WhereClause             = sql.ToString();
                    filter.FeatureSpatialReference = _parent.MapDocument.FocusMap.Display.SpatialReference;
                    #endregion

                    SetMsgText("Query Table " + title, 1);
                    SetMsgText("", 2);

                    #region Query
                    using (IFeatureCursor cursor = await fc.Search(filter) as IFeatureCursor)
                    {
                        if (cursor == null)
                        {
                            continue;
                        }

                        int             counter = 0;
                        IFeature        feature;
                        List <IFeature> features = new List <IFeature>();
                        while ((feature = await cursor.NextFeature()) != null)
                        {
                            if (!_cancelTracker.Continue)
                            {
                                return;
                            }
                            //this.AddFeature(feature, fc.SpatialReference, title);
                            features.Add(feature);
                            counter++;
                            if (counter % 100 == 0)
                            {
                                SetMsgText(counter + " Features...", 2);
                                ManualResetEvent resetEvent = new ManualResetEvent(false);

                                this.AddFeature(features, sRef, layer, title, fields, primaryDisplayField, resetEvent);
                                features = new List <IFeature>();

                                resetEvent.WaitOne();
                            }
                        }
                        if (features.Count > 0)
                        {
                            this.AddFeature(features, sRef, layer, title, fields, primaryDisplayField, null);
                        }
                    }
                    #endregion
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                StopProgress();
            }
        }
Example #5
0
        public ShapeFeatureCursor(IFeatureClass fc, SHPFile file, IQueryFilter filter, IIndexTree tree)
            : base((fc != null) ? fc.SpatialReference : null,
                   (filter != null) ? filter.FeatureSpatialReference : null)
        {
            base.KnowsFunctions = false;

            if (file == null)
            {
                return;
            }

            _file = new SHPFile(file);

            _filter = filter;
            if (filter is ISpatialFilter)
            {
                IEnvelope env = ((ISpatialFilter)filter).Geometry.Envelope;
                if (tree != null)
                {
                    _IDs = tree.FindShapeIds(env);
                    _IDs.Sort();
                }
                //_IDs = tree.FindShapeIds(env);
                _bounds        = new Envelope(env);
                _spatialFilter = filter as ISpatialFilter;
                _queryGeometry = ((ISpatialFilter)filter).Geometry;
                _queryShape    = true;
            }
            else
            {
                foreach (string fname in filter.SubFields.Split(' '))
                {
                    if (fname == "SHAPE" || fname == "*")
                    {
                        _queryShape = true;
                        break;
                    }
                }
            }

            if (filter.WhereClause != "" && _filter.SubFields != "*" && !(filter is IRowIDFilter))
            {
                //StringBuilder sb = new StringBuilder();
                //sb.Append("FID");

                QueryFilter f = new QueryFilter();
                f.SubFields = _filter.SubFields;
                foreach (IField field in _file.Fields.ToEnumerable())
                {
                    if (field.name == "FID")
                    {
                        continue;
                    }

                    if (filter.WhereClause.IndexOf(" " + field.name + " ") != -1 ||
                        filter.WhereClause.IndexOf("(" + field.name + " ") != -1 ||
                        filter.WhereClause.IndexOf(" " + field.name + "=") != -1 ||
                        filter.WhereClause.IndexOf("(" + field.name + "=") != -1 ||
                        filter.WhereClause.IndexOf(" " + field.name + "<") != -1 ||
                        filter.WhereClause.IndexOf("(" + field.name + "<") != -1 ||
                        filter.WhereClause.IndexOf(" " + field.name + ">") != -1 ||
                        filter.WhereClause.IndexOf("(" + field.name + ">") != -1 ||
                        filter.WhereClause.IndexOf("[" + field.name + "]") != -1 ||
                        filter.WhereClause.IndexOf(field.name + " ") == 0 ||
                        filter.WhereClause.IndexOf(field.name + "=") == 0 ||
                        filter.WhereClause.IndexOf(field.name + "<") == 0 ||
                        filter.WhereClause.IndexOf(field.name + ">") == 0
                        )
                    {
                        f.AddField(field.name);
                    }
                }

                /*
                 * _dataReader = _file.DBFDataReader(sb.ToString());
                 * for (uint i = 1; i <= _file.Entities; i++)
                 *  _dataReader.AddRecord(i);
                 *
                 * DataRow [] rows=_dataReader.Table.Select(_filter.WhereClause);
                 *
                 * _IDs = new ArrayList();
                 * foreach (DataRow row in rows)
                 * {
                 *  uint id=_file.GetIndexFromRecNumber((uint)row["FID"]);
                 *  _IDs.Add((int)id);
                 * }
                 * _dataReader.Dispose();
                 */

                _dataReader = _file.DBFDataReader(f.SubFields.Replace(" ", ",").Replace("DISTINCT(", "").Replace(")", ""));
            }
            else
            {
                _dataReader = _file.DBFDataReader(filter.SubFields.Replace(" ", ",").Replace("DISTINCT(", "").Replace(")", ""));
            }

            if (_filter is IDistinctFilter)
            {
                _unique      = new List <object>();
                _uniqueField = _filter.SubFields.Replace("DISTINCT(", "").Replace(")", "");
            }

            if (_filter is FunctionFilter)
            {
            }

            /*
             * if (!(filter is ISpatialFilter))
             * {
             *  DataTable tab = _dataReader.AllRecords;
             *  tab = null;
             * }*/
        }
        protected override void OnClick()
        {
            //
            //  TODO: Sample code showing how to access button host
            //
            ArcMap.Application.CurrentTool = null;

            IMap map = ArcMap.Document.ActivatedView.FocusMap;

            //Check to make sure the map contains a layer
            if (map.LayerCount < 1)
            {
                MessageBox.Show("Must have a layer in your map...");
                return;
            }

            //Get the selected layer
            ILayer selectedLayer = ArcMap.Document.SelectedLayer;

            //Checl that there is a selected layer in the table of contents
            if (selectedLayer == null)
            {
                MessageBox.Show("You must have a layer highlighted in the table of contents.");
                return;
            }
            //Check that the selected layer is a featuer layer
            if (!(selectedLayer is IFeatureLayer))
            {
                MessageBox.Show("The highlighted layer in the TOC must be a feature layer.");
                return;
            }

            IFeatureLayer featureLayer = selectedLayer as IFeatureLayer;
            IFeatureClass featureClass = featureLayer.FeatureClass;

            //Check that the features shape is a line
            if (featureClass.ShapeType != esriGeometryType.esriGeometryPolyline)
            {
                MessageBox.Show("The highlighted layer in the TOC must be a polyline.");
                return;
            }
            //Check that features are selected in the table of contents
            IFeatureSelection featureSelection = featureLayer as IFeatureSelection;

            if (featureSelection.SelectionSet.Count < 1)
            {
                MessageBox.Show("The highlighted layer in the TOC must have some features selected.");
                return;
            }

            ISelectionSet2 selectionSet = featureSelection.SelectionSet as ISelectionSet2;

            int streetFieldIndex = featureClass.FindField(sStreetFldName);

            //Check that the street name exists in the table.
            if (streetFieldIndex < 0)
            {
                MessageBox.Show(sStreetFldName + " was not found in highlighted layer.");
                return;
            }

            int crossA = featureClass.FindField(sCrossAFldName);

            //Check that the cross from field was found in the table
            if (crossA < 1)
            {
                MessageBox.Show(sCrossAFldName + " was not found in highlighted layer.");
                return;
            }
            //Check that the cross to field was found in the table
            int crossB = featureClass.FindField(sCrossBFldName);

            if (crossB < 1)
            {
                MessageBox.Show(sCrossBFldName + " was not found in highlighted layer.");
                return;
            }
            //Find the editor
            UID id = new UID();

            id.Value = "esriEditor.Editor";

            IApplication application     = ArcMap.Application;
            IEditor3     editorExtension = application.FindExtensionByCLSID(id) as IEditor3;

            //Make sure that an active edit session is happening
            if (!(editorExtension.EditState == esriEditState.esriStateEditing))
            {
                MessageBox.Show("Must be in an edit session");
                return;
            }
            //Update the status bar
            application.StatusBar.Message[0] = "Populating Cross Streets...";
            editorExtension.StartOperation();
            IQueryFilter queryFilter = new QueryFilter();

            queryFilter.AddField(sCrossAFldName);
            queryFilter.AddField(sCrossBFldName);
            ICursor featureCursor;

            selectionSet.Update(null, false, out featureCursor);
            IFeature feature = featureCursor.NextRow() as IFeature;
            string   total   = selectionSet.Count.ToString();
            int      count   = 0;

            //Iterate through the features until all of the selected ones have been tested
            do
            {
                count++;
                application.StatusBar.Message[0] = "Populating cross streets... " + count.ToString() + " of " + total;
                string    street   = feature.Value[streetFieldIndex] as string;
                IGeometry geometry = feature.Shape;
                ICurve    curve    = geometry as ICurve;
                IPoint    point    = curve.FromPoint;
                string    sCrossA  = FindStreets(point, featureClass, streetFieldIndex, street, sJoin);
                point = curve.ToPoint;
                string sCrossB = FindStreets(point, featureClass, streetFieldIndex, street, sJoin);

                feature.Value[crossA] = sCrossA;
                feature.Value[crossB] = sCrossB;
                IRow row = feature;

                featureCursor.UpdateRow(feature);

                feature = featureCursor.NextRow() as IFeature;
            } while (!(feature == null));
            editorExtension.StopOperation("Populate Cross Streets");
        }
        async public Task <bool> RemoveUnexisting()
        {
            if (!(_fdb is AccessFDB))
            {
                return(false);
            }

            IFeatureClass rasterFC = await((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 = await rasterFC.GetFeatures(filter))
            {
                IFeature feature;
                while ((feature = await 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 (!await((AccessFDB)_fdb).Delete(rasterFC, oid))
                    {
                        Console.WriteLine(_errMsg = "Can't delete record OID=" + oid);
                        return(false);
                    }
                }

                return(true);
            }
        }
        async private Task <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 (var dsType in compMan.GetPlugins(Plugins.Type.IDataset))
            {
                IRasterFileDataset rds = compMan.CreateInstance <IDataset>(dsType) 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 ((await rfd.Elements()).Count == 0)
                {
                    //Console.WriteLine(_errMsg = fi.FullName + " is not a valid Raster File...");
                    continue;
                }
                IDatasetElement element = (await 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 = 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");

            if (_fdb is AccessFDB)
            {
                filter.WhereClause = ((AccessFDB)_fdb).DbColName("PATH") + "='" + ((AccessFDB)_fdb).EscapeQueryValue(fi.FullName) + "'";
            }
            else
            {
                filter.WhereClause = "PATH='" + fi.FullName.Replace(@"\", @"\\") + "'";
            }

            int deleteOID = -1;
            using (IFeatureCursor cursor = await rasterFC.GetFeatures(filter))
            {
                IFeature existingFeature = await cursor.NextFeature();

                if (existingFeature != null)
                {
                    DateTime dt1 = (DateTime)existingFeature["LAST_MODIFIED"];

                    if (!fi.LastWriteTimeUtc.IsEqual2(dt1, 1))
                    {
                        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((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 (!await fdb.Delete(rasterFC, deleteOID))
                {
                    Console.WriteLine(_errMsg = "Can't delete old record " + fi.FullName + "\n" + fdb.LastErrorMessage);
                    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 IRasterFileBitmap)));
            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 (!await fdb.Insert(rasterFC, feature))
            {
                Console.WriteLine("\nERROR@" + fi.FullName + ": " + fdb.LastErrorMessage);
            }
            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 = await ((SqlFDB)fdb).Query(rasterFC, qfilter);
                //    if (cursor != null)
                //    {
                //        IFeature feat = await cursor.NextFeature();
                //        if (feat != null)
                //        {
                //            await InsertImageDatasetBitmap(feat.OID, rasterLayer, _levels, format);
                //        }
                //        cursor.Dispose();
                //    }
                //}

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

            rFileDataset.Dispose();
            return(true);
        }