private static ITable CreateTable(IWorkspace2 workspace, string tableName, IFields fields)
        {
            UID uid = new UIDClass {Value = "esriGeoDatabase.Object"};

            if (workspace == null) return null;

            IFeatureWorkspace featWorkspace = (IFeatureWorkspace) workspace;

            if (workspace.NameExists[esriDatasetType.esriDTTable, tableName])
            {
                using (ComReleaser releaser = new ComReleaser())
                {
                    ITable table = featWorkspace.OpenTable(tableName);
                    releaser.ManageLifetime(table);
                    ((IDataset) table).Delete();
                }
            }


            IFieldChecker fieldChecker = new FieldCheckerClass();
            IEnumFieldError enumFieldError = null;
            IFields validatedFields = null;
            fieldChecker.ValidateWorkspace = workspace as IWorkspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            return featWorkspace.CreateTable(tableName, validatedFields, uid, null, string.Empty);
        }
Пример #2
0
        /// <summary>
        /// Returns the values in case the field is numeric, otherwise the IEnumerable is empty.
        /// DBNull values are skipped.
        /// </summary>
        /// <returns></returns>
        public IEnumerable <double> GetFieldData()
        {
            if (!IsNumeric && !IsOID)
            {
                return(Enumerable.Empty <double>());
            }

            IList <double> data = new List <double>();

            using (var comReleaser = new ComReleaser())
            {
                var featureCursor = Feature.FeatureClass.Search(null, true);

                comReleaser.ManageLifetime(featureCursor);

                var fieldIndex = Feature.FeatureClass.FindField(FieldName);

                IFeature currentFeature;

                while ((currentFeature = featureCursor.NextFeature()) != null)
                {
                    if (currentFeature.Value[fieldIndex] is DBNull)
                    {
                        continue;
                    }

                    var t = (Convert.ToDouble(currentFeature.Value[fieldIndex]));

                    data.Add(t);
                }
            }

            return(data.AsEnumerable());
        }
Пример #3
0
        private IElement method_1(object object_1)
        {
            if (object_1 is DBNull)
            {
                return(null);
            }
            IMemoryBlobStream o    = object_1 as IMemoryBlobStream;
            IPropertySet      set  = new PropertySetClass();
            IObjectStream     pstm = new ObjectStreamClass
            {
                Stream = o
            };
            IPersistStream stream3 = set as IPersistStream;

            stream3.Load(pstm);
            IElement property = null;

            try
            {
                property = set.GetProperty("Element") as IElement;
            }
            catch (Exception)
            {
            }
            ComReleaser.ReleaseCOMObject(stream3);
            ComReleaser.ReleaseCOMObject(set);
            ComReleaser.ReleaseCOMObject(o);
            set = null;
            return(property);
        }
Пример #4
0
        public DataTable ITable2Tatatable(ITable itable_1, string string_0)
        {
            DataTable dataTable0;

            if (itable_1 != null)
            {
                this.dataTable_0.Rows.Clear();
                this.dataTable_0.Columns.Clear();
                this.method_0(itable_1.Fields, this.dataTable_0);
                string str = "";
                if (itable_1 is IFeatureClass)
                {
                    str = this.method_1(itable_1 as IFeatureClass);
                }
                IQueryFilter queryFilterClass = new QueryFilter()
                {
                    WhereClause = string_0
                };
                ICursor cursor = null;
                cursor        = (string_0 != "" ? itable_1.Search(queryFilterClass, false) : itable_1.Search(null, false));
                this.itable_0 = itable_1;
                this.method_2(true, this.dataTable_0, cursor, str);
                ComReleaser.ReleaseCOMObject(cursor);
                dataTable0 = this.dataTable_0;
            }
            else
            {
                dataTable0 = null;
            }
            return(dataTable0);
        }
Пример #5
0
        private void CatoTemplateApplySelect_Load(object sender, EventArgs e)
        {
            CartoTemplateTableStruct struct2 = new CartoTemplateTableStruct();
            ITable table = AppConfigInfo.OpenTable(struct2.TableName);

            if (table != null)
            {
                ICursor  o     = table.Search(null, false);
                IRow     row   = o.NextRow();
                string[] items = new string[2];
                while (row != null)
                {
                    CartoTemplateData data = new CartoTemplateData(row);
                    items[0] = data.Name;
                    items[1] = data.Description;
                    ListViewItem item = new ListViewItem(items)
                    {
                        Tag = data
                    };
                    this.listView1.Items.Add(item);
                    row = o.NextRow();
                }
                ComReleaser.ReleaseCOMObject(o);
                o = null;
            }
        }
        //双击选中的属性表
        private void gviewSelect_DoubleClick(object sender, EventArgs e)
        {
            GridView gridControl = sender as GridView;

            if (gridControl == null || featureLayer.FeatureClass == null)
            {
                return;
            }
            try
            {
                DataRow  dataRow     = gridControl.GetFocusedDataRow();
                int      oid         = Convert.ToInt32(dataRow[featureLayer.FeatureClass.OIDFieldName]);
                IFeature pSelFeature = featureLayer.FeatureClass.GetFeature(oid);
                if (pSelFeature == null)
                {
                    return;
                }
                using (ComReleaser pComReleaser = new ComReleaser())
                {
                    pComReleaser.ManageLifetime(pSelFeature);
                    IMap      pMap      = BindingMapControl.Map;
                    IGeometry pGeometry = pSelFeature.ShapeCopy;
                    if (!IsEqualSpatialReference(pGeometry.SpatialReference, pMap.SpatialReference))
                    {
                        pGeometry.Project(pMap.SpatialReference);
                    }
                    Flash(BindingMapControl, pGeometry, true);
                }
            }
            catch (Exception ep)
            {
            }
        }
 //右键菜单——当前页全选
 private void barButtonItem2_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
 {
     try
     {
         DataTable  showingDataTable = gridAllAttribute.DataSource as DataTable;
         List <int> oidList          = new List <int>();
         foreach (DataRow dataRow in showingDataTable.Rows)
         {
             oidList.Add(Convert.ToInt32(dataRow[oidFieldName]));
         }
         using (ComReleaser comReleaser = new ComReleaser())
         {
             string       whereClause  = "";
             IQueryFilter pQueryFilter = new QueryFilterClass();
             comReleaser.ManageLifetime(pQueryFilter);
             foreach (int i in oidList)
             {
                 whereClause += "\"" + (featureLayer.FeatureClass as ITable).OIDFieldName + "\"=" + i + " OR ";
             }
             whereClause = whereClause.Substring(0, whereClause.Length - 3);
             pQueryFilter.WhereClause = whereClause;
             (featureLayer as IFeatureSelection).SelectFeatures(pQueryFilter, esriSelectionResultEnum.esriSelectionResultNew, false);
         }
         UpdateCtrlDataSource();
         BindingMapControl.Refresh();
     }
     catch (Exception ex)
     {
         XtraMessageBox.Show("打开属性表错误");
     }
 }
Пример #8
0
        public static void InsertLoadOnly(IFeatureClass featureCls, IList <IGeometry> geoList)
        {
            IFeatureClassLoad featureClsLoad = (IFeatureClassLoad)featureCls;
            ISchemaLock       schemaLock     = (ISchemaLock)featureCls;

            try
            {
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                featureClsLoad.LoadOnlyMode = true;
                using (var comReleaser = new ComReleaser())
                {
                    IFeatureBuffer featureBuffer = featureCls.CreateFeatureBuffer();
                    IFeatureCursor featureCursor = featureCls.Insert(true);
                    comReleaser.ManageLifetime(featureCursor);
                    featureBuffer.set_Value(featureBuffer.Fields.FindField("InstBy"), "B Pierce");
                    for (int ic = 0; ic < geoList.Count; ic++)
                    {
                        featureBuffer.Shape = geoList[0];
                        var featureOID = featureCursor.InsertFeature(featureBuffer);
                        if (ic % 10 == 0)
                        {
                            featureCursor.Flush();
                        }
                    }
                    featureCursor.Flush();
                }
            }
            finally
            {
                featureClsLoad.LoadOnlyMode = false;
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
            }
        }
Пример #9
0
        /// <summary>
        ///测试getFeature与getFeatures
        /// </summary>
        /// <param name="featureCls"></param>
        /// <param name="oids"></param>
        /// <param name="fieldIndex"></param>
        public void SearchById(IFeatureClass featureCls, int[] oids, int fieldIndex)
        {
            foreach (var oid in oids)
            {
                var feature = featureCls.GetFeature(oid);
                Console.WriteLine("oid:" + feature.get_Value(fieldIndex));
            }



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

            using (var comReleaser = new ComReleaser())
            {
                IGeoDatabaseBridge geodatabaseBridge = new GeoDatabaseHelperClass();
                IFeatureCursor     featureCursor     = geodatabaseBridge.GetFeatures(featureCls, oids, true);;
                IFeature           feature           = featureCursor.NextFeature();
                while (feature != null)
                {
                    Console.WriteLine("oid:" + feature.get_Value(fieldIndex));
                    feature = featureCursor.NextFeature();
                }
            }
        }
Пример #10
0
        public static void SaveMxd()
        {
            IMapDocument oMapDoc = new MapDocumentClass();

            oMapDoc.Open(AxMapControl.DocumentFilename);

            if (oMapDoc.IsReadOnly[AxMapControl.DocumentFilename])
            {
                throw new InvalidOperationException("Can not save mxd. Is read only.");
            }

            AxMapControl.Update();
            AxTocControl.Update();

            oMapDoc.ReplaceContents((IMxdContents)AxMapControl.Map);
            oMapDoc.Save(true, true);
            oMapDoc.Close();

            if (oMapDoc != null)
            {
                ComReleaser.ReleaseCOMObject(oMapDoc);
                oMapDoc = null;
            }

            if (AxMapControl.Map != null)
            {
                ComReleaser.ReleaseCOMObject(AxMapControl.Map);
                AxMapControl.Map = null;
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
        }
Пример #11
0
 /// <summary>
 /// An iterator-based implementation that encapsulates COM reference counting operation around ITfFnSearchCandidateProvider.GetSearchCandidates.
 /// </summary>
 public static IEnumerable<string> GetSearchCandidates(this ITfFnSearchCandidateProvider provider, string query, string applicationId = "")
 {
     using (var releaser = new ComReleaser())
     {
         var candidateList = releaser.ReceiveObject((out ITfCandidateList _) => provider.GetSearchCandidates(query, applicationId, out _));
         if (candidateList == null)
         {
             yield break;
         }
         var numResults = default(uint);
         if (!candidateList.GetCandidateNum(out numResults))
         {
             yield break;
         }
         var iter = Enumerable.Range(0, (int)numResults)
                              .Select(index => releaser.ReceiveObject((out ITfCandidateString _) => candidateList.GetCandidate((uint)index, out _)))
                              .Where(candidateString => candidateString != null)
                              .Select(candidateString =>
                              {
                                  var resultString = string.Empty;
                                  candidateString.GetString(out resultString);
                                  return resultString;
                              })
                              .Where(str => !String.IsNullOrEmpty(str));
         foreach (var candiate in iter)
         {
             yield return candiate;
         }
     }
 }
Пример #12
0
        public static void OpenTable(AxMapControl MapControl, ITableName pTName, DataTable dt = null)
        {
            try
            {
                MapControl.Map.ClearLayers();
                MapControl.SpatialReference = null;
                MapControl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewAll, null, null);
                IName  pName = pTName as IName;
                ITable pFc   = pName.Open() as ITable;

                if (null != dt)
                {
                    InitDataTable(pFc, dt);

                    ICursor pCursor = pFc.Search(null, false);
                    IRow    pfea    = pCursor.NextRow();
                    int     j       = 0;
                    while (pfea != null)
                    {
                        DataRow dataRow = dt.NewRow();

                        for (int i = 0; i < pfea.Fields.FieldCount; i++)
                        {
                            dataRow[i] = pfea.get_Value(i).ToString();
                        }

                        dt.Rows.Add(dataRow);
                        pfea = pCursor.NextRow();
                        j++;
                    }
                    ComReleaser.ReleaseCOMObject(pCursor);
                }
            }
            catch { }
        }
