Esempio n. 1
0
        public OperateDefectLayer(string name)
        {
            IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace();

            string path = System.Configuration.ConfigurationSettings.AppSettings["GisPath"].ToString();

            //若不存在shp文件,则创建
            if (!DefineLayer.findLayer(path, name))
            {
                new CreateLayer(path, name).CreateDefectLayer();
            }

            //IFeatureClass pFeatureClass = featureWorkspace.OpenFeatureClass(name);
            //IFeatureLayer flayer = new FeatureLayer();
            //pFeatureLayer.FeatureClass = pFeatureClass;

            pFeatureClass = featureWorkspace.OpenFeatureClass(name);
            pFeatureLayer = new FeatureLayer();
            pFeatureLayer.FeatureClass = pFeatureClass;

            //pFeatureLayer = GISMapApplication.Instance.GetLayer(name) as IFeatureLayer;
            //pFeatureClass = pFeatureLayer.FeatureClass;
            this.GXIDIndex      = pFeatureClass.FindField("GXID");
            this.GYIDIndex      = pFeatureClass.FindField("GYID");
            this.LevelIndex     = pFeatureClass.FindField("Level");
            this.RecePowerIndex = pFeatureClass.FindField("RecePower");
        }
        // 列名
        public OperateCoverGirdLayer(string layerName)
        {
            IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace();

            string path = System.Configuration.ConfigurationSettings.AppSettings["GisPath"].ToString();

            //若不存在shp文件,则创建
            if (!DefineLayer.findLayer(path, layerName))
            {
                //new CreateLayer(path, layerName).Test();
                new CreateLayer(path, layerName).CreateCoverLayer();
            }

            pFeatureClass = featureWorkspace.OpenFeatureClass(layerName);

            pFeatureLayer = new FeatureLayer();
            pFeatureLayer.FeatureClass = pFeatureClass;
            //int n = pFeatureClass.FeatureCount(new QueryFilterClass());

            //pFeatureLayer = GISMapApplication.Instance.GetLayer(LayerNames.CoverGrids) as IFeatureLayer;
            //pFeatureClass = pFeatureLayer.FeatureClass;
            this.RecePowerIndex = pFeatureClass.FindField("RecePower");
            this.PathLossIndex  = pFeatureClass.FindField("PathLoss");
            this.GXIDIndex      = pFeatureClass.FindField("GXID");
            this.GYIDIndex      = pFeatureClass.FindField("GYID");
            this.cellNameIndex  = pFeatureClass.FindField("CellName");
            this.eNodeBIndex    = pFeatureClass.FindField("eNodeB");
            this.CIIndex        = pFeatureClass.FindField("CI");
            this.LongitudeIndex = pFeatureClass.FindField("Longitude");
            this.LatitudeIndex  = pFeatureClass.FindField("Latitude");
            this.LevelIndex     = pFeatureClass.FindField("Level");
        }
Esempio n. 3
0
        public QaSliverPolygon(
            [Doc(nameof(DocStrings.QaSliverPolygon_polygonClass))] IFeatureClass polygonClass,
            [Doc(nameof(DocStrings.QaSliverPolygon_limit))] double limit,
            [Doc(nameof(DocStrings.QaSliverPolygon_maxArea))] double maxArea)
            : base((ITable)polygonClass)
        {
            Assert.ArgumentNotNull(polygonClass, nameof(polygonClass));
            Assert.ArgumentCondition(
                polygonClass.ShapeType == esriGeometryType.esriGeometryPolygon ||
                polygonClass.ShapeType == esriGeometryType.esriGeometryMultiPatch,
                "Not a polygon or Multipatch feature class");

            _limit          = limit;
            _maxArea        = maxArea;
            _shapeFieldName = polygonClass.ShapeFieldName;

            IField areaField   = DatasetUtils.GetAreaField(polygonClass);
            IField lengthField = DatasetUtils.GetLengthField(polygonClass);

            _areaFieldIndex = areaField == null
                                                  ? -1
                                                  : polygonClass.FindField(areaField.Name);
            _lengthFieldIndex = lengthField == null
                                                    ? -1
                                                    : polygonClass.FindField(lengthField.Name);
            _useFields = _areaFieldIndex >= 0 && _lengthFieldIndex >= 0;
        }
Esempio n. 4
0
        public static List <ObservationObject> GetObservationObjectsFromFeatureClass(IFeatureClass featureClass)
        {
            var observationObjects = new List <ObservationObject>();

            var idFieldIndex    = featureClass.FindField(featureClass.OIDFieldName);
            var titleFieldIndex = featureClass.FindField("sTitleOO");

            if (titleFieldIndex == -1)
            {
                titleFieldIndex = idFieldIndex;
            }

            if (idFieldIndex == -1)
            {
                logger.WarnEx($"> GetObservationObjectsFromFeatureClass. Warning: Cannot find fild \"{featureClass.OIDFieldName}\" in featureClass {featureClass.AliasName}");
                return(null);
            }

            IQueryFilter queryFilter = new QueryFilter();

            queryFilter.WhereClause = $"{featureClass.OIDFieldName} >= 0";

            IFeatureCursor featureCursor = featureClass.Search(queryFilter, true);
            IFeature       feature       = featureCursor.NextFeature();

            try
            {
                while (feature != null)
                {
                    var shape = feature.ShapeCopy;

                    var geometry = shape as IGeometry;

                    var id             = (int)feature.Value[idFieldIndex];
                    var displayedField = feature.Value[titleFieldIndex].ToString();

                    observationObjects.Add(new ObservationObject
                    {
                        Id       = id.ToString(),
                        ObjectId = id,
                        Title    = displayedField,
                        DTO      = DateTime.Now,
                        Creator  = Environment.UserName
                    });

                    feature = featureCursor.NextFeature();
                }
            }
            catch (Exception ex)
            {
                logger.ErrorEx($"> GetObservationObjectsFromFeatureClass Exception. ex.Message:{ex.Message}");
                return(null);
            }
            finally
            {
                Marshal.ReleaseComObject(featureCursor);
            }

            return(observationObjects);
        }
        // 列名
        public OperateTINLayer(string layerName)
        {
            //IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace();
            //IFeatureClass fclass = featureWorkspace.OpenFeatureClass(layerName);
            //IFeatureLayer flayer = new FeatureLayer();
            //pFeatureLayer.FeatureClass = pFeatureClass;

            IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace();
            string            path             = System.Configuration.ConfigurationSettings.AppSettings["GisPath"].ToString();

            //若不存在shp文件,则创建
            if (!DefineLayer.findLayer(path, layerName))
            {
                new CreateLayer(path, layerName).CreateTinLayer();
            }
            pFeatureClass = featureWorkspace.OpenFeatureClass(layerName);
            pFeatureLayer = new FeatureLayer();
            pFeatureLayer.FeatureClass = pFeatureClass;
            this.point1Index           = pFeatureClass.FindField("point1");
            this.point2Index           = pFeatureClass.FindField("point2");
            this.point3Index           = pFeatureClass.FindField("point3");

            //pFeatureLayer = GISMapApplication.Instance.GetLayer(LayerNames.TIN) as IFeatureLayer;
            //pFeatureClass = pFeatureLayer.FeatureClass;
        }
Esempio n. 6
0
 public PipeClassInfo(IFeatureClass pipeClass, string lineStartUnderGroundElevString,
                      string lineEndUnderGroundElevString, string lineStartGroundElevString, string lineEndGroundElevString)
 {
     PipeClass = pipeClass;
     StartGroundElevationField = new PipeSpecialFieldInfo
     {
         Name  = lineStartGroundElevString,
         Index = pipeClass.FindField(lineStartGroundElevString)
     };
     EndGroundElevationField = new PipeSpecialFieldInfo
     {
         Name  = lineEndGroundElevString,
         Index = pipeClass.FindField(lineEndGroundElevString)
     };
     StartUnderGroundElevationField = new PipeSpecialFieldInfo
     {
         Name  = lineStartUnderGroundElevString,
         Index = pipeClass.FindField(lineStartUnderGroundElevString)
     };
     EndUnderGroundElevationField = new PipeSpecialFieldInfo
     {
         Name  = lineEndUnderGroundElevString,
         Index = pipeClass.FindField(lineEndUnderGroundElevString)
     };
 }
        private void addAdres2FC(double x, double y, ISpatialReference srs, string adres, string adresType)
        {
            if (reverseFC == null)
            {
                return;
            }

            IPoint pt = new PointClass()
            {
                X = x, Y = y, SpatialReference = srs
            };

            IFeature feature = reverseFC.CreateFeature();

            feature.Shape = (IGeometry)pt;

            if (adres.Length > 254)
            {
                adres = adres.Substring(0, 254);
            }

            int adresIdx     = reverseFC.FindField("adres");
            int adresTypeIdx = reverseFC.FindField("adresType");

            feature.set_Value(adresIdx, adres);
            feature.set_Value(adresTypeIdx, adresType);

            feature.Store();
        }
        //private IFeatureClass Create_PointFeature(List<Point3D> PointList,string FileFullPath)
        //{
        //    string FileName = System.IO.Path.GetFileName(FileFullPath);
        //    IFeatureClass MptFeatureClass;


        //}


        private void Complete_PropertyTable(ref IFeatureClass pFeatureClass, List <Point3D> PointList)
        {
            string[] FieldName = { "ptName", "X", "Y", "Z" };
            IClass   pTable    = pFeatureClass as IClass;   //use ITable or IClass

            for (int i = 0; i < FieldName.Length; i++)
            {
                IField     pField = new FieldClass();
                IFieldEdit pFieldEdit;
                pFieldEdit        = pField as  IFieldEdit;
                pFieldEdit.Name_2 = FieldName[i];
                if (i == 0)
                {
                    pFieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
                }
                else
                {
                    pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                }
                pTable.AddField(pFieldEdit);
            }

            for (int i = 0; i < pFeatureClass.FeatureCount(null); i++)
            {
                IFeature pFeature = pFeatureClass.GetFeature(i);
                pFeature.set_Value(pFeatureClass.FindField(FieldName[0]), PointList[i].ID);
                pFeature.set_Value(pFeatureClass.FindField(FieldName[1]), PointList[i].X);
                pFeature.set_Value(pFeatureClass.FindField(FieldName[2]), PointList[i].Y);
                pFeature.set_Value(pFeatureClass.FindField(FieldName[3]), PointList[i].Z);
                pFeature.Store();
            }
        }