Пример #13
0
        public IList <IFeatureClass> TravelWorkSpace4FeatureClass(IWorkspace workspace, string datasetName)
        {
            IList <IFeatureClass> result = new List <IFeatureClass>();

            using (ComReleaser releaser = new ComReleaser())
            {
                //遍历要素集中的要素类
                IEnumDataset dts = workspace.get_Datasets(esriDatasetType.esriDTFeatureDataset);
                //releaser.ManageLifetime(dts);
                IDataset dt = dts.Next();
                //releaser.ManageLifetime(dt);
                while (dt != null)
                {
                    if (dt.Name.Equals(datasetName))
                    {
                        IEnumDataset fcs = dt.Subsets;
                        //releaser.ManageLifetime(fcs);
                        IDataset fc = fcs.Next();
                        //releaser.ManageLifetime(fc);
                        while (fc != null)
                        {
                            result.Add((fc as IFeatureClass));
                            fc = fcs.Next();
                        }
                    }
                    dt = dts.Next();
                }
            }
            return(result);
        }
Пример #14
0
        /// <summary>
        ///     Iterates through all of those rows that have been resolved forcing a save (aka call store) with AUs enabled.
        /// </summary>
        protected void SaveAfterReconcile()
        {
            this.NotifyCallback(4, "Triggering AUs on the conflicts that are not resolved.");

            // Toggle the AU framework.
            using (new AutoUpdaterModeReverter(mmAutoUpdaterMode.mmAUMArcMap))
            {
                // Iterate through all of the rows that have been marked as 'None' and group by the table.
                foreach (var rows in this.Rows.Where(o => o.Resolution == ConflictResolution.None).GroupBy(o => o.TableName))
                {
                    Log.Info("Calling store on {0} row(s) within the {1} class.", rows.Count(), rows.Key);

                    using (ComReleaser cr = new ComReleaser())
                    {
                        IFeatureWorkspace currentWorkspace = (IFeatureWorkspace)this.Workspace;
                        ITable            currentTable     = currentWorkspace.OpenTable(rows.Key);
                        cr.ManageLifetime(currentTable);

                        foreach (var o in rows)
                        {
                            IRow currentRow = currentTable.Fetch(o.OID);
                            cr.ManageLifetime(currentRow);

                            // Call Store to Trigger the AUs.
                            this.SaveAndRebuild(currentRow);
                        }
                    }
                }
            }
        }
Пример #15
0
        /// <summary>
        ///     Queries the database and populates a <see cref="DataTable" /> with the resulting data from the specified SQL
        ///     statement.
        /// </summary>
        /// <param name="source">The process application reference.</param>
        /// <param name="commandText">The command text.</param>
        /// <returns>
        ///     Returns a <see cref="DataTable" /> representing the records returned by the command text.
        /// </returns>
        /// <exception cref="ArgumentNullException">commandText</exception>
        public static DataTable ExecuteQuery(this IMMPxApplication source, string commandText)
        {
            if (source == null)
            {
                return(null);
            }
            if (commandText == null)
            {
                throw new ArgumentNullException("commandText");
            }

            var table = new DataTable();

            table.Locale = CultureInfo.InvariantCulture;

            using (var cr = new ComReleaser())
            {
                Recordset recordset = new RecordsetClass();
                recordset.Open(commandText, source.Connection, CursorTypeEnum.adOpenDynamic, LockTypeEnum.adLockOptimistic, 0);
                cr.ManageLifetime(recordset);

                var adapter = new OleDbDataAdapter();
                adapter.Fill(table, recordset);
                recordset.Close();
            }

            return(table);
        }
Пример #16
0
        private IFeature FindFeature(IPoint ipoint_0)
        {
            IFeature  feature  = null;
            double    mapUnits = Common.ConvertPixelsToMapUnits((IActiveView)_context.FocusMap, this.double_0);
            IEnvelope envelope = ipoint_0.Envelope;

            envelope.Height = mapUnits;
            envelope.Width  = mapUnits;
            envelope.CenterAt(ipoint_0);
            ISpatialFilter spatialFilterClass = new SpatialFilter()
            {
                Geometry   = envelope,
                SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
            };

            for (int i = 0; i < _context.FocusMap.LayerCount; i++)
            {
                IFeatureLayer layer = _context.FocusMap.Layer[i] as IFeatureLayer;
                if (layer != null && layer.Visible && layer.FeatureClass != null &&
                    layer.FeatureClass.ShapeType == esriGeometryType.esriGeometryPolyline)
                {
                    spatialFilterClass.GeometryField = layer.FeatureClass.ShapeFieldName;
                    IFeatureCursor featureCursor = layer.Search(spatialFilterClass, false);
                    this.GetProximityFeature(ipoint_0, featureCursor, ref feature);
                    ComReleaser.ReleaseCOMObject(featureCursor);
                }
            }
            return(feature);
        }
Пример #17
0
        public List <IObjectTemplate> GetTemplatesByDataset(string datasetName)
        {
            List <IObjectTemplate> templates = new List <IObjectTemplate>();
            ITable pTemplateTable            = _workspace.OpenTable("YT_TEMPLATE_FEATURECLASS");


            IQueryFilter pFilter1 = new QueryFilter();

            pFilter1.WhereClause = "Dataset='" + datasetName + "'";

            ICursor pCursor = pTemplateTable.Search(pFilter1, false);

            int[]        fieldIndexes = new int[6];
            IRow         pRow         = pCursor.NextRow();
            IQueryFilter pQueryFilter = new QueryFilter();

            IObjectTemplate oneTemplate = null;

            while (pRow != null)
            {
                oneTemplate = new ObjectTemplate(pRow);
                templates.Add(oneTemplate);
                pRow = pCursor.NextRow();
            }
            ComReleaser.ReleaseCOMObject(pFilter1);
            ComReleaser.ReleaseCOMObject(pCursor);
            ComReleaser.ReleaseCOMObject(pTemplateTable);
            return(templates);
        }
Пример #18
0
        private IFeature FindEdgeFeature(string osmid)
        {
            List <IFeatureClass> fcEdges = OsmEdgeFeatureClasses;

            foreach (IFeatureClass fcEdge in fcEdges)
            {
                IQueryFilter filter = new QueryFilterClass();
                filter.SubFields   = string.Join(",", new string[] { fcEdge.OIDFieldName, fcEdge.ShapeFieldName, "OSMID" });
                filter.WhereClause = fcEdge.WhereClauseByExtensionVersion(osmid, "OSMID", OsmExtVersion);

                using (ComReleaser cr = new ComReleaser())
                {
                    IFeatureCursor cursor = fcEdge.Search(filter, false);
                    cr.ManageLifetime(cursor);

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

            return(null);
        }
Пример #19
0
        private bool UpdateFieldValue(IField pField, object str)
        {
            IWorkspaceEdit workspace = (this.m_pFeatLayer.FeatureClass as IDataset).Workspace as IWorkspaceEdit;
            bool           flag      = false;

            try
            {
                ICursor cursor;
                workspace.StartEditOperation();
                int index = this.m_pFeatLayer.FeatureClass.Fields.FindField(pField.Name);
                (this.m_pFeatLayer as IFeatureSelection).SelectionSet.Search(null, false, out cursor);
                for (IRow row = cursor.NextRow(); row != null; row = cursor.NextRow())
                {
                    row.set_Value(index, str);
                    row.Store();
                }
                ComReleaser.ReleaseCOMObject(cursor);
                workspace.StopEditOperation();
                try
                {
                }
                catch
                {
                }
                flag = true;
            }
            catch (Exception exception)
            {
                MessageBox.Show("输入数据格式错误");
                CErrorLog.writeErrorLog(null, exception, "");
            }
            return(flag);
        }
Пример #20
0
        private static ITable CreateTable(IWorkspace2 workspace, string tableName, IFields fields)
        {
            UID uid = new UIDClass {
                Value = "esriGeoDatabase.Object"
            };

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

            IFeatureWorkspace featWorkspace = (IFeatureWorkspace)workspace;

            if (workspace.NameExists[esriDatasetType.esriDTTable, tableName])
            {
                using (ComReleaser releaser = new ComReleaser())
                {
                    ITable table = featWorkspace.OpenTable(tableName);
                    releaser.ManageLifetime(table);
                    ((IDataset)table).Delete();
                }
            }


            IFieldChecker   fieldChecker    = new FieldCheckerClass();
            IEnumFieldError enumFieldError  = null;
            IFields         validatedFields = null;

            fieldChecker.ValidateWorkspace = workspace as IWorkspace;
            fieldChecker.Validate(fields, out enumFieldError, out validatedFields);

            return(featWorkspace.CreateTable(tableName, validatedFields, uid, null, string.Empty));
        }
Пример #21
0
        public void Load()
        {
            if (this.mapTemplate != null)
            {
                this.mapTemplate.Clear();
            }
            IQueryFilter queryFilter = new QueryFilterClass
            {
                WhereClause = "ClassID=" + this.OID
            };
            ICursor cursor = this.MapTemplateGallery.MapTemplateTable.Search(queryFilter, false);
            IRow    row    = cursor.NextRow();
            int     index  = this.MapTemplateGallery.MapTemplateTable.FindField("Name");

            while (row != null)
            {
                string str = row.get_Value(index).ToString();
                MapCartoTemplateLib.MapTemplate template2 = new MapCartoTemplateLib.MapTemplate(row.OID, this)
                {
                    Name = str
                };
                this.AddMapTemplate(template2);
                row = cursor.NextRow();
            }
            ComReleaser.ReleaseCOMObject(row);
        }
Пример #22
0
        private string method_0(object object_0)
        {
            if (object_0 is DBNull)
            {
                return("");
            }
            IMemoryBlobStream o    = object_0 as IMemoryBlobStream;
            IPropertySet      set  = new PropertySetClass();
            IObjectStream     pstm = new ObjectStreamClass {
                Stream = o
            };
            IPersistStream stream3 = set as IPersistStream;

            stream3.Load(pstm);
            string str2 = "";

            try
            {
                str2 = set.GetProperty("TK").ToString();
            }
            catch (Exception)
            {
            }
            ComReleaser.ReleaseCOMObject(stream3);
            ComReleaser.ReleaseCOMObject(set);
            ComReleaser.ReleaseCOMObject(o);
            set = null;
            return(str2);
        }
 public bool Apply()
 {
     if (this.bool_0)
     {
         this.bool_0 = false;
         if (this.itableDefinition_0 != null)
         {
             if (this.itableDefinition_0 is ITable)
             {
                 IQueryFilter queryFilter = new QueryFilterClass
                 {
                     WhereClause = this.memoEdit.Text
                 };
                 try
                 {
                     ComReleaser.ReleaseCOMObject((this.itableDefinition_0 as ITable).Search(queryFilter, false));
                 }
                 catch (Exception)
                 {
                     MessageBox.Show("过滤条件输入错误,请检查!", "错误", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                     return(false);
                 }
             }
             this.itableDefinition_0.DefinitionExpression = this.memoEdit.Text;
         }
     }
     return(true);
 }
Пример #24
0
        /// <summary>
        ///     Queries for the features that satisfies the attribute and/or spatial query as specified by an
        ///     <paramref name="filter" /> object
        ///     and executes the specified <paramref name="action" /> on each feature returned from the query.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="filter">The attribute and/or spatial requirement that the features must satisify.</param>
        /// <param name="action">The action to take for each feature in the cursor.</param>
        /// <param name="recycling">if set to <c>true</c> when a recycling memory for the features is used.</param>
        /// <returns>
        ///     Returns a <see cref="int" /> representing the number of features affected by the action.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">action</exception>
        /// <exception cref="ArgumentNullException">action</exception>
        public static int Fetch(this IFeatureClass source, IQueryFilter filter, Func <IFeature, bool> action, bool recycling)
        {
            if (source == null)
            {
                return(0);
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            int recordsAffected = 0;

            using (ComReleaser cr = new ComReleaser())
            {
                IFeatureCursor cursor = source.Search(filter, recycling);
                cr.ManageLifetime(cursor);

                foreach (var feature in cursor.AsEnumerable())
                {
                    if (!action(feature))
                    {
                        return(recordsAffected);
                    }

                    recordsAffected++;
                }
            }

            return(recordsAffected);
        }
Пример #25
0
        void IClip.ClipByLayerFileInsideSde(object in_feature, string in_layer_file_path, object clip_feature, string clip_layer_file_path, string out_feature)
        {
            using (ComReleaser releaser = new ComReleaser())
            {
                try
                {
                    Geoprocessor gp = new Geoprocessor();
                    IDataManager _dataManager = new DataManager(this._environment);
                    ESRI.ArcGIS.AnalysisTools.Clip clipTool = new ESRI.ArcGIS.AnalysisTools.Clip();

                    //releaser.ManageLifetime(gp);
                    //releaser.ManageLifetime(clipTool);
                    //IVariantArray param = new VarArrayClass();

                    string inlayer = string.Format("{0}.lyr", in_layer_file_path);
                    string cliplayer = string.Format("{0}.lyr", clip_layer_file_path);
                    //MessageBox.Show(string.Format("line 61 GExtractTool in={0}, clip={1}", inlayer, cliplayer));
                    _dataManager.SaveToLayerFile((ILayer)in_feature, inlayer);
                    _dataManager.SaveToLayerFile((ILayer)clip_feature, cliplayer);

                    //MessageBox.Show(((IFeatureLayer)in_feature).FeatureClass.AliasName);
                    gp.SetEnvironmentValue("workspace", this._environment);
                    clipTool.in_features = inlayer;
                    clipTool.clip_features = cliplayer;
                    clipTool.out_feature_class = out_feature;//string.Format("{0}{1}", this._temFullPath, out_feature);//"C:\\tayninh\\temp\\tempmdb.mdb\\" + out_feature;

                    runTool(gp, clipTool, null);
                }
                catch (Exception err) { MessageBox.Show("loi clip: " + err.ToString()); }
            }
        }
Пример #26
0
        /// <summary>
        ///     Queries for the rows that satisfy the attribute query as specified by an <paramref name="filter" /> object
        ///     and executes the specified <paramref name="action" /> on each row returned from the query.
        /// </summary>
        /// <param name="source">The source.</param>
        /// <param name="filter">The attribute requirement that features must satisify.</param>
        /// <param name="action">The action to take for each feature in the cursor.</param>
        /// <param name="recycling">
        ///     if set to <c>true</c> when the cursor rehydrates a single row object on each fetch and can be
        ///     used to optimize read-only access.
        /// </param>
        /// <returns>
        ///     Returns a <see cref="int" /> representing the number of rows affected by the action.
        /// </returns>
        /// <exception cref="System.ArgumentNullException">action</exception>
        /// <exception cref="ArgumentNullException">action</exception>
        /// <remarks>
        ///     Uses a recycling cursors rehydrate a single feature object on each fetch and can be used to optimize read-only
        ///     access
        /// </remarks>
        public static int Fetch(this ITable source, IQueryFilter filter, Action <IRow> action, bool recycling)
        {
            if (source == null)
            {
                return(0);
            }
            if (action == null)
            {
                throw new ArgumentNullException("action");
            }

            int recordsAffected = 0;

            using (ComReleaser cr = new ComReleaser())
            {
                ICursor cursor = source.Search(filter, recycling);
                cr.ManageLifetime(cursor);

                foreach (var row in cursor.AsEnumerable())
                {
                    action(row);

                    recordsAffected++;
                }
            }

            return(recordsAffected);
        }
Пример #27
0
        private static bool FeatureLayerIdentify(IBasicMap ibasicMap_0, IFeatureLayer ifeatureLayer_0,
                                                 IGeometry igeometry_0, IArray iarray_0)
        {
            bool           flag;
            ISpatialFilter spatialFilterClass = new SpatialFilter()
            {
                Geometry   = igeometry_0,
                SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects
            };

            try
            {
                IFeatureCursor featureCursor = ifeatureLayer_0.FeatureClass.Search(spatialFilterClass, false);
                for (IFeature i = featureCursor.NextFeature(); i != null; i = featureCursor.NextFeature())
                {
                    AEFeatureIdentifyObject aEFeatureIdentifyObject = new AEFeatureIdentifyObject()
                    {
                        BasicMap = ibasicMap_0,
                        Feature  = i
                    };
                    iarray_0.Add(aEFeatureIdentifyObject);
                }
                ComReleaser.ReleaseCOMObject(featureCursor);
                flag = true;
                return(flag);
            }
            catch (Exception exception)
            {
                Logger.Current.Error("", exception, "");
            }
            flag = false;
            return(flag);
        }
Пример #28
0
 public void RefreshCurrentPageDataTable()
 {
     using (ComReleaser comreleaser = new ComReleaser())
     {
         IFeatureCursor cursor = TargetFeatureClass.Search(null, false);
         comreleaser.ManageLifetime(cursor);
         IFeature tempFt = cursor.NextFeature();
         comreleaser.ManageLifetime(tempFt);
         ISet <int> IngoreFieldIndex = ConvertIngoreColName2FieldIndex();
         for (int index = 0; index < FeatureCount; index++)
         {
             if (index < CurrentPage * PageContains)
             {
                 tempFt = cursor.NextFeature();
             }
             else if (index > (CurrentPage + 1) * PageContains)
             {
                 break;
             }
             else
             {
                 int     colIndex = 0;
                 DataRow tempRow  = ResultTable.NewRow();
                 for (int i = 0; i < TargetFeatureClass.Fields.FieldCount; i++)
                 {
                     if (IngoreFieldIndex.Contains(i))
                     {
                         continue;
                     }
                     tempRow[colIndex++] = tempFt.get_Value(index);
                 }
             }
         }
     }
 }
Пример #29
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="table"></param>
        /// <param name="filter"></param>
        /// <param name="readOnly"></param>
        /// <param name="funcLoopBody">(row, current record count 1-based)</param>
        /// <returns>Looped record count.</returns>
        public static int Loop(ITable table, IQueryFilter filter, bool readOnly, Func <IRow, int, bool> funcLoopBody)
        {
            IRow row;
            int  count        = 0;
            bool continueLoop = true;

            using (ComReleaser comReleaser = new ComReleaser())
            {
                ICursor cursor = table.Search(filter, readOnly);
                comReleaser.ManageLifetime(cursor);

                while ((row = cursor.NextRow()) != null)
                {
                    count++;

                    if (funcLoopBody != null)
                    {
                        continueLoop = funcLoopBody(row, count);
                        if (continueLoop == false)
                        {
                            break;
                        }
                    }
                }
            }
            return(count);
        }
Пример #30
0
        public IList <T> QuerySingleFieldValue <T>(ITable targetTable, string QueryFieldName, string whereclause = null)
        {
            IList <T> result = new List <T>();

            int colIndex = -1;

            if ((colIndex = targetTable.FindField(QueryFieldName)) == -1)
            {
                return(result);
            }

            IQueryFilter filter = new QueryFilter();

            if (string.IsNullOrEmpty(whereclause))
            {
                filter.WhereClause = whereclause;
            }
            filter.SubFields = QueryFieldName;


            using (ComReleaser releaser = new ComReleaser())
            {
                ICursor cursor = targetTable.Search(filter, false);
                IRow    row    = cursor.NextRow();
                while (row != null)
                {
                    result.Add(row.get_Value(colIndex));
                    row = cursor.NextRow();
                }
            }
            return(result.Cast <T>().ToList());
        }
Пример #31
0
        private void OutputTxt(string shpfile, string txtPath)
        {
            FileInfo finfo     = new FileInfo(shpfile);
            string   parFolder = System.IO.Path.GetDirectoryName(shpfile);

            if (!Directory.Exists(parFolder))
            {
                Directory.CreateDirectory(parFolder);
            }
            IWorkspaceFactory shpwf        = new ShapefileWorkspaceFactory();
            IFeatureWorkspace featureWs    = shpwf.OpenFromFile(parFolder, 0) as IFeatureWorkspace;
            IFeatureClass     featureclass = featureWs.OpenFeatureClass(finfo.Name);
            IFeatureCursor    cursor       = featureclass.Search(null, false);
            IFeature          pfeat        = cursor.NextFeature();
            StringBuilder     sb           = new StringBuilder();

            sb.Append("ID,x,y,z\r\n");
            int index = 1;

            while (pfeat != null)
            {
                IPoint pt = pfeat.Shape as IPoint;
                sb.Append(string.Format("{0},{1},{2},{3}\r\n", index++, pt.X, pt.Y, pt.Z));
                pfeat = cursor.NextFeature();
            }
            ComReleaser.ReleaseCOMObject(cursor);
            ComReleaser.ReleaseCOMObject(pfeat);
            ComReleaser.ReleaseCOMObject(featureclass);
            ComReleaser.ReleaseCOMObject(shpwf);
            File.WriteAllText(txtPath, sb.ToString(), Encoding.Default);
        }
Пример #32
0
        public void CreateAllRecordTable(bool ColNameUseAlias = false)
        {
            NotifyDestoryResultTable();
            CreateNullRecordTable(ColNameUseAlias);
            ISet <int> IngoreFieldIndex = ConvertIngoreColName2FieldIndex();

            using (ComReleaser comreleaser = new ComReleaser())
            {
                IFeatureCursor cursor = TargetFeatureClass.Search(null, false);
                comreleaser.ManageLifetime(cursor);
                IFeature tempFt = cursor.NextFeature();
                comreleaser.ManageLifetime(tempFt);
                while (tempFt != null)
                {
                    int     colIndex = 0;
                    DataRow tempRow  = ResultTable.NewRow();
                    for (int index = 0; index < TargetFeatureClass.Fields.FieldCount; index++)
                    {
                        if (IngoreFieldIndex.Contains(index))
                        {
                            continue;
                        }
                        tempRow[colIndex++] = tempFt.get_Value(index);
                    }
                    ResultTable.Rows.Add(tempRow);
                    tempFt = cursor.NextFeature();
                }
            }
            IngoreFieldIndex.Clear();
        }
Пример #33
0
        private IElement method_2(object object_0)
        {
            IMemoryBlobStream o    = object_0 as IMemoryBlobStream;
            IPropertySet      set  = new PropertySetClass();
            IObjectStream     pstm = new ObjectStreamClass
            {
                Stream = o
            };

            ESRI.ArcGIS.esriSystem.IPersistStream stream3 = set as ESRI.ArcGIS.esriSystem.IPersistStream;
            stream3.Load(pstm);
            IElement property = null;

            try
            {
                property = set.GetProperty("Element") as IElement;
            }
            catch (Exception)
            {
            }
            ComReleaser.ReleaseCOMObject(stream3);
            ComReleaser.ReleaseCOMObject(set);
            ComReleaser.ReleaseCOMObject(o);
            set = null;
            return(property);
        }
        protected override void OnClick()
        {
            string tablePath = Path.Combine(DataPath, @"Geodatabase\ManhattanKS.gdb\ParcelIDs");
            string tableName = Path.GetFileName(tablePath);
            const string searchField = "PID";

            Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory");
            IWorkspaceFactory workspaceFactory = Activator.CreateInstance(factoryType) as IWorkspaceFactory;
            IWorkspace workspace = workspaceFactory.OpenFromFile(Path.GetDirectoryName(tablePath), 0);

            IObjectClassDescription objClassDesc = new ObjectClassDescriptionClass();

            IFields fields = objClassDesc.RequiredFields;
            IFieldsEdit fieldsEdit = (IFieldsEdit) fields;

            IField field = new FieldClass();
            IFieldEdit fieldEdit = (IFieldEdit) field;

            fieldEdit.Name_2 = searchField;
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
            fieldEdit.IsNullable_2 = true;
            fieldEdit.AliasName_2 = searchField;
            fieldEdit.Editable_2 = true;
            fieldEdit.Length_2 = 250;

            fieldsEdit.AddField(field);
            fields = fieldsEdit;

            ITable table = CreateTable((IWorkspace2) workspace, tableName, fields);

            using (ComReleaser releaser = new ComReleaser())
            {
                ICursor cursor = table.Insert(true);
                releaser.ManageLifetime(cursor);

                string txtPath = Path.Combine(DataPath, "UniqueValues.txt");
                int searchFieldIndex = table.FindField(searchField);

                IRowBuffer buffer = table.CreateRowBuffer();

                using (StreamReader reader = new StreamReader(txtPath))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        string id = line.Split(new[] {'.', ' '}, StringSplitOptions.RemoveEmptyEntries)[1];
                        buffer.Value[searchFieldIndex] = id;
                        cursor.InsertRow(buffer);
                    }

                    cursor.Flush();
                }
            }

            ((ITableCollection) ArcMap.Document.FocusMap).AddTable(table);
            ArcMap.Document.UpdateContents();
            Marshal.FinalReleaseComObject(table);
        }
 private static Dictionary<string, int> GetAllValues(string fieldName, IGeoFeatureLayer layer)
 {
     var results = new Dictionary<string, int>();
     IQueryFilter query = new QueryFilter { SubFields = fieldName };
     using (var comReleaser = new ComReleaser())
     {
         IFeatureCursor cursor = layer.Search(query, true);
         comReleaser.ManageLifetime(cursor);
         IFeature feature;
         int fieldIndex = cursor.FindField(fieldName);
         while ((feature = cursor.NextFeature()) != null)
         {
             results[feature.Value[fieldIndex].ToString()] = 1;
         }
     }
     return results;
 }
Пример #36
0
        public static void UpdateFeature(IFeatureClass featureClass)
        {
            // Create a COM releaser for cursor management
            using (ComReleaser comReleaser = new ComReleaser())
            {
                // Use IFeatureClass.Update to create an update cursor
                IFeatureCursor featureCursor = featureClass.Update(null, true);
                comReleaser.ManageLifetime(featureCursor);

                // find the index of the field named "country"
                int fieldIndex = featureClass.FindField("Country");

                IFeature feature = null;
                while ((feature = featureCursor.NextFeature()) != null)
                {
                    feature.set_Value(fieldIndex, "USA");
                    featureCursor.UpdateFeature(feature); // Do not use IFeature.Store with UpdateCursors
                }
            }
        }
Пример #37
0
 private static Dictionary<object, List<Observation>> GetObservations(ITable table)
 {
     var observationData = new Dictionary<object, List<Observation>>();
     using (var comReleaser = new ComReleaser())
     {
         ICursor cursor = table.Search(null, true);
         comReleaser.ManageLifetime(cursor);
         IRow row;
         while ((row = cursor.NextRow()) != null)
         {
             string data = string.Format("{0},{1},\"{2}\",{3},\"{4}\"", row.Value[10], row.Value[11], row.Value[3], row.Value[4], row.Value[5]);
             string comment = string.Format("\"{0}\"", row.Value[6]);
             object gpsId = row.Value[12];
             if (observationData.ContainsKey(gpsId))
                 observationData[gpsId].Add(new Observation {Data = data, Comment = comment});
             else
                 observationData[gpsId] = new List<Observation>
                                              {new Observation {Data = data, Comment = comment}};
         }
     }
     return observationData;
 }
Пример #38
0
        ///<summary>Flash geometry on the display.</summary>
        ///<param name="geometry"> The input IGeometry to flash.  Supported geometry types are GeometryBag, Polygon, Polyline, Point and Multipoint.</param>
        ///<param name="screenDisplay">An IScreenDisplay reference</param>
        ///<param name="delay">An integer that is the time in milliseconds to wait.</param>
        public static void FlashGeometry(IGeometry geometry, IScreenDisplay screenDisplay, int delay, int times)
        {
            if (geometry == null || screenDisplay == null)
            {
                return;
            }
            bool continueFlashing = true;

            using (ComReleaser comReleaser = new ComReleaser())
            {
                ITrackCancel cancelTracker = new CancelTrackerClass();
                comReleaser.ManageLifetime(cancelTracker);
                screenDisplay.CancelTracker = cancelTracker;
                short cacheID = screenDisplay.AddCache();
                int cacheMemDC = screenDisplay.get_CacheMemDC(cacheID);
                
                IRgbColor fillColor = new RgbColorClass();
                comReleaser.ManageLifetime(fillColor);
                fillColor.Green = 128;
                IRgbColor lineColor = new RgbColorClass();
                comReleaser.ManageLifetime(lineColor);

                screenDisplay.StartDrawing(cacheMemDC, cacheID);
                DrawGeometry(geometry, fillColor, lineColor, (IDisplay)screenDisplay, cancelTracker);
                ESRI.ArcGIS.esriSystem.tagRECT RECT = new tagRECT();
                screenDisplay.FinishDrawing();

                for (int j = 0; j < times; j++)
                {
                    if (continueFlashing == true)
                    {
                        screenDisplay.DrawCache(screenDisplay.hDC, cacheID, ref RECT, ref RECT);
                        if (delay > 0)
                        {
                            System.Threading.Thread.Sleep(delay);
                            screenDisplay.Invalidate(null, true, cacheID);
                            screenDisplay.UpdateWindow();
                            System.Threading.Thread.Sleep(delay);
                        }
                    }
                }
                //---------------------------------------------------------------------

                screenDisplay.RemoveCache(cacheID);
                cancelTracker.Reset();
            }
        }
Пример #39
0
        void IFeatureClassManager.DeleteFcInSde(string data)
        {
            using (ComReleaser releaser = new ComReleaser())
               {
               _workspaceEdit = (IWorkspaceEdit)_workspace;
               _mWorkspaceEdit = (IMultiuserWorkspaceEdit)_workspace;
               IFeatureWorkspace fw = (IFeatureWorkspace)_workspace;
               IFeatureClass fc=null;
               //releaser.ManageLifetime(_workspaceEdit);
               //releaser.ManageLifetime(_mWorkspaceEdit);
               //releaser.ManageLifetime(fw);
               //releaser.ManageLifetime(fc);
               try
               {
                   fc = fw.OpenFeatureClass(data);
               }
               catch
               {
                   return;
               }

               _mWorkspaceEdit.StartMultiuserEditing(esriMultiuserEditSessionMode.esriMESMVersioned);
               _workspaceEdit.StartEditOperation();

               try
               {
                   ((IDataset)fc).Delete();
                   _workspaceEdit.StartEditOperation();
                   _workspaceEdit.StopEditing(true);
               }
               catch (Exception ex)
               {
                   _workspaceEdit.AbortEditOperation();
                   _workspaceEdit.StopEditing(false);
               }

               }
        }
        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");
        }
Пример #41
0
        private static void Main(string[] args)
        {
            try
            {
                // ESRI License Initializer generated code.
                if (!arcobjectsLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeEngine, esriLicenseProductCode.esriLicenseProductCodeBasic, esriLicenseProductCode.esriLicenseProductCodeStandard, esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { }))
                {
                    Console.WriteLine(arcobjectsLicenseInitializer.LicenseMessage());
                    Console.WriteLine("This application could not initialize with the correct ArcGIS license and will shutdown.");
                    arcobjectsLicenseInitializer.ShutdownApplication();
                    return;
                }

                var options = new Options();
                Parser parser = new Parser();

                if (args.Length == 0 || args[0] == "-h" || args[0].Trim().ToLowerInvariant() == "help")
                {
                    Console.WriteLine(options.GetUsage());
                    Console.WriteLine("Press any key to continue ...");
                    Console.ReadKey();
                    return;
                }

                if (parser.ParseArguments(args, options))
                {
                    if (!Helper.ExistsFileGdb(options.PathAndFGDB))
                    {
                        Console.WriteLine("Filegeodatabase '{0}' not exists!", options.PathAndFGDB);
                        Console.WriteLine("Press any key to continue ...");
                        Console.ReadKey();
                        return;
                    }

                    IWorkspace workspace = Helper.FileGdbWorkspaceFromPath(options.PathAndFGDB);
                    IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;

                    string inputFeatureClassName = options.FeatureClassNameInput ?? "Points";

                    IWorkspace2 workspace2 = workspace as IWorkspace2;
                    if (!workspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, inputFeatureClassName))
                    {
                        Console.WriteLine("FeatureClass '{0}' not exists in filegeodatabase '{1}'!", inputFeatureClassName, options.PathAndFGDB);
                        Console.WriteLine("Press any key to continue ...");
                        Console.ReadKey();
                        return;
                    }

                    IFeatureClass featureClassPoints = featureWorkspace.OpenFeatureClass(inputFeatureClassName);
                    if (featureClassPoints.ShapeType != esriGeometryType.esriGeometryPoint)
                    {
                        Console.WriteLine("FeatureClass '{0}' is not type point!", inputFeatureClassName);
                        Console.WriteLine("Press any key to continue ...");
                        Console.ReadKey();
                        return;
                    }

                    string outputFeatureClassName = options.FeatureClassNameOutput ?? "Polygons";
                    if (workspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, outputFeatureClassName))
                    {
                        Console.Write("\nThe featureClass '{0}' exists. You want to overwrite it? Y/N ", outputFeatureClassName);
                        while (true)
                        {
                            ConsoleKeyInfo answer = Console.ReadKey(true);

                            if (answer.Key == ConsoleKey.N)
                            {
                                return;
                            }
                            else if (answer.Key == ConsoleKey.Y)
                            {
                                Console.Write("\n");
                                break;
                            }
                            else
                            {
                                Console.Write("\nPlease select a valid option (Y/N)!");
                            }
                        }

                        IDataset outputDataset = (IDataset)featureWorkspace.OpenFeatureClass(outputFeatureClassName);
                        if (outputDataset.CanDelete())
                        {
                            outputDataset.Delete();
                        }
                        else
                        {
                            Console.WriteLine("FeatureClass '{0}' couldn't be deleted", outputFeatureClassName);
                            Console.WriteLine("Press any key to continue ...");
                            Console.ReadKey();
                            return;
                        }
                    }

                    IFeatureClass featureClassPolygons = Program.CreateFeatureClassOutput(workspace, Helper.GetSpatialReference(featureClassPoints), outputFeatureClassName);

                    List<IPoint> locations = new List<IPoint>();

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        IFeatureCursor cursor = featureClassPoints.Search(null, true);
                        comReleaser.ManageLifetime(cursor);
                        IFeature feature = null;
                        while ((feature = cursor.NextFeature()) != null)
                        {
                            IPoint p = feature.ShapeCopy as IPoint;
                            locations.Add(p);
                        }
                    }

                    IList<IGeometry> thiessenPolygons = Triangulation.GeometryVoronoi(locations);

                    int idxId = featureClassPolygons.FindField(Program.nameFieldIdOutput);
                    int i = 0;
                    StringBuilder errorGeneratePolygon = new StringBuilder();
                    foreach (IGeometry pg in thiessenPolygons)
                    {
                        i++;
                        try
                        {
                            IFeature feature = featureClassPolygons.CreateFeature();
                            feature.Shape = pg as IPolygon;
                            feature.set_Value(idxId, i);
                            feature.Store();
                        }
                        catch (Exception ex)
                        {
                            errorGeneratePolygon.AppendLine(string.Format("Polygon id: {0} - Error: Message[{1}]\r\nSource[{2}]\r\nTrace[{3}]", i, ex.Message, ex.Source, ex.StackTrace));
                            errorGeneratePolygon.AppendLine();
                        }
                    }

                    string errorResult = errorGeneratePolygon.ToString();
                    if (!string.IsNullOrEmpty(errorResult))
                    {
                        Console.WriteLine(errorResult);
                        Console.WriteLine("Create polygons voronoi with errors!");
                    }
                    else
                    {
                        Console.WriteLine("Create polygons voronoi with success!");
                    }

                    Console.WriteLine("Press any key to continue ...");
                    Console.ReadKey();
                }
                else
                {
                    Console.WriteLine(options.GetUsageError());
                    Console.WriteLine("Press any key to continue ...");
                    Console.ReadKey();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error: Message[{0}]\r\nSource[{1}]\r\nTrace[{2}]", ex.Message, ex.Source, ex.StackTrace);
                Console.WriteLine("Press any key to continue ...");
                Console.ReadKey();
            }
            finally
            {
                try
                {
                    // ESRI License Initializer generated code.
                    // Do not make any call to ArcObjects after ShutDownApplication()
                    arcobjectsLicenseInitializer.ShutdownApplication();
                }
                catch
                {
                }
            }
        }