Esempio n. 9
0
        public void convertFeatureToRaster(IFeatureClass InFeatureClass, string fldName)
        {
            ftrCls   = InFeatureClass;
            ftrField = fldName;
            IDataset dSet    = (IDataset)InFeatureClass;
            string   outRsNm = dSet.BrowseName;

            wks = dSet.Workspace;
            if (vRs != null)
            {
                if (!checkProjectionsFtr())
                {
                    if (rd != null)
                    {
                        rd.addMessage("Re-projecting feature class to match value raster's projection");
                    }
                    InFeatureClass = reprojectInFeatureClass(InFeatureClass, vRs.RasterInfo.SpatialReference);
                }
            }
            IWorkspace             wksTemp = geoUtil.OpenRasterWorkspace(tempWksStr);
            IFunctionRasterDataset rs      = rsUtil.createIdentityRaster(rsUtil.convertFeatureClassToRaster(InFeatureClass, rasterUtil.rasterType.IMAGINE, wksTemp, outRsNm, vRs.RasterInfo.CellSize.X, (IRasterDataset)vRs));

            rs = rsUtil.createIdentityRaster(rs, rstPixelType.PT_FLOAT);
            int fieldIndex = InFeatureClass.FindField(fldName);

            if (fieldIndex == -1)
            {
                fieldIndex = InFeatureClass.FindField(fldName + "_1");
            }
            if (fldName.ToLower() == InFeatureClass.OIDFieldName.ToLower() || fieldIndex == -1)
            {
                zRs = rs;
            }
            else
            {
                IRemapFilter   rFilt  = new RemapFilterClass();
                IFeatureCursor ftrCur = InFeatureClass.Search(null, false);
                IFeature       ftr    = ftrCur.NextFeature();

                while (ftr != null)
                {
                    double id  = ftr.OID;
                    double nVl = System.Convert.ToDouble(ftr.get_Value(fieldIndex));
                    if (Double.IsNaN(nVl) || Double.IsInfinity(nVl))
                    {
                        ftr = ftrCur.NextFeature();
                    }
                    else
                    {
                        //Console.WriteLine("adding oid = " + id.ToString() + " and value = " + nVl.ToString());
                        rFilt.AddClass(id, id + 1, nVl);
                        ftr = ftrCur.NextFeature();
                    }
                }
                zRs = rsUtil.calcRemapFunction(rs, rFilt);
            }
        }
        public override void OnClick()
        {
            if (_AppHk == null)
            {
                return;
            }
            if (_AppHk.MapControl == null)
            {
                return;
            }
            IMap pMap = _AppHk.MapControl.Map;

            if (frmSQL != null)
            {
                frmSQL.Close();
            }
            if (this.WriteLog)
            {
                Plugin.LogTable.Writelog("河流查询");//xisheng 日志记录;
            }
            string        strLayerName   = "";
            string        strFieldName   = ""; //名称字段
            string        strFieldCode   = ""; //编码字段
            IFeatureClass pRiverFeaClass = null;

            try
            {//查找河流地物类
                ModQuery.GetQueryConfig("河流查询", out pRiverFeaClass, out strLayerName, out strFieldName, out strFieldCode);
                if (pRiverFeaClass == null)
                {
                    MessageBox.Show("找不到河流数据,请检查配置文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                //检查河流名称字段
                if (pRiverFeaClass.FindField(strFieldName) < 0)
                {
                    MessageBox.Show("找不到河流名称属性,请检查配置文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    pRiverFeaClass = null;
                    return;
                }
                //检查河流编码字段
                if (pRiverFeaClass.FindField(strFieldCode) < 0)
                {
                    MessageBox.Show("找不到河流编码属性,请检查配置文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    pRiverFeaClass = null;
                    return;
                }
                frmQueryRoad fmQD = new frmQueryRoad((_AppHk as Plugin.Application.IAppFormRef).MainForm, _AppHk.MapControl, pRiverFeaClass, strLayerName, strFieldName, strFieldCode, "河 流 名:", "河流编码:", "河流查询");
                fmQD.WriteLog = this.WriteLog;
                fmQD.Show((_AppHk as Plugin.Application.IAppFormRef).MainForm);
            }
            catch (Exception ex)
            {
                ErrorHandle.ShowFrmErrorHandle("提示", ex.Message);
            }
        }
Esempio n. 11
0
        public void CanMatchRows()
        {
            const string  textField1    = "Text1";
            const string  textField2    = "Text2";
            const string  textFieldBoth = "Text";
            IFeatureClass fc1           = CreateFeatureClass("CanMatchRows_fc1",
                                                             esriGeometryType.esriGeometryPolygon,
                                                             FieldUtils.CreateTextField(textField1, 1),
                                                             FieldUtils.CreateTextField(textFieldBoth, 1));
            IFeatureClass fc2 = CreateFeatureClass("CanMatchRows_fc2",
                                                   esriGeometryType.esriGeometryPolygon,
                                                   FieldUtils.CreateTextField(textFieldBoth, 1),
                                                   FieldUtils.CreateTextField(textField2, 1));

            const bool     caseSensitive = true;
            MultiTableView view          = TableViewFactory.Create(new[] { (ITable)fc1, (ITable)fc2 },
                                                                   new[] { "G1", "G2" },
                                                                   "G1.TEXT1 = G2.TEXT2 AND G1.Text = 'x' AND G2.Text = 'y'",
                                                                   caseSensitive);

            IFeature f1A = fc1.CreateFeature();

            f1A.Value[fc1.FindField(textField1)]    = "A";
            f1A.Value[fc1.FindField(textFieldBoth)] = "x";
            f1A.Store();

            IFeature f2A = fc2.CreateFeature();

            f2A.Value[fc2.FindField(textField2)]    = "A";
            f2A.Value[fc2.FindField(textFieldBoth)] = "y";
            f2A.Store();

            Assert.IsTrue(view.MatchesConstraint(f1A, f2A));
            Assert.AreEqual("G1.TEXT1 = 'A'; G2.TEXT2 = 'A'; G1.TEXT = 'x'; G2.TEXT = 'y'",
                            view.ToString(f1A, f2A));

            IFeature f1B = fc1.CreateFeature();

            f1B.Value[fc1.FindField(textField1)]    = "b";
            f1B.Value[fc1.FindField(textFieldBoth)] = "x";
            f1B.Store();

            IFeature f2B = fc2.CreateFeature();

            f2B.Value[fc2.FindField(textField2)]    = "B";          // different case --> no match
            f2B.Value[fc2.FindField(textFieldBoth)] = "y";
            f2B.Store();

            Assert.IsFalse(view.MatchesConstraint(f1B, f2B));
            Assert.AreEqual("G1.TEXT1 = 'b'; G2.TEXT2 = 'B'; G1.TEXT = 'x'; G2.TEXT = 'y'",
                            view.ToString(f1B, f2B));
        }
        // 列名
        public OperateBuildingLayer(string layerName)
        {
            IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace();

            pFeatureClass = featureWorkspace.OpenFeatureClass(layerName);
            pFeatureLayer = new FeatureLayer();
            pFeatureLayer.FeatureClass = pFeatureClass;

            //pFeatureLayer = GISMapApplication.Instance.GetLayer(layerName) as IFeatureLayer;
            //pFeatureClass = pFeatureLayer.FeatureClass;
            this.bidIndex    = pFeatureClass.FindField("BID");
            this.heightIndex = pFeatureClass.FindField("Height");
        }
Esempio n. 13
0
        public override void OnClick()
        {
            if (_AppHk == null)
            {
                return;
            }
            if (_AppHk.MapControl == null)
            {
                return;
            }
            IMap pMap = _AppHk.MapControl.Map;

            string        strFieldName  = ""; //名称字段
            string        strFieldCode  = ""; //编码字段
            string        strRoadName   = "铁路查询";
            string        strLayerName  = "";
            IFeatureClass pRoadFeaClass = null;

            try
            {//获取道路地物类
                ModQuery.GetQueryConfig(strRoadName, out pRoadFeaClass, out strLayerName, out strFieldName, out strFieldCode);
                if (pRoadFeaClass == null)
                {
                    MessageBox.Show("找不到铁路数据,请检查配置文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return;
                }
                //检查河流名称字段
                if (pRoadFeaClass.FindField(strFieldName) < 0)
                {
                    MessageBox.Show("找不到铁路名称属性,请检查配置文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    pRoadFeaClass = null;
                    return;
                }
                //检查河流编码字段
                if (pRoadFeaClass.FindField(strFieldCode) < 0)
                {
                    MessageBox.Show("找不到铁路编码属性,请检查配置文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    pRoadFeaClass = null;
                    return;
                }
                frmQueryRoad fmQD = new frmQueryRoad(_pAppForm.MainForm, _AppHk.MapControl, pRoadFeaClass, strLayerName, strFieldName, strFieldCode, "铁 路 名:", "铁路编码:", "铁路查询");
                fmQD.WriteLog = this.WriteLog;
                fmQD.Show(_pAppForm.MainForm);
            }
            catch (Exception ex)
            {
                ErrorHandle.ShowFrmErrorHandle("提示", ex.Message);
            }
        }
        public OperateInterferenceLocLayer()
        {
            IFeatureWorkspace featureWorkspace = MapWorkSpace.getWorkSpace();
            IFeatureClass     fclass           = featureWorkspace.OpenFeatureClass(LayerNames.InfSource);
            IFeatureLayer     flayer           = new FeatureLayer();

            pFeatureLayer.FeatureClass = pFeatureClass;

            //pFeatureLayer = GISMapApplication.Instance.GetLayer(LayerNames.InfSource) as IFeatureLayer;
            //pFeatureClass = pFeatureLayer.FeatureClass;
            this.GXIDIndex      = pFeatureClass.FindField("GXID");
            this.GYIDIndex      = pFeatureClass.FindField("GYID");
            this.LevelIndex     = pFeatureClass.FindField("Level");
            this.RecePowerIndex = pFeatureClass.FindField("RecePower");
        }
Esempio n. 15
0
        private void method_0()
        {
            IFeatureClass featureClass = this.ifeatureLayer_0.FeatureClass;
            IRepresentationWorkspaceExtension repWSExtFromFClass =
                RepresentationAssist.GetRepWSExtFromFClass(featureClass);
            string str  = this.ifeatureLayer_0.FeatureClass.AliasName + "_Rep";
            string str2 = "RuleID";
            string str3 = "Override";

            if (repWSExtFromFClass.get_FeatureClassHasRepresentations(featureClass))
            {
                IList <string>   list = new List <string>();
                IEnumDatasetName name = repWSExtFromFClass.get_FeatureClassRepresentationNames(featureClass);
                for (IDatasetName name2 = name.Next(); name2 != null; name2 = name.Next())
                {
                    list.Add(name2.Name);
                }
                int    num  = 1;
                string item = str;
                while (list.IndexOf(item) != -1)
                {
                    item = str + num.ToString();
                    num++;
                }
                str  = item;
                num  = 1;
                item = str2;
                while (featureClass.FindField(item) != -1)
                {
                    item = str2 + "_" + num.ToString();
                    num++;
                }
                str2 = item;
                num  = 1;
                item = str3;
                while (featureClass.FindField(item) != -1)
                {
                    item = str3 + "_" + num.ToString();
                    num++;
                }
                str3 = item;
            }
            this.txtruleIDFldName.Text      = str2;
            this.txtoverrideFldName.Text    = str3;
            this.txtRepresentationName.Text = str;
            this.lblFC.Text = this.ifeatureLayer_0.FeatureClass.AliasName;
            this.rdoSelectFeature.Enabled = (this.ifeatureLayer_0 as IFeatureSelection).SelectionSet.Count > 0;
        }
Esempio n. 16
0
        private void appendParcelField(IFeatureClass parcelFC)
        {
            if (perceel == null)
            {
                return;
            }

            IFeatureCursor insertCursor = parcelFC.Insert(false);

            datacontract.geojsonPolygon jsPoly = JsonConvert.DeserializeObject <datacontract.geojsonPolygon>(perceel.geometry.shape);
            IPolygon lbShape  = geopuntHelper.geojson2esriPolygon(jsPoly, (int)dataHandler.CRS.Lambert72);
            IPolygon mapShape = (IPolygon)geopuntHelper.Transform(lbShape, map.SpatialReference);

            IFeature feature = parcelFC.CreateFeature();

            feature.Shape = (IGeometry)mapShape;

            int capakeyIdx = parcelFC.FindField("capakey");

            feature.set_Value(capakeyIdx, perceel.capakey);

            int perceelnrIdx = parcelFC.FindField("perceelnr");

            feature.set_Value(perceelnrIdx, perceel.perceelnummer);

            int grondnrIdx = parcelFC.FindField("grondnr");

            feature.set_Value(grondnrIdx, perceel.grondnummer);

            int exponentIdx = parcelFC.FindField("exponent");

            feature.set_Value(exponentIdx, perceel.exponent);

            int machtIdx = parcelFC.FindField("macht");

            feature.set_Value(machtIdx, perceel.macht);

            int bisnrIdx = parcelFC.FindField("bisnr");

            feature.set_Value(bisnrIdx, perceel.bisnummer);

            int perceeltypeIdx = parcelFC.FindField("type");

            feature.set_Value(perceeltypeIdx, perceel.type);

            string adres = string.Join("-", perceel.adres.ToArray());

            if (adres.Length > 254)
            {
                adres = adres.Substring(0, 254);
            }

            int adresIdx = parcelFC.FindField("adres");

            feature.set_Value(adresIdx, adres);

            feature.Store();
        }
Esempio n. 17
0
        private Dictionary <string, IPolygon> GetUIDPolygonDict(IFeatureClass featureClass, string uidFieldName)
        {
            if (featureClass.ShapeType != esriGeometryType.esriGeometryPolygon)
            {
                return(null);
            }

            Dictionary <string, IPolygon> outputDict = new Dictionary <string, IPolygon>();

            int uid_idx = featureClass.FindField(uidFieldName);

            IFeatureCursor featureCursor = featureClass.Search(null, true);
            IFeature       feature       = null;

            AddStepProgressor(featureClass.FeatureCount(null), "Reading polygon in feature class . . .");
            while ((feature = featureCursor.NextFeature()) != null)
            {
                if (!ContinueStepProgressor(new object[] { featureCursor }))
                {
                    return(null);
                }

                string keyStr = feature.Value[uid_idx].ToString();

                outputDict[keyStr] = (IPolygon)feature.ShapeCopy;
            }

            Marshal.ReleaseComObject(featureCursor);
            GC.Collect();
            GC.WaitForPendingFinalizers();

            return(outputDict);
        }
        private void btnInsertValue_Click(object sender, EventArgs e)
        {
            if (_renderer == null || _fc == null) return;

            IField field = _fc.FindField(_renderer.ValueField);
            if (field == null) return;

            PropertyForm_QuantityRenderer_Dialog_InsertValue dlg = new PropertyForm_QuantityRenderer_Dialog_InsertValue(field);
            if (dlg.ShowDialog() == DialogResult.OK)
            {
                QuantityRenderer.QuantityClass qClass = new QuantityRenderer.QuantityClass(
                    dlg.MinValue, dlg.MaxValue,
                    RendererFunctions.CreateStandardSymbol(_renderer.GeometryType));

                if (qClass.Symbol is ILegendItem)
                {
                    ((ILegendItem)qClass.Symbol).LegendLabel = dlg.Label;
                }
                try
                {
                    _renderer.AddClass(qClass);
                    BuildList();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Exception", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
            }
        }
Esempio n. 19
0
        public static string ReturnCounty(IFeatureClass SiteLayer, IFeatureClass intersectLayer, string fieldName)
        {//Returns a string saying what County and State the SiteLayer is in
            // Get the feature and its geometry given an Object ID.
            IFeature  stateFeature  = SiteLayer.GetFeature(0);
            IGeometry queryGeometry = stateFeature.Shape;

            IFeature intersectFeature = intersectLayer.GetFeature(0);

            // Create the spatial filter.
            ISpatialFilter spatialFilter = new SpatialFilter();

            spatialFilter.Geometry      = queryGeometry;
            spatialFilter.GeometryField = intersectLayer.ShapeFieldName;
            spatialFilter.SpatialRel    = esriSpatialRelEnum.esriSpatialRelIntersects;
            spatialFilter.SubFields     = fieldName;

            // Find the position of the field provided the fieldName variable
            int nameFieldPosition = intersectLayer.FindField(fieldName);

            // Execute the query and iterate through the cursor's results.
            IFeatureCursor highwayCursor  = intersectLayer.Search(spatialFilter, false);
            IFeature       highwayFeature = null;

            while ((highwayFeature = highwayCursor.NextFeature()) != null)
            {
                name = Convert.ToString(highwayFeature.get_Value(nameFieldPosition));
            }

            // The cursors is no longer needed, so dispose of it.
            Marshal.ReleaseComObject(highwayCursor);

            return(name);
        }
        private void AddHField(IFeatureClass fc)
        {
            FacilityClass fac = FacilityClassManager.Instance.GetFacilityClassByName("GCD");

            DFDataConfig.Class.FieldInfo fi = fac.GetFieldInfoBySystemName("Height");
            if (fi == null)
            {
                return;
            }

            int index = fc.FindField(fi.Name);

            if (index == -1)
            {
                IField     Field      = new FieldClass();
                IFieldEdit pFieldEdit = Field as IFieldEdit;
                pFieldEdit.Name_2 = "HEIGHT";
                pFieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
                fc.AddField(Field);
            }
            else
            {
                return;
            }
        }
Esempio n. 21
0
        /// <summary>
        /// 创建标准要素类
        /// </summary>
        /// <param name="sourceFeatureClass">原要素类</param>
        /// <param name="target_FeatureClass">标准要素类</param>
        /// <param name="contrastTable">字段对照表,二维数组</param>
        /// <returns>返回创建的标准要素类</returns>
        public IFeatureClass CreateStandardFeatureClass(IFeatureClass sourceFeatureClass, IFeatureClass target_FeatureClass
                                                        , string[,] contrastTable)
        {
            IFeature       pFeature;
            IFeatureCursor sourceCursor = sourceFeatureClass.Search(null, false);
            //用IFeatureBuffer提高运算速度
            IFeatureBuffer pFeaBuffer   = null;
            IFeatureCursor targetCursor = target_FeatureClass.Insert(true);

            while ((pFeature = sourceCursor.NextFeature()) != null)
            {
                pFeaBuffer       = target_FeatureClass.CreateFeatureBuffer();
                pFeaBuffer.Shape = pFeature.Shape;
                for (int i = 0; i < contrastTable.Length / 2; i++)
                {
                    pFeaBuffer.set_Value(target_FeatureClass.FindField(contrastTable[i, 0]), pFeature.Value[sourceFeatureClass.Fields.FindField(contrastTable[i, 1])]);
                }
                targetCursor.InsertFeature(pFeaBuffer);
            }
            targetCursor.Flush();
            //运用IfeatureBuffer和IfeatureCursor时需要手动释放非托管对象
            System.Runtime.InteropServices.Marshal.ReleaseComObject(sourceCursor);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeaBuffer);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(targetCursor);

            return(target_FeatureClass);
        }
Esempio n. 22
0
        private static CoordinateField GetCoordinateField(
            [NotNull] IFeatureClass featureClass,
            [NotNull] string fieldName)
        {
            int fieldIndex = featureClass.FindField(fieldName);

            if (fieldIndex < 0)
            {
                throw new InvalidConfigurationException(
                          string.Format("Field '{0}' does not exist in feature class '{1}'",
                                        fieldName,
                                        DatasetUtils.GetName(featureClass)));
            }

            IField field = featureClass.Fields.Field[fieldIndex];

            bool isSupported = IsFieldTypeSupported(field.Type);

            if (!isSupported)
            {
                throw new InvalidConfigurationException(
                          string.Format(
                              "Type {0} of field '{1}' is not supported for coordinate fields",
                              FieldUtils.GetFieldTypeDisplayText(field.Type),
                              field.Name));
            }

            return(new CoordinateField(field, fieldIndex));
        }
Esempio n. 23
0
        /*
         * This method queries the device layer and returns a set of features
         */
        private IPropertySetArray QueryDevices(string whereClause, IStringArray outFields)
        {
            IPropertySetArray results = new PropertySetArray();

            int           deviceLayerId = soeUtil.GetLayerIdByName(mapService, DEVICE_LAYER_NAME);
            IFeatureClass deviceFC      = (IFeatureClass)mapServerDataAccess.GetDataSource(mapService.DefaultMapName, deviceLayerId);

            IQueryFilter filter = new QueryFilterClass();

            filter.WhereClause = whereClause;
            IFeatureCursor resultsFeatureCursor = deviceFC.Search(filter, false);

            IArray fieldIndex = new ArrayClass();

            for (int i = 0; i < outFields.Count; i++)
            {
                fieldIndex.Add(deviceFC.FindField(outFields.Element[i]));
            }
            IFeature resultFeature = null;

            while ((resultFeature = resultsFeatureCursor.NextFeature()) != null)
            {
                IPropertySet values = new PropertySet();
                for (int i = 0; i < outFields.Count; i++)
                {
                    values.SetProperty(outFields.Element[i], resultFeature.Value[(int)fieldIndex.Element[i]]);
                }
                results.Add(values);
            }
            Marshal.ReleaseComObject(resultsFeatureCursor);

            return(results);
        }
Esempio n. 24
0
        public bool CanDisplayObject(IGxObject igxObject_0)
        {
            if ((igxObject_0 is IGxDiskConnection) || (igxObject_0 is IGxFolder))
            {
                return(true);
            }
            if (igxObject_0 is IGxDatabase)
            {
                return(true);
            }
            if (igxObject_0 is IGxDataset)
            {
                switch ((igxObject_0 as IGxDataset).Type)
                {
                case esriDatasetType.esriDTFeatureDataset:
                    return(true);

                case esriDatasetType.esriDTFeatureClass:
                {
                    IFeatureClass dataset = (igxObject_0 as IGxDataset).Dataset as IFeatureClass;
                    if (dataset.ShapeType != esriGeometryType.esriGeometryPolyline)
                    {
                        dataset = null;
                        break;
                    }
                    int    index = dataset.FindField(dataset.ShapeFieldName);
                    IField field = dataset.Fields.get_Field(index);
                    dataset = null;
                    return(field.GeometryDef.HasM);
                }
                }
            }
            return(false);
        }
Esempio n. 25
0
        public string AddPolygonTo3D(Dictionary <IPolygon, bool> polygons)
        {
            string featureClassName = GenerateTemp3DPolygonStorage();

            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)calcWorkspace;

            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureClass calc    = GetCalcProfileFeatureClass(featureClassName);
            var           GCS_WGS = Helper.GetBasePointSpatialReference();

            polygons.ToList().ForEach(polygon =>
            {
                var pointFeature   = calc.CreateFeature();
                pointFeature.Shape = polygon.Key;

                int isVisibleFieldIndex = calc.FindField("IS_VISIBLE");
                pointFeature.set_Value(isVisibleFieldIndex, polygon.Value ? 1 : 0);

                pointFeature.Store();
            });

            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            return(featureClassName);
        }
Esempio n. 26
0
        public static void EditDoubleField(IFeatureClass featureClass, string fieldName, int length, int precision,
                                           IDomain domain = null)
        {
            int idx = featureClass.FindField(fieldName);

            if (idx == -1)
            {
                return;
            }
            IField     pField     = featureClass.Fields.Field[idx];
            IFieldEdit pFieldEdit = pField as IFieldEdit;

            pFieldEdit.Name_2       = fieldName;
            pFieldEdit.AliasName_2  = fieldName;
            pFieldEdit.Type_2       = esriFieldType.esriFieldTypeDouble;
            pFieldEdit.IsNullable_2 = true;
            pFieldEdit.Editable_2   = true;
            pFieldEdit.Length_2     = length;
            pFieldEdit.Precision_2  = precision;
            if (domain != null)
            {
                pFieldEdit.Domain_2 = domain;
            }
            pField = pFieldEdit;
        }
Esempio n. 27
0
        public string AddProfilePointsTo3D(IEnumerable <IPoint> points)
        {
            string featureClassName = GenerateTemp3DPointStorage();

            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)calcWorkspace;

            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureClass calc    = GetCalcProfileFeatureClass(featureClassName);
            var           GCS_WGS = Helper.GetBasePointSpatialReference();

            int i = 0;

            points.ToList().ForEach(point =>
            {
                var pointFeature = calc.CreateFeature();

                int idFieldIndex = calc.FindField("ID");
                pointFeature.set_Value(idFieldIndex, i);

                pointFeature.Shape = point;
                pointFeature.Store();
            });

            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            return(featureClassName);
        }
Esempio n. 28
0
        public static void Execute(IFeatureClass featureClass, String indexName, String nameOfField)
        {
            // Ensure the feature class contains the specified field.
            int fieldIndex = featureClass.FindField(nameOfField);

            if (fieldIndex == -1)
            {
                throw new ArgumentException("The specified field does not exist in the feature class.");
            }

            // Get the specified field from the feature class.
            IFields featureClassFields = featureClass.Fields;
            IField  field = featureClassFields.get_Field(fieldIndex);

            // Create a fields collection and add the specified field to it.
            IFields     fields     = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;

            fieldsEdit.FieldCount_2 = 1;
            fieldsEdit.set_Field(0, field);

            // Create an index and cast to the IIndexEdit interface.
            IIndex     index     = new IndexClass();
            IIndexEdit indexEdit = (IIndexEdit)index;

            // Set the index's properties, including the associated fields.
            indexEdit.Fields_2      = fields;
            indexEdit.IsAscending_2 = false;
            indexEdit.IsUnique_2    = false;
            indexEdit.Name_2        = indexName;

            // Add the index to the feature class.
            featureClass.AddIndex(index);
        }
Esempio n. 29
0
        private void listBoxField_SelectedIndexChanged(object sender, System.EventArgs e)
        {
            string sFieldName = listBoxField.Text;
            bool   bLayerType = GetLayerType(comboBoxLayer.Text);

            listBoxValue.Items.Clear();
            int    iFieldIndex = 0;
            IField pField      = null;
            int    i           = 0;

            if (bLayerType == false)
            {
                IFeatureCursor pFeatCursor = m_pFeatCls.Search(null, true);
                IFeature       pFeat       = pFeatCursor.NextFeature();
                iFieldIndex = m_pFeatCls.FindField(sFieldName);
                pField      = m_pFeatCls.Fields.get_Field(iFieldIndex);
                while (pFeat != null)
                {
                    listBoxValue.Items.Add(pFeat.get_Value(iFieldIndex));
                    pFeat = pFeatCursor.NextFeature();
                }
            }
            else
            {
                iFieldIndex = m_pTable.FindField(sFieldName);
                pField      = m_pTable.Fields.get_Field(iFieldIndex);
                for (i = 0; i <= m_pTable.RowCount(null) - 1; i++)
                {
                    IRow pRow = m_pTable.GetRow(i);
                    listBoxValue.Items.Add(pRow.get_Value(iFieldIndex));
                }
            }
        }
Esempio n. 30
0
 private void CreateFeature(IGeometry geo, IMap pMap, IFeatureClass fc)
 {
     try
     {
         if (geo == null || fc == null || pMap == null)
         {
             return;
         }
         IDataset       pDataset       = fc as IDataset;
         IWorkspaceEdit pWorkspaceEdit = pDataset.Workspace as IWorkspaceEdit;
         int            index          = fc.FindField(fc.ShapeFieldName);
         IGeometryDef   pGD            = fc.Fields.get_Field(index).GeometryDef;
         if (pGD.HasZ)
         {
             IZAware pZA = geo as IZAware;
             pZA.ZAware = true;
             IZ     pZ = geo as IZ;
             double zmin = -1000, zmax = 1000;
             if (pGD.SpatialReference.HasZPrecision())
             {
                 pGD.SpatialReference.GetZDomain(out zmin, out zmax);
             }
             if (pZ != null)
             {
                 pZ.SetConstantZ(0);
             }
             else
             {
                 IPoint p = geo as IPoint;
                 if (p.Z.ToString() == "非数字")
                 {
                     p.Z = 0;
                 }
             }
         }
         if (pGD.HasM)
         {
             IMAware pMA = geo as IMAware;
             pMA.MAware = true;
         }
         if (!pWorkspaceEdit.IsBeingEdited())
         {
             pWorkspaceEdit.StartEditing(true);
             pWorkspaceEdit.StartEditOperation();
         }
         IFeature pFeature = fc.CreateFeature();
         pFeature.Shape = geo;
         pFeature.Store();
         if (pWorkspaceEdit.IsBeingEdited())
         {
             pWorkspaceEdit.StartEditOperation();
             pWorkspaceEdit.StopEditing(true);
         }
         pMap.ClearSelection();
     }
     catch (System.Exception ex)
     {
         return;
     }
 }
        private City GetCity(IFeature city, IFeatureClass cityClass)
        {
            IPoint capitalShape = city.Shape as IPoint;
            int areaNameIndex = cityClass.FindField(CityConst.AREA_NAME);

            return new City()
            {
                AreaName = city.get_Value(areaNameIndex) as string,
                X = capitalShape.X,
                Y = capitalShape.Y
            };
        }
Esempio n. 32
0
        public static void CreateFeature(IFeatureClass featureClass, IPoint point)
        {
            // Build the feature
            IFeature feature = featureClass.CreateFeature();
            feature.Shape = point;

            //Update a value on string field - name of the new feature (city)
            int fieldIndex = featureClass.FindField("AREANAME");
            feature.set_Value(fieldIndex, "Mentone");

            //Commit the new feature to the geodatabase
            feature.Store();
        }
Esempio n. 33
0
        /// <summary>
        /// 参数说明,栅格面,写入这个面的字段名称,点要素,点要素的速度字段,计算平均速度
        /// </summary>
        /// <param name="pPolygonFClass"></param>
        /// <param name="pFieldName"></param>
        /// <param name="pPointFClass"></param>
        /// <param name="FieldName"></param>
        public void Calculate(IFeatureClass pPolygonFClass, string pFieldName,IFeatureClass pPointFClass, string FieldName)
        {
            IFeatureCursor pPolyCursor = pPolygonFClass.Search(null, false);

            int pFieldIndex = pPointFClass.FindField(FieldName);

            IFeature pPolyFeature = pPolyCursor.NextFeature();

            int pPolygonIndex = pPolygonFClass.FindField(pFieldName);

            while (pPolyFeature != null)
            {
                IGeometry pPolGeo = pPolyFeature.Shape;

                int Count = 0;

                ISpatialFilter spatialFilter = new SpatialFilterClass();

                spatialFilter.Geometry = pPolGeo;

                spatialFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains;

                IFeatureCursor pPointCur = pPointFClass.Search(spatialFilter, false);
                double TotalSpeed = 0;

                if (pPointCur != null)
                {
                    IFeature pPointFeature = pPointCur.NextFeature();

                    while (pPointFeature != null)
                    {
                        pPointFeature = pPointCur.NextFeature();

                        TotalSpeed = TotalSpeed + (double)pPointFeature.get_Value(pFieldIndex);
                        Count++;
                    }

                }

                if (Count != 0)
                {
                    pPolyFeature.set_Value(pPolygonIndex, TotalSpeed / Count);

                }
                pPolyFeature = pPolyCursor.NextFeature();

            }
        }
Esempio n. 34
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
                }
            }
        }
 public void Bind(object pArgument)
 {
     if (pArgument is mergeFunctionArguments)
     {
         mergeFunctionArguments arg = (mergeFunctionArguments)pArgument;
         inrs = arg.InRaster;
         outrs = arg.OutRaster;
         //Console.WriteLine("Number of Bands in outrs = " + ((IRasterBandCollection)outrs).Count.ToString());
         ftrCls = arg.Boundary;
         //ftrCls = arg.Boundary.Catalog;
         catIndex = ftrCls.FindField("catIndex");
         IRasterProps rsProp = (IRasterProps)outrs;
         myFunctionHelper.Bind(outrs);
         myRasterInfo = myFunctionHelper.RasterInfo;
         myPixeltype = myRasterInfo.PixelType;
         myValidFlag = true;
     }
     else
     {
         throw new System.Exception("Incorrect arguments object. Expected: mergeFunctionArguments");
     }
 }
Esempio n. 36
0
        private StateDetails GetStateDetails(IFeature state, IFeatureClass statesClass)
        {
            int areaIdx = statesClass.FindField(StateConst.AREA);
            int stateNameIdx = statesClass.FindField(StateConst.STATE_NAME);
            int subRegionIdx = statesClass.FindField(StateConst.SUB_REGION);
            int stateAbbrIdx = statesClass.FindField(StateConst.STATE_ABBR);
            int pop2000Idx = statesClass.FindField(StateConst.POP2000);
            int pop00_sqmiIdx = statesClass.FindField(StateConst.POP00_SQMI);

            return new StateDetails
            {
                Area = (double)state.get_Value(areaIdx),
                StateName = state.get_Value(stateNameIdx) as string,
                SubRegion = state.get_Value(subRegionIdx) as string,
                StateAbbr = state.get_Value(stateAbbrIdx) as string,
                Pop2000 = (int)state.get_Value(pop2000Idx),
                Pop00_SQMI = (int)state.get_Value(pop00_sqmiIdx)
            };
        }
        public IFeatureClass reprojectInFeatureClass(IFeatureClass InFeatureClass, ISpatialReference SpatialReference)
        {
            IWorkspace tempWorkspace = geoUtil.OpenWorkSpace(tempWksStr);
            string outNm = ((IDataset)InFeatureClass).BrowseName+"_PR";
            outNm = geoUtil.getSafeOutputNameNonRaster(wks,outNm);
            IFields outFlds = new FieldsClass();
            IFieldsEdit outFldsE = (IFieldsEdit)outFlds;
            IField inFld = InFeatureClass.Fields.get_Field(InFeatureClass.FindField(ftrField));
            IField outFld = new FieldClass();
            if (inFld.Type == esriFieldType.esriFieldTypeOID)
            {
                IFieldEdit outFldE = (IFieldEdit)outFld;
                outFldE.Type_2 = esriFieldType.esriFieldTypeInteger;
                outFldE.Name_2 = inFld.Name;
            }
            else
            {
                IClone cl = (IClone)inFld;
                outFld = (IField)cl.Clone();
            }
            outFldsE.AddField(outFld);
            IFeatureClass outFtrCls = geoUtil.createFeatureClass((IWorkspace2)tempWorkspace,outNm,outFldsE,InFeatureClass.ShapeType,SpatialReference);
            string ozName = ftrField;
            int ozIndex = outFtrCls.FindField(ozName);
            if (ozIndex == -1)
            {
                ozName = ftrField+"_1";
                ozIndex = outFtrCls.FindField(ozName);

            }
            int izIndex = InFeatureClass.FindField(ftrField);
            IQueryFilter qf = new QueryFilterClass();
            qf.SubFields = InFeatureClass.ShapeFieldName + "," + ftrField;
            IFeatureCursor fCur = InFeatureClass.Search(qf, false);
            IFeature ftr = fCur.NextFeature();
            IWorkspaceEdit wksE = (IWorkspaceEdit)tempWorkspace;
            bool weStart = true;
            if(wksE.IsBeingEdited())
            {
                weStart=false;
            }
            else
            {
                wksE.StartEditing(false);
            }
            wksE.StartEditOperation();
            try
            {
                while (ftr != null)
                {
                    object vl = ftr.get_Value(izIndex);
                    IFeatureProject ftrP = (IFeatureProject)ftr;
                    ftrP.Project(SpatialReference);
                    IFeature oFtr = outFtrCls.CreateFeature();
                    oFtr.Shape = ftr.Shape;
                    if(ozIndex>-1) oFtr.set_Value(ozIndex, vl);
                    oFtr.Store();
                    ftr = fCur.NextFeature();
                }
                ftrField = ozName;
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
            finally
            {
                wksE.StopEditOperation();
                if (weStart) wksE.StopEditing(true);
            }
            return outFtrCls;
        }
        public void convertFeatureToRaster(IFeatureClass InFeatureClass, string fldName)
        {
            ftrCls = InFeatureClass;
            ftrField = fldName;
            IDataset dSet = (IDataset)InFeatureClass;
            string outRsNm = dSet.BrowseName;
            wks = dSet.Workspace;
            if (vRs != null)
            {
                if (!checkProjectionsFtr())
                {
                    if (rd != null) rd.addMessage("Re-projecting feature class to match value raster's projection");
                    InFeatureClass = reprojectInFeatureClass(InFeatureClass, vRs.RasterInfo.SpatialReference);

                }
            }
            IWorkspace wksTemp = geoUtil.OpenRasterWorkspace(tempWksStr);
            IFunctionRasterDataset rs = rsUtil.createIdentityRaster(rsUtil.convertFeatureClassToRaster(InFeatureClass, rasterUtil.rasterType.IMAGINE, wksTemp, outRsNm, vRs.RasterInfo.CellSize.X, (IRasterDataset)vRs));
            rs = rsUtil.createIdentityRaster(rs, rstPixelType.PT_FLOAT);
            int fieldIndex = InFeatureClass.FindField(fldName);
            if(fieldIndex == -1)
            {
                fieldIndex = InFeatureClass.FindField(fldName + "_1");
            }
            if (fldName.ToLower() == InFeatureClass.OIDFieldName.ToLower()||fieldIndex == -1)
            {
                zRs = rs;
            }
            else
            {
                IRemapFilter rFilt = new RemapFilterClass();
                IFeatureCursor ftrCur = InFeatureClass.Search(null, false);
                IFeature ftr = ftrCur.NextFeature();

                while (ftr != null)
                {
                    double id = ftr.OID;
                    double nVl = System.Convert.ToDouble(ftr.get_Value(fieldIndex));
                    if (Double.IsNaN(nVl) || Double.IsInfinity(nVl))
                    {
                        ftr = ftrCur.NextFeature();
                    }
                    else
                    {
                        //Console.WriteLine("adding oid = " + id.ToString() + " and value = " + nVl.ToString());
                        rFilt.AddClass(id, id + 1, nVl);
                        ftr = ftrCur.NextFeature();
                    }
                }
                zRs = rsUtil.calcRemapFunction(rs, rFilt);
            }
        }
        private void AddQALayerToActiveView(IMap map, IFeatureClass SourceLineFeatureClass, IFeatureClass SourcePolygonFeatureClass,
      string layerPathFile, double metersPerUnit, bool bIsBefore1022, bool bFabricIsInGCS)
        {
            if (map == null || layerPathFile == null || !layerPathFile.EndsWith(".lyr"))
              {
            return;
              }

              // Create a new GxLayer
              IGxLayer gxLayer = new GxLayerClass();
              IGxFile gxFile = (IGxFile)gxLayer;

              // Set the path for where the layerfile is located on disk
              gxFile.Path = layerPathFile;

              // Test if we have a valid layer and add it to the map
              if (!(gxLayer.Layer == null))
              {
            if (!(gxLayer.Layer is ICompositeLayer))
              return;
            ICompositeLayer pCompLyr = (ICompositeLayer)gxLayer.Layer;
            for (int i=0; i<pCompLyr.Count; i++)
            {
              ILayer pLyr = pCompLyr.get_Layer(i);
              //
              if (pLyr is IFeatureLayer)
              {
            IFeatureLayer pFlyr = (IFeatureLayer)pLyr;
            //now update the definition query
            IFeatureLayerDefinition pFeatLyrDef = (IFeatureLayerDefinition)pFlyr;
            string sLyrName = pFlyr.Name;
            bool bExc = false;
            if (sLyrName.Contains("Minus"))
            {
              pFlyr.FeatureClass = SourceLineFeatureClass;
              bExc = false;

              //ILayerFields pLayerFields = pFlyr as ILayerFields;
              //First turn off all layers
              //for (int kk = 0; kk < pLayerFields.FieldCount; kk++)
              //{
              //  IFieldInfo pFieldInfo = pLayerFields.get_FieldInfo(kk);
              //  pFieldInfo.Visible = false;
              //}

              SetLabelExpressionOnFeatureLayer(pFlyr, out bExc);
              if (bExc || bFabricIsInGCS)
              {
                int jj=pFlyr.FeatureClass.FindField("ComputedMinusObserved");
                if (jj>-1)
                {
                  string sVal = (0.1 / metersPerUnit).ToString("0.00");
                  string sCminusO=pFlyr.FeatureClass.Fields.get_Field(jj).Name;
                  pFeatLyrDef.DefinitionExpression = sCminusO + " > "+sVal+" AND " + sCminusO + " < "+sVal;

                  //IFieldInfo pFieldInfo = pLayerFields.get_Field(jj) as IFieldInfo;
                  //pFieldInfo.Visible = true;

                }
                continue;
              }
              string s = pFeatLyrDef.DefinitionExpression;
              int iField = SourceLineFeatureClass.FindField("ArcLength");
              if (iField > -1)
              {

                //IFieldInfo pFieldInfo = pLayerFields.get_Field(iField) as IFieldInfo;
                //pFieldInfo.Visible = true;

                string s2 = SourceLineFeatureClass.Fields.get_Field(iField).Name;
                pFeatLyrDef.DefinitionExpression = s.Replace("\"ArcLength\"", s2);
                pFeatLyrDef.DefinitionExpression = pFeatLyrDef.DefinitionExpression.Replace("ArcLength", s2);
              }

              s = pFeatLyrDef.DefinitionExpression;
              iField = SourceLineFeatureClass.FindField("Distance");
              if (iField > -1)
              {

                //IFieldInfo pFieldInfo = pLayerFields.get_Field(iField) as IFieldInfo;
                //pFieldInfo.Visible = true;

                string s2 = SourceLineFeatureClass.Fields.get_Field(iField).Name;
                pFeatLyrDef.DefinitionExpression = s.Replace("\"Distance\"", s2);
                pFeatLyrDef.DefinitionExpression = pFeatLyrDef.DefinitionExpression.Replace("Distance", s2);
              }

              s = pFeatLyrDef.DefinitionExpression;
              iField = SourceLineFeatureClass.FindField("DensifyType");
              if (iField > -1)
              {
                string s2 = SourceLineFeatureClass.Fields.get_Field(iField).Name;
                pFeatLyrDef.DefinitionExpression = s.Replace("\"DensifyType\"", s2);
                pFeatLyrDef.DefinitionExpression = pFeatLyrDef.DefinitionExpression.Replace("DensifyType", s2);
              }

              s = pFeatLyrDef.DefinitionExpression;
              pFeatLyrDef.DefinitionExpression = s.Replace("\"Shape_Length\"", SourceLineFeatureClass.LengthField.Name);
              pFeatLyrDef.DefinitionExpression = pFeatLyrDef.DefinitionExpression.Replace("Shape_Length", SourceLineFeatureClass.LengthField.Name);

            }
            else if (sLyrName.Contains("Parcel"))
            { //In 10.1 start editing crashes if the definition query in these layers that use POWER function is present.
              //Can test if the release is 10.1 and knock out the def query, or else exclude the layers.

              string s = pFeatLyrDef.DefinitionExpression;
              int iField=SourcePolygonFeatureClass.FindField("MiscloseDistance");
              string s2 = SourcePolygonFeatureClass.Fields.get_Field(iField).Name;
              pFeatLyrDef.DefinitionExpression = s.Replace("\"MiscloseDistance\"", s2);
              pFeatLyrDef.DefinitionExpression = pFeatLyrDef.DefinitionExpression.Replace("MiscloseDistance", s2);

              s = pFeatLyrDef.DefinitionExpression;
              iField = SourcePolygonFeatureClass.FindField("ShapeStdErrorE");
              s2 = SourcePolygonFeatureClass.Fields.get_Field(iField).Name;
              pFeatLyrDef.DefinitionExpression = s.Replace("\"ShapeStdErrorE\"", s2);
              pFeatLyrDef.DefinitionExpression = pFeatLyrDef.DefinitionExpression.Replace("ShapeStdErrorE", s2);

              s = pFeatLyrDef.DefinitionExpression;
              iField = SourcePolygonFeatureClass.FindField("ShapeStdErrorN");
              s2 = SourcePolygonFeatureClass.Fields.get_Field(iField).Name;
              pFeatLyrDef.DefinitionExpression = s.Replace("\"ShapeStdErrorN\"", s2);
              pFeatLyrDef.DefinitionExpression = pFeatLyrDef.DefinitionExpression.Replace("ShapeStdErrorN", s2);

              pFlyr.FeatureClass = SourcePolygonFeatureClass;
              SetLabelExpressionOnFeatureLayer(pFlyr, out bExc);

              if (s.ToLower().Contains("power") && bIsBefore1022)
              {//remove the def query CR278039
                pFeatLyrDef.DefinitionExpression = "";
                continue;
              }

            }
              }
            }
            gxLayer.Layer.Name = "QA Symbology";

            IMxDocument pMXDoc = ArcMap.Document;
            IOperationStack pOpSt = pMXDoc.OperationStack;
            IAddLayersOperation pAddLyrOp = new AddLayersOperationClass();
            pAddLyrOp.SetDestinationInfo(0,map,null);
            pAddLyrOp.Name = "Add Fabric QA Layer";
            pAddLyrOp.AddLayer(gxLayer.Layer);
            IOperation pOp=(IOperation)pAddLyrOp;
            pOpSt.Do(pOp);
              }
        }
Esempio n. 40
0
        private static bool InsertFeatures(fulcrumrecords fulcrumRecords, IFeatureClass featureClass)
        {
            try
            {
                    // Create an insert cursor.
                    IFeatureCursor insertCursor = featureClass.Insert(false);
                    //comReleaser.ManageLifetime(insertCursor);

                    foreach (fulcrumrecord record in fulcrumRecords.records)
                    {
                        // Create a feature buffer.
                        IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                        //comReleaser.ManageLifetime(featureBuffer);

                        IPoint pt = new Point();
                        pt.PutCoords(record.longitude, record.latitude);
                        featureBuffer.Shape = pt as IGeometry;
                        //handle photos separately
                        if (record.photos.Count >= 1)
                        {
                            try
                            {
                                //only link to the first photo for now
                                //ToDo: how to put the actual image in the photos field (the actual image is held in the photos property of the record)
                                //like so...
                                //featureBuffer.set_Value(featureClass.FindField("photos"), record.photos[0]);
                                featureBuffer.set_Value(featureClass.FindField(photoFieldName), record.photolinks[0]);
                                //ToDo: enhancement: multiple photo support; could create a separate table to store the photo links and join it back to resulting feature class via record id
                            }
                            catch (Exception e)
                            {
                                string photoInsertError = e.Message;
                            }
                        }
                        foreach (fulcrumattribute attr in record.attributes)
                        {
                            if (attr.fieldName != "photos")
                            {
                                //ToDo: why are some (first?) field names empty strings?
                                if (attr.fieldName != "" && attr.fieldName != null)
                                {
                                    try
                                    {
                                        featureBuffer.set_Value(featureClass.FindField(attr.fieldName), attr.fieldValue);
                                    }
                                    catch(Exception e)
                                    {
                                        string ouch = e.Message;
                                    }
                                }
                            }
                        }
                        try
                        {
                            insertCursor.InsertFeature(featureBuffer);
                            featureBuffer = null;
                            GC.Collect();
                        }
                        catch (Exception e)
                        {
                            string insertFailed = e.Message;
                        }
                    }
                    // Flush the buffer to the geodatabase.
                    insertCursor.Flush();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        public static Hashtable FillFeatureCache(ITable inputSignsTable, int inFromIDFI, int inToIDFI,
                                                 IFeatureClass inputLineFeatures, string linesIDFieldName,
                                                 ITrackCancel trackcancel)
        {
            // make and fill a SortedList from the IDs referenced in the table

            // for MultiNet data, there is only one ID field, so its index will be
            // passed in as inFromIDFI, while -1 will be passed in to inToIDFI.

            SortedList IDs = new System.Collections.SortedList();

            ICursor inCursor = inputSignsTable.Search(null, true);
            IRow row;

            long fromID, toID;
            bool exists;
            int cancelCheckInterval = 100;

            if (inToIDFI == -1)
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                        IDs.Add(fromID, fromID);
                }
            }
            else
            {
                while ((row = inCursor.NextRow()) != null)
                {
                    fromID = Convert.ToInt64(row.get_Value(inFromIDFI));
                    toID = Convert.ToInt64(row.get_Value(inToIDFI));

                    exists = IDs.Contains(fromID);
                    if (!exists)
                        IDs.Add(fromID, fromID);

                    exists = IDs.Contains(toID);
                    if (!exists)
                        IDs.Add(toID, toID);
                }
            }

            // make the query filter for fetching features

            IQueryFilter queryFilter = new QueryFilterClass();
            queryFilter.SubFields = "*";

            // Now fetch batches of features

            long currID;
            int numFeaturesPerQuery = 200;
            int numToFetch = IDs.Count;
            int totalRemaining, totalDone = 0;

            int linesIDFieldIndex = inputLineFeatures.FindField(linesIDFieldName);

            Hashtable outputFeatures = new System.Collections.Hashtable((int)numToFetch);

            if (numFeaturesPerQuery > numToFetch)
                numFeaturesPerQuery = numToFetch;

            while (totalDone < numToFetch)
            {
                // Populate the QueryDef Where clause IN() statement for the current batch of features.
                // This is going to be very slow unless linesIDFieldName is indexed and this is why
                // we added a warning to the GP message window if this is the case.  If you cannot
                // index linesIDFieldName, then this code would run faster scanning the whole feature
                // class looking for the records we need (no Where clause).

                string whereClause = linesIDFieldName + " IN(";

                for (int i = 0; i < numFeaturesPerQuery; i++)
                {
                    currID = Convert.ToInt64(IDs.GetByIndex(totalDone + i), System.Globalization.CultureInfo.InvariantCulture);
                    whereClause += Convert.ToString(currID, System.Globalization.CultureInfo.InvariantCulture);
                    if (i != (numFeaturesPerQuery - 1))
                        whereClause += ",";
                    else
                        whereClause += ")";
                }

                queryFilter.WhereClause = whereClause;

                // select the features

                IFeatureCursor inputFeatureCursor = inputLineFeatures.Search(queryFilter, false);

                // get the features

                IFeature feature;

                while ((feature = inputFeatureCursor.NextFeature()) != null)
                {
                    // keep a copy of the OID and shape of feature - skip records that cause errors
                    // (perhaps pass the GPMessages in and log warnings in there if you need to log exceptions)

                    try
                    {
                        FeatureData data = new FeatureData(feature.OID, feature.ShapeCopy);
                        outputFeatures.Add(Convert.ToInt64(feature.get_Value(linesIDFieldIndex)), data);
                    }
                    catch
                    {
                    }

                    if ((totalDone % cancelCheckInterval) == 0)
                    {
                        // check for user cancel

                        if (trackcancel != null && !trackcancel.Continue())
                            throw (new COMException("Function cancelled."));
                    }
                }

                // finished? set up for next batch

                totalDone += numFeaturesPerQuery;

                totalRemaining = numToFetch - totalDone;
                if (totalRemaining > 0)
                {
                    if (numFeaturesPerQuery > totalRemaining)
                        numFeaturesPerQuery = totalRemaining;
                }
            }

            return outputFeatures;
        }
    private IUniqueValueRenderer CreateTrackUniqueValueRenderer(IFeatureClass featureClass, string fieldName)
    {
      IRgbColor color = new RgbColorClass();
      color.Red = 0;
      color.Blue = 0;
      color.Green = 255;

      ISimpleLineSymbol simpleLineSymbol = new SimpleLineSymbolClass();
      simpleLineSymbol.Color = (IColor)color;
      simpleLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
      simpleLineSymbol.Width = 1.0;

      IUniqueValueRenderer uniqueRenderer = new UniqueValueRendererClass();
      uniqueRenderer.FieldCount = 1;
      uniqueRenderer.set_Field(0, fieldName);
      uniqueRenderer.DefaultSymbol = (ISymbol)simpleLineSymbol;
      uniqueRenderer.UseDefaultSymbol = true;

      Random rand = new Random();
      bool bValFound = false;
      IFeatureCursor featureCursor = featureClass.Search(null, true);
      IFeature feature = null;
      string val = string.Empty;
      int fieldID = featureClass.FindField(fieldName);
      if (-1 == fieldID)
        return uniqueRenderer;

      while ((feature = featureCursor.NextFeature()) != null)
      {
        bValFound = false;
        val = Convert.ToString(feature.get_Value(fieldID));
        for (int i = 0; i < uniqueRenderer.ValueCount - 1; i++)
        {
          if (uniqueRenderer.get_Value(i) == val)
            bValFound = true;
        }

        if (!bValFound)//need to add the value to the renderer
        {
          color.Red = rand.Next(255);
          color.Blue = rand.Next(255);
          color.Green = rand.Next(255);

          simpleLineSymbol = new SimpleLineSymbolClass();
          simpleLineSymbol.Color = (IColor)color;
          simpleLineSymbol.Style = esriSimpleLineStyle.esriSLSSolid;
          simpleLineSymbol.Width = 1.0;

          //add the value to the renderer
          uniqueRenderer.AddValue(val, "name", (ISymbol)simpleLineSymbol);
        }
      }

      //release the featurecursor
      ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(featureCursor);

      return uniqueRenderer;
    }
        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();
                }
            }
        }
        public static void summarizeBiomassPolygon(IFeatureClass pointFtr, IField[] fldsToSummarize, IFeatureClass strataFtr, IFeatureClass standsFtr = null, geoDatabaseUtility geoUtil=null )
        {
            if(geoUtil==null) geoUtil = new geoDatabaseUtility();
            int cnt = 0;
            int[] ptFldIndex = new int[fldsToSummarize.Length];
            int[] meanFldIndex = new int[fldsToSummarize.Length];
            int[] varFldIndex = new int[fldsToSummarize.Length];
            int[] cntFldIndex = new int[fldsToSummarize.Length];
            foreach (IField fld in fldsToSummarize)
            {

                ptFldIndex[cnt] = pointFtr.FindField(fld.Name);
                string sName = geoUtil.createField(strataFtr, "v_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                varFldIndex[cnt] = strataFtr.FindField(sName);
                string mName = geoUtil.createField(strataFtr, "m_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                meanFldIndex[cnt] = strataFtr.FindField(mName);
                string cntName = geoUtil.createField(strataFtr, "n_" + fld.Name, esriFieldType.esriFieldTypeInteger, false);
                cntFldIndex[cnt] = strataFtr.FindField(cntName);
                cnt++;
            }
            IFeatureCursor uCur = strataFtr.Update(null, true);
            IFeature uFtr = uCur.NextFeature();
            while (uFtr != null)
            {
                ISpatialFilter sFilt = new SpatialFilter();
                sFilt.Geometry = uFtr.Shape;
                sFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
                double[][] fldVlsArr = new double[fldsToSummarize.Length][];
                for (int i = 0; i < fldsToSummarize.Length; i++)
                {
                    fldVlsArr[i] = new double[3];
                }
                IFeatureCursor psCur = pointFtr.Search(sFilt, true);
                IFeature psFtr = psCur.NextFeature();

                while (psFtr != null)
                {
                    for (int i = 0; i < ptFldIndex.Length; i++)
                    {
                        int indexVl = ptFldIndex[i];
                        object objVl = psFtr.get_Value(indexVl);
                        if (objVl != null)
                        {
                            double vl = System.Convert.ToDouble(objVl);
                            double vl2 = vl*vl;
                            fldVlsArr[i][0] += vl;
                            fldVlsArr[i][1] += vl2;
                            fldVlsArr[i][2] += 1;
                        }
                    }
                    psFtr = psCur.NextFeature();
                }

                System.Runtime.InteropServices.Marshal.ReleaseComObject(psCur);
                for (int i = 0; i < ptFldIndex.Length; i++)
                {
                    double s = fldVlsArr[i][0];
                    double s2 = fldVlsArr[i][1];
                    double n = fldVlsArr[i][2];
                    double mean = s / n;//mean
                    double var = (s2 - (Math.Pow(s, 2) / n)) / (n - 1);//variance
                    int mIndex = meanFldIndex[i];
                    int vIndex = varFldIndex[i];
                    int cntIndex = cntFldIndex[i];
                    uFtr.set_Value(mIndex, mean);
                    uFtr.set_Value(vIndex, var);
                    uFtr.set_Value(cntIndex, n);
                }
                uCur.UpdateFeature(uFtr);
                uFtr = uCur.NextFeature();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(uCur);
            if (standsFtr != null)
            {
                calcStandMeans(strataFtr, standsFtr, meanFldIndex, varFldIndex, cntFldIndex, fldsToSummarize,geoUtil);
            }
        }
Esempio n. 45
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();
            }
        }
        private void InsertPivoTableRowsToFeatureClass(
            IFeatureClass featureClass,
            PivotTable ptable,
            Dictionary<string, string> uniqueFieldNames)
        {
            // get the polygon of the geohash
            var insertCur = featureClass.Insert(true);
            this.pbarChangeDet.Maximum = ptable.Count;
            this.pbarChangeDet.Minimum = 0;
            this.pbarChangeDet.Value = 0;
            var fieldsInFc = new List<string>();
            for (var y = 0; y < featureClass.Fields.FieldCount; y++)
            {
                fieldsInFc.Add(featureClass.Fields.Field[y].Name);
            }

            var i = 0;
            foreach (var entry in ptable)
            {
                i++;
                this.UpdatePBar(i);

                var poly = this.GetGeoHashPoly(entry.RowKey);
                var buffer = featureClass.CreateFeatureBuffer();

                // Setup the features geometry.
                buffer.Shape = (IGeometry)poly;

                buffer.Value[featureClass.FindField("Geohash")] = entry.RowKey;
                foreach (var val in entry.Data.Keys)
                {
                    if (uniqueFieldNames.ContainsKey(val))
                    {
                        try
                        {
                            if (val.EndsWith("_str"))
                            {
                                var fieldName = "DG_" + uniqueFieldNames[val];
                                var field = featureClass.FindField(fieldName);
                                var value = entry.Label;

                                buffer.Value[field] = value;
                            }
                            else
                            {
                                var fieldName = "DG_" + uniqueFieldNames[val];
                                var field = featureClass.FindField(fieldName);
                                var value = entry.Data[val];

                                buffer.Value[field] = value;
                            }
                        }
                        catch (Exception error)
                        {
                            Jarvis.Logger.Error(error);
                        }
                    }
                }
                // Feature has been created so add to the feature class.
                insertCur.InsertFeature(buffer);
            }
            insertCur.Flush();
        }
        //---------------------------------------------------------------------
        // CHANGED: CR13 (Export features performance)
        // Add a new attribute index to a feature class.
        /// <summary>
        /// Adds an attribute index to a field in a feature class.
        /// </summary>
        /// <param name="featureClass">The feature class.</param>
        /// <param name="indexName">Name of the index.</param>
        /// <param name="fieldName">Name of the field.</param>
        public void AddFieldIndex(IFeatureClass featureClass, String indexName, String fieldName)
        {
            // Ensure the feature class contains the specified field.
            int fieldIndex = featureClass.FindField(fieldName);
            if (fieldIndex == -1)
                return;

            // Get the specified field from the feature class.
            IFields featureClassFields = featureClass.Fields;
            IField field = featureClassFields.get_Field(fieldIndex);

            // Create a fields collection and add the specified field to it.
            IFields fields = new FieldsClass();
            IFieldsEdit fieldsEdit = (IFieldsEdit)fields;
            fieldsEdit.FieldCount_2 = 1;
            fieldsEdit.set_Field(0, field);

            //Create an index and cast to the IIndexEdit interface.
            IIndex index = new IndexClass();
            IIndexEdit indexEdit = (IIndexEdit)index;

            // Set the index's properties, including the associated fields.
            indexEdit.Fields_2 = fields;
            indexEdit.IsAscending_2 = false;
            indexEdit.IsUnique_2 = false;
            indexEdit.Name_2 = indexName;

            // Attempt to acquire an exclusive schema lock on the feature class.
            ISchemaLock schemaLock = (ISchemaLock)featureClass;
            try
            {
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                featureClass.AddIndex(index);
            }
            catch (COMException comExc)
            {
                // Handle this in a way appropriate to your application.
                Console.WriteLine("A COM Exception was thrown: {0}", comExc.Message);
            }
            finally
            {
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
            }
        }
Esempio n. 48
0
        /// <summary>
        /// Geocodes a table of addresses
        /// </summary>
        /// <param name="addressTable">Input address table</param>
        /// <param name="addressFieldNames">Fields defined in the table</param>
        /// <param name="whereClause">Query filter where clause</param>
        /// <param name="outputFeatureClass">Output feature class for matched addresses</param>
        /// <param name="outputFieldNames">Output field names</param>
        /// <param name="fieldsToCopy"></param>
        /// <param name="cancelTracker"></param>
        public virtual void MatchTable(ITable addressTable, String addressFieldNames, String whereClause,
          IFeatureClass outputFeatureClass, String outputFieldNames, IPropertySet fieldsToCopy, ITrackCancel cancelTracker)
        {
            _log.Debug("IAddressGeocoding MatchTable");

              // Obtain the read and insert cursors
              IQueryFilter queryFilter = new QueryFilterClass();
              queryFilter.WhereClause = whereClause;
              ICursor readCursor = null;
              IFeatureCursor insertCursor = null;
              IFeatureCursor updateCursor = null;

              // m_needToUpdate will be True when a Rematch is being preformed
              if (m_needToUpdate)
              {
              // Create update cursor to update matched records
              updateCursor = outputFeatureClass.Update(queryFilter, false);
              if (isSameObject(addressTable, outputFeatureClass))
                  readCursor = updateCursor as ICursor;
              else
                  readCursor = addressTable.Search(queryFilter, true);
              }
              else
              {
              // Create insert cursor to add new records
              readCursor = addressTable.Search(queryFilter, true);
              insertCursor = outputFeatureClass.Insert(true);
              }

              int count = addressTable.RowCount(queryFilter);

              // Progress dialog setup
              IStepProgressor progressor = null;
              if (cancelTracker != null)
              progressor = cancelTracker.Progressor as IStepProgressor;
              IProgressStatistics progStats = cancelTracker as IProgressStatistics;
              if (progressor != null)
              {
              progressor.StepValue = 1;
              progressor.MaxRange = addressTable.RowCount(null);
              }

              // Separate the input field names
              string[] multilineFields = addressFieldNames.Split(',');

              // Read the first row and get the address field
              IRow row = readCursor.NextRow();

              Dictionary<int, string> addressFieldIndexes = new Dictionary<int, string>();

              // Get the index of each valid field
              for (int i = 0; i < multilineFields.Length; i++)
              {
              if (multilineFields[i].Trim().Length > 0)
                  addressFieldIndexes.Add(row.Fields.FindField(multilineFields[i].Trim()), multilineFields[i].Trim());
              }

              string address;
              IPropertySet addressProperties = new PropertySetClass();
              IPropertySet resultSet;
              IFeatureBuffer featureBuffer;
              object copyTo, copyFrom, key, value;

              // Get the name and value of all the properties in the property set
              fieldsToCopy.GetAllProperties(out copyTo, out copyFrom);
              string[] copyToArray = copyTo as string[];
              object[] copyFromArray = copyFrom as object[];
              string matchStatus = "U";

              // Populate the output feature class
              while (row != null)
              {
              featureBuffer = outputFeatureClass.CreateFeatureBuffer();
              foreach (KeyValuePair<int,string> entry in addressFieldIndexes)
              {
                  if (entry.Key != -1)
                      address = row.get_Value(entry.Key) as string;
                  else
                      address = row.get_Value(0) as string;

                  addressProperties.SetProperty(entry.Value, address);
              }

              resultSet = MatchAddress(addressProperties);

              // Get all of the fields and values of the result
              resultSet.GetAllProperties(out key, out value);
              string[] names = key as string[];
              object[] items = value as object[];

              // Output match fields and values
              // Insert the Feature into the output featureClass and get the next row
              if (m_needToUpdate)
              {
                  _log.Debug("IAddressGeocoding Updating Feature" + row.OID.ToString());

                  // Record is being rematched so find record to update
                  IFeature feature = outputFeatureClass.GetFeature(row.OID);

                  for (int i = 0; i < names.Length; i++)
                  {
                      if (names[i] == "Shape")
                          feature.Shape = items[i] as IGeometry;
                      else
                      {
                          if (names[i] == "Status")
                          {
                              matchStatus = items[i] as string;
                              feature.set_Value(outputFeatureClass.FindField(names[i]), items[i]);
                          }
                      }
                  }

                  // Set the match type
                  if (outputFeatureClass.FindField("Match_type") != -1)
                  {
                      feature.set_Value(outputFeatureClass.FindField("Match_type"), "A");
                  }

                  // Copy over values from address table
                  for (int j = 0; j < copyToArray.Length; j++)
                  {
                      feature.set_Value(outputFeatureClass.FindField(copyToArray[j]),
                      row.get_Value(addressTable.FindField(copyFromArray[j] as string)));
                  }

                  updateCursor.UpdateFeature(feature);
              }
              else
              {
                  // set shape and status of matched record
                  for (int i = 0; i < names.Length; i++)
                  {
                      if (names[i] == "Shape")
                          featureBuffer.Shape = items[i] as IGeometry;
                      else
                      {
                          if (names[i] == "Status")
                          matchStatus = items[i] as string;
                          featureBuffer.set_Value(outputFeatureClass.FindField(names[i]), items[i]);
                      }
                  }

                  // Set the match type
                  if (outputFeatureClass.FindField("Match_type") != -1)
                  {
                      featureBuffer.set_Value(outputFeatureClass.FindField("Match_type"), "A");
                  }

                  // Copy over values from address table
                  for (int j = 0; j < copyToArray.Length; j++)
                  {
                      try
                      {
                          featureBuffer.set_Value(outputFeatureClass.FindField(copyToArray[j]),
                              row.get_Value(addressTable.FindField(copyFromArray[j] as string)));
                      }
                      catch (Exception ex)
                      {
                          _log.Error("An error occurred copying values from the address table: " + ex.Message);
                      }
                  }

                  insertCursor.InsertFeature(featureBuffer);
              }

              row = readCursor.NextRow();

              // Update the MatchTable progress
              if (progStats != null)
              {
                  progStats.StepByValue(matchStatus);
                  progStats.Update();
              }
              if (cancelTracker != null)
              {
                  if (!cancelTracker.Continue())
                      break;
              }
              }

              _log.Debug("IAddressGeocoding MatchTable End of updating features.");

              // Clean up the cursors
              if (insertCursor != null)
              {
              insertCursor.Flush();
              Marshal.ReleaseComObject(insertCursor);
              }
              if (updateCursor != null)
              {
              updateCursor.Flush();
              Marshal.ReleaseComObject(updateCursor);
              }
              if (readCursor != null)
              Marshal.ReleaseComObject(readCursor);
        }
    private IUniqueValueRenderer CreateUniqueValueRenderer(IFeatureClass featureClass, string fieldName)
    {
      IRgbColor color = new RgbColorClass();
      color.Red = 255;
      color.Blue = 0;
      color.Green = 0;

      ICharacterMarkerSymbol charMarkersymbol = new CharacterMarkerSymbolClass();
      charMarkersymbol.Font = Converter.ToStdFont(new Font(new FontFamily("ESRI Default Marker"), 12.0f, FontStyle.Regular));
      charMarkersymbol.CharacterIndex = 96;
      charMarkersymbol.Size = 12.0;
      charMarkersymbol.Color = (IColor)color;


      IRandomColorRamp randomColorRamp = new RandomColorRampClass();
      randomColorRamp.MinSaturation = 20;
      randomColorRamp.MaxSaturation = 40;
      randomColorRamp.MaxValue = 85;
      randomColorRamp.MaxValue = 100;
      randomColorRamp.StartHue = 75;
      randomColorRamp.EndHue = 190;
      randomColorRamp.UseSeed = true;
      randomColorRamp.Seed = 45;

      IUniqueValueRenderer uniqueRenderer = new UniqueValueRendererClass();
      uniqueRenderer.FieldCount = 1;
      uniqueRenderer.set_Field(0, fieldName);
      uniqueRenderer.DefaultSymbol = (ISymbol)charMarkersymbol;
      uniqueRenderer.UseDefaultSymbol = true;



      Random rand = new Random();
      bool bValFound = false;
      IFeatureCursor featureCursor = featureClass.Search(null, true);
      IFeature feature = null;
      string val = string.Empty;
      int fieldID = featureClass.FindField(fieldName);
      if (-1 == fieldID)
        return uniqueRenderer;

      while ((feature = featureCursor.NextFeature()) != null)
      {
        bValFound = false;
        val = Convert.ToString(feature.get_Value(fieldID));
        for (int i = 0; i < uniqueRenderer.ValueCount - 1; i++)
        {
          if (uniqueRenderer.get_Value(i) == val)
            bValFound = true;
        }

        if (!bValFound)//need to add the value to the renderer
        {
          color.Red = rand.Next(255);
          color.Blue = rand.Next(255);
          color.Green = rand.Next(255);

          charMarkersymbol = new CharacterMarkerSymbolClass();
          charMarkersymbol.Font = Converter.ToStdFont(new Font(new FontFamily("ESRI Default Marker"), 10.0f, FontStyle.Regular));
          charMarkersymbol.CharacterIndex = rand.Next(40, 118);
          charMarkersymbol.Size = 20.0;
          charMarkersymbol.Color = (IColor)color;

          //add the value to the renderer
          uniqueRenderer.AddValue(val, "name", (ISymbol)charMarkersymbol);
        }
      }

      //release the featurecursor
      ESRI.ArcGIS.ADF.ComReleaser.ReleaseCOMObject(featureCursor);

      return uniqueRenderer;
    }
        private bool UpdateCircularArcValues(IFeatureClass LineTable, IQueryFilter QueryFilter, bool Unversioned, IDictionary<int, InferredCurve> CurveLookup, myProgessor progressor, Dictionary<int, int> MaxSequenceCache)
        {
            IFeature pLineFeat = null;
            IFeatureBuffer buffer = null;
            IFeatureCursor pLineCurs = null;
            IFeatureCursor pRadialCur = null;
            IFeatureCursor maxCursor = null;
            IDataStatistics dataStatistics = null;

            IGeometryFactory3 geometryFactory = new GeometryEnvironmentClass();
            IGeometry geometry = new PolylineClass();
            geometryFactory.CreateEmptyGeometryByType(LineTable.ShapeType, out geometry);

            IGeometryDef geometryDef = LineTable.Fields.get_Field(LineTable.FindField(LineTable.ShapeFieldName)).GeometryDef;

            if (geometryDef.HasZ)
            {
                IZAware zAware = (IZAware)(geometry);
                zAware.ZAware = true;
            }
            if (geometryDef.HasM)
            {
                IMAware mAware = (IMAware)(geometry);
                mAware.MAware = true;
            }


            try
            {
                CurveByInferenceSettings.FieldPositions positions = new CurveByInferenceSettings.FieldPositions((ITable)LineTable);

                buffer = LineTable.CreateFeatureBuffer();
                pLineCurs = LineTable.Update(QueryFilter, false);
                pRadialCur = LineTable.Insert(false);

                while ((pLineFeat = pLineCurs.NextFeature()) != null)
                {
                    //loop through all of the given lines, and update centerpoint ids, radius, and arc length values
                    if (!progressor.Continue())
                        return false;
                    progressor.Step();

                    InferredCurve curveInfo = CurveLookup[pLineFeat.OID];

                    pLineFeat.set_Value(positions.RadiusFieldIdx, curveInfo.InferredRadius);
                    pLineFeat.set_Value(positions.CenterpointIDFieldIdx, curveInfo.InferredCenterpointID);
                    IFeature feature = pLineFeat as IFeature;
                    double length = 0;
                    if (feature != null)
                    {
                        IPolyline polyline = feature.ShapeCopy as IPolyline;
                        if (polyline != null)
                        {
                            length = ((IProximityOperator)polyline.FromPoint).ReturnDistance(polyline.ToPoint);
                            pLineFeat.set_Value(positions.ArcLengthFieldIdx, length);
                            Marshal.ReleaseComObject(polyline);
                        }
                    }

                    if (Unversioned)
                        pLineCurs.UpdateFeature(pLineFeat);
                    else
                        pLineFeat.Store();

                    //fine the max sequence value 
                    int maxSequence = -1;
                    if (MaxSequenceCache.ContainsKey(curveInfo.Parcel))
                    {
                        maxSequence = MaxSequenceCache[curveInfo.Parcel];
                    }
                    else
                    {
                        maxCursor = LineTable.Search(new QueryFilter() {
                            SubFields = String.Format("{0}, {1}, {2}", LineTable.OIDFieldName, CurveByInferenceSettings.Instance.SequenceFieldName, CurveByInferenceSettings.Instance.ParcelIDFieldName),
                            WhereClause = String.Format("{0} = {1}", CurveByInferenceSettings.Instance.ParcelIDFieldName, curveInfo.Parcel) }, true);

                        int seqenceIdx = maxCursor.Fields.FindField(CurveByInferenceSettings.Instance.SequenceFieldName);

                        IRow maxFeat = null;
                        while ((maxFeat = maxCursor.NextFeature()) != null)
                        {
                            maxSequence = Math.Max((int)maxFeat.get_Value(seqenceIdx), maxSequence);
                            Marshal.ReleaseComObject(maxFeat);
                        }
                        Marshal.ReleaseComObject(maxCursor);

                        MaxSequenceCache.Add(curveInfo.Parcel, maxSequence);
                        dataStatistics = null;
                        maxCursor = null;                        
                    }
                    if (maxSequence <= 0)
                        throw new Exception("Failed to find max sequence value");

                    //the chord bearing
                    double featureBearing = (double)pLineFeat.get_Value(positions.BearingFieldIdx);

                    //half the delta of the proposed curve would be:
                    double halfdelta = toDegrees(Math.Asin(length / 2 / curveInfo.InferredRadius.Value));

                    //perpendicular to the chord
                    double perpendicular = (curveInfo.InferredRadius.Value > 0) ? featureBearing + 90 : featureBearing - 90;
                    if (perpendicular > 360)
                        perpendicular = perpendicular - 360;
                    else if (perpendicular < 0)
                        perpendicular = perpendicular + 360;

                    for (int i = 0; i < 2; i++)
                    {
                        buffer.set_Value(positions.ParcelIDFieldIdx, curveInfo.Parcel);
                        buffer.set_Value(positions.ToPointFieldIdx, curveInfo.InferredCenterpointID);
                        buffer.set_Value(positions.CategoryFieldIdx, 4);
                        buffer.set_Value(positions.SequenceFieldIdx, ++maxSequence);
                        buffer.set_Value(positions.TypeFieldIdx, 0);
                        buffer.set_Value(positions.DistanceFieldIdx, curveInfo.InferredRadius);
                        buffer.set_Value(positions.HistoricalFieldIdx, 0);
                        buffer.set_Value(positions.LineParametersFieldIdx, 0);
                        buffer.set_Value(positions.DensifyTypeIdx, 0);
                        buffer.set_Value(positions.SystemStartDateFieldIdx, pLineFeat.get_Value(positions.SystemStartDateFieldIdx));
                        buffer.Shape = geometry;

                        if (i == 0) // startpoing
                        {
                            buffer.set_Value(positions.FromPointFieldIdx, pLineFeat.get_Value(positions.FromPointFieldIdx));
                            buffer.set_Value(positions.BearingFieldIdx, perpendicular + halfdelta);
                        }
                        else  //endpoint
                        {
                            buffer.set_Value(positions.FromPointFieldIdx, pLineFeat.get_Value(positions.ToPointFieldIdx));
                            buffer.set_Value(positions.BearingFieldIdx, perpendicular - halfdelta);
                        }

                        pRadialCur.InsertFeature(buffer);
                    }

                    MaxSequenceCache[curveInfo.Parcel] = maxSequence; 
                    Marshal.ReleaseComObject(pLineFeat);
                }

                return true;
            }
            catch (COMException ex)
            {
                messageBox.Show(String.Format("Problem updating circular arc: {0} ({1})", ex.Message, ex.ErrorCode));
                return false;
            }
            finally
            {
                if(pLineCurs != null) Marshal.ReleaseComObject(pLineCurs);
                if(buffer != null) Marshal.ReleaseComObject(buffer);
                if(pRadialCur != null) Marshal.ReleaseComObject(pRadialCur);

                if(dataStatistics != null) Marshal.ReleaseComObject(dataStatistics);
                if (maxCursor != null) Marshal.ReleaseComObject(maxCursor);

                if (geometry != null) Marshal.FinalReleaseComObject(geometry);
                if (geometryFactory != null) Marshal.FinalReleaseComObject(geometryFactory);
            }
        }
Esempio n. 51
0
        private void appendParcelField(IFeatureClass parcelFC)
        {
            if (perceel == null) return;

            IFeatureCursor insertCursor = parcelFC.Insert(false);

            datacontract.geojsonPolygon jsPoly = JsonConvert.DeserializeObject<datacontract.geojsonPolygon>(perceel.geometry.shape);
            IPolygon lbShape = geopuntHelper.geojson2esriPolygon( jsPoly , (int)dataHandler.CRS.Lambert72 );
            IPolygon mapShape = (IPolygon)geopuntHelper.Transform(lbShape, map.SpatialReference);

            IFeature feature = parcelFC.CreateFeature();
            feature.Shape = (IGeometry)mapShape;

            int capakeyIdx = parcelFC.FindField("capakey");
            feature.set_Value(capakeyIdx, perceel.capakey);

            int perceelnrIdx = parcelFC.FindField("perceelnr");
            feature.set_Value(perceelnrIdx, perceel.perceelnummer);

            int grondnrIdx = parcelFC.FindField("grondnr");
            feature.set_Value(grondnrIdx, perceel.grondnummer);

            int exponentIdx = parcelFC.FindField("exponent");
            feature.set_Value(exponentIdx, perceel.exponent);

            int machtIdx = parcelFC.FindField("macht");
            feature.set_Value(machtIdx, perceel.macht);

            int bisnrIdx = parcelFC.FindField("bisnr");
            feature.set_Value(bisnrIdx, perceel.bisnummer);

            int perceeltypeIdx = parcelFC.FindField("type");
            feature.set_Value(perceeltypeIdx, perceel.type);

            string adres = string.Join("-", perceel.adres.ToArray()) ;
            if (adres.Length > 254)
                adres = adres.Substring(0, 254);

            int adresIdx = parcelFC.FindField("adres");
            feature.set_Value(adresIdx, adres);

            feature.Store();
        }
        /// <summary>
        /// 获取数据表
        /// </summary>
        /// <param name="dataGridView"></param>
        /// <param name="pFeatureLayer"></param>
        public static DataTable GetAttributeTable(IFeatureClass pFeatureClass, IFeatureCursor pFeatureCuror)
        {
            if (pFeatureClass == null) return null;

            DataTable dt = new DataTable();
            DataColumn dc = null;

            for (int i = 0; i < pFeatureClass.Fields.FieldCount; i++)
            {
                dc = new DataColumn(pFeatureClass.Fields.get_Field(i).Name);
                dt.Columns.Add(dc);
            }

            //IFeatureCursor pFeatureCuror = pFeatureClass.Search(null, false);
            IFeature pFeature = pFeatureCuror.NextFeature();

            DataRow dr = null;
            while (pFeature != null)
            {
                dr = dt.NewRow();
                for (int j = 0; j < pFeatureClass.Fields.FieldCount; j++)
                {
                    if (pFeatureClass.FindField(pFeatureClass.ShapeFieldName) == j)
                    {

                        dr[j] = pFeatureClass.ShapeType.ToString();
                    }
                    else
                    {
                        dr[j] = pFeature.get_Value(j).ToString();

                    }
                }

                dt.Rows.Add(dr);
                pFeature = pFeatureCuror.NextFeature();
            }
            //dataGridView.DataSource = dt;
            return dt;
        }
        /// <summary>
        ///     Insert a row into the feature class.
        /// </summary>
        /// <param name="featureClass">
        ///     The feature class that will have rows inserted
        /// </param>
        /// <param name="key">
        ///     The key.
        /// </param>
        /// <param name="insertCur">
        ///     The insert cur.
        /// </param>
        /// <param name="resultDictionary">
        ///     The result dictionary.
        /// </param>
        /// <param name="uniqueFieldNames">
        ///     The unique field names.
        /// </param>
        private void InsertRow(
            IFeatureClass featureClass,
            string key,
            IFeatureCursor insertCur,
            Dictionary<string, Dictionary<string, double>> resultDictionary,
            Dictionary<string, string> uniqueFieldNames)
        {
            try
            {
                // get the polygon of the geohash
                var poly = this.GetGeoHashPoly(key);
                var buffer = featureClass.CreateFeatureBuffer();

                // Setup the features geometry.
                buffer.Shape = (IGeometry)poly;
                buffer.Value[featureClass.FindField("GeoHash")] = key;
                foreach (var subKey in resultDictionary[key].Keys)
                {
                    var field = uniqueFieldNames[subKey];
                    var value = resultDictionary[key][subKey];
                    var index = featureClass.FindField("DG_" + field);

                    if (index != -1)
                    {
                        buffer.Value[index] = value;
                    }
                }

                // Feature has been created so add to the feature class.
                insertCur.InsertFeature(buffer);
            }
            catch (Exception error)
            {
                Jarvis.Logger.Error(error);
            }
        }
Esempio n. 54
0
        private bool InsertTopoError(IFeatureClass destFClass)
        {
            try
            {
                string strSQL = @"SELECT
                            b.CheckType,
                            IIF(b.TargetFeatClass1 is Null,'',b.TargetFeatClass1) as YSTC,
                            IIF(a.SourceBSM is Null,'',a.SourceBSM) as SourceBSM,
                            IIF(a.MBTC is Null,'',a.MBTC) as MBTC,
                            IIF(a.TargetBSM is Null,'',a.TargetBSM) as BSM2,
                            a.TPTC as TopoLayerName,
                            a.Reason as Description,
                            a.IsException as IsException,
                            IIf(a.Remark is Null,'',a.Remark) as Remark,
                            b.GZBM ,
                            a.ArcGisRule as ArcGisRule,
                            a.JHLX as JHLX,
                            a.SourceLayerID,
                            a.TargetLayerID,
                            a.SourceOID as OID,
                            a.TargetOID as OID2
                            from LR_ResAutoTopo as a, LR_ResultEntryRule as b where a.RuleInstID=b.RuleInstID
                            ";

                DataTable dtError = Hy.Common.Utility.Data.AdoDbHelper.GetDataTable(this.ResultConnection, strSQL);

                IFeatureCursor fCusorInsert = destFClass.Insert(false);
                Dictionary<int, int> dictFieldIndex = new Dictionary<int, int>();
                for (int i = 0; i < m_FieldCaptions.Count; i++)
                {
                    dictFieldIndex.Add(i,destFClass.FindField(m_FieldCaptions[i]));
                }
                int xFieldIndex = destFClass.FindField("X����");
                int yFieldIndex = destFClass.FindField("Y����");

                IErrorFeatureContainer errFeatureContainer = this.Topology as IErrorFeatureContainer;
                ISpatialReference spatialRef = (this.Topology as IGeoDataset).SpatialReference;
                for (int i = 0; i < dtError.Rows.Count; i++)
                {
                    DataRow rowError = dtError.Rows[i];
                    int fClassID = Convert.ToInt32(rowError["SourceLayerID"]);
                    int fClassID2 = Convert.ToInt32(rowError["TargetLayerID"]);
                    int oid = Convert.ToInt32(rowError["OID"]);
                    int oid2 = Convert.ToInt32(rowError["OID2"]);
                    esriGeometryType geoType = (esriGeometryType)Convert.ToInt32(rowError["JHLX"]);
                    esriTopologyRuleType ruleType = (esriTopologyRuleType)Convert.ToInt32(rowError["ArcGISRule"]);

                    IFeature srcFeature = errFeatureContainer.get_ErrorFeature(spatialRef, ruleType, geoType, fClassID, fClassID2, oid, oid2) as IFeature;

                    IFeatureBuffer fNew = destFClass.CreateFeatureBuffer();
                    for (int j = 0; j < m_FieldCaptions.Count; j++)
                    {
                        int fIndex = dictFieldIndex[j];
                        if (fIndex < 0)
                            continue;

                        fNew.set_Value(fIndex, rowError[j]);
                    }
                    fNew.Shape = GetErrorGeometry(srcFeature);
                    IPoint point = fNew.Shape as IPoint;
                    fNew.set_Value(xFieldIndex, point.X);
                    fNew.set_Value(yFieldIndex, point.Y);

                    fCusorInsert.InsertFeature(fNew);

                    if (i % 2000 == 0)
                        fCusorInsert.Flush();

                }

                fCusorInsert.Flush();

                return true;
            }
            catch(Exception exp)
            {
                Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString());
                return false;
            }
        }
        public static void summarizeBiomassPolygon(IFeatureClass pointFtr, IField[] fldsToSummarize, IFunctionRasterDataset strataRaster, IFeatureClass standsFtr, geoDatabaseUtility geoUtil = null, rasterUtil rsUtil = null)
        {
            if (geoUtil == null) geoUtil = new geoDatabaseUtility();
            if(rsUtil == null) rsUtil = new rasterUtil();
            int cnt = 0;
            //need to work on calculating N
            Dictionary<string,double[][]> vlDic = getDictionaryValues(pointFtr, fldsToSummarize, strataRaster, geoUtil, rsUtil); //Strata: SummaryFields [{sum,sum2,cnt},...]
            int[] meanFldIndex = new int[fldsToSummarize.Length];
            int[] varFldIndex = new int[fldsToSummarize.Length];
            int[] cntFldIndex = new int[fldsToSummarize.Length];
            //string cntName = geoUtil.createField(standsFtr, "n", esriFieldType.esriFieldTypeInteger, false);
            //int cntIndex = standsFtr.FindField(cntName);
            foreach (IField fld in fldsToSummarize)
            {
                string sName = geoUtil.createField(standsFtr, "v_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                varFldIndex[cnt] = standsFtr.FindField(sName);
                string mName = geoUtil.createField(standsFtr, "m_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                meanFldIndex[cnt] = standsFtr.FindField(mName);
                string cntName = geoUtil.createField(standsFtr, "n_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
                cntFldIndex[cnt] = standsFtr.FindField(cntName);
                cnt++;
            }
            IFeatureCursor uCur = standsFtr.Update(null, true);
            IFeature uFtr = uCur.NextFeature();
            while (uFtr != null)
            {
                ESRI.ArcGIS.Geometry.IGeometry geo = uFtr.Shape;
                IFunctionRasterDataset cRs = rsUtil.clipRasterFunction(strataRaster, geo, esriRasterClippingType.esriRasterClippingOutside);
                //Console.WriteLine("Clipping raster");
                Dictionary<string, double> rsStrataPropDic = getStrataProportion(cRs,rsUtil); //Strata: proportion of area
                //int tn = 0;
                //double[] tn = new double[meanFldIndex.Length];
                double[][] updateValuesArr = new double[meanFldIndex.Length][];
                for (int i = 0; i < meanFldIndex.Length; i++)
                {
                    updateValuesArr[i] = new double[3];
                }
                foreach (KeyValuePair<string, double> kvp in rsStrataPropDic)
                {
                    string stratum = kvp.Key;
                    double proportion = kvp.Value;
                    //Console.WriteLine(stratum + " = " + proportion.ToString());
                    double[][] vlDicArr;
                    if (vlDic.TryGetValue(stratum, out vlDicArr))
                    {
                        //double n = vlDicArr[0][2];
                        //tn += System.Convert.ToInt32(n);
                        for (int i = 0; i < meanFldIndex.Length; i++)
                        {
                            double[] dArr = vlDicArr[i];
                            double n = dArr[2];
                            //tn[i] += n;
                            double s=dArr[0];
                            double s2=dArr[1];
                            updateValuesArr[i][0] += (s/n) * proportion;//mean
                            updateValuesArr[i][1] += (s2-Math.Pow(s,2)/n)/(n-1) * proportion;//variance
                            updateValuesArr[i][2] += n;
                        }

                    }
                }
                //uFtr.set_Value(cntIndex, tn);
                for (int i = 0; i < meanFldIndex.Length; i++)
                {
                    uFtr.set_Value(meanFldIndex[i], updateValuesArr[i][0]);
                    uFtr.set_Value(varFldIndex[i], updateValuesArr[i][1]);
                    uFtr.set_Value(cntFldIndex[i], updateValuesArr[i][2]);
                }
                uCur.UpdateFeature(uFtr);
                uFtr = uCur.NextFeature();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(uCur);
        }
Esempio n. 56
0
        public void OpenTurnFeatureClass(IFeatureWorkspace fws, string turnClassName)
        {
            TurnFeatureClass = fws.OpenFeatureClass(turnClassName);

            idxEdge1End = TurnFeatureClass.FindField("Edge1End");
            idxEdge1FCID = TurnFeatureClass.FindField("Edge1FCID");
            idxEdge1FID = TurnFeatureClass.FindField("Edge1FID");
            idxEdge1Pos = TurnFeatureClass.FindField("Edge1Pos");
            idxEdge2FCID = TurnFeatureClass.FindField("Edge2FCID");
            idxEdge2FID = TurnFeatureClass.FindField("Edge2FID");
            idxEdge2Pos = TurnFeatureClass.FindField("Edge2Pos");
            idxRestrict = TurnFeatureClass.FindField("RestrictionType");
        }
 private static void calcStandMeans(IFeatureClass strataFtr, IFeatureClass standsFtr, int[] meanStrataFldIndex, int[] varStrataFldIndex, int[] countFldStrataIndex, IField[] fldsToSummarize, geoDatabaseUtility geoUtil)
 {
     int cnt = 0;
     int[] ptFldIndex = new int[fldsToSummarize.Length];
     int[] meanFldIndex = new int[fldsToSummarize.Length];
     int[] varFldIndex = new int[fldsToSummarize.Length];
     int[] cntFldIndex = new int[fldsToSummarize.Length];
     foreach (IField fld in fldsToSummarize)
     {
         string sName = geoUtil.createField(standsFtr, "v_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
         varFldIndex[cnt] = standsFtr.FindField(sName);
         string mName = geoUtil.createField(standsFtr, "m_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
         meanFldIndex[cnt] = standsFtr.FindField(mName);
         string cName = geoUtil.createField(standsFtr, "n_" + fld.Name, esriFieldType.esriFieldTypeDouble, false);
         cntFldIndex[cnt] = standsFtr.FindField(cName);
         cnt++;
     }
     IFeatureCursor uCur = standsFtr.Update(null, true);
     IFeature uFtr = uCur.NextFeature();
     while (uFtr != null)
     {
         ESRI.ArcGIS.Geometry.IGeometry geo = uFtr.Shape;
         ISpatialFilter spFlt = new SpatialFilter();
         spFlt.Geometry = geo;
         spFlt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects;
         double totalArea = 0;
         IFeatureCursor sCur = strataFtr.Search(spFlt, true);
         IFeature sFtr = sCur.NextFeature();
         double[][] vlArr = new double[meanFldIndex.Length][];
         for (int i = 0; i < meanFldIndex.Length; i++)
         {
             vlArr[i] = new double[3];
         }
         while (sFtr != null)
         {
             ESRI.ArcGIS.Geometry.IGeometry sgeo = sFtr.Shape;
             ESRI.ArcGIS.Geometry.ITopologicalOperator4 topo = (ESRI.ArcGIS.Geometry.ITopologicalOperator4)sgeo;
             ESRI.ArcGIS.Geometry.IGeometry sgeo2 = topo.Intersect(geo, ESRI.ArcGIS.Geometry.esriGeometryDimension.esriGeometry2Dimension);
             double subArea = (((ESRI.ArcGIS.Geometry.IArea)sgeo2).Area);
             totalArea += subArea;
             for (int i = 0; i < meanFldIndex.Length; i++)
             {
                 vlArr[i][0] += System.Convert.ToDouble(sFtr.get_Value(meanStrataFldIndex[i])) * subArea;
                 vlArr[i][1] += System.Convert.ToDouble(sFtr.get_Value(varStrataFldIndex[i])) * subArea;
                 vlArr[i][2] += System.Convert.ToDouble(sFtr.get_Value(countFldStrataIndex[i]));
             }
             sFtr = sCur.NextFeature();
         }
         System.Runtime.InteropServices.Marshal.ReleaseComObject(sCur);
         if (totalArea != 0)
         {
             for (int i = 0; i < meanFldIndex.Length; i++)
             {
                 uFtr.set_Value(meanFldIndex[i], vlArr[i][0]/totalArea);
                 uFtr.set_Value(varFldIndex[i], vlArr[i][1]/totalArea);
                 uFtr.set_Value(cntFldIndex[i], vlArr[i][2]);
             }
             uCur.UpdateFeature(uFtr);
         }
         uFtr = uCur.NextFeature();
     }
     System.Runtime.InteropServices.Marshal.ReleaseComObject(uCur);
 }
        private void handlingOnFields(IFeatureClass feacls, string[] strFields)
        {
            IFieldEdit fieldEdit = null;
            IClass cls = feacls as IClass;

            int defvalue = 100;
            foreach (string item in strFields)
            {
                if (feacls.FindField(item) < 0)
                {
                    IField vField = new FieldClass();
                    fieldEdit = vField as IFieldEdit;
                    fieldEdit.Name_2 = item;
                    fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger;
                    fieldEdit.DefaultValue_2 = defvalue;
                    cls.AddField(vField);
                    fieldEdit = null;

                }
            }
            //添加总分字段
            if (feacls.FindField("FinalScore") >= 0)
                return;
            IField scoreField = new FieldClass();
            fieldEdit = scoreField as IFieldEdit;
            fieldEdit.Name_2 = "FinalScore";
            fieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble;
            double d = 0.0;
            fieldEdit.DefaultValue_2 = d;
            cls.AddField(scoreField);
        }
 private void setFeatureClassFieldValue(IFeatureClass feacls, string strfield, int val)
 {
     if(feacls.FindField(strfield)<0)
     {
         IField field = new FieldClass();
         IFieldEdit fe = field as IFieldEdit;
         fe.Name_2 = strfield;
         fe.Type_2 = esriFieldType.esriFieldTypeInteger;
         feacls.AddField(field);
     }
     int index = feacls.FindField(strfield);
     IFeatureCursor cursor = feacls.Search(null, false);
     IFeature fea = cursor.NextFeature();
     while (fea != null)
     {
         fea.set_Value(index, val);
         fea.Store();
         fea = cursor.NextFeature();
     }
 }
Esempio n. 60
0
        private string FindFKey(FeatureClassField[] theFkeys, IFeatureClass fc, out int fkeyIndex)
        {
            string theReturn = "";
            fkeyIndex = -1;
            IDataset theDataset = (IDataset)fc;

            foreach (FeatureClassField fcf in theFkeys)
            {
                if (fcf.FeatureClassName == theDataset.Name)
                {
                    fkeyIndex = fc.FindField(fcf.FieldName);
                    if (fkeyIndex == -1)
                        return "";
                    theReturn = fcf.FieldName;
                    break;
                }
            }

            return theReturn;
        }