Пример #42
0
        private void addValuesToPointsFC(string prfName)
        {
            using (ComReleaser comReleaser = new ComReleaser())
            {
                if( pointsFC == null || profileData == null) return;

                List<List<double>> data = profileData.Where(c => c[3] > -999).ToList();

                //Spatialreference
                ISpatialReference srs = view.FocusMap.SpatialReference;
                // Create a feature buffer.
                IFeatureBuffer featureBuffer = pointsFC.CreateFeatureBuffer();
                comReleaser.ManageLifetime(featureBuffer);

                // Create an insert cursor.
                IFeatureCursor insertCursor = pointsFC.Insert(true);
                comReleaser.ManageLifetime(insertCursor);

                foreach (List<double> row in data)
                {
                    IPoint fromXY; IPoint toXY;

                    IPolyline4 geom = (IPolyline4)polyLineLam72;
                    fromXY = new PointClass();
                    geom.QueryPoint(esriSegmentExtension.esriNoExtension, row[0], false, fromXY);

                    //reproject the point
                    toXY = geopuntHelper.Transform(fromXY as IGeometry, map.SpatialReference) as IPoint;

                    featureBuffer.Shape = toXY as IGeometry;

                    int naamIdx = pointsFC.FindField("naam");
                    featureBuffer.set_Value(naamIdx, prfName);
                    int AfstandIdx = pointsFC.FindField("Afstand");
                    featureBuffer.set_Value(AfstandIdx, row[0]);
                    int HoogteIdx = pointsFC.FindField("Hoogte");
                    featureBuffer.set_Value(HoogteIdx, row[3]);

                    insertCursor.InsertFeature(featureBuffer);
                }
                insertCursor.Flush();
            }
        }
Пример #43
0
        object ICopyFeatures.CopyBulkFeature(IFeature copiedFeature, IFeatureClass toFeatureClass)
        {
            // Create a ComReleaser for cursor management.
               using (ComReleaser comReleaser = new ComReleaser())
               {
               // Create and manage a feature buffer.
               IFeatureBuffer featureBuffer = toFeatureClass.CreateFeatureBuffer();
               comReleaser.ManageLifetime(featureBuffer);

               // Create and manage an insert cursor.
               IFeatureCursor featureCursor = toFeatureClass.Insert(true);
               comReleaser.ManageLifetime(featureCursor);
               featureBuffer.Shape = copiedFeature.ShapeCopy;
               featureCursor.InsertFeature(featureBuffer);
               // Attempt to flush the buffer.
               featureCursor.Flush();
               //MessageBox.Show(string.Format("line 529 DataManager \n{0}", featureBuffer.get_Value(0)));
               //return featureBuffer.get_Value(0);
               return 1;
               }
        }
        public void DeleteShapeFile(string shapeFilePath)
        {
            string fcName = System.IO.Path.GetFileName(shapeFilePath);
            string folderName = System.IO.Path.GetDirectoryName(shapeFilePath);

            using (ComReleaser oComReleaser = new ComReleaser())
            {
                IWorkspaceFactory workspaceFactory = new ShapefileWorkspaceFactory();
                IWorkspace workspace = workspaceFactory.OpenFromFile(folderName, 0);
                IFeatureWorkspace fWorkspace = (IFeatureWorkspace)workspace;
                IDataset ipDs = fWorkspace.OpenFeatureClass(fcName) as IDataset;
                ipDs.Delete();

                File.Delete(shapeFilePath);

                System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace);
                workspace = null;
                fWorkspace = null;
                ipDs = null;
            }
 
            GC.Collect();
            
        }
        internal static void ThreadMain(SearchCandidateProviderProfile profile, TaskCompletionSource<SearchCandidateProvider> createComplete)
        {
            using (var mainReleaser = new ComReleaser())
            {
                try
                {
                    var profileMgr = mainReleaser.CreateComObject<ITfInputProcessorProfileMgr>();
                    if (profile == null)
                    {
                        var keyboardGuid = Guids.GUID_TFCAT_TIP_KEYBOARD;
                        var activeProfile = default(TF_INPUTPROCESSORPROFILE);
                        if (!profileMgr.GetActiveProfile(ref keyboardGuid, out activeProfile))
                        {
                            return;
                        }
                        if (activeProfile.dwProfileType == TF_PROFILETYPE.TF_PROFILETYPE_KEYBOARDLAYOUT)
                        {
                            // This is not a TIP.
                            return;
                        }
                        profile = new SearchCandidateProviderProfile(activeProfile.langid.ToCultureInfo(), activeProfile.clsid, activeProfile.guidProfile);
                    }
                    var name = profile.Name;
                    var langid = profile.LangId;
                    var clsid = profile.Clsid;
                    var profileGuid = profile.ProfileGuid;

                    if (!profileMgr.ActivateProfile(TF_PROFILETYPE.TF_PROFILETYPE_INPUTPROCESSOR, langid, ref clsid, ref profileGuid, IntPtr.Zero, TF_IPPMF.TF_IPPMF_DONTCARECURRENTINPUTLANGUAGE))
                    {
                        return;
                    }

                    var threadMgr = mainReleaser.CreateComObject<ITfThreadMgr2>();
                    var clientId = TextFrameworkDeclarations.TF_CLIENTID_NULL;
                    if (!threadMgr.ActivateEx(out clientId, default(TF_TMAE)))
                    {
                        return;
                    }
                    mainReleaser.RegisterCleanup(() => threadMgr.Deactivate());

                    var functionProvider = mainReleaser.ReceiveObject((out ITfFunctionProvider _) => threadMgr.GetFunctionProvider(ref clsid, out _));
                    if (functionProvider == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(name))
                    {
                        functionProvider.GetDescription(out name);
                    }
                    var guidNull = new Guid();
                    var iid = typeof(ITfFnSearchCandidateProvider).GUID;
                    var searchCandidateProvider = mainReleaser.ReceiveObject((out object _) => functionProvider.GetFunction(ref guidNull, ref iid, out _)) as ITfFnSearchCandidateProvider;
                    if (searchCandidateProvider == null)
                    {
                        return;
                    }
                    if (string.IsNullOrEmpty(name))
                    {
                        searchCandidateProvider.GetDisplayName(out name);
                    }

                    // Refresh the |profile| with the latest |name|.
                    profile = new SearchCandidateProviderProfile(profile.LangId.ToCultureInfo(), profile.Clsid, profile.ProfileGuid, name);

                    // It's time to enter the event loop.
                    using (var queue = new BlockingCollection<RequestQueueItem>())
                    {
                        createComplete.SetResult(new SearchCandidateProvider { RequestQueue = queue, Profile = profile });
                        foreach (var task in queue.GetConsumingEnumerable())
                        {
                            using (var releaser = new ComReleaser())
                            {
                                var stopWatch = Stopwatch.StartNew();
                                var response = task.Response;
                                try
                                {
                                    var result = searchCandidateProvider.GetSearchCandidates(task.Query).ToArray();
                                    response.SetResult(new SearchCandidateResponse(profile, task.Query, result, stopWatch.Elapsed));
                                }
                                catch (Exception e)
                                {
                                    if (!response.Task.IsCompleted)
                                    {
                                        response.SetResult(new SearchCandidateResponse(profile, task.Query, Enumerable.Empty<string>().ToArray(), stopWatch.Elapsed, e));
                                    }
                                }
                                finally
                                {
                                    if (!response.Task.IsCompleted)
                                    {
                                        response.SetResult(new SearchCandidateResponse(profile, task.Query, Enumerable.Empty<string>().ToArray(), stopWatch.Elapsed));
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception e)
                {
                    if (!createComplete.Task.IsCompleted)
                    {
                        createComplete.SetException(e);
                    }
                }
                finally
                {
                    if (!createComplete.Task.IsCompleted)
                    {
                        createComplete.SetResult(null);
                    }
                }
            }
        }
Пример #46
0
        /// <summary>insert the records from the GIPOD service into the shapefile </summary>
        private void populateGipodShape(IFeatureClass gipodFC, List<datacontract.gipodResponse> gipodRecords, dataHandler.gipodtype gtype)
        {
            //return if something is null
            if (gipodFC == null || gipodRecords == null) return;

            //get the srs
            ISpatialReference srs = view.FocusMap.SpatialReference;

            using (ComReleaser comReleaser = new ComReleaser())
            {
                // Create a feature buffer.
                IFeatureBuffer featureBuffer = gipodFC.CreateFeatureBuffer();
                comReleaser.ManageLifetime(featureBuffer);

                // Create an insert cursor.
                IFeatureCursor insertCursor = gipodFC.Insert(true);
                comReleaser.ManageLifetime(insertCursor);

                foreach (datacontract.gipodResponse row in gipodRecords)
                {
                    Double x = row.coordinate.coordinates[0];
                    Double y = row.coordinate.coordinates[1];
                    IPoint pt = new PointClass() { X = x, Y = y, SpatialReference = lam72 };
                    IPoint toPt =  geopuntHelper.Transform(pt, srs) as IPoint;

                    featureBuffer.Shape = toPt;

                    int id = row.gipodId;
                    int idIdx = gipodFC.FindField("gipodID");
                    featureBuffer.set_Value(idIdx, id);

                    string owner = row.owner;
                    if (owner.Length > 254) owner = owner.Substring(0, 254);
                    int ownerIdx = gipodFC.FindField("owner");
                    featureBuffer.set_Value(ownerIdx, owner);

                    //sometime very long, handle that
                    string description = row.description.Replace("\n", " ").Replace("\r", "");
                    int descriptionIdx = gipodFC.FindField("info");
                    int maxLen = featureBuffer.Fields.get_Field(descriptionIdx).Length;
                    if (description.Length > maxLen)
                    {
                        description = description.Substring(0, maxLen);
                    }
                    featureBuffer.set_Value(descriptionIdx, description);

                    DateTime startDate = row.startDateTime;
                    int startDateIdx = gipodFC.FindField("beginDate");
                    featureBuffer.set_Value(startDateIdx, startDate);

                    DateTime endDate = row.endDateTime;
                    int endDateIdx = gipodFC.FindField("endDate");
                    featureBuffer.set_Value(endDateIdx, endDate);

                    int hinder = row.importantHindrance ? 1 : 0;
                    int hinderIdx = gipodFC.FindField("hinder");
                    featureBuffer.set_Value(hinderIdx, hinder);

                    string detail = String.Format("http://www.geopunt.be/kaart?app=Hinder_in_kaart_app&GIPODID={0}&maximize=1", row.gipodId);//row.detail;
                    if (detail.Length > 254) detail = detail.Substring(0, 254);
                    int detailIdx = gipodFC.FindField("link");
                    featureBuffer.set_Value(detailIdx, detail);

                    string cities = string.Join(", ", row.cities.ToArray());
                    if (cities.Length > 254) cities = cities.Substring(0, 254);
                    int citiesIdx = gipodFC.FindField("cities");
                    featureBuffer.set_Value(citiesIdx, cities);

                    if (gtype == dataHandler.gipodtype.manifestation)
                    {
                        string initiator = row.initiator ;
                        if (initiator != null) {
                            if (initiator.Length > 254) initiator = initiator.Substring(0, 254);
                            int initiatorIdx = gipodFC.FindField("initiatief");
                            featureBuffer.set_Value(initiatorIdx, initiator);
                        }
                        string eventType = row.eventType ;
                        if (eventType != null) {
                            if (eventType.Length > 254) eventType = eventType.Substring(0, 254);
                            int eventTypeIdx = gipodFC.FindField("eventType");
                            featureBuffer.set_Value(eventTypeIdx, eventType);
                        }
                        string recurrencePattern = row.recurrencePattern ;
                        if (recurrencePattern != null) {
                            if (recurrencePattern.Length > 254) recurrencePattern = recurrencePattern.Substring(0, 254);
                            int recurrencePatternIdx = gipodFC.FindField("patroon");
                            featureBuffer.set_Value(recurrencePatternIdx, recurrencePattern);
                        }
                    }

                    insertCursor.InsertFeature(featureBuffer);
                }
                insertCursor.Flush();
            }
        }
Пример #47
0
        private static void WriteTable(StreamWriter tw, IFeatureWorkspace workspace, string dateWhereClause)
        {
            //Get the Featureclasses
            IFeatureClass gpsPoints = workspace.OpenFeatureClass("GpsPoints");
            IFeatureClass observations = workspace.OpenFeatureClass("Observations");
            IFeatureClass birdGroups = workspace.OpenFeatureClass("BirdGroups");
            IFeatureClass tracks = workspace.OpenFeatureClass("Tracks");

            // Get the Relationship Class Factory
            Type memRelClassFactoryType = Type.GetTypeFromProgID("esriGeodatabase.MemoryRelationshipClassFactory");
            var memRelClassFactory = (IMemoryRelationshipClassFactory)Activator.CreateInstance(memRelClassFactoryType);

            // Get the RelQueryTable factory.
            Type rqtFactoryType = Type.GetTypeFromProgID("esriGeodatabase.RelQueryTableFactory");
            var rqtFactory = (IRelQueryTableFactory)Activator.CreateInstance(rqtFactoryType);

            //Must create the relationship class in memory (don't load from fgdb), else NO outer join.
            //IRelationshipClass rc = featureWorkspace.OpenRelationshipClass("GpsPoint_Observation");

            // You can't do an left outer join with a one-to-many relationship
            //(many-to-one relationships are not supported and right outer joins are not supported)
            // must set first parameter to false to make the many table the sourece (i.e. to get all the records in the many table)
            // you must leave the first parameter to true to get all the records in the left table for the outer join.
            //
            //Solution is to create two tables and do the join in my code.  Yuck!

            IRelationshipClass relationship1 = memRelClassFactory.Open("Obs_Bg",
                observations, "ObservationID", birdGroups, "ObservationID",
                String.Empty, String.Empty, esriRelCardinality.esriRelCardinalityOneToMany);

            //Last parameter must be true to get a left outer join (right outer join if first param is false).
            //if first parameter is false, then tables are swapped.  Must swap tables to get many to 1 (source/origin/left to dest/foriegn/right)
            var table1 = (ITable)rqtFactory.Open(relationship1, false, null, null, String.Empty, false, false);

            #if DEBUG
            tw.WriteLine("table1"); DebugPrintTable(tw, table1);
            #endif
            var observationData = GetObservations(table1);

            IRelationshipClass relationship2 = memRelClassFactory.Open("Gps_Tracks",
                gpsPoints, "TrackID", tracks, "TrackID",
                String.Empty, String.Empty, esriRelCardinality.esriRelCardinalityOneToOne);
            //Last parameter must be true in order to do a query on the table.  Observed, not documented.
            var table2 = (ITable)rqtFactory.Open(relationship2, true, null, null, String.Empty, false, true);

            #if DEBUG
            tw.WriteLine("table2"); DebugPrintTable(tw, table2);
            #endif
            //filter results to only the year requested.
            var query = new QueryFilter {WhereClause = dateWhereClause};
            //Query does not sort correctly when doing outer joins
            //Can't use query when sorting by time point time and transect start
            //((IQueryFilterDefinition)query).PostfixClause = "ORDER BY GpsPoints.Time_local";

            tw.WriteLine(
                "TRANSECT_ID,DATE_LOCAL,TIME_LOCAL,VESSEL,"+
                "RECORDER,OBSERVER_1,OBSERVER_2,BEAUFORT,"+
                "WEATHER_CODE,VISIBILITY,LATITUDE_WGS84,LONGITUDE_WGS84," +
                "UTM8_EASTING,UTM8_NORTHING,SPEED,BEARING," +
                "ANGLE,DISTANCE,BEHAVIOR,GROUP_SIZE,"+
                "SPECIES,ON_TRANSECT,PROTOCOL_ID,GPS_STATUS,"+
                "SATELLITES,HDOP,TRACK_LENGTH,COMMENTS,"+
                "DATA_QUALITY,DATA_QUALITY_CODE");

            var lines = new List<Line>();
            var lengths = new Dictionary<string, Dictionary<string, double>>();
            var transectLengths = new Dictionary<string, double>();

            using (var comReleaser = new ComReleaser())
            {
                //ICursor is a one pass object.  We search twice, once to get tracklengths by transect;
                ICursor cursor = table2.Search(query, true);
                comReleaser.ManageLifetime(cursor);
                IRow row;
                while ((row = cursor.NextRow()) != null)
                {
                    string transect = row.Value[26].ToString();
                    bool ontransect = Boolean.Parse(row.Value[28].ToString());
                    string trackId = row.Value[25].ToString();
                    var tracklength = (double)row.Value[29];
                    if (!lengths.ContainsKey(transect))
                        lengths[transect] = new Dictionary<string, double>();
                    //skip tracks I've already seen
                    if (!lengths[transect].ContainsKey(trackId))
                        if (ontransect)
                            lengths[transect][trackId] = tracklength;
                }
                //Sum up the on-transect tracks for each transect
                foreach (var length in lengths)
                {
                    if (!transectLengths.ContainsKey(length.Key))
                        transectLengths[length.Key] = 0;
                    foreach (var trackLength in length.Value)
                    {
                        transectLengths[length.Key] += trackLength.Value;
                    }
                }

                var emptyObservationList = new List<Observation>{new Observation{Data = ",,,,", Comment=""}};

                //Second search to format output
                cursor = table2.Search(query, true);
                while ((row = cursor.NextRow()) != null)
                {
                    var utm = (IPoint)row.Value[1];
                    var localDateTime = (DateTime) row.Value[6];
                    var trackDateTime = (DateTime) row.Value[20];
                    string date = localDateTime.ToString("yyyy-MM-dd");
                    string time = localDateTime.ToString("HH:mm:ss");
                    string transect = row.Value[26].ToString();
                    object gpsId = row.Value[13];
                    List<Observation> observationList = observationData.ContainsKey(gpsId) ? observationData[gpsId] : emptyObservationList;
                    foreach (var observation in observationList)
                    {
                        var sb = new StringBuilder();
                        sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",", transect, date, time, row.Value[16]);
                        sb.AppendFormat("\"{0}\",\"{1}\",\"{2}\",\"{3}\",", row.Value[17], row.Value[18], row.Value[19], row.Value[24]);
                        sb.AppendFormat("\"{0}\",{1},{2},{3},", row.Value[23], row.Value[22], row.Value[3], row.Value[4]);
                        sb.AppendFormat("{0},{1},{2},{3},", utm.X, utm.Y, row.Value[10], row.Value[11]);
                        sb.AppendFormat("{0},", observation.Data);
                        sb.AppendFormat("\"{0}\",\"{1}\",{2},", row.Value[28], row.Value[27], row.Value[12]);
                        sb.AppendFormat("{0},{1},{2},{3},", row.Value[8], row.Value[7], transectLengths[transect], observation.Comment);
                        sb.Append(",,");
                        lines.Add(new Line { Date = localDateTime, TrackDate = trackDateTime, Text = sb.ToString() });
                    }
                }
            }
            lines.Sort();
            foreach (var line in lines)
                tw.WriteLine(line.Text);
        }
Пример #48
0
        private static void DebugPrintTable(StreamWriter tw, ITable table)
        {
            using (var comReleaser = new ComReleaser())
            {
                ICursor cursor = table.Search(null, true);
                comReleaser.ManageLifetime(cursor);
                IRow row;
                var sb = new StringBuilder();
                int c = table.Fields.FieldCount;

                for (int i = 0; i < c; i++)
                    sb.AppendFormat("\"{0}\",", table.Fields.Field[i].Name);
                tw.WriteLine(sb.ToString());

                while ((row = cursor.NextRow()) != null)
                {
                    sb = new StringBuilder();
                    for (int i = 0; i < c; i++)
                        sb.AppendFormat("\"{0}\",", row.Value[i]);
                    tw.WriteLine(sb.ToString());
                }
            }
        }
Пример #49
0
        public static void InsertFeaturesUsingCursor(IFeatureClass featureClass, List<IGeometry> geometryList)
        {
            using (ComReleaser comReleaser = new ComReleaser())
            {
                IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                comReleaser.ManageLifetime(featureBuffer);

                IFeatureCursor insertCursor = featureClass.Insert(true);
                comReleaser.ManageLifetime(insertCursor);

                int typeFieldIndex = featureClass.FindField("Name");
                int i = 1;
                foreach (IGeometry geometry in geometryList)
                {
                    featureBuffer.Shape = geometry;
                    featureBuffer.set_Value(typeFieldIndex, i++.ToString());
                    insertCursor.InsertFeature(featureBuffer);
                }
                insertCursor.Flush();
            }
        }
Пример #50
0
        public void IteratioRecyclingTest()
        {
            IFeatureClass feacl = loadFeatureClasFromFolder(@"E:\data", "origin");
            if (feacl == null)
                return;
            using (ComReleaser comReleaser = new ComReleaser())
            {
                IFeatureCursor feaCursor = feacl.Search(null, true);
                comReleaser.ManageLifetime(feaCursor);
                IFeature fea1 = feaCursor.NextFeature();
                if (fea1 == null)
                    return;

                int index = feacl.FindField("FinalScore");
                while (fea1 != null)
                {
                    object ovalue = fea1.get_Value(index);
                    fea1.set_Value(index, Convert.ToDouble(ovalue) + 100);
                    fea1.Store();
                    Console.WriteLine(Convert.ToDouble(ovalue));
                    //fea1.Store();
                    fea1 = feaCursor.NextFeature();
                }
            }
        }
Пример #51
0
        private void weigthingOnFeatureClass(IFeatureClass feacls, string[] strFields, double[] weights)
        {
            int[] index = new int[strFields.Length];
            for (int i = 0; i < index.Length; i++)
            {
                index[i] = feacls.FindField(strFields[i]);
            }

            int scoreIndex=feacls.FindField("FinalScore");

            int Count=1;
            using (ComReleaser comReleaser = new ComReleaser())
            {
                IFeatureCursor cursor = feacls.Search(null, false);
                comReleaser.ManageLifetime(cursor);
                IFeature feature = cursor.NextFeature();

                while (feature != null)
                {
                    double weightedscore = 0;
                    for (int j=0;j<index.Length;j++)
                    {
                        object obj=feature.get_Value(index[j]);
                        if (obj is DBNull)
                            obj = feature.Fields.get_Field(index[j]).DefaultValue;
                        weightedscore+=weights[j]*Convert.ToDouble(obj);
                    }

                    feature.set_Value(scoreIndex,weightedscore);
                    feature.Store();
                    Console.WriteLine(Count + "   finished");
                    Count++;
                    feature = cursor.NextFeature();
                }
            }
        }
Пример #52
0
        private void addScoreToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IFeatureLayer fealyr = axMapControl1.get_Layer(0) as IFeatureLayer;
            IFeatureClass feacls = fealyr.FeatureClass;
            IField field = new FieldClass();
            IFieldEdit2 fe = field as IFieldEdit2;
            fe.Name_2 = "FinalScore";
            fe.Type_2 = esriFieldType.esriFieldTypeDouble;

            feacls.AddField(field);
            int index = feacls.FindField("FinalScore");
            object obj = null;
            Random rand = new Random();
            using (ComReleaser com = new ComReleaser())
            {

                IFeatureCursor cursor = feacls.Search(null, true);
                com.ManageLifetime(cursor);

                IFeature fea = cursor.NextFeature();
                while (fea != null)
                {
                    obj = rand.NextDouble() * 100;
                    fea.set_Value(index, obj);
                    fea.Store();
                    fea = cursor.NextFeature();
                }
            }
        }
        /// <summary>
        /// Export graphics to a shapefile
        /// </summary>
        /// <param name="fileNamePath">Path to shapefile</param>
        /// <param name="graphicsList">List of graphics for selected tab</param>
        /// <param name="ipSpatialRef">Spatial Reference being used</param>
        /// <returns>Created featureclass</returns>
        private IFeatureClass ExportToShapefile(string fileNamePath, List<Graphic> graphicsList, ISpatialReference ipSpatialRef)
        {
            int index = fileNamePath.LastIndexOf('\\');
            string folder = fileNamePath.Substring(0, index);
            string nameOfShapeFile = fileNamePath.Substring(index + 1);
            string shapeFieldName = "Shape";
            IFeatureClass featClass = null;

            using (ComReleaser oComReleaser = new ComReleaser())
            {
                try
                {
                    IWorkspaceFactory workspaceFactory = null;
                    workspaceFactory = new ShapefileWorkspaceFactoryClass();
                    IWorkspace workspace = workspaceFactory.OpenFromFile(folder, 0);
                    IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace;
                    IFields fields = null;
                    IFieldsEdit fieldsEdit = null;
                    fields = new Fields();
                    fieldsEdit = (IFieldsEdit)fields;
                    IField field = null;
                    IFieldEdit fieldEdit = null;
                    field = new FieldClass();///###########
                    fieldEdit = (IFieldEdit)field;
                    fieldEdit.Name_2 = "Shape";
                    fieldEdit.Type_2 = (esriFieldType.esriFieldTypeGeometry);
                    IGeometryDef geomDef = null;
                    IGeometryDefEdit geomDefEdit = null;
                    geomDef = new GeometryDefClass();///#########
                    geomDefEdit = (IGeometryDefEdit)geomDef;

                    //This is for line shapefiles
                    geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline;
                    geomDefEdit.SpatialReference_2 = ipSpatialRef;

                    fieldEdit.GeometryDef_2 = geomDef;
                    fieldsEdit.AddField(field);

                    ////Add another miscellaneous text field
                    //field = new FieldClass();
                    //fieldEdit = (IFieldEdit)field;
                    //fieldEdit.Length_2 = 30;
                    //fieldEdit.Name_2 = "TextField";
                    //fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                    //fieldsEdit.AddField(field);

                    featClass = featureWorkspace.CreateFeatureClass(nameOfShapeFile, fields, null, null, esriFeatureType.esriFTSimple, shapeFieldName, "");

                    foreach (Graphic graphic in graphicsList)
                    {
                        IFeature feature = featClass.CreateFeature();

                        feature.Shape = graphic.Geometry;
                        feature.Store();
                    }

                    IFeatureLayer featurelayer = null;
                    featurelayer = new FeatureLayerClass();
                    featurelayer.FeatureClass = featClass;
                    featurelayer.Name = featClass.AliasName;

                    System.Runtime.InteropServices.Marshal.FinalReleaseComObject(workspace);
                    workspace = null;
                    GC.Collect();

                    return featClass;
                }
                catch (Exception ex)
                {
                    return featClass;
                }
            }
        }
        public long unversionedEdit(IQueryFilter qFilterGen, int sequenceColumnNum, int idxSeqField, int curLoop, ref ITransactions transactions)
        {
            long sequenceValue = -1;
            using (ComReleaser comReleaser = new ComReleaser())
            {

                if (AAState._gentabWorkspace.IsInEditOperation)
                {
                    // throw new Exception("Cannot use ITransactions during an edit operation.");
                }
                // Begin a transaction.
                if (transactions == null)
                {
                    transactions = (ITransactions)AAState._gentabWorkspace;
                }

                transactions.StartTransaction();
                try
                {
                    // Use ITable.Update to create an update cursor.
                    ICursor seq_updateCursor = AAState._gentab.Update(qFilterGen, true);
                    comReleaser.ManageLifetime(seq_updateCursor);

                    IRow seq_row = null;
                    seq_row = seq_updateCursor.NextRow();
                    int sequenceInt = 1;

                    if (seq_row != null)
                    {
                        if (idxSeqField > 0)
                        {
                            object seqInt = seq_row.get_Value(idxSeqField);
                            if (seqInt != null)
                            {
                                if (seqInt != DBNull.Value)
                                    try
                                    {
                                        sequenceInt = Convert.ToInt32(seqInt);
                                    }
                                    catch
                                    {

                                    }
                            }
                        }
                        object seqValue = seq_row.get_Value(sequenceColumnNum);

                        if (seqValue == null)
                        {
                            sequenceValue = 0;
                        }
                        else if (seqValue.ToString() == "")
                        {
                            sequenceValue = 0;
                        }
                        else
                            try
                            {
                                sequenceValue = Convert.ToInt64(seqValue);
                            }
                            catch
                            {
                                sequenceValue = 0;
                            }

                        AAState.WriteLine("                  " + sequenceValue + " is the existing value and the interval is " + sequenceInt + ": " + DateTime.Now.ToString("h:mm:ss tt"));

                        sequenceValue = sequenceValue + sequenceInt;

                        seq_row.set_Value(sequenceColumnNum, sequenceValue);
                        AAState.WriteLine("                  " + seq_row.Fields.get_Field(sequenceColumnNum).AliasName + " changed to " + sequenceValue + ": " + DateTime.Now.ToString("h:mm:ss tt"));

                        seq_updateCursor.UpdateRow(seq_row);

                        transactions.CommitTransaction();

                        seq_updateCursor = AAState._gentab.Search(qFilter, true);
                        if (seq_row != null)
                        {
                            seqValue = seq_row.get_Value(sequenceColumnNum);

                            if (seqValue == null)
                            {
                                return sequenceValue;
                            }
                            else if (seqValue.ToString() == "")
                            {
                                return sequenceValue;
                            }
                            else
                                try
                                {
                                    if (sequenceValue == Convert.ToInt64(seqValue))
                                    {
                                        return sequenceValue;
                                    }
                                    else
                                    {
                                        if (curLoop > 30)
                                        {
                                            MessageBox.Show("A unique ID could not be generated after 30 attempts: " + DateTime.Now.ToString("h:mm:ss tt"));
                                        }
                                        else
                                        {
                                            return unversionedEdit(qFilterGen, sequenceColumnNum, idxSeqField, curLoop + 1, ref transactions);
                                        }
                                    }
                                }
                                catch
                                {
                                    return sequenceValue;
                                }
                        }
                        return sequenceValue;
                    }
                    else
                    {
                        AAState.WriteLine("                  No records found in Generate ID table" + ": " + DateTime.Now.ToString("h:mm:ss tt"));
                        transactions.AbortTransaction();
                        return -1;
                    }
                }
                catch (COMException comExc)
                {
                    AAState.WriteLine("                  Error saving transaction to DB" + ": " + DateTime.Now.ToString("h:mm:ss tt"));

                    // If an error occurs during the inserts and updates, rollback the transaction.
                    transactions.AbortTransaction();
                    return -1;
                }

            }
        }
Пример #55
0
        public bool InsertNewRow(ITable table,IWorkspaceEdit workspace)
        {
            using (ComReleaser comReleaser = new ComReleaser())
            {
                try
                {
                    multiWspEdit.StartMultiuserEditing(esriMultiuserEditSessionMode.esriMESMVersioned);
                    workspace.StartEditOperation();
                    _currentRow = table.CreateRow();
                    _currentRow.Store();
                    workspace.StopEditOperation();
                    workspace.StopEditing(true);
                    return true;
                }
                catch {
                    workspace.StopEditOperation();
                    workspace.StopEditing(false);
                    return false; }

            }
        }
 /// <summary>
 /// 4.去除多边形内的空白区域
 ///   多边形面积/空白面积>3
 /// </summary>
 /// <param name="radio"></param>
 private void RemoveBlankSpace(IFeatureClass feacls,double radio)
 {
     //确定多边形内存在环,且环中无其他多边形
     using(ComReleaser com=new ComReleaser())
     {
         IFeatureCursor cursor = feacls.Update(null, true);
         com.ManageLifetime(cursor);
         IFeature fea = cursor.NextFeature();
         while (fea != null)
         {
             IPolygon3 poly = fea.Shape as IPolygon3;
             IGeometryCollection geomCollection = poly as IGeometryCollection;
             if (geomCollection.GeometryCount <= 1)
             {
                 fea = cursor.NextFeature();
                 continue;
             }
             else
             {
                /* IRing ring = null;
                 IRing exRing = null;
                 List<IRing> rlist = new List<IRing>();
                 for (int i = 0; i < geomCollection.GeometryCount; i++)
                 {
                     ring = geomCollection.get_Geometry(i) as IRing;
                     if (ring.IsExterior)
                     {
                         exRing = ring;
                         continue;
                     }
                     rlist.Add(ring);
                 }
                 IArea area = exRing as IArea;
                 double extArea = area.Area;
                 foreach (IRing item in rlist)
                 {
                     double inArea = ((IArea)item).Area;
                     if(extArea/inArea>3)
                     {
                         item.SetEmpty();
                     }
                 }
                 geomCollection.GeometriesChanged();
                 fea.Store();
                 fea = cursor.NextFeature();*/
                 int i = 0;
                 while(i<geomCollection.GeometryCount)
                 {
                     IRing ring = geomCollection.get_Geometry(i) as IRing;
                     if(ring.IsExterior)
                     {
                         i++;
                         continue;
                     }
                     else
                     {
                         geomCollection.RemoveGeometries(i, 1);
                         geomCollection.GeometriesChanged();
                         continue;
                     }
                 }
                 fea.Store();
                 fea = cursor.NextFeature();
             }
         }
     }
 }
Пример #57
0
        private static void PutGridInFeatureClass(IFeatureClass featureClass, Grid grid)
        {
            using (var comReleaser = new ComReleaser())
            {
                // Create a feature buffer.
                IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                comReleaser.ManageLifetime(featureBuffer);

                // Create an insert cursor.
                IFeatureCursor insertCursor = featureClass.Insert(true);
                comReleaser.ManageLifetime(insertCursor);

                // All of the features to be created are classified as Primary Highways.
                int colFieldIndex = featureClass.FindField("Col");
                int rowFieldIndex = featureClass.FindField("Row");
                int colLabelFieldIndex = featureClass.FindField("Col_Label");
                int rowLabelFieldIndex = featureClass.FindField("Row_Label");
                int cellLabelFieldIndex = featureClass.FindField("Cell_Label");
                int pageFieldIndex = featureClass.FindField("Page");

                foreach (Cell cell in grid.Cells)
                {
                    featureBuffer.Shape = cell.Shape;
                    featureBuffer.Value[colFieldIndex] = cell.Column;
                    featureBuffer.Value[rowFieldIndex] = cell.Row;
                    featureBuffer.Value[colLabelFieldIndex] = cell.ColumnLabel;
                    featureBuffer.Value[rowLabelFieldIndex] = cell.RowLabel;
                    featureBuffer.Value[cellLabelFieldIndex] = cell.Label;
                    featureBuffer.Value[pageFieldIndex] = cell.Page;
                    insertCursor.InsertFeature(featureBuffer);
                }

                // Flush the buffer to the geodatabase.
                insertCursor.Flush();
            }
        }
Пример #58
0
        void IFeatureClassManager.DeleteFeatureClass(IDataset data)
        {
            using (ComReleaser releaser = new ComReleaser())
               {
               _workspaceEdit = (IWorkspaceEdit)_workspace;
               _mWorkspaceEdit = (IMultiuserWorkspaceEdit)_workspace;
               //releaser.ManageLifetime(_workspaceEdit);
               //releaser.ManageLifetime(_mWorkspaceEdit);

               _mWorkspaceEdit.StartMultiuserEditing(esriMultiuserEditSessionMode.esriMESMVersioned);
               _workspaceEdit.StartEditOperation();

               try
               {
                   data.Delete();
                   _workspaceEdit.StartEditOperation();
                   _workspaceEdit.StopEditing(true);
               }
               catch (Exception ex)
               {
                   _workspaceEdit.AbortEditOperation();
                   _workspaceEdit.StopEditing(false);
               }

               }
               //fcThuaCliped = fw.OpenFeatureClass("thua_sau50m_clip");
               //IDataset ft = (IDataset)fcThuaCliped;
        }
        /// <summary>
        /// 1.数据预处理
        /// 遍历整个Feature Class 完成
        /// 获取打分字段最大最小值
        /// 去除不合理狭长区域(数据本身存在问题)
        /// 去除极小块斑点 50平米
        /// </summary>
        private void PreProcessingData(out double minval, out double maxval, double deleteArea, double radio)
        {
            minval = 0;
            maxval = 0;
            using (ComReleaser comReleaser = new ComReleaser())
            {
                //IFeatureCursor feaCursor = m_FeaCls.Search(null, true);
                IFeatureCursor feaCursor = m_FeaCls.Update(null, true);
                int targetIndex = m_FeaCls.FindField(m_PartitionField);
                int lengthIndex = m_FeaCls.FindField("Shape_Leng");
                int areaIndex = m_FeaCls.FindField("Shape_Area");

                comReleaser.ManageLifetime(feaCursor);

                IFeature fea = feaCursor.NextFeature();
                maxval = Convert.ToDouble(fea.get_Value(targetIndex));
                minval = Convert.ToDouble(fea.get_Value(targetIndex));
                while (fea != null)
                {
                    double length = Convert.ToDouble(fea.get_Value(lengthIndex));
                    double area = Convert.ToDouble(fea.get_Value(areaIndex));
                    if (length / area >= radio)
                    {
                        feaCursor.DeleteFeature();
                        fea = feaCursor.NextFeature();
                        continue;
                    }
                    if (area <= 50)
                    {
                        feaCursor.DeleteFeature();
                        fea = feaCursor.NextFeature();
                        continue;
                    }

                    double tempV = Convert.ToDouble(fea.get_Value(targetIndex));

                    if (tempV >= maxval)
                        maxval = tempV;
                    if (tempV < minval)
                        minval = tempV;

                    fea = feaCursor.NextFeature();
                }

            }
        }
Пример #60
0
        private List<string> GetNames()
        {
            if (_data == null)
                throw new Exception("Unable to build this picklist due to invalid (or unvalidated) configuration properties.");

            var results = new List<string>();

            using(var comReleaser = new ComReleaser())
            {
                ICursor cursor = _data.Search(null, true);
                comReleaser.ManageLifetime(cursor);
                IRow row;
                // typically field 0 has the OID, and field 1 has the picklist value
                // however if there is only one field, then use it
                int index = _data.Fields.FieldCount < 2 ? 0 : 1;
                while ((row = cursor.NextRow()) != null)
                {
                    results.Add(row.Value[index].ToString());
                }
            }

            return results;
        }