Exemple #1
0
        /// <summary>
        /// 构造小区的一个立体覆盖网格
        /// </summary>
        /// <param name="cellName"></param>
        /// <param name="lac"></param>
        /// <param name="ci"></param>
        /// <param name="gxid"></param>
        /// <param name="gyid"></param>
        /// <param name="level"></param>
        /// <param name="x1"></param>
        /// <param name="y1"></param>
        /// <param name="x2"></param>
        /// <param name="y2"></param>
        /// <param name="z"></param>
        /// <param name="recePower"></param>
        /// <param name="pathLoss"></param>
        public void constructGrid3D(string cellName, int lac, int ci, int gxid, int gyid, int level, double x1, double y1, double x2, double y2, double z, double recePower, double pathLoss)
        {
            IDataset   dataset   = (IDataset)pFeatureLayer.FeatureClass;
            IWorkspace workspace = dataset.Workspace;
            //Cast for an IWorkspaceEdit
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

            //start an edit session and operation
            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();

            IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true);
            IFeatureBuffer pFeatureBuffer;

            Geometric.Point p   = GridHelper.getInstance().GridToGeo(gxid, gyid);
            double          lon = p.X;
            double          lat = p.Y;

            IPoint pointA = GeometryUtilities.ConstructPoint3D(x1, y1, z);
            IPoint pointB = GeometryUtilities.ConstructPoint3D(x2, y1, z);
            IPoint pointC = GeometryUtilities.ConstructPoint3D(x2, y2, z);
            IPoint pointD = GeometryUtilities.ConstructPoint3D(x1, y2, z);

            IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD });

            pFeatureBuffer       = pFeatureClass.CreateFeatureBuffer();
            pFeatureBuffer.Shape = pGeometryColl as IGeometry;
            pFeatureBuffer.set_Value(this.GXIDIndex, gxid);
            pFeatureBuffer.set_Value(this.GYIDIndex, gyid);
            pFeatureBuffer.set_Value(this.LevelIndex, level);
            pFeatureBuffer.set_Value(this.eNodeBIndex, lac);
            pFeatureBuffer.set_Value(this.CIIndex, ci);
            pFeatureBuffer.set_Value(this.cellNameIndex, cellName);
            pFeatureBuffer.set_Value(this.RecePowerIndex, recePower);
            pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss);
            pFeatureBuffer.set_Value(this.LongitudeIndex, lon);
            pFeatureBuffer.set_Value(this.LatitudeIndex, lat);

            pFeatureCursor.InsertFeature(pFeatureBuffer);

            //一次性提交
            pFeatureCursor.Flush();

            //stop editing
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            //IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass;
            //pFeatureClassManage.UpdateExtent();

            GISMapApplication.Instance.RefreshLayer(pFeatureLayer);
            //GISMapApplication.Instance.FullExtent(pFeatureLayer.AreaOfInterest);
        }
Exemple #2
0
        /// <summary>
        /// 刷新Mobike数据
        /// </summary>
        public void RefreshmobikeInfo()
        {
            //获取车辆位置信息
            var mobikecars = new List <mobikeInfo>();

            NetUtils.GetmobikeCars(out mobikecars);
            if (mobikecars == null)
            {
                view.ShowError("数据出现问题,可能是mobike用户认证出错 返回示例数据");
                mobikecars = SampleData.mobikeSampleList;
            }

            IFeatureClass  featureclass  = CreateFeatureClass("mobike");
            IFeatureCursor featureCursor = featureclass.Insert(true);

            //遍历照片链表 以创建缓存的形式插入数据
            foreach (var c in mobikecars)
            {
                IPoint pPoint = new PointClass();
                //坐标转换
                var t = CoordinateUtils.gcj02_To_Wgs84(c.distY, c.distX);
                pPoint.PutCoords(t.longtitude, t.latitude);
                pPoint.SpatialReference = ApplicationV.GlobalMapControl.SpatialReference;
                pPoint.Project(ApplicationV.GlobalMapControl.SpatialReference);
                IFeatureBuffer featureBuffer = featureclass.CreateFeatureBuffer();
                featureBuffer.Shape = pPoint;
                featureBuffer.set_Value(featureBuffer.Fields.FindField("Latitude"), t.latitude);
                featureBuffer.set_Value(featureBuffer.Fields.FindField("Longtitude"), t.longtitude);
                featureCursor.InsertFeature(featureBuffer);
            }
            featureCursor.Flush();

            //创建图层
            IFeatureLayer pFeaturelayer = new FeatureLayerClass();

            pFeaturelayer.FeatureClass = featureclass;
            pFeaturelayer.Name         = "mobike分布";

            //修饰该图层
            IPictureMarkerSymbol mobikeMarkerSymbol = new PictureMarkerSymbolClass();

            mobikeMarkerSymbol.Size = 18;
            mobikeMarkerSymbol.CreateMarkerSymbolFromFile(esriIPictureType.esriIPicturePNG, ApplicationV.Data_ImgPath + "//mobike.png");

//            ISimpleMarkerSymbol pMarkerSymbol = new SimpleMarkerSymbol();
//            pMarkerSymbol.Style = esriSimpleMarkerStyle.esriSMSCircle;
//            var pRgbColor = ColorUtils.GetRgbColor(226, 61, 14);
//            pMarkerSymbol.Color = pRgbColor;

            ISimpleRenderer pSimpleRenderer = new SimpleRendererClass();

            pSimpleRenderer.Symbol = (ISymbol)mobikeMarkerSymbol;
            (pFeaturelayer as IGeoFeatureLayer).Renderer = pSimpleRenderer as IFeatureRenderer;

            //正式归为图层
            ofoLayer = pFeaturelayer as ILayer;

            ApplicationV.GlobalMapControl.AddLayer(ofoLayer);
            ApplicationV.GlobalMapControl.Refresh();
        }
Exemple #3
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);
        }
Exemple #4
0
        private static void InsertFeaturesBoun(IFeatureClass newFeatureClass, IFeatureCursor featureCursorSearch, IGeometry clipGeo)
        {
            int intFeatureCount = 0;

            IFeatureCursor featureCursorInsert = newFeatureClass.Insert(true);
            IFeatureBuffer featureBufferInsert = newFeatureClass.CreateFeatureBuffer();

            IFeature feature = featureCursorSearch.NextFeature();

            while (feature != null)
            {
                ITopologicalOperator topoOpe   = feature.Shape as ITopologicalOperator;
                IGeometry            intersect = topoOpe.Intersect(clipGeo, feature.Shape.Dimension);
                featureBufferInsert.Shape = intersect;

                AddFields(featureBufferInsert, feature);

                featureCursorInsert.InsertFeature(featureBufferInsert);

                if (++intFeatureCount == 100)
                {
                    featureCursorInsert.Flush();
                    intFeatureCount = 0;
                }

                feature = featureCursorSearch.NextFeature();
            }

            featureCursorInsert.Flush();
        }
Exemple #5
0
        /// <summary>
        /// jzd保存进入map
        /// </summary>
        /// <param name="jzd"></param>
        public static void SaveMap(IList <JZD> jzds)
        {
            IFeatureClass           featureClass = GetJZDLayer().FeatureClass;
            Dictionary <int, Clazz> dic          = ArcGisService.GetTitleClzz <JZD>(featureClass.Fields, false);

            dic.Remove(-1);
            IFeatureCursor featureCursor = featureClass.Insert(true);
            IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();

            foreach (JZD jzd in jzds)
            {
                if (jzd.Point == null)
                {
                    featureBuffer.Shape = jzd.Feature.ShapeCopy;
                }
                else
                {
                    IPoint point = new PointClass();
                    point.PutCoords(jzd.Point.X, jzd.Point.Y);
                    featureBuffer.Shape = point;
                }
                SetFeatureBufferValue(featureBuffer, dic, jzd);
                featureCursor.InsertFeature(featureBuffer);
            }
        }
Exemple #6
0
        public void makeSinglePart(string timeStep)
        {
            IFeatureCursor      searchCurr;
            IFeatureCursor      insertCurr;
            IFeatureBuffer      insertBuff;
            IFeature            f;
            IGeometryCollection geoColl;
            int i = 1;

            mLog.Debug("inside animal map make single part");
            IFeatureClass ifc = getShapeFile("TimeStep" + timeStep);

            mLog.Debug("file we are going to work with is " + ifc.AliasName);

            searchCurr = ifc.Search(null, false);
            mLog.Debug("there are " + ifc.FeatureCount(null).ToString() + " polygons to work with");
            insertCurr = ifc.Insert(true);
            insertBuff = ifc.CreateFeatureBuffer();
            f          = searchCurr.NextFeature();

            geoColl = (IGeometryCollection)f.Shape;
            mLog.Debug("we have " + geoColl.GeometryCount + " geometries to work on");
            if (timeStep == "1")
            {
                i = 0;
            }

            for (i = 0; i < geoColl.GeometryCount; i++)
            {
                this.InsertFeature(insertCurr, insertBuff, f, geoColl.get_Geometry(i));
            }
            insertCurr.Flush();
            f.Delete();
        }
Exemple #7
0
        /// <summary>
        /// 将拓扑错误要素存入要素类中
        /// </summary>
        /// <param name="topoErrorFeatures">拓扑错误要素</param>
        /// <param name="resultFeatureClass">保存拓扑错误要素的要素类,注意其坐标系和类型(点/线/面)必须与拓扑错误要素相同</param>
        public static void TopoErrorInsertToFeatureClass(this IEnumerable <ITopologyErrorFeature> topoErrorFeatures, IFeatureClass resultFeatureClass)
        {
            int typeIndex      = resultFeatureClass.AddField("TRuleType", "拓扑规则", esriFieldType.esriFieldTypeInteger);
            int orClassIdIndex = resultFeatureClass.AddField("OriClsID", "源要素类ID", esriFieldType.esriFieldTypeInteger);
            int deClassIdIndex = resultFeatureClass.AddField("DesClsID", "目标要素类ID", esriFieldType.esriFieldTypeInteger);
            int orOidIndex     = resultFeatureClass.AddField("OriOID", "源要素OID", esriFieldType.esriFieldTypeInteger);
            int deOidIndex     = resultFeatureClass.AddField("DesOID", "目标要素OID", esriFieldType.esriFieldTypeInteger);

            IWorkspaceEdit tmpWorkspaceEdit = (IWorkspaceEdit)(resultFeatureClass as IDataset).Workspace;

            tmpWorkspaceEdit.StartEditing(true);
            tmpWorkspaceEdit.StartEditOperation();
            IFeatureBuffer featureBuffer = resultFeatureClass.CreateFeatureBuffer();

            //在目标要素类中插入所有错误要素
            IFeatureCursor featureCursor = resultFeatureClass.Insert(true);

            foreach (var errorFeature in topoErrorFeatures)
            {
                IFeature tmpFeature = errorFeature as IFeature;
                featureBuffer.set_Value(typeIndex, errorFeature.TopologyRuleType);
                featureBuffer.set_Value(orClassIdIndex, errorFeature.OriginClassID);
                featureBuffer.set_Value(deClassIdIndex, errorFeature.DestinationClassID);
                featureBuffer.set_Value(orOidIndex, errorFeature.OriginOID);
                featureBuffer.set_Value(deOidIndex, errorFeature.DestinationOID);

                featureBuffer.Shape = tmpFeature.Shape;
                object featureOID = featureCursor.InsertFeature(featureBuffer);
            }
            featureCursor.Flush();//保存要素
            tmpWorkspaceEdit.StopEditOperation();
            tmpWorkspaceEdit.StopEditing(true);
            Marshal.ReleaseComObject(featureCursor);
        }
Exemple #8
0
        /// <summary>
        /// 批次新增圖徵
        /// </summary>
        /// <param name="points"></param>
        /// <param name="featureclass"></param>
        public void InsertFeature(List <IPoint> points, ref IFeatureClass featureclass)
        {
            if (featureclass == null)
            {
                throw new ArgumentNullException(nameof(featureclass));
            }
            if (points == null || points.Count == 0)
            {
                throw new ArgumentNullException(nameof(points));
            }

            IFeatureCursor pFeatCur     = featureclass.Insert(true);
            int            mustFlush    = 1000; //每n筆儲存一次
            int            featureCount = 0;

            foreach (var item in points)
            {
                IFeatureBuffer pFeatBuffer = featureclass.CreateFeatureBuffer();
                pFeatBuffer.Shape = item;
                pFeatCur.InsertFeature(pFeatBuffer);
                ++featureCount;
                if (featureCount % mustFlush == 0)
                {
                    pFeatCur.Flush();
                }
            }

            pFeatCur.Flush();
        }
Exemple #9
0
        public static void InsertLoadOnly(IFeatureClass featureCls, IList <IGeometry> geoList)
        {
            IFeatureClassLoad featureClsLoad = (IFeatureClassLoad)featureCls;
            ISchemaLock       schemaLock     = (ISchemaLock)featureCls;

            try
            {
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
                featureClsLoad.LoadOnlyMode = true;
                using (var comReleaser = new ComReleaser())
                {
                    IFeatureBuffer featureBuffer = featureCls.CreateFeatureBuffer();
                    IFeatureCursor featureCursor = featureCls.Insert(true);
                    comReleaser.ManageLifetime(featureCursor);
                    featureBuffer.set_Value(featureBuffer.Fields.FindField("InstBy"), "B Pierce");
                    for (int ic = 0; ic < geoList.Count; ic++)
                    {
                        featureBuffer.Shape = geoList[0];
                        var featureOID = featureCursor.InsertFeature(featureBuffer);
                        if (ic % 10 == 0)
                        {
                            featureCursor.Flush();
                        }
                    }
                    featureCursor.Flush();
                }
            }
            finally
            {
                featureClsLoad.LoadOnlyMode = false;
                schemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
            }
        }
Exemple #10
0
        //添加点实体
        private void addFeature(string layerName, IPoint point)
        {
            int    i     = 0;
            ILayer layer = null;

            for (i = 0; i < axMapControl1.LayerCount; i++)
            {
                layer = axMapControl1.Map.get_Layer(i);
                if (layer.Name.ToLower() == layerName)
                {
                    break;
                }
            }
            IFeatureLayer  featureLayer  = layer as IFeatureLayer;
            IFeatureClass  featureClass  = featureLayer.FeatureClass;
            IDataset       dataset       = (IDataset)featureClass;
            IWorkspace     workspace     = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

            workspaceEdit.StartEditing(true);
            workspaceEdit.StartEditOperation();
            IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
            IFeatureCursor featureCursor = featureClass.Insert(true);

            featureBuffer.Shape = point;
            object featureOID = featureCursor.InsertFeature(featureBuffer);

            featureCursor.Flush();
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);
        }
        //函数号:
        //函数名:LoadRasterToCatalogDatabase
        //函数功能:Raster导入Database
        //参数:pWorkspace:数据库,pWorkspace可以是Access 或者SDE
        //		strCata:Catalog名称
        //		pRasterDs:需要入库的Rasterdataset
        //备注:insert a raster dataset with given path and file name to an existing raster catalog
        public void LoadRasterToCatalogDatabase(IWorkspace pWorkspace, string strCata, IRasterDataset pRasterDs, string name)
        {
            //QI IRasterWorkspaceEx to IWorkspace
            IRasterWorkspaceEx pRasWKS = pWorkspace as IRasterWorkspaceEx;

            //Open raster catalog
            //IRasterCatalog相当于一个FeatureClass(表),表中的每一个记录可以存放Raster
            IRasterCatalog pInCatalog = pRasWKS.OpenRasterCatalog(strCata);
            // get raster field index
            int iRaster = pInCatalog.RasterFieldIndex;

            // QI IFeatureClass for inserting
            IFeatureClass pFeatureClass = pInCatalog as IFeatureClass;

            // get insert cursor
            IFeatureCursor pCursor = pFeatureClass.Insert(false);

            // create raster value from raster dataset with default storagedef
            IRasterValue pRasterValue = new RasterValueClass();

            pRasterValue.RasterDataset    = pRasterDs;
            pRasterValue.RasterStorageDef = new RasterStorageDefClass();

            pRasterValue.RasterDatasetName.NameString = name;
            //这里可以设置新的RasterStorageDef

            // insert the rastervalue  ' it will update name, metadata and geometry field
            IFeatureBuffer pRow = pFeatureClass.CreateFeatureBuffer();

            pRow.set_Value(iRaster, pRasterValue);
            pCursor.InsertFeature(pRow);
        }
        //RasterDataset to RasterCatalog
        public void RasDSToCatalog(IRasterDataset pRasterDs, IFeatureClass pCatalog)
        {
            //IRasterCatalogItem pCatalogFeature;

            IFeatureCursor pCursor;
            IFeatureBuffer pRow;

            pCursor = pCatalog.Insert(false);
            IRasterCatalog pCat = pCatalog as IRasterCatalog;

            IDataset pDs;

            // loop through all the datasets and load
            if (pRasterDs != null)
            {
                pDs  = pRasterDs as IDataset;
                pRow = pCatalog.CreateFeatureBuffer();
                pRow.set_Value(pCat.RasterFieldIndex, createRasterValue(pRasterDs));

                /*try
                 * {
                 *  pCursor.InsertFeature(pRow);
                 * }
                 * catch
                 * {
                 *
                 * }*/
                pCursor.InsertFeature(pRow);
            }
            //pCursor.Flush();
            pRasterDs = null;
        }
        /// <summary>
        /// 从指定要素中获取数据添加到目标要素类中(复制同名字段的值)
        /// </summary>
        /// <param name="features"></param>
        /// <param name="targetClass"></param>
        public static void CopyDataTo(this IEnumerable <IFeature> features, IFeatureClass targetClass)
        {
            //获取源要素类与目标要素类相同的字段的索引
            var dict = new Dictionary <int, int>();//key:字段在源要素类的索引;value:在目标要素类中的索引

            var tarFeatureCursor = targetClass.Insert(true);
            var tarFeatureBuffer = targetClass.CreateFeatureBuffer();
            var sourceFields     = features.First().Fields;

            for (var i = 0; i < sourceFields.FieldCount; i++)
            {
                var index1 = tarFeatureBuffer.Fields.FindField(sourceFields.get_Field(i).Name);
                if (index1 > -1 && tarFeatureBuffer.Fields.get_Field(index1).Editable)
                {
                    dict.Add(i, index1);
                }
            }
            foreach (var feature in features)
            {
                foreach (var pair in dict)
                {
                    tarFeatureBuffer.set_Value(pair.Value, feature.get_Value(pair.Key));
                }
                tarFeatureCursor.InsertFeature(tarFeatureBuffer);
            }
            tarFeatureCursor.Flush();
            Marshal.ReleaseComObject(tarFeatureCursor);
        }
        /// <summary>
        /// 复制featureclass图形和属性的方法
        /// </summary>
        /// <param name="name">待创建要素类的名称</param>
        /// <param name="target_FeatureClass">需要写入图形和属性的空要素</param>
        /// <param name="CADFeatureClass">需要复制的CAD要素类</param>
        public void CreateFeatureClassByAtt(string name, IFeatureClass target_FeatureClass, IFeatureClass CADFeatureClass)
        {
            List <string>  AttList      = new List <string>();
            IQueryFilter   pQueryFilter = new QueryFilterClass();
            IFeatureCursor pFeaCursor;
            IFeature       pFeature;
            IFeatureBuffer pFeaBuffer = null;

            AttList = getUniqueValue(CADFeatureClass, "Layer");
            pQueryFilter.WhereClause = "Layer = '" + name.Substring(name.IndexOf('-') + 1) + "'";
            pFeaCursor = CADFeatureClass.Search(pQueryFilter, false);
            //用IFeatureBuffer提高运算速度
            IFeatureCursor targetCursor = target_FeatureClass.Insert(true);

            while ((pFeature = pFeaCursor.NextFeature()) != null)
            {
                pFeaBuffer = target_FeatureClass.CreateFeatureBuffer();
                IGeoDataset pGeoDataset = pFeature.Class as IGeoDataset;
                pFeaBuffer.Shape = pFeature.Shape;
                for (int j = 2; j < CADFeatureClass.Fields.FieldCount; j++)
                {
                    try
                    {
                        pFeaBuffer.set_Value(j, pFeature.Value[CADFeatureClass.FindField(target_FeatureClass.Fields.Field[j].Name)]);
                    }catch
                    {
                        continue;
                    }
                }
                targetCursor.InsertFeature(pFeaBuffer);
                targetCursor.Flush();
            }
        }
Exemple #15
0
        public void mypoints()
        {
            IMap pMap = axMapControl.Map;
            //第一个图层是点,第二个图层是线,第三个图层是面。这里就不判断,主要在于功能的实现
            ILayer         pLayer         = pMap.get_Layer(0);
            IFeatureLayer  pFeatureLyr    = pLayer as IFeatureLayer;
            IFeatureClass  pFeatCls       = pFeatureLyr.FeatureClass;
            IDataset       pDataset       = pFeatCls as IDataset;
            IWorkspace     pWS            = pDataset.Workspace;
            IWorkspaceEdit pWorkspaceEdit = pWS as IWorkspaceEdit;

            pWorkspaceEdit.StartEditing(false);
            pWorkspaceEdit.StartEditOperation();
            IFeatureBuffer pFeatureBuffer;
            IFeatureCursor pFeatureCuror;
            IFeature       pFeature;
            IPoint         pPoint = new PointClass();

            pFeatureBuffer = pFeatCls.CreateFeatureBuffer();
            pFeatureCuror  = pFeatCls.Insert(true);
            pFeature       = pFeatureBuffer as IFeature;
            //pPoint = (IPoint)pSOC.CreateObject("esriGeometry.Point");
            pPoint.X = 110;
            pPoint.Y = 40;
            IGeometry pPointGeo = pPoint as IGeometry;

            pFeature.Shape = pPointGeo;
            pFeatureCuror.InsertFeature(pFeatureBuffer);

            pWorkspaceEdit.StopEditOperation();
            pWorkspaceEdit.StopEditing(true);
            axMapControl.Refresh();
        }
Exemple #16
0
        public override void OnClick()
        {
            IFeatureClass fc = (MoData.v_CurLayer as IFeatureLayer).FeatureClass;

            foreach (KeyValuePair <IGeometry, IElement> item in GeometriesToBePasted)
            {
                if (fc.ShapeType != item.Key.GeometryType)
                {
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "几何类型不匹配!");
                    return;
                }
            }

            MoData.v_CurWorkspaceEdit.StartEditOperation();
            IFeatureCursor cursor = fc.Insert(true);

            IFeatureBuffer buffer  = fc.CreateFeatureBuffer();
            IFeature       feature = buffer as IFeature;

            foreach (KeyValuePair <IGeometry, IElement> item in GeometriesToBePasted)
            {
                Exception Err = null;
                try
                {
                    feature.Shape = item.Key;
                }
                catch (Exception exErr)
                {
                    //******************************************
                    //guozheng added System Exception log
                    if (SysCommon.Log.Module.SysLog == null)
                    {
                        SysCommon.Log.Module.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog();
                    }
                    SysCommon.Log.Module.SysLog.Write(exErr);
                    //******************************************

                    Err = exErr;
                    SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", exErr.Message);
                }

                if (Err == null)
                {
                    if (feature.FeatureType == esriFeatureType.esriFTAnnotation)
                    {
                        IAnnotationFeature af = feature as IAnnotationFeature;
                        af.Annotation = item.Value;

                        feature = af as IFeature;
                    }

                    buffer = feature as IFeatureBuffer;
                    cursor.InsertFeature(buffer);
                }
            }

            cursor.Flush();
            MoData.v_CurWorkspaceEdit.StopEditOperation();
            myHook.MapControl.ActiveView.Refresh();
        }
Exemple #17
0
        private void AddGeometryColToFeatureClass(IGeometryCollection pGeometryCollection, IFeatureClass pFeatureClass)
        {
            IFeatureCursor pFeatureCursor;
            IFeatureBuffer pFeatureBuffer;

            pFeatureCursor = pFeatureClass.Insert(true);
            pFeatureBuffer = pFeatureClass.CreateFeatureBuffer();

            IFields pFields;
            IField  pField;

            pFields = pFeatureClass.Fields;


            for (int i = 0; i < pGeometryCollection.GeometryCount; i++)
            {
                IGeometry pCurrentGeometry = pGeometryCollection.get_Geometry(i) as IGeometry;

                for (int n = 1; n <= pFields.FieldCount - 1; n++)
                {
                    pField = pFields.get_Field(n);

                    if (pField.Type == esriFieldType.esriFieldTypeGeometry)
                    {
                        pFeatureBuffer.set_Value(n, pCurrentGeometry);
                    }
                }
                pFeatureCursor.InsertFeature(pFeatureBuffer);
            }
            pFeatureCursor.Flush();
        }
Exemple #18
0
        private void CopyGeometryToFeatureClass(List <IGeometry> pGeometrys, IFeatureClass targetFeatureclass)
        {
            // if (pGeometry == null) { return; }
            IFeatureCursor pFeatureCursor = targetFeatureclass.Insert(true);
            IFeatureBuffer pFeatureBuffer = targetFeatureclass.CreateFeatureBuffer();

            foreach (IGeometry geo in pGeometrys)
            {
                //IGeometry geo2=null;
                //if (index == 2)
                //{
                //    ITopologicalOperator top = geo as ITopologicalOperator;
                //    top.Simplify();
                //    geo2 = top.Boundary;
                //}
                //else
                //{
                //    geo2 = geo;
                //}
                pFeatureBuffer.Shape = geo;
                pFeatureCursor.InsertFeature(pFeatureBuffer);
                pFeatureCursor.Flush();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
            pFeatureCursor = null;
        }
Exemple #19
0
        /// <summary>
        /// 从查询结果复制数据(数据结构相同)
        /// </summary>
        /// <param name="cursor"></param>
        public static void CopyFrom(this IFeatureClass featureClass, IFeatureCursor otherCursor)
        {
            IFeatureCursor thisCursor   = featureClass.Insert(true);
            IFeature       otherFeature = null;

            while (null != (otherFeature = otherCursor.NextFeature()))
            {
                IFeatureBuffer thisBuffer = featureClass.CreateFeatureBuffer();
                // thisBuffer.Shape = otherFeature.Shape;
                for (int i = 0; i < featureClass.Fields.FieldCount; i++)
                {
                    IField thisField = featureClass.Fields.get_Field(i);
                    if (thisField.Editable)
                    {
                        int otherFieldIndex = otherCursor.Fields.FindField(thisField.Name);
                        if (otherFieldIndex > -1)
                        {
                            thisBuffer.Value[i] = otherFeature.GetValue(otherFieldIndex);
                        }
                    }
                }
                thisCursor.InsertFeature(thisBuffer);
            }
            thisCursor.Flush();
        }
Exemple #20
0
        public void AddFeature(IFeatureLayer fealyr, IGeometry geometry)
        {
            IFeatureClass featurecls = fealyr.FeatureClass;

            if (featurecls.ShapeType != geometry.GeometryType)
            {
                return;                                           //这个if语句也是迷
            }
            IDataset       dataset       = featurecls as IDataset;
            IWorkspace     workspace     = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = workspace as IWorkspaceEdit;

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

            IFeatureBuffer featurebuffer = featurecls.CreateFeatureBuffer();

            featurebuffer.Shape = geometry;                ///实锤

            ////以下代码为测试设置其他字段值
            //int index = featureBuffer.Fields.FindField("Name");
            //featureBuffer.set_Value(index, "测试点");
            IFeatureCursor featurecusor = featurecls.Insert(true);

            featurecusor.InsertFeature(featurebuffer);
            featurecusor.Flush();

            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);            //C#庐山真面目,让你感觉到可以这样写
        }
Exemple #21
0
        /// <summary>
        /// 插入从MapServer获取到的JSON数据
        /// </summary>
        /// <param name="features"></param>
        /// <returns></returns>
        public static int InsertFeaturesByJson(this IFeatureClass featureClass, JArray features)
        {
            int featureNum = 0;

            try
            {
                IFeatureCursor cursor = featureClass.Insert(true);
                foreach (JObject feature in features)
                {
                    try
                    {
                        IFeatureBuffer buffer = featureClass.CreateFeatureBuffer();
                        buffer.SetShapeByJson(feature.Value <JObject>("geometry"));
                        buffer.SetAttrsByJson(feature.Value <JObject>("attributes"));
                        cursor.InsertFeature(buffer);
                    }
                    catch (Exception ex)
                    {
                        // Logger.log("ZFeatureClass.InsertFeaturesByJson", ex);
                    }
                    featureNum++;
                }
                cursor.Flush();
            }
            catch (Exception ex)
            {
                throw new Exception($"将JSON数据插入图层【{featureClass.AliasName}】时报错", ex);
            }
            return(featureNum);
        }
        public void ExecuteSpatialInsert(IFeatureClass pFeatureClass, IGeometry geometry, string[] columnNames, object[] insertValues)
        {
            try
            {
                //创建一个插入的游标
                IFeatureCursor featureCursorInsert = pFeatureClass.Insert(true);

                //创建要插入的缓冲对象
                IFeatureBuffer featureBufferInsert = pFeatureClass.CreateFeatureBuffer();

                // 给Shape字段赋值
                featureBufferInsert.Shape = geometry;

                // 根据字段名称和值,给属性表赋值
                for (int columnCounter = 0; columnCounter < columnNames.Length; columnCounter++)
                {
                    string columnName    = columnNames.GetValue(columnCounter).ToString();
                    int    fieldPosition = featureBufferInsert.Fields.FindField(columnName);
                    object insertValue   = insertValues.GetValue(columnCounter);
                    featureBufferInsert.set_Value(fieldPosition, insertValue);
                }

                //保存到数据库中,看是否要扩到try-catch中
                featureCursorInsert.InsertFeature(featureBufferInsert);
                featureCursorInsert.Flush();
            }
            catch (Exception ex)
            {
                MessageBox.Show("保存图形数据时出错: " + ex.Message, "错误!", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Exemple #23
0
        /// <summary>
        /// 使用游标插入要素
        /// </summary>
        /// <param name="selectionLayer">旧图层</param>
        /// <param name="newFeatureClass">新要素集合</param>
        /// <param name="fidValue">FID值</param>
        /// <param name="selectFieldName">选中字段名称</param>
        private static void InsertFeaturesUsingCursor(IFeatureLayer selectionLayer, IFeatureClass newFeatureClass,
                                                      Dictionary <string, int> fidValue, List <string> selectFieldName)
        {
            IFeatureCursor featureCursor = selectionLayer.FeatureClass.Search(null, false);
            IFeature       oldFeature    = featureCursor.NextFeature();
            IFeatureCursor insertCursor  = newFeatureClass.Insert(true);

            while (oldFeature != null)
            {
                //判断当前要素FID是否在FID集合中,在的话,则赋值给新图层
                if (fidValue.ContainsKey(oldFeature.Value[0].ToString()))
                {
                    // Create a feature buffer.
                    IFeatureBuffer featureBuffer = newFeatureClass.CreateFeatureBuffer();
                    for (int i = 0; i < featureBuffer.Fields.FieldCount; i++)
                    {
                        IField field = featureBuffer.Fields.Field[i];
                        //字段是选中且可编辑的
                        if (selectFieldName.Contains(field.Name) && field.Editable)
                        {
                            featureBuffer.set_Value(i, oldFeature.Value[i]); //字段赋值
                        }
                    }
                    insertCursor.InsertFeature(featureBuffer);
                    // Flush the buffer to the geodatabase.
                    insertCursor.Flush();
                }
                oldFeature = featureCursor.NextFeature(); //游标移动
            }
        }
        //step.3 遍历待复制的要素类,复制图形和属性并改变图形的坐标系
        /// <summary>
        /// 遍历待复制的要素类,复制图形和属性并改变图形的坐标系
        /// </summary>
        /// <param name="fromFeatureClass">待复制的要素类</param>
        /// <param name="toFeatureClass">目标要素类</param>
        private void featureClassTransSpatialRef(IFeatureClass fromFeatureClass, IFeatureClass toFeatureClass)
        {
            IFeature       pFeature;
            IGeometry2     pGeometry;
            IFeatureCursor toCursor     = toFeatureClass.Insert(true);
            int            FeatureCount = fromFeatureClass.FeatureCount(null);

            for (int i = 0; i < FeatureCount; i++)
            {
                pFeature  = fromFeatureClass.GetFeature(i);
                pGeometry = pFeature.Shape as IGeometry2;
                IZAware pZAware = pGeometry as IZAware;
                pZAware.ZAware = true;
                pGeometry.ProjectEx(spatialRefTo, esriTransformDirection.esriTransformForward, geoTransformation, false, 0, 0);
                IFeatureBuffer pFeaBuffer = toFeatureClass.CreateFeatureBuffer();
                pFeaBuffer.Shape = pGeometry;
                for (int j = 2; j < fromFeatureClass.Fields.FieldCount; j++)
                {
                    try
                    {
                        pFeaBuffer.set_Value(j, pFeature.Value[fromFeatureClass.FindField(toFeatureClass.Fields.Field[j].Name)]);
                    }
                    catch
                    {
                        continue;
                    }
                }
                toCursor.InsertFeature(pFeaBuffer);
                toCursor.Flush();
            }
        }
Exemple #25
0
        //不剪裁输出forShp
        public static void notcutExportShp(IFeatureCursor pCursor, IFeatureClass pToFeatureClass, int featurecount)
        {
            progressStep.Minimum = 0;
            progressStep.Maximum = featurecount;
            progressStep.Step    = 1;
            IFeature       pFeature       = pCursor.NextFeature();
            IFeatureCursor pFeatureCursor = pToFeatureClass.Insert(true);
            int            iCount         = 0;

            while (pFeature != null)
            {
                IFeatureBuffer pFeatureBuffer = pToFeatureClass.CreateFeatureBuffer();

                for (int i = 0; i < pFeature.Fields.FieldCount; i++)
                {
                    //string sFieldName = pFeature.Fields.get_Field(i).Name;

                    //int iIndex = pFeatureBuffer.Fields.FindField(toShpField[sFieldName]);
                    string sFieldName = pFeature.Fields.get_Field(i).Name;

                    int iIndex = -1;
                    if (m_DicFields.Keys.Contains(sFieldName))
                    {
                        iIndex = pFeatureBuffer.Fields.FindField(m_DicFields[sFieldName]);
                    }
                    else
                    {
                        iIndex = pFeatureBuffer.Fields.FindField(sFieldName);
                    }

                    try
                    {
                        if ((iIndex > -1) && (pFeatureBuffer.Fields.get_Field(iIndex).Editable == true))
                        {
                            pFeatureBuffer.set_Value(iIndex, pFeature.get_Value(i));
                        }
                    }
                    catch
                    { }
                }
                pFeatureBuffer.Shape = pFeature.ShapeCopy;
                pFeatureCursor.InsertFeature(pFeatureBuffer);
                if (iCount == 500)
                {
                    pFeatureCursor.Flush();
                    iCount = 0;
                }
                iCount++;
                progressStep.PerformStep();
                pFeature = pCursor.NextFeature();
            }
            if (iCount > 0)
            {
                pFeatureCursor.Flush();
            }

            System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatureCursor);
            pFeatureCursor = null;
        }
        /// <summary>
        /// 构造小区的一个网格
        /// </summary>
        /// <param name="cellName"></param>
        /// <param name="gxid"></param>
        /// <param name="gyid"></param>
        /// <param name="x1"></param>
        /// <param name="y1"></param>
        /// <param name="x2"></param>
        /// <param name="y2"></param>
        /// <param name="recePower"></param>
        /// <param name="pathLoss"></param>
        public void constructGrid(string cellName, int enodeb, int ci, int gxid, int gyid, double x1, double y1, double x2, double y2, double recePower, double pathLoss)
        {
            IDataset       dataset       = (IDataset)pFeatureLayer.FeatureClass;
            IWorkspace     workspace     = dataset.Workspace;
            IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)workspace;

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

            IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true);
            IFeatureBuffer pFeatureBuffer;

            IPoint pointA = GeometryUtilities.ConstructPoint2D(x1, y1);
            IPoint pointB = GeometryUtilities.ConstructPoint2D(x2, y1);
            IPoint pointC = GeometryUtilities.ConstructPoint2D(x2, y2);
            IPoint pointD = GeometryUtilities.ConstructPoint2D(x1, y2);

            IGeometryCollection pGeometryColl = GeometryUtilities.ConstructPolygon(new IPoint[] { pointA, pointB, pointC, pointD });

            pFeatureBuffer       = pFeatureClass.CreateFeatureBuffer();
            pFeatureBuffer.Shape = pGeometryColl as IGeometry;
            pFeatureBuffer.set_Value(this.GXIDIndex, gxid);
            pFeatureBuffer.set_Value(this.GYIDIndex, gyid);
            pFeatureBuffer.set_Value(this.eNodeBIndex, enodeb);
            pFeatureBuffer.set_Value(this.CIIndex, ci);
            pFeatureBuffer.set_Value(this.cellNameIndex, cellName);
            pFeatureBuffer.set_Value(this.RecePowerIndex, recePower);
            pFeatureBuffer.set_Value(this.PathLossIndex, pathLoss);
            pFeatureCursor.InsertFeature(pFeatureBuffer);

            //一次性提交
            pFeatureCursor.Flush();

            //stop editing
            workspaceEdit.StopEditOperation();
            workspaceEdit.StopEditing(true);

            IFeatureClassManage pFeatureClassManage = (IFeatureClassManage)pFeatureClass;

            pFeatureClassManage.UpdateExtent();

            //GISMapApplication.Instance.RefreshLayer(pFeatureLayer);
            //GISMapApplication.Instance.FullExtent(pFeatureLayer.AreaOfInterest);
        }
Exemple #27
0
        /// <summary>
        /// 添加实体对象
        /// </summary>
        /// <param name="obj"></param>
        /// <param name="geometry"></param>
        /// <param name="featureClass"></param>
        public static void AddFeature(object obj, IGeometry geometry, IFeatureClass featureClass)
        {
            Dictionary <int, Clazz> dic           = ArcGisService.GetTitleClzz(obj, featureClass.Fields, false);
            IFeatureCursor          featureCursor = featureClass.Insert(true);
            IFeatureBuffer          featureBuffer = featureClass.CreateFeatureBuffer();

            featureBuffer.Shape = geometry;
            SetFeatureBufferValue(featureBuffer, dic, obj);
            featureCursor.InsertFeature(featureBuffer);
        }
        private void CopyFeatureClassData(IFeatureClass sourceFeatureClass, IFeatureClass targetFeatureClass, IDictionary <int, int> filedIndexDictionary)
        {
            errorRowCount = 0;
            using (var comReleaser = new ComReleaser())
            {
                IFeatureCursor sourceFeatureCursor = sourceFeatureClass.Search(null, false);
                IFeatureCursor targetFeatureCursor = targetFeatureClass.Insert(true);
                comReleaser.ManageLifetime(sourceFeatureCursor);
                comReleaser.ManageLifetime(targetFeatureCursor);

                List <int> targeFieldIndexs = filedIndexDictionary.Keys.ToList();
                int        fieldsLen        = targeFieldIndexs.Count;

                IFeature sourceFeature = sourceFeatureCursor.NextFeature();
                var      count         = 0;
                while (sourceFeature != null)
                {
                    try
                    {
                        //错误:Geometry cannot have Z values 处理
                        IGeometry geometry = sourceFeature.ShapeCopy;
                        IZAware   zAware   = geometry as IZAware;
                        if (zAware != null && zAware.ZAware == true)
                        {
                            zAware.ZAware = false;
                        }

                        IFeatureBuffer targetFatureBuffer = targetFeatureClass.CreateFeatureBuffer();
                        targetFatureBuffer.Shape = geometry;//sourceFeature.ShapeCopy;
                        for (int i = 0; i < fieldsLen; i++)
                        {
                            var targetIndex = targeFieldIndexs[i];
                            int sourceIndex = filedIndexDictionary[targeFieldIndexs[i]];
                            var value       = sourceFeature.get_Value(sourceIndex);
                            targetFatureBuffer.set_Value(targetIndex, value);
                        }
                        targetFeatureCursor.InsertFeature(targetFatureBuffer);
                        count++;
                        if (count == 1000)
                        {
                            targetFeatureCursor.Flush();
                            count = 0;
                        }
                    }
                    catch (Exception ex)
                    {
                        errorRowCount++;
                        var message = "字段赋值错误";
                        //LoggingManager.GetLogger(GetType()).Error(message, ex);
                    }
                    sourceFeature = sourceFeatureCursor.NextFeature();
                }
                targetFeatureCursor.Flush();
            }
        }
Exemple #29
0
            public void Write(NRCPStatisticFeatureClassRow a_Row)
            {
                if (m_FeatureCursor == null)
                {
                    m_FeatureCursor = m_FeatureClass.Insert(true);
                    m_FeatureBuffer = m_FeatureClass.CreateFeatureBuffer();
                }

                a_Row.Write(m_FeatureBuffer);
                m_FeatureCursor.InsertFeature(m_FeatureBuffer);
            }
Exemple #30
0
        /// <summary>
        /// 插入新要素
        /// </summary>
        /// <param name="featureLayer">图层</param>
        /// <param name="geom">插入要素几何图形</param>
        /// <param name="ID">要素ID(绑定ID)</param>
        /// <returns></returns>
        public static bool InsertNewFeature(IFeatureLayer featureLayer, IGeometry geom, string ID)
        {
            IWorkspaceEdit workspaceEdit = null;
            IFeatureCursor featureCursor = null;

            try
            {
                IFeatureClass featureClass = featureLayer.FeatureClass;

                IDataset   dataset   = (IDataset)featureClass;
                IWorkspace workspace = dataset.Workspace;
                workspaceEdit = workspace as IWorkspaceEdit;

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

                IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                DataEditCommon.ZMValue(featureBuffer, geom);    //几何图形Z值处理
                featureBuffer.Shape = geom;

                int iFieldID = featureBuffer.Fields.FindField("ID");
                featureBuffer.Value[iFieldID] = ID.ToString();

                //开始插入要素
                featureCursor = featureClass.Insert(true);
                object featureOID = featureCursor.InsertFeature(featureBuffer);

                //保存要素
                featureCursor.Flush();

                IFeature feature = featureCursor.NextFeature();

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

                return(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

                workspaceEdit.AbortEditOperation();
                workspaceEdit.StopEditing(false);

                return(false);
            }
            finally
            {
                if (featureCursor != null)
                {
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);  //释放指针
                }
            }
        }
Exemple #31
0
        //RasterDataset to RasterCatalog
        public void RasDSToCatalog(IRasterDataset pRasterDs, IFeatureClass pCatalog)
        {
            //IRasterCatalogItem pCatalogFeature;

            IFeatureCursor pCursor;
            IFeatureBuffer pRow;

            pCursor = pCatalog.Insert(false);
            IRasterCatalog pCat = pCatalog as IRasterCatalog;

            IDataset pDs;

            // loop through all the datasets and load
            if (pRasterDs != null)
            {
                pDs = pRasterDs as IDataset;
                pRow = pCatalog.CreateFeatureBuffer();
                pRow.set_Value(pCat.RasterFieldIndex, createRasterValue(pRasterDs));
                /*try
                {
                    pCursor.InsertFeature(pRow);
                }
                catch
                {

                }*/
                pCursor.InsertFeature(pRow);
            }
            //pCursor.Flush();
            pRasterDs = null;
        }
        private bool processFeatureClass(string rule, string geometry, IFeatureClass inputFeatureClass, IFeatureClass outputFeatureClass, string sidcFieldName)
        {
            repRulesWereAdded = false;

            // allows testing without writing the output to the feature
            const bool DEBUG_DONT_WRITE_OUTPUT = false; //  true;

            if ((mapper == null) || (inputFeatureClass == null) || (outputFeatureClass == null)
                || (militaryFeatures == null) || (symbolCreator == null)
                || (!mapper.Initialized) || (!militaryFeatures.Initialized))
                return false;

            bool success = false;

            int sicFieldIndex = inputFeatureClass.Fields.FindField(sidcFieldName);

            if (sicFieldIndex < 0)
            {
                Console.WriteLine("SIDC field not found: {0} - ABORTING", sidcFieldName);
                return false;
            }

            doFieldMapping(inputFeatureClass, outputFeatureClass, sidcFieldName);

            // Start Editing
            IWorkspaceEdit workspaceEdit = militaryFeatures.Workspace as IWorkspaceEdit;
            if (workspaceEdit == null) return false;
            workspaceEdit.StartEditing(false);
            workspaceEdit.StartEditOperation();

            IRepresentationClass repClass = militaryFeatures.GetRepresentationClassForFeatureClass(outputFeatureClass);
            if (repClass == null)
            {
                Console.WriteLine("RepresentationClass not found in output - ABORTING");
                return false;
            }

            // setup insert cursor
            IFeatureBuffer targetFeatureBuffer = outputFeatureClass.CreateFeatureBuffer();
            IFeatureCursor targetFeatureCursor = outputFeatureClass.Insert(true);

            IFeatureCursor featureCursor = inputFeatureClass.Search(null, true);
            IFeature currentFeature = featureCursor.NextFeature();

            int matchingFeatureCount = 0;

            while (currentFeature != null)
            {
                string sidc = currentFeature.get_Value(sicFieldIndex) as string;

                string matchingRule = mapper.RuleNameFromSymbolIdAndGeometry(sidc, geometry);

                if (matchingRule != rule)
                {
                    currentFeature = featureCursor.NextFeature();
                    continue;
                }

                matchingFeatureCount++;

                Console.WriteLine("Processing Matching Feature: #:{0}, SIDC:{1}, Rule:{2}", matchingFeatureCount, sidc, rule);

                try
                {
                    targetFeatureBuffer.Shape = currentFeature.Shape;
                }
                catch (System.Runtime.InteropServices.COMException ce)
                {
                    Console.WriteLine("-->Could not copy geometry - you may need to add Z-values or run Fix Geometry Tool, error code=" + ce.ErrorCode);
                }

                processFieldMapping(currentFeature, targetFeatureBuffer);

                processSidc(repClass, targetFeatureBuffer, sidc);

                processMiscellaneousFields(targetFeatureBuffer, sidc);

                if (!DEBUG_DONT_WRITE_OUTPUT)
                {
                    // insert new feature
                    targetFeatureCursor.InsertFeature(targetFeatureBuffer);
                }

                currentFeature = featureCursor.NextFeature();
            }

            if (!DEBUG_DONT_WRITE_OUTPUT)
            {
                targetFeatureCursor.Flush();
            }

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

            // Release the cursors to remove the lock on the data.
            System.Runtime.InteropServices.Marshal.ReleaseComObject(targetFeatureCursor);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);
            targetFeatureCursor = null;
            featureCursor = null;

            if (!DEBUG_DONT_WRITE_OUTPUT)
            {
                // looks totally nonsensical - but this forces any new rules to written
                if (repRulesWereAdded)
                    repClass.RepresentationRules = repClass.RepresentationRules;
            }

            return success;
        }
        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);
            }
        }
        /// <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);
            }
        }
Exemple #35
0
        public void Store(IFeatureClass exceptionFC)
        {
            IFeatureBuffer theFBuffer;

            // New exceptions need to be inserted
            if (this.ObjectID == -1)
            {
                theFBuffer = exceptionFC.CreateFeatureBuffer();
            }
            else
            {
                theFBuffer = (IFeatureBuffer)exceptionFC.GetFeature(this.ObjectID);
            }

            int idx;
            idx = theFBuffer.Fields.FindField("ATTACHMENT");
            theFBuffer.set_Value(idx, this._attachment);

            //idx = theFBuffer.Fields.FindField("DATA_EXCEPTION_POINT_ID");
            //theFBuffer.set_Value(idx, {populated by trigger});

            idx = theFBuffer.Fields.FindField("DATA_EXCEPTION_STATUS");
            theFBuffer.set_Value(idx, this._status);

            idx = theFBuffer.Fields.FindField("EXCEPTION_DESCRIPTION");
            theFBuffer.set_Value(idx, this._description);

            idx = theFBuffer.Fields.FindField("LATITUDE");
            theFBuffer.set_Value(idx, this._location.Y);

            idx = theFBuffer.Fields.FindField("LONGITUDE");
            theFBuffer.set_Value(idx, this._location.X);

            idx = theFBuffer.Fields.FindField("OPERATIONAL_DATASET_NAME");
            theFBuffer.set_Value(idx, this._operationDSName);

            idx = theFBuffer.Fields.FindField("QA_TEST_NAME");
            theFBuffer.set_Value(idx, this._testName);

            // Shape
            theFBuffer.Shape = this._location;

            if (this.ObjectID == -1)
            {
                ICursor theInsertCursor = ((ITable)exceptionFC).Insert(false);
                this._objectID = (int)theInsertCursor.InsertRow(theFBuffer);
                theInsertCursor.Flush();

                Marshal.ReleaseComObject(theInsertCursor);
            }
            else
            {
                ((IFeature)theFBuffer).Store();
            }
        }
        private void ExportInsertFeatures(IDisplayTable hluDisplayTable, IQueryFilter exportQueryFilter, 
            int exportRowCount, int[] exportFieldMap, bool isShp, object outWS, IFeatureClass outFeatureClass)
        {
            // Create a Cancel Tracker.
            ITrackCancel trackCancel = new CancelTrackerClass();

            // Create the Progress Dialog. This automatically displays the dialog.
            IProgressDialogFactory progressDlgFactory = new ProgressDialogFactoryClass();
            IProgressDialog2 progressDlg = progressDlgFactory.Create(trackCancel, _application.hWnd) as IProgressDialog2;

            // Set the properties of the Progress Dialog.
            progressDlg.CancelEnabled = true;
            progressDlg.Title = "Export Progress";
            progressDlg.Description = string.Format("Exporting HLU Features and Attributes\n({0} features)", exportRowCount.ToString());
            progressDlg.Animation = esriProgressAnimationTypes.esriNoAnimation;

            // Set the properties of the Step Progressor.
            IStepProgressor stepProgressor = progressDlg as IStepProgressor;
            stepProgressor.MinRange = 0;
            stepProgressor.MaxRange = exportRowCount;
            stepProgressor.StepValue = 1;
            stepProgressor.Message = "";

            // Set the continue progress to true.
            bool contProgress = true;

            IWorkspaceEdit workspaceEdit = null;
            IWorkspace wsOut = outWS as IWorkspace;
            bool restoreEditSession = InEditingSession;
            if (restoreEditSession) CloseEditSession(true);

            // If the workspace is remote then the data is being accessed
            // via ArcSDE.
            if (wsOut.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
            {
                Editor.StartEditing(wsOut);
                Editor.StartOperation();
            }
            // Otherwise, it must be a FileSystem (for shapefiles)
            // or LocalDatabase (for geodatabases) workspace.
            else
            {
                workspaceEdit = (IWorkspaceEdit)outWS;
                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();
            }
            
            IFeatureCursor exportFeatureCursor =
                (IFeatureCursor)hluDisplayTable.SearchDisplayTable(exportQueryFilter, true);
            IFeature exportFeature;

            IFeatureCursor insertCursor = outFeatureClass.Insert(true);
            IFeatureBuffer featureBuffer = outFeatureClass.CreateFeatureBuffer();

            bool calcGeometry = _hluFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint || isShp;
            double geom1;
            double geom2;
            // The last two fields are always the geometry fields.
            int ixGeom1 = featureBuffer.Fields.FieldCount - 2;
            int ixGeom2 = featureBuffer.Fields.FieldCount - 1;

            try
            {
                object item;
                while ((exportFeature = exportFeatureCursor.NextFeature()) != null)
                {
                    featureBuffer.Shape = exportFeature.ShapeCopy;

                    for (int i = 2; i < exportFieldMap.Length; i++)
                    {
                        item = exportFeature.get_Value(exportFieldMap[i]);
                        if (item != DBNull.Value)
                            featureBuffer.set_Value(i, item);
                        //---------------------------------------------------------------------
                        // FIX: 036 Clear all missing fields when exporting features from ArcGIS.
                        else
                            featureBuffer.set_Value(i, null);
                        //---------------------------------------------------------------------
                    }

                    if (calcGeometry)
                    {
                        GetGeometryProperties(exportFeature, out geom1, out geom2);
                        if (geom1 != -1)
                            featureBuffer.set_Value(ixGeom1, geom1);
                        if (geom2 != -1)
                            featureBuffer.set_Value(ixGeom2, geom2);
                    }

                    try { insertCursor.InsertFeature(featureBuffer); }
                    catch { }

                    // Check if the cancel button was pressed. If so, stop the process.
                    contProgress = trackCancel.Continue();
                    if (!contProgress)
                        throw new Exception("Export cancelled by user.");
                }
                FlushCursor(false, ref insertCursor);

                if (workspaceEdit == null)
                {
                    Editor.StopOperation(String.Empty);
                    Editor.StopEditing(true);
                }
                else
                {
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(true);
                }
            }
            catch
            {
                if (workspaceEdit == null)
                {
                    Editor.AbortOperation();
                    Editor.StopEditing(false);
                }
                else
                {
                    workspaceEdit.AbortEditOperation();
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(false);
                }
                throw;
            }
            finally
            {
                FlushCursor(true, ref exportFeatureCursor);

                if (restoreEditSession) OpenEditSession();

                // Hide the progress dialog.
                trackCancel = null;
                stepProgressor = null;
                progressDlg.HideDialog();
                progressDlg = null;
                progressDlgFactory = null;
            }
        }
Exemple #37
0
        private static void InsertFeaturesBoun(IFeatureClass newFeatureClass, IFeatureCursor featureCursorSearch, IGeometry clipGeo)
        {
            int intFeatureCount = 0;

            IFeatureCursor featureCursorInsert = newFeatureClass.Insert(true);
            IFeatureBuffer featureBufferInsert = newFeatureClass.CreateFeatureBuffer();

            IFeature feature = featureCursorSearch.NextFeature();
            while (feature != null)
            {
                ITopologicalOperator topoOpe = feature.Shape as ITopologicalOperator;
                IGeometry intersect = topoOpe.Intersect(clipGeo, feature.Shape.Dimension);
                featureBufferInsert.Shape = intersect;

                AddFields(featureBufferInsert, feature);

                featureCursorInsert.InsertFeature(featureBufferInsert);

                if (++intFeatureCount == 100)
                {
                    featureCursorInsert.Flush();
                    intFeatureCount = 0;
                }

                feature = featureCursorSearch.NextFeature();
            }

            featureCursorInsert.Flush();
        }
Exemple #38
0
        object ICopyFeatures.CopyBulkFeature(IFeature copiedFeature, IFeatureClass toFeatureClass)
        {
            // Create a ComReleaser for cursor management.
               using (ComReleaser comReleaser = new ComReleaser())
               {
               // Create and manage a feature buffer.
               IFeatureBuffer featureBuffer = toFeatureClass.CreateFeatureBuffer();
               comReleaser.ManageLifetime(featureBuffer);

               // Create and manage an insert cursor.
               IFeatureCursor featureCursor = toFeatureClass.Insert(true);
               comReleaser.ManageLifetime(featureCursor);
               featureBuffer.Shape = copiedFeature.ShapeCopy;
               featureCursor.InsertFeature(featureBuffer);
               // Attempt to flush the buffer.
               featureCursor.Flush();
               //MessageBox.Show(string.Format("line 529 DataManager \n{0}", featureBuffer.get_Value(0)));
               //return featureBuffer.get_Value(0);
               return 1;
               }
        }
Exemple #39
0
        object ICopyFeatures.CopyWithAllAttribute(IFeature copiedFeature, IFeatureClass toFeatureClass)
        {
            object id = 0;
               try
               {
               IFeatureCursor featureCursorInsert = toFeatureClass.Insert(true);
               IFeatureBuffer featureBufferInsert = toFeatureClass.CreateFeatureBuffer();
               //releaser.ManageLifetime(featureBufferInsert);
               //releaser.ManageLifetime(featureCursorInsert);
               // Add the original feature's geometry to the feature buffer.
               featureBufferInsert.Shape = copiedFeature.Shape;
               // Add all the original feature's fields to the feature buffer.
               //((ICopyFeatures)this).AddFields(featureBufferInsert, copiedFeature);
               // Insert the feature into the cursor.

               for (int i = 1; i < copiedFeature.Fields.FieldCount; i++)
               {
                   IFeatureClass sourceFeatureClass = (IFeatureClass)copiedFeature.Class;

                   string fieldName = copiedFeature.Fields.get_Field(i).Name;
                   bool bCondition1 = fieldName == sourceFeatureClass.ShapeFieldName;
                   bool bCondition2 = (sourceFeatureClass.LengthField != null &&
                                       fieldName == sourceFeatureClass.LengthField.Name);
                   bool bCondition3 = (sourceFeatureClass.AreaField != null &&
                                       fieldName == sourceFeatureClass.AreaField.Name);

                   if (!(bCondition1 || bCondition2 || bCondition3))
                   // Don't do shape fields
                   {
                       int myTargetFieldId = toFeatureClass.FindField(fieldName);
                       // Id of field in source feature
                       featureBufferInsert.set_Value(myTargetFieldId, copiedFeature.get_Value(i)); // Copy value

                   }
               }

               id = featureCursorInsert.InsertFeature(featureBufferInsert);
               featureCursorInsert.Flush();
               //_workspaceEdit.StopEditOperation();
               //_workspaceEdit.StopEditing(true);
               }
               catch (Exception ex)
               {
               //_workspaceEdit.AbortEditOperation();
               //_workspaceEdit.StopEditing(false);
               }
               return id;
        }
Exemple #40
0
        public static bool AddFeature(Dictionary<string, string> FieldValDict, Dictionary<string, int> FieldIndexDict, IFeatureClass FeatureClass, IGeometry geometry)
        {
            IField tempField = null;
            int Index = 0;
            int val1 = 0;
            double val2 = 0.0;
            string temp = string.Empty;
            if (FeatureClass != null)
            {
                IFeatureBuffer featureBuffer = FeatureClass.CreateFeatureBuffer();
                featureBuffer.Shape = geometry;
                IFeatureCursor featureCursor = FeatureClass.Insert(true);
                foreach (var field in FieldValDict.Keys)
                {
                    if (FieldIndexDict.ContainsKey(field))
                    {
                        Index = FieldIndexDict[field];
                        tempField = FeatureClass.Fields.get_Field(Index);
                        temp = FieldValDict[field];
                        switch (tempField.Type)
                        {
                            case esriFieldType.esriFieldTypeString:
                                featureBuffer.set_Value(Index, temp);
                                break;
                            case esriFieldType.esriFieldTypeDouble:
                                if (double.TryParse(temp, out val2))
                                {
                                    featureBuffer.set_Value(Index, val2);
                                }

                                break;
                            case esriFieldType.esriFieldTypeInteger:
                                if (int.TryParse(temp, out val1))
                                {
                                    featureBuffer.set_Value(Index, val1);
                                }

                                break;
                            default:
                                try
                                {
                                    featureBuffer.set_Value(Index, temp);
                                }
                                catch
                                {

                                }
                                break;
                        }
                    }
                }
                try
                {
                    object featureOID = featureCursor.InsertFeature(featureBuffer);
                    featureCursor.Flush();
                }
                catch
                {
                    return false;
                }
                System.Runtime.InteropServices.Marshal.ReleaseComObject(featureCursor);
                return true;
            }
            return false;
        }
    public void InsertFeaturesUsingCursor(IFeatureClass ipTargetFC, IFeatureCursor featuresToCopy, string sShakeMapID)
    {
      IFeatureCursor ipInsCursor = null;
      try
      {
        IFeatureBuffer ipFBuff = ipTargetFC.CreateFeatureBuffer();
        ipInsCursor = ipTargetFC.Insert(true);
        IFeature ipFeat;
        IFields ipTargetFields;
        IField ipTargetField;
        int featureOID;

        while ((ipFeat = featuresToCopy.NextFeature()) != null)
        {
          ipFBuff.Shape = ipFeat.ShapeCopy;

          ipTargetFields = ipTargetFC.Fields as IFields;
          for (int i = 0; i < ipTargetFields.FieldCount; i++)
          {
            ipTargetField = ipTargetFields.get_Field(i);

            //skip field that is not editable or is an OID field (OID field automatically being filled)
            if ((!ipTargetField.Editable) || (ipTargetField.Type == esriFieldType.esriFieldTypeOID)
                || ipTargetField.Type == ESRI.ArcGIS.Geodatabase.esriFieldType.esriFieldTypeGeometry)
            {
              continue;
            }

            //not geometry column, not subtype, and not OID or other read-only type
            string sFieldName = ipTargetField.Name;
            int iIndex = ipFeat.Fields.FindField(sFieldName);

            object oValue = null;

            //if the field exists in the srcFeatureCls and the types match, copy the value over
            if ((iIndex != -1) && (ipFeat.Fields.get_Field(iIndex).Type == ipTargetField.Type))
            {
              oValue = ipFeat.get_Value(iIndex);

              if (ipTargetField.CheckValue(oValue) == false)
              {
                // Source feature's value for this field is invalid for destination field
                oValue = ipTargetField.DefaultValue;
              }
            }
            //if the field doesn't exist, set default value for the field
            else
            {
              // Check if sShakeMapID field to populate it.
              if (sFieldName == "ShakeMapID")
              {
                oValue = sShakeMapID;
              }
              else
              {
                oValue = ipTargetField.DefaultValue;
              }
            }

            // assign the value, unless it's null and the field is not nullable
            if (((oValue != null) && (oValue.ToString() != "")) || ipTargetField.IsNullable)
            {
              ipFBuff.set_Value(i, oValue);
            }
          }

          featureOID = (int)ipInsCursor.InsertFeature(ipFBuff);

        }

        ipInsCursor.Flush();
        
      }
      catch (Exception ex)
      {
        throw ex;
      }
      finally
      {
        if (ipInsCursor != null)
        {
          System.Runtime.InteropServices.Marshal.ReleaseComObject(ipInsCursor);
          ipInsCursor = null;
        }
      }
    }
        internal void loadOSMNodes(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message,IGPValue targetGPValue,  IFeatureClass osmPointFeatureClass, bool conserveMemory, bool fastLoad, int nodeCapacity, ref Dictionary<string, simplePointRef> osmNodeDictionary, IFeatureWorkspace featureWorkspace, ISpatialReference downloadSpatialReference, OSMDomains availableDomains, bool checkForExisting)
        {
            XmlReader osmFileXmlReader = null;
            XmlSerializer nodeSerializer = null;

            try
            {
                osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation);
                nodeSerializer = new XmlSerializer(typeof(node));

                ISpatialReferenceFactory spatialRef = new SpatialReferenceEnvironmentClass();
                ISpatialReference wgs84 = spatialRef.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

                bool shouldProject = !((IClone)wgs84).IsEqual((IClone)downloadSpatialReference);

                int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmPointDomainAttributeFieldLength = new Dictionary<string, int>();

                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPointFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmPointDomainAttributeFieldLength.Add(domains.name, osmPointFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }

                int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags");
                int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser");
                int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid");
                int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible");
                int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion");
                int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset");
                int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf");
                int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement");
                int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");

                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

                if (stepProgressor != null)
                {
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = nodeCapacity;
                    stepProgressor.StepValue = (1);
                    stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingNodes");
                    stepProgressor.Position = 0;
                    stepProgressor.Show();
                }

                // flag to determine if a computation of indices is required
                bool indexBuildRequired = false;
                if (nodeCapacity > 0)
                    indexBuildRequired = true;

                int pointCount = 0;

                // let's insert all the points first
                if (osmPointFeatureClass != null)
                {
                    IFeatureBuffer pointFeature = null;
                    IFeatureClassLoad pointFeatureLoad = null;

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        using (SchemaLockManager schemaLockManager = new SchemaLockManager(osmPointFeatureClass as ITable))
                        {

                            if (((IWorkspace)featureWorkspace).WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                            {
                                pointFeatureLoad = osmPointFeatureClass as IFeatureClassLoad;
                            }

                            IFeatureCursor pointInsertCursor = osmPointFeatureClass.Insert(true);
                            comReleaser.ManageLifetime(pointInsertCursor);

                            pointFeature = osmPointFeatureClass.CreateFeatureBuffer();
                            comReleaser.ManageLifetime(pointFeature);

                            if (pointFeatureLoad != null)
                            {
                                pointFeatureLoad.LoadOnlyMode = true;
                            }

                            osmFileXmlReader.MoveToContent();

                            while (osmFileXmlReader.Read())
                            {
                                if (osmFileXmlReader.IsStartElement())
                                {
                                    if (osmFileXmlReader.Name == "node")
                                    {
                                        string currentNodeString = osmFileXmlReader.ReadOuterXml();
                                        // turn the xml node representation into a node class representation
                                        ESRI.ArcGIS.OSM.OSMClassExtension.node currentNode = null;
                                        using (StringReader nodeReader = new System.IO.StringReader(currentNodeString))
                                        {
                                            currentNode = nodeSerializer.Deserialize(nodeReader) as ESRI.ArcGIS.OSM.OSMClassExtension.node;
                                        }

                                        // check if a feature with the same OSMID already exists, because the can only be one
                                        if (checkForExisting == true)
                                        {
                                            if (CheckIfExists(osmPointFeatureClass as ITable, currentNode.id))
                                            {
                                                continue;
                                            }
                                        }

                                        try
                                        {
                                            //if (pointFeature == null)
                                            //{
                                            pointFeature = osmPointFeatureClass.CreateFeatureBuffer();
                                            comReleaser.ManageLifetime(pointFeature);
                                            //}

                                            IPoint pointGeometry = new PointClass();
                                            comReleaser.ManageLifetime(pointGeometry);

                                            pointGeometry.X = Convert.ToDouble(currentNode.lon, new CultureInfo("en-US"));
                                            pointGeometry.Y = Convert.ToDouble(currentNode.lat, new CultureInfo("en-US"));
                                            pointGeometry.SpatialReference = wgs84;

                                            if (shouldProject)
                                            {
                                                pointGeometry.Project(downloadSpatialReference);
                                            }

                                            pointFeature.Shape = pointGeometry;

                                            pointFeature.set_Value(osmPointIDFieldIndex, currentNode.id);

                                            string isSupportingNode = "";
                                            if (_osmUtility.DoesHaveKeys(currentNode))
                                            {
                                                // if case it has tags I assume that the node presents an entity of it own,
                                                // hence it is not a supporting node in the context of supporting a way or relation
                                                isSupportingNode = "no";

                                                if (conserveMemory == false)
                                                {
                                                    osmNodeDictionary[currentNode.id] = new simplePointRef(Convert.ToSingle(currentNode.lon, new CultureInfo("en-US")), Convert.ToSingle(currentNode.lat, new CultureInfo("en-US")), 0, 0);
                                                }
                                            }
                                            else
                                            {
                                                // node has no tags -- at this point I assume that the absence of tags indicates that it is a supporting node
                                                // for a way or a relation
                                                isSupportingNode = "yes";

                                                if (conserveMemory == false)
                                                {
                                                    osmNodeDictionary[currentNode.id] = new simplePointRef(Convert.ToSingle(currentNode.lon, new CultureInfo("en-US")), Convert.ToSingle(currentNode.lat, new CultureInfo("en-US")), 0, 0);
                                                }
                                            }

                                            insertTags(osmPointDomainAttributeFieldIndices, osmPointDomainAttributeFieldLength, tagCollectionPointFieldIndex, pointFeature, currentNode.tag);

                                            if (fastLoad == false)
                                            {
                                                if (osmSupportingElementPointFieldIndex > -1)
                                                {
                                                    pointFeature.set_Value(osmSupportingElementPointFieldIndex, isSupportingNode);
                                                }

                                                if (osmWayRefCountFieldIndex > -1)
                                                {
                                                    pointFeature.set_Value(osmWayRefCountFieldIndex, 0);
                                                }

                                                // store the administrative attributes
                                                // user, uid, version, changeset, timestamp, visible
                                                if (osmUserPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.user))
                                                    {
                                                        pointFeature.set_Value(osmUserPointFieldIndex, currentNode.user);
                                                    }
                                                }

                                                if (osmUIDPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.uid))
                                                    {
                                                        pointFeature.set_Value(osmUIDPointFieldIndex, Convert.ToInt32(currentNode.uid));
                                                    }
                                                }

                                                if (osmVisiblePointFieldIndex > -1)
                                                {
                                                    pointFeature.set_Value(osmVisiblePointFieldIndex, currentNode.visible.ToString());
                                                }

                                                if (osmVersionPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.version))
                                                    {
                                                        pointFeature.set_Value(osmVersionPointFieldIndex, Convert.ToInt32(currentNode.version));
                                                    }
                                                }

                                                if (osmChangesetPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.changeset))
                                                    {
                                                        pointFeature.set_Value(osmChangesetPointFieldIndex, Convert.ToInt32(currentNode.changeset));
                                                    }
                                                }

                                                if (osmTimeStampPointFieldIndex > -1)
                                                {
                                                    if (!String.IsNullOrEmpty(currentNode.timestamp))
                                                    {
                                                        try
                                                        {
                                                            pointFeature.set_Value(osmTimeStampPointFieldIndex, Convert.ToDateTime(currentNode.timestamp));
                                                        }
                                                        catch (Exception ex)
                                                        {
                                                            message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message));
                                                        }
                                                    }
                                                }
                                            }
                                            try
                                            {
                                                pointInsertCursor.InsertFeature(pointFeature);
                                                pointCount = pointCount + 1;

                                                if (stepProgressor != null)
                                                {
                                                    stepProgressor.Position = pointCount;
                                                }
                                            }
                                            catch (Exception ex)
                                            {
                                                System.Diagnostics.Debug.WriteLine(ex.Message);
                                                message.AddWarning(ex.Message);
                                            }

                                            if (TrackCancel.Continue() == false)
                                            {
                                                return;
                                            }

                                            if ((pointCount % 50000) == 0)
                                            {
                                                message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_pointsloaded"), pointCount));
                                                pointInsertCursor.Flush();
                                                System.GC.Collect();
                                            }

                                            if (pointGeometry != null)
                                                Marshal.ReleaseComObject(pointGeometry);
                                        }
                                        catch (Exception ex)
                                        {
                                            System.Diagnostics.Debug.WriteLine(ex.Message);
                                            message.AddWarning(ex.Message);
                                        }
                                        finally
                                        {
                                            if (pointFeature != null)
                                            {
                                                Marshal.ReleaseComObject(pointFeature);

                                                if (pointFeature != null)
                                                    pointFeature = null;

                                            }
                                        }

                                        currentNode = null;
                                    }
                                }
                            }

                            if (stepProgressor != null)
                            {
                                stepProgressor.Hide();
                            }

                            pointInsertCursor.Flush();
                            osmFileXmlReader.Close();

                            message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_pointsloaded"), pointCount));
                            message.AddMessage(_resourceManager.GetString("GPTools_buildingpointidx"));

                            if (pointFeatureLoad != null)
                            {
                                pointFeatureLoad.LoadOnlyMode = false;
                            }
                        }
                    }

                    if (TrackCancel.Continue() == false)
                    {
                        return;
                    }

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        IFeatureCursor updatePoints = osmPointFeatureClass.Update(null, false);
                        comReleaser.ManageLifetime(updatePoints);

                        IFeature feature2Update = updatePoints.NextFeature();

                        while (feature2Update != null)
                        {
                            IPoint pointGeometry = feature2Update.Shape as IPoint;
                            pointGeometry.ID = feature2Update.OID;
                            feature2Update.Shape = pointGeometry;

                            if (conserveMemory == false)
                            {
                                string osmid = Convert.ToString(feature2Update.get_Value(osmPointIDFieldIndex));
                                if (osmNodeDictionary.ContainsKey(osmid))
                                    osmNodeDictionary[osmid].pointObjectID = feature2Update.OID;
                            }

                            updatePoints.UpdateFeature(feature2Update);

                            if (TrackCancel.Continue() == false)
                            {
                                return;
                            }

                            if (feature2Update != null)
                                Marshal.ReleaseComObject(feature2Update);

                            if (pointGeometry != null)
                                Marshal.ReleaseComObject(pointGeometry);

                            feature2Update = updatePoints.NextFeature();
                        }
                    }

                    if (indexBuildRequired)
                    {

                        IGeoProcessor2 geoProcessor = new GeoProcessorClass();
                        bool storedOriginal = geoProcessor.AddOutputsToMap;

                        try
                        {
                            IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                            IGPValue pointFeatureClass = gpUtilities3.MakeGPValueFromObject(osmPointFeatureClass);

                            string fcLocation = GetLocationString(targetGPValue, osmPointFeatureClass);

                            IIndexes featureClassIndexes = osmPointFeatureClass.Indexes;
                            int indexPosition = -1;
                            featureClassIndexes.FindIndex("osmID_IDX", out indexPosition);

                            if (indexPosition == -1)
                            {
                                {
                                    geoProcessor.AddOutputsToMap = false;

                                    IVariantArray parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                                    IGeoProcessorResult2 gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                                }
                            }
                            if (pointCount > 500)
                            {
                                if (pointFeatureLoad == null)
                                {
                                    UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation);
                                }
                            }
                        }
                        catch (COMException comEx)
                        {
                            message.AddWarning(comEx.Message);
                        }
                        catch (Exception ex)
                        {
                            message.AddWarning(ex.Message);
                        }
                        finally
                        {
                            geoProcessor.AddOutputsToMap = storedOriginal;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                message.AddError(120100, String.Format(_resourceManager.GetString("GPTools_Utility_NodeLoadError"), ex.Message));
            }
            finally
            {
                if (osmFileXmlReader != null)
                    osmFileXmlReader = null;

                if (nodeSerializer != null)
                    nodeSerializer = null;
            }
        }
        internal List<string> loadOSMRelations(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message, IGPValue targetGPValue, IFeatureClass osmPointFeatureClass, IFeatureClass osmLineFeatureClass, IFeatureClass osmPolygonFeatureClass, int relationCapacity, ITable relationTable, OSMDomains availableDomains, bool fastLoad, bool checkForExisting)
        {
            List<string> missingRelations = null;
            XmlReader osmFileXmlReader = null;
            XmlSerializer relationSerializer = null;

            try
            {

                missingRelations = new List<string>();

                if (osmLineFeatureClass == null)
                {
                    throw new ArgumentNullException("osmLineFeatureClass");
                }

                if (osmPolygonFeatureClass == null)
                {
                    throw new ArgumentNullException("osmPolygonFeatureClass");
                }

                if (relationTable == null)
                {
                    throw new ArgumentNullException("relationTable");
                }

                int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPointFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                    }
                }
                int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags");
                int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser");
                int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid");
                int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible");
                int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion");
                int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset");
                int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf");
                int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement");
                int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");

                int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmLineDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmLineFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmLineDomainAttributeFieldLength.Add(domains.name, osmLineFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags");
                int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser");
                int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid");
                int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible");
                int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion");
                int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf");
                int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement");

                int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmPolygonDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmPolygonDomainAttributeFieldLength.Add(domains.name, osmPolygonFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags");
                int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser");
                int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid");
                int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible");
                int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion");
                int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf");
                int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement");

                int osmRelationIDFieldIndex = relationTable.FindField("OSMID");
                int tagCollectionRelationFieldIndex = relationTable.FindField("osmTags");
                int osmUserRelationFieldIndex = relationTable.FindField("osmuser");
                int osmUIDRelationFieldIndex = relationTable.FindField("osmuid");
                int osmVisibleRelationFieldIndex = relationTable.FindField("osmvisible");
                int osmVersionRelationFieldIndex = relationTable.FindField("osmversion");
                int osmChangesetRelationFieldIndex = relationTable.FindField("osmchangeset");
                int osmTimeStampRelationFieldIndex = relationTable.FindField("osmtimestamp");
                int osmMemberOfRelationFieldIndex = relationTable.FindField("osmMemberOf");
                int osmMembersRelationFieldIndex = relationTable.FindField("osmMembers");
                int osmSupportingElementRelationFieldIndex = relationTable.FindField("osmSupportingElement");

                // list for reference count and relation list for lines/polygons/relations
                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

                if (stepProgressor != null)
                {
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = relationCapacity;
                    stepProgressor.Position = 0;
                    stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingRelations");
                    stepProgressor.StepValue = 1;
                    stepProgressor.Show();
                }

                bool relationIndexRebuildRequired = false;

                if (relationTable != null)
                {
                    osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation);
                    relationSerializer = new XmlSerializer(typeof(relation));

                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        using (SchemaLockManager linelock = new SchemaLockManager(osmLineFeatureClass as ITable), polygonLock = new SchemaLockManager(osmPolygonFeatureClass as ITable), relationLock = new SchemaLockManager(relationTable))
                        {
                            ICursor rowCursor = relationTable.Insert(true);
                            comReleaser.ManageLifetime(rowCursor);

                            IRowBuffer rowBuffer = relationTable.CreateRowBuffer();
                            comReleaser.ManageLifetime(rowBuffer);

                            IFeatureCursor lineFeatureInsertCursor = osmLineFeatureClass.Insert(true);
                            comReleaser.ManageLifetime(lineFeatureInsertCursor);

                            IFeatureBuffer lineFeatureBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                            comReleaser.ManageLifetime(lineFeatureBuffer);

                            IFeatureCursor polygonFeatureInsertCursor = osmPolygonFeatureClass.Insert(true);
                            comReleaser.ManageLifetime(polygonFeatureInsertCursor);

                            IFeatureBuffer polygonFeatureBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();
                            comReleaser.ManageLifetime(polygonFeatureBuffer);

                            int relationCount = 1;
                            int relationDebugCount = 1;

                            string lineSQLIdentifier = osmLineFeatureClass.SqlIdentifier("OSMID");
                            string polygonSQLIdentifier = osmPolygonFeatureClass.SqlIdentifier("OSMID");

                            message.AddMessage(_resourceManager.GetString("GPTools_OSMGPFileReader_resolvegeometries"));

                            osmFileXmlReader.MoveToContent();
                            while (osmFileXmlReader.Read())
                            {
                                if (osmFileXmlReader.IsStartElement())
                                {
                                    if (osmFileXmlReader.Name == "relation")
                                    {
                                        relation currentRelation = null;
                                        try
                                        {
                                            // read the full relation node
                                            string currentrelationString = osmFileXmlReader.ReadOuterXml();

                                            using (StringReader relationReader = new System.IO.StringReader(currentrelationString))
                                            {
                                                // de-serialize the xml into to the class instance
                                                currentRelation = relationSerializer.Deserialize(relationReader) as relation;
                                            }

                                            if (currentRelation == null)
                                                continue;

                                            relationDebugCount = relationDebugCount + 1;
                                            esriGeometryType detectedGeometryType = determineRelationGeometryType(osmLineFeatureClass, osmPolygonFeatureClass, relationTable, currentRelation);

                                            if (checkForExisting)
                                            {
                                                switch (detectedGeometryType)
                                                {
                                                    case esriGeometryType.esriGeometryAny:
                                                        if (CheckIfExists(relationTable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryBag:
                                                        if (CheckIfExists(relationTable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryBezier3Curve:
                                                        break;
                                                    case esriGeometryType.esriGeometryCircularArc:
                                                        break;
                                                    case esriGeometryType.esriGeometryEllipticArc:
                                                        break;
                                                    case esriGeometryType.esriGeometryEnvelope:
                                                        break;
                                                    case esriGeometryType.esriGeometryLine:
                                                        if (CheckIfExists(osmLineFeatureClass as ITable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryMultiPatch:
                                                        break;
                                                    case esriGeometryType.esriGeometryMultipoint:
                                                        break;
                                                    case esriGeometryType.esriGeometryNull:
                                                        if (CheckIfExists(relationTable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryPath:
                                                        break;
                                                    case esriGeometryType.esriGeometryPoint:
                                                        break;
                                                    case esriGeometryType.esriGeometryPolygon:
                                                        if (CheckIfExists(osmPolygonFeatureClass as ITable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryPolyline:
                                                        if (CheckIfExists(osmLineFeatureClass as ITable, currentRelation.id))
                                                            continue;
                                                        break;
                                                    case esriGeometryType.esriGeometryRay:
                                                        break;
                                                    case esriGeometryType.esriGeometryRing:
                                                        break;
                                                    case esriGeometryType.esriGeometrySphere:
                                                        break;
                                                    case esriGeometryType.esriGeometryTriangleFan:
                                                        break;
                                                    case esriGeometryType.esriGeometryTriangleStrip:
                                                        break;
                                                    case esriGeometryType.esriGeometryTriangles:
                                                        break;
                                                    default:
                                                        break;
                                                }
                                            }

                                            List<tag> relationTagList = new List<tag>();
                                            List<member> relationMemberList = new List<member>();
                                            Dictionary<string, string> wayList = new Dictionary<string, string>();

                                            // sanity check that the overall relation notation contains at least something
                                            if (currentRelation.Items == null)
                                                continue;

                                            List<OSMNodeFeature> osmPointList = null;
                                            List<OSMLineFeature> osmLineList = null;
                                            List<OSMPolygonFeature> osmPolygonList = null;
                                            List<OSMRelation> osmRelationList = null;

                                            rowBuffer = relationTable.CreateRowBuffer();
                                            comReleaser.ManageLifetime(rowBuffer);

                                            lineFeatureBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                                            comReleaser.ManageLifetime(lineFeatureBuffer);

                                            polygonFeatureBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();
                                            comReleaser.ManageLifetime(polygonFeatureBuffer);

                                            foreach (var item in currentRelation.Items)
                                            {
                                                if (item is member)
                                                {
                                                    member memberItem = item as member;
                                                    relationMemberList.Add(memberItem);

                                                    switch (memberItem.type)
                                                    {
                                                        case memberType.way:

                                                            if (!wayList.ContainsKey(memberItem.@ref))
                                                                wayList.Add(memberItem.@ref, memberItem.role);

                                                            if (IsThisWayALine(memberItem.@ref, osmLineFeatureClass, lineSQLIdentifier, osmPolygonFeatureClass, polygonSQLIdentifier))
                                                            {
                                                                if (osmLineList == null)
                                                                {
                                                                    osmLineList = new List<OSMLineFeature>();
                                                                }

                                                                OSMLineFeature lineFeature = new OSMLineFeature();
                                                                lineFeature.relationList = new List<string>();
                                                                lineFeature.lineID = memberItem.@ref;

                                                                if (detectedGeometryType == esriGeometryType.esriGeometryPolygon)
                                                                {
                                                                    lineFeature.relationList.Add(currentRelation.id + "_ply");
                                                                }
                                                                else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline)
                                                                {
                                                                    lineFeature.relationList.Add(currentRelation.id + "_ln");
                                                                }
                                                                else
                                                                {
                                                                    lineFeature.relationList.Add(currentRelation.id + "_rel");
                                                                }

                                                                osmLineList.Add(lineFeature);
                                                            }
                                                            else
                                                            {
                                                                if (osmPolygonList == null)
                                                                {
                                                                    osmPolygonList = new List<OSMPolygonFeature>();
                                                                }

                                                                OSMPolygonFeature polygonFeature = new OSMPolygonFeature();
                                                                polygonFeature.relationList = new List<string>();
                                                                polygonFeature.polygonID = memberItem.@ref;

                                                                if (detectedGeometryType == esriGeometryType.esriGeometryPolygon)
                                                                {
                                                                    polygonFeature.relationList.Add(currentRelation.id + "_ply");
                                                                }
                                                                else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline)
                                                                {
                                                                    polygonFeature.relationList.Add(currentRelation.id + "_ln");
                                                                }
                                                                else
                                                                {
                                                                    polygonFeature.relationList.Add(currentRelation.id + "_rel");
                                                                }

                                                                osmPolygonList.Add(polygonFeature);
                                                            }

                                                            break;
                                                        case memberType.node:

                                                            if (osmPointList == null)
                                                            {
                                                                osmPointList = new List<OSMNodeFeature>();
                                                            }

                                                            OSMNodeFeature nodeFeature = new OSMNodeFeature();
                                                            nodeFeature.relationList = new List<string>();
                                                            nodeFeature.nodeID = memberItem.@ref;

                                                            nodeFeature.relationList.Add(currentRelation.id + "_rel");

                                                            osmPointList.Add(nodeFeature);

                                                            break;
                                                        case memberType.relation:

                                                            if (osmRelationList == null)
                                                            {
                                                                osmRelationList = new List<OSMRelation>();
                                                            }

                                                            OSMRelation relation = new OSMRelation();
                                                            relation.relationList = new List<string>();
                                                            relation.relationID = memberItem.@ref;
                                                            relation.relationList.Add(currentRelation.id + "_rel");

                                                            break;
                                                        default:
                                                            break;
                                                    }

                                                }
                                                else if (item is tag)
                                                {
                                                    relationTagList.Add((tag)item);
                                                }
                                            }

                                            // if there is a defined geometry type use it to generate a multipart geometry
                                            if (detectedGeometryType == esriGeometryType.esriGeometryPolygon)
                                            {
                                                #region create multipart polygon geometry
                                                //IFeature mpFeature = osmPolygonFeatureClass.CreateFeature();

                                                IPolygon relationMPPolygon = new PolygonClass();
                                                relationMPPolygon.SpatialReference = ((IGeoDataset)osmPolygonFeatureClass).SpatialReference;

                                                ISegmentCollection relationPolygonGeometryCollection = relationMPPolygon as ISegmentCollection;

                                                IQueryFilter osmIDQueryFilter = new QueryFilterClass();
                                                string sqlPolyOSMID = osmPolygonFeatureClass.SqlIdentifier("OSMID");
                                                object missing = Type.Missing;
                                                bool relationComplete = true;

                                                // loop through the list of referenced ways that are listed in a relation
                                                // for each of the items we need to make a decision if they have merit to qualify as stand-alone features
                                                // due to the presence of meaningful attributes (tags)
                                                foreach (KeyValuePair<string, string> wayKey in wayList)
                                                {
                                                    if (relationComplete == false)
                                                        break;

                                                    if (TrackCancel.Continue() == false)
                                                    {
                                                        return missingRelations;
                                                    }

                                                    osmIDQueryFilter.WhereClause = sqlPolyOSMID + " = '" + wayKey.Key + "'";

                                                    System.Diagnostics.Debug.WriteLine("Relation (Polygon) #: " + relationDebugCount + " :___: " + currentRelation.id + " :___: " + wayKey.Key);

                                                    using (ComReleaser relationComReleaser = new ComReleaser())
                                                    {
                                                        IFeatureCursor featureCursor = osmPolygonFeatureClass.Search(osmIDQueryFilter, false);
                                                        relationComReleaser.ManageLifetime(featureCursor);

                                                        IFeature partFeature = featureCursor.NextFeature();

                                                        // set the appropriate field attribute to become invisible as a standalone features
                                                        if (partFeature != null)
                                                        {
                                                            IGeometryCollection ringCollection = partFeature.Shape as IGeometryCollection;

                                                            // test for available content in the geometry collection
                                                            if (ringCollection.GeometryCount > 0)
                                                            {
                                                                // test if we dealing with a valid geometry
                                                                if (ringCollection.get_Geometry(0).IsEmpty == false)
                                                                {
                                                                    // add it to the new geometry and mark the added geometry as a supporting element
                                                                    relationPolygonGeometryCollection.AddSegmentCollection((ISegmentCollection)ringCollection.get_Geometry(0));

                                                                    if (osmSupportingElementPolygonFieldIndex > -1)
                                                                    {
                                                                        // if the member of a relation has the role of "inner" and it has tags, then let's keep it
                                                                        // as a standalone feature as well
                                                                        // the geometry is then a hole in the relation but due to the tags it also has merits to be
                                                                        // considered a stand-alone feature
                                                                        if (wayKey.Value.ToLower().Equals("inner"))
                                                                        {
                                                                            if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolygonFieldIndex, null))
                                                                            {
                                                                                partFeature.set_Value(osmSupportingElementPolygonFieldIndex, "yes");
                                                                            }
                                                                        }
                                                                        else
                                                                        {
                                                                            // relation member without an explicit role or the role of "outer" are turned into
                                                                            // supporting features if they don't have relevant attribute
                                                                            if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                            {
                                                                                partFeature.set_Value(osmSupportingElementPolygonFieldIndex, "yes");
                                                                            }
                                                                        }
                                                                    }

                                                                    partFeature.Store();
                                                                }
                                                            }
                                                        }
                                                        else
                                                        {
                                                            // it still can be a line geometry that will be pieced together into a polygon
                                                            IFeatureCursor lineFeatureCursor = osmLineFeatureClass.Search(osmIDQueryFilter, false);
                                                            relationComReleaser.ManageLifetime(lineFeatureCursor);

                                                            partFeature = lineFeatureCursor.NextFeature();

                                                            if (partFeature != null)
                                                            {
                                                                IGeometryCollection ringCollection = partFeature.Shape as IGeometryCollection;

                                                                // test for available content in the geometry collection
                                                                if (ringCollection.GeometryCount > 0)
                                                                {
                                                                    // test if we dealing with a valid geometry
                                                                    if (ringCollection.get_Geometry(0).IsEmpty == false)
                                                                    {
                                                                        // add it to the new geometry and mark the added geometry as a supporting element
                                                                        relationPolygonGeometryCollection.AddSegmentCollection((ISegmentCollection)ringCollection.get_Geometry(0));

                                                                        if (osmSupportingElementPolylineFieldIndex > -1)
                                                                        {
                                                                            // if the member of a relation has the role of "inner" and it has tags, then let's keep it
                                                                            // as a standalone feature as well
                                                                            // the geometry is then a hole in the relation but due to the tags it also has merits to be
                                                                            // considered a stand-alone feature
                                                                            if (wayKey.Value.ToLower().Equals("inner"))
                                                                            {
                                                                                if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                                {
                                                                                    partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                                                }
                                                                            }
                                                                            else
                                                                            {
                                                                                // relation member without an explicit role or the role of "outer" are turned into
                                                                                // supporting features if they don't have relevant attribute
                                                                                if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                                {
                                                                                    partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                                                }
                                                                            }
                                                                        }

                                                                        partFeature.Store();
                                                                    }
                                                                }
                                                            }
                                                            else
                                                            {
                                                                relationComplete = false;
                                                                continue;
                                                            }
                                                        }
                                                    }
                                                }

                                                // mark the relation as incomplete
                                                if (relationComplete == false)
                                                {
                                                    missingRelations.Add(currentRelation.id);
                                                    continue;
                                                }

                                                // transform the added collections for geometries into a topological correct geometry representation
                                                ((IPolygon4)relationMPPolygon).SimplifyEx(true, false, true);

                                                polygonFeatureBuffer.Shape = relationMPPolygon;

                                                if (_osmUtility.DoesHaveKeys(currentRelation))
                                                {
                                                }
                                                else
                                                {
                                                    relationTagList = MergeTagsFromOuterPolygonToRelation(currentRelation, osmPolygonFeatureClass);
                                                }

                                                insertTags(osmPolygonDomainAttributeFieldIndices, osmPolygonDomainAttributeFieldLength, tagCollectionPolygonFieldIndex, polygonFeatureBuffer, relationTagList.ToArray());

                                                if (fastLoad == false)
                                                {
                                                    if (osmMembersPolygonFieldIndex > -1)
                                                    {
                                                        _osmUtility.insertMembers(osmMembersPolygonFieldIndex, (IFeature)polygonFeatureBuffer, relationMemberList.ToArray());
                                                    }

                                                    // store the administrative attributes
                                                    // user, uid, version, changeset, timestamp, visible
                                                    if (osmUserPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.user))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmUserPolygonFieldIndex, currentRelation.user);
                                                        }
                                                    }

                                                    if (osmUIDPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.uid))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmUIDPolygonFieldIndex, Convert.ToInt32(currentRelation.uid));
                                                        }
                                                    }

                                                    if (osmVisiblePolygonFieldIndex != -1)
                                                    {
                                                        if (String.IsNullOrEmpty(currentRelation.visible) == false)
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmVisiblePolygonFieldIndex, currentRelation.visible.ToString());
                                                        }
                                                        else
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmVisiblePolygonFieldIndex, "unknown");
                                                        }
                                                    }

                                                    if (osmVersionPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.version))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmVersionPolygonFieldIndex, Convert.ToInt32(currentRelation.version));
                                                        }
                                                    }

                                                    if (osmChangesetPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.changeset))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmChangesetPolygonFieldIndex, Convert.ToInt32(currentRelation.changeset));
                                                        }
                                                    }

                                                    if (osmTimeStampPolygonFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.timestamp))
                                                        {
                                                            polygonFeatureBuffer.set_Value(osmTimeStampPolygonFieldIndex, Convert.ToDateTime(currentRelation.timestamp));
                                                        }
                                                    }

                                                    if (osmPolygonIDFieldIndex != -1)
                                                    {
                                                        polygonFeatureBuffer.set_Value(osmPolygonIDFieldIndex, currentRelation.id);
                                                    }

                                                    if (osmSupportingElementPolygonFieldIndex > -1)
                                                    {
                                                        polygonFeatureBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "no");
                                                    }
                                                }

                                                try
                                                {
                                                    //mpFeature.Store();
                                                    polygonFeatureInsertCursor.InsertFeature(polygonFeatureBuffer);
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddWarning(ex.Message);
                                                }
                                                #endregion
                                            }
                                            else if (detectedGeometryType == esriGeometryType.esriGeometryPolyline)
                                            {
                                                #region create multipart polyline geometry
                                                //IFeature mpFeature = osmLineFeatureClass.CreateFeature();

                                                IPolyline relationMPPolyline = new PolylineClass();
                                                relationMPPolyline.SpatialReference = ((IGeoDataset)osmLineFeatureClass).SpatialReference;

                                                IGeometryCollection relationPolylineGeometryCollection = relationMPPolyline as IGeometryCollection;

                                                IQueryFilter osmIDQueryFilter = new QueryFilterClass();
                                                object missing = Type.Missing;

                                                // loop through the
                                                foreach (KeyValuePair<string, string> wayKey in wayList)
                                                {
                                                    if (TrackCancel.Continue() == false)
                                                    {
                                                        return missingRelations;
                                                    }

                                                    osmIDQueryFilter.WhereClause = osmLineFeatureClass.WhereClauseByExtensionVersion(wayKey.Key, "OSMID", 2);

                                                    System.Diagnostics.Debug.WriteLine("Relation (Polyline) #: " + relationDebugCount + " :___: " + currentRelation.id + " :___: " + wayKey);

                                                    using (ComReleaser relationComReleaser = new ComReleaser())
                                                    {
                                                        IFeatureCursor featureCursor = osmLineFeatureClass.Search(osmIDQueryFilter, false);
                                                        relationComReleaser.ManageLifetime(featureCursor);

                                                        IFeature partFeature = featureCursor.NextFeature();

                                                        // set the appropriate field attribute to become invisible as a standalone features
                                                        if (partFeature != null)
                                                        {
                                                            if (partFeature.Shape.IsEmpty == false)
                                                            {
                                                                IGeometryCollection pathCollection = partFeature.Shape as IGeometryCollection;
                                                                relationPolylineGeometryCollection.AddGeometry(pathCollection.get_Geometry(0), ref missing, ref missing);

                                                                if (osmSupportingElementPolylineFieldIndex > -1)
                                                                {
                                                                    if (!_osmUtility.DoesHaveKeys(partFeature, tagCollectionPolylineFieldIndex, null))
                                                                    {
                                                                        partFeature.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                                    }
                                                                }

                                                                partFeature.Store();
                                                            }
                                                        }
                                                    }
                                                }

                                                lineFeatureBuffer.Shape = relationMPPolyline;

                                                insertTags(osmLineDomainAttributeFieldIndices, osmLineDomainAttributeFieldLength, tagCollectionPolylineFieldIndex, lineFeatureBuffer, relationTagList.ToArray());

                                                if (fastLoad == false)
                                                {
                                                    if (osmMembersPolylineFieldIndex > -1)
                                                    {
                                                        _osmUtility.insertMembers(osmMembersPolylineFieldIndex, (IFeature)lineFeatureBuffer, relationMemberList.ToArray());
                                                    }

                                                    // store the administrative attributes
                                                    // user, uid, version, changeset, timestamp, visible
                                                    if (osmUserPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.user))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmUserPolylineFieldIndex, currentRelation.user);
                                                        }
                                                    }

                                                    if (osmUIDPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.uid))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmUIDPolylineFieldIndex, Convert.ToInt32(currentRelation.uid));
                                                        }
                                                    }

                                                    if (osmVisiblePolylineFieldIndex != -1)
                                                    {
                                                        if (String.IsNullOrEmpty(currentRelation.visible) == false)
                                                        {
                                                            lineFeatureBuffer.set_Value(osmVisiblePolylineFieldIndex, currentRelation.visible.ToString());
                                                        }
                                                        else
                                                        {
                                                            lineFeatureBuffer.set_Value(osmVisiblePolylineFieldIndex, "unknown");
                                                        }
                                                    }

                                                    if (osmVersionPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.version))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmVersionPolylineFieldIndex, Convert.ToInt32(currentRelation.version));
                                                        }
                                                    }

                                                    if (osmChangesetPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.changeset))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmChangesetPolylineFieldIndex, Convert.ToInt32(currentRelation.changeset));
                                                        }
                                                    }

                                                    if (osmTimeStampPolylineFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.timestamp))
                                                        {
                                                            lineFeatureBuffer.set_Value(osmTimeStampPolylineFieldIndex, Convert.ToDateTime(currentRelation.timestamp));
                                                        }
                                                    }

                                                    if (osmLineIDFieldIndex != -1)
                                                    {
                                                        lineFeatureBuffer.set_Value(osmLineIDFieldIndex, currentRelation.id);
                                                    }

                                                    if (osmSupportingElementPolylineFieldIndex > -1)
                                                    {
                                                        lineFeatureBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "no");
                                                    }
                                                }

                                                try
                                                {
                                                    lineFeatureInsertCursor.InsertFeature(lineFeatureBuffer);
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddWarning(ex.Message);
                                                }
                                                #endregion

                                            }
                                            else if (detectedGeometryType == esriGeometryType.esriGeometryPoint)
                                            {
                                                System.Diagnostics.Debug.WriteLine("Relation #: " + relationDebugCount + " :____: POINT!!!");

                                                if (TrackCancel.Continue() == false)
                                                {
                                                    return missingRelations;
                                                }
                                            }
                                            else
                                            // otherwise it is relation that needs to be dealt with separately
                                            {
                                                if (TrackCancel.Continue() == false)
                                                {
                                                    return missingRelations;
                                                }

                                                System.Diagnostics.Debug.WriteLine("Relation #: " + relationDebugCount + " :____: Kept as relation");

                                                if (tagCollectionRelationFieldIndex != -1)
                                                {
                                                    _osmUtility.insertOSMTags(tagCollectionRelationFieldIndex, rowBuffer, relationTagList.ToArray());
                                                }

                                                if (fastLoad == false)
                                                {
                                                    if (osmMembersRelationFieldIndex != -1)
                                                    {
                                                        _osmUtility.insertMembers(osmMembersRelationFieldIndex, rowBuffer, relationMemberList.ToArray());
                                                    }

                                                    // store the administrative attributes
                                                    // user, uid, version, changeset, timestamp, visible
                                                    if (osmUserRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.user))
                                                        {
                                                            rowBuffer.set_Value(osmUserRelationFieldIndex, currentRelation.user);
                                                        }
                                                    }

                                                    if (osmUIDRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.uid))
                                                        {
                                                            rowBuffer.set_Value(osmUIDRelationFieldIndex, Convert.ToInt64(currentRelation.uid));
                                                        }
                                                    }

                                                    if (osmVisibleRelationFieldIndex != -1)
                                                    {
                                                        if (currentRelation.visible != null)
                                                        {
                                                            rowBuffer.set_Value(osmVisibleRelationFieldIndex, currentRelation.visible.ToString());
                                                        }
                                                    }

                                                    if (osmVersionRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.version))
                                                        {
                                                            rowBuffer.set_Value(osmVersionRelationFieldIndex, Convert.ToInt32(currentRelation.version));
                                                        }
                                                    }

                                                    if (osmChangesetRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.changeset))
                                                        {
                                                            rowBuffer.set_Value(osmChangesetRelationFieldIndex, Convert.ToInt32(currentRelation.changeset));
                                                        }
                                                    }

                                                    if (osmTimeStampRelationFieldIndex != -1)
                                                    {
                                                        if (!String.IsNullOrEmpty(currentRelation.timestamp))
                                                        {
                                                            try
                                                            {
                                                                rowBuffer.set_Value(osmTimeStampRelationFieldIndex, Convert.ToDateTime(currentRelation.timestamp));
                                                            }
                                                            catch (Exception ex)
                                                            {
                                                                message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message));
                                                            }
                                                        }
                                                    }

                                                    if (osmRelationIDFieldIndex != -1)
                                                    {
                                                        rowBuffer.set_Value(osmRelationIDFieldIndex, currentRelation.id);
                                                    }
                                                }

                                                try
                                                {
                                                    rowCursor.InsertRow(rowBuffer);
                                                    relationCount = relationCount + 1;

                                                    relationIndexRebuildRequired = true;
                                                }
                                                catch (Exception ex)
                                                {
                                                    System.Diagnostics.Debug.WriteLine(ex.Message);
                                                }

                                                // check for user interruption
                                                if (TrackCancel.Continue() == false)
                                                {
                                                    return missingRelations;
                                                }
                                            }

                                            // update the isMemberOf fields of the attached features
                                            if (osmPointList != null)
                                            {
                                                foreach (OSMNodeFeature nodeFeature in osmPointList)
                                                {
                                                    updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, nodeFeature.nodeID, nodeFeature.relationList);
                                                }
                                            }

                                            if (osmLineList != null)
                                            {
                                                foreach (OSMLineFeature lineFeature in osmLineList)
                                                {
                                                    updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, lineFeature.lineID, lineFeature.relationList);
                                                }
                                            }

                                            if (osmPolygonList != null)
                                            {
                                                foreach (OSMPolygonFeature polygonFeature in osmPolygonList)
                                                {
                                                    updateIsMemberOf(osmLineFeatureClass, osmMemberOfPolylineFieldIndex, polygonFeature.polygonID, polygonFeature.relationList);
                                                }
                                            }

                                            if (stepProgressor != null)
                                            {
                                                stepProgressor.Position = relationCount;
                                            }

                                            if ((relationCount % 50000) == 0)
                                            {
                                                message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_relationsloaded"), relationCount));
                                            }
                                        }
                                        catch (Exception ex)
                                        {
                                            message.AddWarning(ex.Message);
                                        }
                                        finally
                                        {
                                            if (rowBuffer != null)
                                            {
                                                Marshal.ReleaseComObject(rowBuffer);

                                                if (rowBuffer != null)
                                                    rowBuffer = null;
                                            }
                                            if (lineFeatureBuffer != null)
                                            {
                                                Marshal.ReleaseComObject(lineFeatureBuffer);

                                                if (lineFeatureBuffer != null)
                                                    lineFeatureBuffer = null;
                                            }

                                            if (polygonFeatureBuffer != null)
                                            {
                                                Marshal.ReleaseComObject(polygonFeatureBuffer);

                                                if (polygonFeatureBuffer != null)
                                                    polygonFeatureBuffer = null;
                                            }

                                            currentRelation = null;
                                        }
                                    }
                                }
                            }

                            // close the OSM file
                            osmFileXmlReader.Close();

                            // flush any remaining entities from the cursor
                            rowCursor.Flush();
                            polygonFeatureInsertCursor.Flush();
                            lineFeatureInsertCursor.Flush();

                            // force a garbage collection
                            System.GC.Collect();

                            // let the user know that we are done dealing with the relations
                            message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_relationsloaded"), relationCount));
                        }
                    }

                    if (stepProgressor != null)
                    {
                        stepProgressor.Hide();
                    }

                    // Addd index for osmid column as well
                    IGeoProcessor2 geoProcessor = new GeoProcessorClass();
                    bool storedOriginalLocal = geoProcessor.AddOutputsToMap;
                    IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();

                    try
                    {
                        geoProcessor.AddOutputsToMap = false;

                        if (relationIndexRebuildRequired)
                        {
                            IIndexes tableIndexes = relationTable.Indexes;
                            int indexPosition = -1;
                            tableIndexes.FindIndex("osmID_IDX", out indexPosition);

                            if (indexPosition == -1)
                            {
                                IGPValue relationTableGPValue = gpUtilities3.MakeGPValueFromObject(relationTable);
                                string sddd = targetGPValue.GetAsText();
                                string tableLocation = GetLocationString(targetGPValue, relationTable);
                                IVariantArray parameterArrary = CreateAddIndexParameterArray(tableLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                                IGeoProcessorResult2 gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        message.AddWarning(ex.Message);
                    }
                    finally
                    {
                        geoProcessor.AddOutputsToMap = storedOriginalLocal;

                        Marshal.FinalReleaseComObject(gpUtilities3);
                        Marshal.FinalReleaseComObject(geoProcessor);
                    }
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
                if (relationSerializer != null)
                    relationSerializer = null;

                if (osmFileXmlReader != null)
                    osmFileXmlReader = null;

                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }

            return missingRelations;
        }
Exemple #44
0
        public static void InsertFeaturesUsingCursor(IFeatureClass featureClass, List<IGeometry> geometryList)
        {
            using (ComReleaser comReleaser = new ComReleaser())
            {
                IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                comReleaser.ManageLifetime(featureBuffer);

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

                int typeFieldIndex = featureClass.FindField("Name");
                int i = 1;
                foreach (IGeometry geometry in geometryList)
                {
                    featureBuffer.Shape = geometry;
                    featureBuffer.set_Value(typeFieldIndex, i++.ToString());
                    insertCursor.InsertFeature(featureBuffer);
                }
                insertCursor.Flush();
            }
        }
        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;
            }
        }
Exemple #46
0
        private bool InsertNomarlError(IFeatureClass destFClass)
        {
            try
            {
                string strSQL = @"
                            SELECT
                            b.CheckType,
                            a.TargetFeatClass1 as YSTC,
                            a.BSM as SourceBSM,
                            a.TargetFeatClass2 as MBTC,
                            a.BSM2 as BSM2,
                            '' as TopoLayerName,
                            a.ErrMsg as Description,
                            IIF(a.IsException,1,0) as IsException,
                            IIf(a.Remark is Null,'',a.Remark) as Remark,
                            b.GZBM,
                            a.OID as OID

                            from LR_ResAutoAttr 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<string, IFeatureClass> dictFeatureClass = new Dictionary<string, IFeatureClass>();
                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����");

                for (int i = 0; i < dtError.Rows.Count; i++)
                {
                    DataRow rowError = dtError.Rows[i];
                    IFeatureClass curFClass;
                    string strFClassAlias = rowError["YSTC"] as string;
                    if (!dictFeatureClass.ContainsKey(strFClassAlias))
                    {
                        int standardID = SysDbHelper.GetStandardIDBySchemaID(this.SchemaID);
                        string strFClass = LayerReader.GetNameByAliasName(strFClassAlias, standardID);
                        IFeatureClass fClass = (this.BaseWorkspace as IFeatureWorkspace).OpenFeatureClass(strFClass);
                        dictFeatureClass.Add(strFClassAlias, fClass);
                        curFClass = fClass;
                    }
                    else
                    {
                        curFClass = dictFeatureClass[strFClassAlias];
                    }

                    if (curFClass == null)
                        continue;

                    object objOID = rowError["OID"];
                    if (objOID == null)
                        continue;

                    int oid = Convert.ToInt32(objOID);
                    IFeature srcFeature = curFClass.GetFeature(oid);
                    if (srcFeature == null)
                        continue;

                    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;
            }
        }
Exemple #47
0
        public static List<int> SplitPolyline(IPolyline srcLine, List<IPoint> pts, Dictionary<string, string> values, IFeatureClass fc, IFeatureClass districtFC, bool dropHead, bool dropTail)
        {
            var lines = SplitPolylineInner(srcLine, pts);
            var cursor = fc.Insert(true);
            var idIndex = cursor.FindField(IDField);
            var count = 0;
            var ret = new List<int>();
            var id = GetNewId(fc);
            var dIndex = cursor.FindField("DISTRICT");
            var dIndex2 = cursor.FindField("DISTRICTNO");
            foreach (var line in lines)
            {
                if ((dropHead == true && count == 0) || (dropTail == true && count == lines.Count - 1))
                {
                    count++;
                    continue;
                }

                var buff = fc.CreateFeatureBuffer();
                buff.Shape = line;
                CopyValues(buff, values);
                string d,dNO;
                GetDistrictInfo(line, districtFC, out d, out dNO);
                buff.set_Value(dIndex, d);
                if(string.IsNullOrEmpty(dNO))
                {
                    buff.set_Value(dIndex2, DBNull.Value);
                }
                else
                {
                    buff.set_Value(dIndex2, int.Parse(dNO));
                }

                buff.set_Value(idIndex, id);
                ret.Add(id);
                cursor.InsertFeature(buff);
                cursor.Flush();
                id++;
                count++;
            }

            Marshal.ReleaseComObject(cursor);
            return ret;
        }
Exemple #48
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;
            }
        }
Exemple #49
0
        public static List<int> SplitPolyline(int oid, List<IPoint> pts, IFeatureClass fc)
        {
            var f = fc.GetFeature(oid);

            var geo = f.ShapeCopy as IPolyline;
            var ret = new List<int>();

            var lines = SplitPolylineInner(geo, pts);

            if (lines.Count < 2) return ret ;

            var cursor = fc.Insert(true);
            var idIndex = cursor.FindField(IDField);
            var id = GetNewId(fc);
            foreach(var line in lines)
            {
                var buff = fc.CreateFeatureBuffer();
                ret.Add(id);
                buff.set_Value(idIndex, id);
                buff.Shape = line;
                CopyFields(f, buff);
                cursor.InsertFeature(buff);
                cursor.Flush();
                id++;
            }

            Marshal.ReleaseComObject(cursor);
            f.Delete();
            return ret;
        }
Exemple #50
0
        public void AppendAnnoElements(ILayer pSrcLayer, IFeatureClass pTargetFC,IActiveView activeview)
        {
            //首先从cad的注记层得到一个注记,然后得到他的Annotation,再赋给新建的要素
            //IQueryFilter queryfilter = new QueryFilterClass();
            //queryfilter.WhereClause = "Layer = '" + filter + "'";
            try
            {
                IFeatureLayer pSrcFLayer = pSrcLayer as IFeatureLayer;
                IFeatureClass pSrcFC = pSrcFLayer.FeatureClass;
                IFeature cadFeat;
                IElement featElement;
                IDataset pDataset;
                pDataset = pTargetFC as IDataset;
                IFDOGraphicsLayer pFDOGLayer;
                IFDOGraphicsLayerFactory pGLF = new FDOGraphicsLayerFactoryClass();
                ICoverageAnnotationLayer pCadAnnoLayer;
                pCadAnnoLayer = pSrcLayer as ICoverageAnnotationLayer;
                IWorkspace pWorkspace = pDataset.Workspace as IWorkspace;
                IWorkspaceEdit pWorkspaceEdit = pWorkspace as IWorkspaceEdit;

                IScreenDisplay screendis = activeview.ScreenDisplay;
                pFDOGLayer = pGLF.OpenGraphicsLayer((IFeatureWorkspace)pDataset.Workspace, pTargetFC.FeatureDataset, pDataset.Name) as IFDOGraphicsLayer;
                pCadAnnoLayer.StartGeneratingGraphics(null, screendis, false);
                pCadAnnoLayer.NextFeatureAndGraphic(out cadFeat, out featElement);
                //IFeature newFeature;
                IFeature cadFeature;
                IAnnotationFeature pAnnoFeature;
                IPolygon poly = new PolygonClass();
                //IEnvelope box;
                pWorkspaceEdit.StartEditing(false);
                pWorkspaceEdit.StartEditOperation();
                //int index;
                //pFDOGLayer.BeginAddElements();
                int count = 0;
                //pstepro.StepValue = 1;
                IFeatureBuffer featbuffer = pTargetFC.CreateFeatureBuffer();
                IFeatureCursor featCur = pTargetFC.Insert(true);

                while (cadFeat != null && featElement != null)
                {
                    //pFDOGLayer.DoAddFeature(cadFeat, featElement, 0);
                    //判断分在那一个层
                    count++;
                    //pstepro.Position = count;//进度条增加
                    cadFeature = pSrcFC.GetFeature(cadFeat.OID);
                    //if (cadFeature.get_Value(cadFeature.Fields.FindField("Layer")).ToString() != filter)
                    //{
                    //    pCadAnnoLayer.NextFeatureAndGraphic(out cadFeat, out featElement);
                    //    continue;
                    //}
                    //newFeature = pTargetFC.CreateFeature();
                    poly = cadFeat.ShapeCopy as IPolygon;
                    featbuffer.Shape = poly as IGeometry;
                    pAnnoFeature = featbuffer as IAnnotationFeature;
                    pAnnoFeature.Annotation = featElement;

                    int index1 = getLayerIndex(cadFeature.get_Value(cadFeature.Fields.FindField("Layer")).ToString());

                    featbuffer.set_Value(4, index1);
                    featCur.InsertFeature(featbuffer);
                    //newFeature.Store();
                    ///////////////
                    pCadAnnoLayer.NextFeatureAndGraphic(out cadFeat, out featElement);
                }
                featCur.Flush();
                //pFDOGLayer.EndAddElements();
                pWorkspaceEdit.StopEditOperation();
                pWorkspaceEdit.StopEditing(true);
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        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();
        }
        private void ExportInsertFeatures(IDisplayTable hluDisplayTable, IQueryFilter exportQueryFilter, 
            int exportRowCount, int[] exportFieldMap, bool isShp, object outWS, IFeatureClass outFeatureClass)
        {
            IStatusBar statusBar = _application.StatusBar;
            IStepProgressor progressBar = statusBar.ProgressBar;
            progressBar.Position = 0;
            statusBar.ShowProgressBar("Exporting...", 0, exportRowCount, 1, true);

            IWorkspaceEdit workspaceEdit = null;
            IWorkspace wsOut = outWS as IWorkspace;
            bool restoreEditSession = InEditingSession;
            if (restoreEditSession) CloseEditSession(true);

            if (wsOut.WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
            {
                Editor.StartEditing(wsOut);
                Editor.StartOperation();
            }

            else
            {
                workspaceEdit = (IWorkspaceEdit)outWS;
                workspaceEdit.StartEditing(true);
                workspaceEdit.StartEditOperation();
            }
            
            IFeatureCursor exportFeatureCursor =
                (IFeatureCursor)hluDisplayTable.SearchDisplayTable(exportQueryFilter, true);
            IFeature exportFeature;

            IFeatureCursor insertCursor = outFeatureClass.Insert(true);
            IFeatureBuffer featureBuffer = outFeatureClass.CreateFeatureBuffer();

            bool calcGeometry = _hluFeatureClass.ShapeType == esriGeometryType.esriGeometryPoint || isShp;
            double geom1;
            double geom2;
            int ixGeom1 = featureBuffer.Fields.FieldCount - 2;
            int ixGeom2 = featureBuffer.Fields.FieldCount - 1;

            try
            {
                object item;
                while ((exportFeature = exportFeatureCursor.NextFeature()) != null)
                {
                    featureBuffer.Shape = exportFeature.ShapeCopy;

                    for (int i = 2; i < exportFieldMap.Length; i++)
                    {
                        item = exportFeature.get_Value(exportFieldMap[i]);
                        if (item != DBNull.Value) featureBuffer.set_Value(i, item);
                    }

                    if (calcGeometry)
                    {
                        GetGeometryProperties(exportFeature, out geom1, out geom2);
                        if (geom1 != -1)
                            featureBuffer.set_Value(ixGeom1, geom1);
                        if (geom2 != -1)
                            featureBuffer.set_Value(ixGeom2, geom2);
                    }

                    try { insertCursor.InsertFeature(featureBuffer); }
                    catch { }

                    progressBar.Step();
                }
                FlushCursor(false, ref insertCursor);

                if (workspaceEdit == null)
                {
                    Editor.StopOperation(String.Empty);
                    Editor.StopEditing(true);
                }
                else
                {
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(true);
                }
            }
            catch
            {
                if (workspaceEdit == null)
                {
                    Editor.AbortOperation();
                    Editor.StopEditing(false);
                }
                else
                {
                    workspaceEdit.AbortEditOperation();
                    workspaceEdit.StopEditOperation();
                    workspaceEdit.StopEditing(false);
                }
                throw;
            }
            finally
            {
                FlushCursor(true, ref exportFeatureCursor);
                if (restoreEditSession) OpenEditSession();
                statusBar.set_Message((int)esriStatusBarPanes.esriStatusMain, "");
                statusBar.HideProgressBar();
            }
        }
Exemple #53
0
        public void RasDSToCatalogWithTime(IRasterDataset pRasterDs, IFeatureClass pCatalog, string DataField, string strData, IRasterStorageDef pRasStoreDef)
        {
            //IRasterCatalogItem pCatalogFeature;

            IFeatureCursor pCursor;
            IFeatureBuffer pRow;

            pCursor = pCatalog.Insert(false);
            IRasterCatalog pCat = pCatalog as IRasterCatalog;

            IDataset pDs;

            // loop through all the datasets and load
            if (pRasterDs != null)
            {
                pDs = pRasterDs as IDataset;
                pRow = pCatalog.CreateFeatureBuffer();
                pRow.set_Value(pCat.RasterFieldIndex, createRasterValue(pRasterDs, pRasStoreDef));
                pRow.set_Value(pCatalog.FindField(DataField), Convert.ToDateTime(strData));
                pCursor.InsertFeature(pRow);
            }

            pRasterDs = null;
        }
Exemple #54
0
        object ICopyFeatures.Copy(IFeature copiedFeature, IFeatureClass toFeatureClass)
        {
            object id = 0;
               //using (ComReleaser releaser = new ComReleaser())
               //{
               //    _workspaceEdit = (IWorkspaceEdit)_workspace;
               //    _mWorkspaceEdit = (IMultiuserWorkspaceEdit)_workspace;
               //releaser.ManageLifetime(_workspaceEdit);
               //releaser.ManageLifetime(_mWorkspaceEdit);

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

               try
               {
                   IFeatureCursor featureCursorInsert = toFeatureClass.Insert(true);
                   IFeatureBuffer featureBufferInsert = toFeatureClass.CreateFeatureBuffer();
                   //releaser.ManageLifetime(featureBufferInsert);
                   //releaser.ManageLifetime(featureCursorInsert);
                   // Add the original feature's geometry to the feature buffer.
                   //MessageBox.Show(copiedFeature.Shape.ToString());
                   featureBufferInsert.Shape = copiedFeature.Shape;

                   // Add all the original feature's fields to the feature buffer.
                   //((ICopyFeatures)this).AddFields(featureBufferInsert, copiedFeature);
                   // Insert the feature into the cursor.

                   id = featureCursorInsert.InsertFeature(featureBufferInsert);
                   featureCursorInsert.Flush();
                   //_workspaceEdit.StopEditOperation();
                   //_workspaceEdit.StopEditing(true);
               }
               catch (Exception ex)
               {
                   //MessageBox.Show("line 493 DataManager, ex=" + ex.ToString());
                   //_workspaceEdit.AbortEditOperation();
                   //_workspaceEdit.StopEditing(false);
               }
               //}
               //MessageBox.Show("new id=" + id.ToString());
               return id;
        }
        public void LoadTempImportFC(int SurveyID, int BatchID, int NextTransectID, IFeatureCursor ImportFCursor,
            IFeatureClass TempImportFC, IGeoDataset ThisDEM, double TargetLength, ref List<int> NewOIDs,
            ref int TotalInExcluded, ref int TotalOutsideBndy, ref int TotalPassed,string ThisDEMUnits, ref string ErrorMessage)
        {
            IFeature ImportFeature;
            IFeatureCursor ImportToCursor = null;
            IFeatureBuffer ImportToBuffer = null;
            esriGeometryType FType;
            bool IsInExcludedAreas, IsInBndPoly;
            ESRI.ArcGIS.GeoAnalyst.ISurfaceOp2 npsSurfaceOp = null;
            int ThisFieldIndex;
            IPoint TempPoint;
            IPolyline NewTrnPolyline;
            double Elev;
            IPolyline CPolyline;
            IPoint centerPoint;
            IFeatureClass ExclPolyFC, BndPolyFC;

            ThisDEMUnits = ThisDEMUnits.ToLower();
            NewOIDs = new List<int>();
            TotalInExcluded = 0;
            TotalOutsideBndy = 0;
            TotalPassed = 0;

            ExclPolyFC = Util.GetFeatureClass(m_NPS.LYR_EXCLUDED_AREAS, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            BndPolyFC = Util.GetFeatureClass(m_NPS.LYR_SURVEY_BOUNDARY, ref ErrorMessage);
            if (string.IsNullOrEmpty(ErrorMessage) == false) return;

            FType = TempImportFC.ShapeType;

            //get insert cursor in the nps feature class we are going to insert into
            ImportToCursor = TempImportFC.Insert(true);
            ImportToBuffer = TempImportFC.CreateFeatureBuffer();

            if (FType == esriGeometryType.esriGeometryPolyline)
                npsSurfaceOp = new ESRI.ArcGIS.GeoAnalyst.RasterSurfaceOpClass();

            //loop through each import feature and import it to it's appropriate featureclass
            while ((ImportFeature = ImportFCursor.NextFeature()) != null)
            {
                //make sure the shape is valid
                if (ImportFeature.ShapeCopy == null)
                {
                    TotalOutsideBndy++;
                    continue;
                }

                if (FType == esriGeometryType.esriGeometryPoint)
                {

                    //check if rand point  falls in excluded areas
                    IsInExcludedAreas = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelWithin,
                        ExclPolyFC, "SurveyID=" + SurveyID);

                    //if point is in excluded areas, don't add
                    if (IsInExcludedAreas)
                    {
                        TotalInExcluded++;
                        continue;
                    }

                    //check if  rand point is within boundary
                    IsInBndPoly = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelWithin,
                        BndPolyFC, "SurveyID=" + SurveyID);

                    //if random point is not in boundary, dont add it
                    if (IsInBndPoly == false)
                    {
                        TotalOutsideBndy++;
                        continue;
                    }

                }

                if (FType == esriGeometryType.esriGeometryPolyline)
                {

                    //check if new line falls in excluded areas
                    IsInExcludedAreas = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelCrosses,
                         ExclPolyFC, "SurveyID=" + SurveyID);

                    //if point is in excluded areas, don't add
                    if (IsInExcludedAreas)
                    {
                        TotalInExcluded++;
                        continue;
                    }

                    //check if new line is within in boundary
                    IsInBndPoly = Util.HasRelationshipWithFC(ImportFeature.ShapeCopy, esriSpatialRelEnum.esriSpatialRelWithin,
                         BndPolyFC, "SurveyID=" + SurveyID);

                    //if random point is not in boundary, dont add it
                    if (IsInBndPoly == false)
                    {
                        TotalOutsideBndy++;
                        continue;
                    }

                }

                TotalPassed++;

                //add feature to temp feature class
                ImportToBuffer.Shape = ImportFeature.ShapeCopy;
                ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("SurveyID"), SurveyID);
                ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("BATCH_ID"), BatchID);

                if (FType == esriGeometryType.esriGeometryPolyline)
                {

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("Flown");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("Flown"), "N");

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("TransectID");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ImportToBuffer.Fields.FindField("TransectID"), NextTransectID);

                    NextTransectID++;

                    NewTrnPolyline = ImportToBuffer.Shape as IPolyline;

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("LENGTH_MTR");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, NewTrnPolyline.Length);

                    //add the name of the default projection
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJECTION");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, NewTrnPolyline.SpatialReference.Name);

                    ThisFieldIndex = ImportToBuffer.Fields.FindField("TARGETLEN");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TargetLength);

                    //clone from point
                    TempPoint = ((ESRI.ArcGIS.esriSystem.IClone)NewTrnPolyline.FromPoint).Clone() as IPoint;

                    //add from point projected coords
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_X1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_Y1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //add from point geo coords
                    ((IGeometry2)TempPoint).ProjectEx(Util.GetWGSSpatRef(), esriTransformDirection.esriTransformForward, null, false, 0, 0);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LONG1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LAT1");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //clone to point
                    TempPoint = ((ESRI.ArcGIS.esriSystem.IClone)NewTrnPolyline.ToPoint).Clone() as IPoint;

                    //add to point projected coords
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_X2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("PROJTD_Y2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //add to point geo coords
                    ((IGeometry2)TempPoint).ProjectEx(Util.GetWGSSpatRef(), esriTransformDirection.esriTransformForward, null, false, 0, 0);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LONG2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.X);
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("DD_LAT2");
                    if (ThisFieldIndex > -1) ImportToBuffer.set_Value(ThisFieldIndex, TempPoint.Y);

                    //get center point
                    centerPoint = new PointClass();
                    ((ICurve)NewTrnPolyline).QueryPoint(esriSegmentExtension.esriNoExtension, 0.5, true, centerPoint);

                    //get elevation for transect center
                    CPolyline = new PolylineClass();
                    npsSurfaceOp.ContourAsPolyline(ThisDEM, centerPoint, out CPolyline, out Elev);

                    //set elevation in meters
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("ELEV_M");
                    if (ThisFieldIndex > -1)
                    {
                        if (ThisDEMUnits == "feet") ImportToBuffer.set_Value(ThisFieldIndex, 0.3048 * Elev);
                        if (ThisDEMUnits == "meters") ImportToBuffer.set_Value(ThisFieldIndex, Elev);

                    }

                    //get elevation in feet
                    ThisFieldIndex = ImportToBuffer.Fields.FindField("ELEVFT");
                    if (ThisFieldIndex > -1)
                    {
                        if (ThisDEMUnits == "feet") ImportToBuffer.set_Value(ThisFieldIndex, Elev);
                        if (ThisDEMUnits == "meters") ImportToBuffer.set_Value(ThisFieldIndex, Elev * 3.2808399);
                    }

                }

                NewOIDs.Add((int)Util.SafeConvert(ImportToCursor.InsertFeature(ImportToBuffer), typeof(int)));

            }

            ImportFCursor = null;
            ImportToCursor = null;
            ImportToBuffer = null;
        }
Exemple #56
0
        private void BoboDataGeneration(IFeatureClass featureClass, IFeatureWorkspace featureWorkspace)
        {
            ((IWorkspaceEdit)featureWorkspace).StartEditing(true);
            ((IWorkspaceEdit)featureWorkspace).StartEditOperation();

            IFeatureCursor featureCursor = featureClass.Insert(false);
            int XCoord;
            int YCoord;
            int histValue;
            Random random = new Random();

            for(int i = 0; i < 1000; i++)
            {
                //Generate random values for points and for point values

                XCoord = random.Next(-179, 179);
                YCoord = random.Next(-89, 89);
                histValue = random.Next(1, 255);

                int histoGramData = featureCursor.Fields.FindField("HistoField");
                //Andrew Method
                //IFeature f = featureClass.CreateFeature();
                //f.Value[histoGramData] = histValue;
                //f.Shape = new Point() {X = XCoord, Y = YCoord};
                //f.Store();
                //Nohe method
                IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer();
                featureBuffer.Value[histoGramData] = histValue;
                featureBuffer.Shape = new Point() { X = XCoord, Y = YCoord };

                featureCursor.InsertFeature(featureBuffer);

            }
            //featureCursor.Flush();
            ((IWorkspaceEdit)featureWorkspace).StopEditOperation();
            ((IWorkspaceEdit) featureWorkspace).StopEditing(true);
        }
        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();
            }
        }
        /// <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);
        }
Exemple #59
0
        /// <summary>insert the records from the GIPOD service into the shapefile </summary>
        private void populateGipodShape(IFeatureClass gipodFC, List<datacontract.gipodResponse> gipodRecords, dataHandler.gipodtype gtype)
        {
            //return if something is null
            if (gipodFC == null || gipodRecords == null) return;

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

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

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

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

                    featureBuffer.Shape = toPt;

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

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

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

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

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

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

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

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

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

                    insertCursor.InsertFeature(featureBuffer);
                }
                insertCursor.Flush();
            }
        }
        internal List<string> loadOSMWays(string osmFileLocation, ref ITrackCancel TrackCancel, ref IGPMessages message, IGPValue targetGPValue, IFeatureClass osmPointFeatureClass, IFeatureClass osmLineFeatureClass, IFeatureClass osmPolygonFeatureClass, bool conserveMemory, bool fastLoad, int wayCapacity, ref Dictionary<string, simplePointRef> osmNodeDictionary, IFeatureWorkspace featureWorkspace, ISpatialReference downloadSpatialReference, OSMDomains availableDomains, bool checkForExisting)
        {
            if (osmLineFeatureClass == null)
            {
                throw new ArgumentNullException("osmLineFeatureClass");
            }

            if (osmPolygonFeatureClass == null)
            {
                throw new ArgumentNullException("osmPolygonFeatureClass");
            }

            XmlReader osmFileXmlReader = null;
            XmlSerializer waySerializer = null;
            List<string> missingWays = null;

            try
            {
                missingWays = new List<string>();

                int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
                int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");

                int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmLineDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmLineFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmLineDomainAttributeFieldLength.Add(domains.name, osmLineFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags");
                int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser");
                int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid");
                int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible");
                int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion");
                int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf");
                int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement");

                int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID");
                Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>();
                Dictionary<string, int> osmPolygonDomainAttributeFieldLength = new Dictionary<string, int>();
                foreach (var domains in availableDomains.domain)
                {
                    int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name);

                    if (currentFieldIndex != -1)
                    {
                        osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
                        osmPolygonDomainAttributeFieldLength.Add(domains.name, osmPolygonFeatureClass.Fields.get_Field(currentFieldIndex).Length);
                    }
                }
                int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags");
                int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser");
                int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid");
                int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible");
                int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion");
                int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset");
                int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp");
                int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf");
                int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers");
                int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement");

                ISpatialReferenceFactory spatialRef = new SpatialReferenceEnvironmentClass();
                ISpatialReference wgs84 = spatialRef.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);

                bool shouldProject = !((IClone)wgs84).IsEqual((IClone)downloadSpatialReference);

                // set up the progress indicator
                IStepProgressor stepProgressor = TrackCancel as IStepProgressor;

                if (stepProgressor != null)
                {
                    stepProgressor.MinRange = 0;
                    stepProgressor.MaxRange = wayCapacity;
                    stepProgressor.Position = 0;
                    stepProgressor.Message = _resourceManager.GetString("GPTools_OSMGPFileReader_loadingWays");
                    stepProgressor.StepValue = 1;
                    stepProgressor.Show();
                }

                bool lineIndexRebuildRequired = false;
                bool polygonIndexRebuildRequired = false;

                int wayCount = 0;
                object missingValue = System.Reflection.Missing.Value;

                // enterprise GDB indicator -- supporting load only mode
                IFeatureClassLoad lineFeatureLoad = null;
                IFeatureClassLoad polygonFeatureLoad = null;

                using (SchemaLockManager lineLock = new SchemaLockManager(osmLineFeatureClass as ITable), polygonLock = new SchemaLockManager(osmPolygonFeatureClass as ITable))
                {
                    using (ComReleaser comReleaser = new ComReleaser())
                    {
                        IFeatureCursor insertLineCursor = osmLineFeatureClass.Insert(true);
                        comReleaser.ManageLifetime(insertLineCursor);

                        IFeatureBuffer featureLineBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                        comReleaser.ManageLifetime(featureLineBuffer);

                        IFeatureCursor insertPolygonCursor = osmPolygonFeatureClass.Insert(true);
                        comReleaser.ManageLifetime(insertPolygonCursor);

                        IFeatureBuffer featurePolygonBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();
                        comReleaser.ManageLifetime(featurePolygonBuffer);

                        if (((IWorkspace)featureWorkspace).WorkspaceFactory.WorkspaceType == esriWorkspaceType.esriRemoteDatabaseWorkspace)
                        {
                            lineFeatureLoad = osmLineFeatureClass as IFeatureClassLoad;
                            polygonFeatureLoad = osmPolygonFeatureClass as IFeatureClassLoad;
                        }

                        if (lineFeatureLoad != null)
                        {
                            lineFeatureLoad.LoadOnlyMode = true;
                        }

                        if (polygonFeatureLoad != null)
                        {
                            polygonFeatureLoad.LoadOnlyMode = true;
                        }

                        ISpatialReference nativeLineSpatialReference = ((IGeoDataset)osmLineFeatureClass).SpatialReference;
                        ISpatialReference nativePolygonSpatialReference = ((IGeoDataset)osmPolygonFeatureClass).SpatialReference;

                        IQueryFilter osmIDQueryFilter = new QueryFilterClass();
                        string sqlPointOSMID = osmPointFeatureClass.SqlIdentifier("OSMID");
                        IFeatureCursor updatePointCursor = null;

                        osmFileXmlReader = System.Xml.XmlReader.Create(osmFileLocation);
                        waySerializer = new XmlSerializer(typeof(way));

                        // the point query filter for updates will not changes, so let's do that ahead of time
                        try
                        {
                            osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name;
                        }
                        catch
                        { }

                        osmFileXmlReader.MoveToContent();
                        while (osmFileXmlReader.Read())
                        {
                            if (osmFileXmlReader.IsStartElement())
                            {
                                if (osmFileXmlReader.Name == "way")
                                {
                                    string currentwayString = osmFileXmlReader.ReadOuterXml();

                                    // assuming the way to be a polyline is sort of a safe assumption
                                    // and won't cause any topology problem due to orientation and closeness
                                    bool wayIsLine = true;
                                    bool wayIsComplete = true;

                                    way currentWay = null;

                                    try
                                    {
                                        using (StringReader wayReader = new System.IO.StringReader(currentwayString))
                                        {
                                            currentWay = waySerializer.Deserialize(wayReader) as way;
                                        }

                                        // if the deserialization fails then go ahead and read the next xml element
                                        if (currentWay == null)
                                        {
                                            continue;
                                        }

                                        // and we are expecting at least some nodes on the way itself
                                        if (currentWay.nd == null)
                                        {
                                            continue;
                                        }

                                        featureLineBuffer = osmLineFeatureClass.CreateFeatureBuffer();
                                        featurePolygonBuffer = osmPolygonFeatureClass.CreateFeatureBuffer();

                                        IPointCollection wayPointCollection = null;
                                        wayIsLine = IsThisWayALine(currentWay);

                                        if (wayIsLine)
                                        {

                                            // check if a feature with the same OSMID already exists, because the can only be one
                                            if (checkForExisting == true)
                                            {
                                                if (CheckIfExists(osmLineFeatureClass as ITable, currentWay.id))
                                                {
                                                    continue;
                                                }
                                            }

                                            IPolyline wayPolyline = new PolylineClass();
                                            comReleaser.ManageLifetime(wayPointCollection);

                                            wayPolyline.SpatialReference = downloadSpatialReference;

                                            IPointIDAware polylineIDAware = wayPolyline as IPointIDAware;
                                            polylineIDAware.PointIDAware = true;

                                            wayPointCollection = wayPolyline as IPointCollection;

                                            # region generate line geometry
                                            if (conserveMemory == false)
                                            {
                                                for (int ndIndex = 0; ndIndex < currentWay.nd.Length; ndIndex++)
                                                {
                                                    string ndID = currentWay.nd[ndIndex].@ref;
                                                    if (osmNodeDictionary.ContainsKey(ndID))
                                                    {
                                                        IPoint newPoint = new PointClass();
                                                        newPoint.X = osmNodeDictionary[ndID].Longitude;
                                                        newPoint.Y = osmNodeDictionary[ndID].Latitude;

                                                        newPoint.SpatialReference = wgs84;

                                                        if (shouldProject)
                                                        {
                                                            newPoint.Project(((IGeoDataset)osmLineFeatureClass).SpatialReference);
                                                        }

                                                        IPointIDAware idAware = newPoint as IPointIDAware;
                                                        idAware.PointIDAware = true;

                                                        newPoint.ID = osmNodeDictionary[ndID].pointObjectID;

                                                        wayPointCollection.AddPoint(newPoint, ref missingValue, ref missingValue);

                                                        osmNodeDictionary[ndID].RefCounter = osmNodeDictionary[ndID].RefCounter + 1;
                                                    }
                                                    else
                                                    {
                                                        message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedline_node"), currentWay.id, ndID));
                                                        // set the flag that the way is complete due to a missing node
                                                        wayIsComplete = false;
                                                        break;
                                                    }
                                                }

                                            }
                                            else
                                            {
                                                for (int pointIndex = 0; pointIndex < currentWay.nd.Length; pointIndex++)
                                                {
                                                    wayPointCollection.AddPoint(new PointClass());
                                                }

                                                List<string> idRequests = SplitOSMIDRequests(currentWay, 2);

                                                // build a list of node ids we can use to determine the point index in the line geometry
                                                // as well as a dictionary to determine the position in the list in case of duplicates nodes
                                                Dictionary<string, int> nodePositionDictionary = new Dictionary<string, int>(currentWay.nd.Length);
                                                List<string> nodeIDs = new List<string>(currentWay.nd.Length);

                                                foreach (nd wayNode in currentWay.nd)
                                                {
                                                    nodeIDs.Add(wayNode.@ref);

                                                    if (nodePositionDictionary.ContainsKey(wayNode.@ref) == false)
                                                    {
                                                        nodePositionDictionary.Add(wayNode.@ref, 0);
                                                    }
                                                }

                                                try
                                                {
                                                    osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name;
                                                }
                                                catch
                                                { }

                                                foreach (string request in idRequests)
                                                {
                                                    string idCompareString = request;
                                                    osmIDQueryFilter.WhereClause = sqlPointOSMID + " IN " + request;
                                                    using (ComReleaser innerComReleaser = new ComReleaser())
                                                    {
                                                        updatePointCursor = osmPointFeatureClass.Update(osmIDQueryFilter, true);
                                                        innerComReleaser.ManageLifetime(updatePointCursor);

                                                        IFeature nodeFeature = updatePointCursor.NextFeature();

                                                        while (nodeFeature != null)
                                                        {
                                                            // determine the index of the point in with respect to the node position
                                                            string nodeOSMIDString = Convert.ToString(nodeFeature.get_Value(osmPointIDFieldIndex));

                                                            // remove the ID from the request string
                                                            idCompareString = idCompareString.Replace(nodeOSMIDString, String.Empty);

                                                            int nodePositionIndex = -1;

                                                            while ((nodePositionIndex = nodeIDs.IndexOf(nodeOSMIDString, nodePositionDictionary[nodeOSMIDString])) != -1)
                                                            {
                                                                //// update the new position start search index
                                                                nodePositionDictionary[nodeOSMIDString] = nodePositionIndex + 1;

                                                                wayPointCollection.UpdatePoint(nodePositionIndex, (IPoint)nodeFeature.Shape);

                                                                // increase the reference counter
                                                                if (osmWayRefCountFieldIndex != -1)
                                                                {
                                                                    nodeFeature.set_Value(osmWayRefCountFieldIndex, ((int)nodeFeature.get_Value(osmWayRefCountFieldIndex)) + 1);

                                                                    updatePointCursor.UpdateFeature(nodeFeature);
                                                                }
                                                            }

                                                            if (nodeFeature != null)
                                                                Marshal.ReleaseComObject(nodeFeature);

                                                            nodeFeature = updatePointCursor.NextFeature();
                                                        }

                                                        idCompareString = CleanReportedNodes(idCompareString);

                                                        // after removing the commas we should be left with only paranthesis left, meaning a string of length 2
                                                        // if we have more then we have found a missing node, resulting in an incomplete way geometry
                                                        if (idCompareString.Length > 2)
                                                        {
                                                            message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedline_node"), currentWay.id, idCompareString));
                                                            wayIsComplete = false;
                                                        }
                                                    }
                                                }
                                            }
                                            #endregion

                                            if (wayIsComplete == false)
                                            {
                                                // if the way geometry is incomplete due to a missing node let's continue to the next way element
                                                missingWays.Add(currentWay.id);
                                                continue;
                                            }

                                            featureLineBuffer.Shape = wayPolyline;
                                            featureLineBuffer.set_Value(osmLineIDFieldIndex, currentWay.id);
                                        }
                                        else
                                        {
                                            // check if a feature with the same OSMID already exists, because the can only be one
                                            if (checkForExisting == true)
                                            {
                                                if (CheckIfExists(osmPolygonFeatureClass as ITable, currentWay.id))
                                                {
                                                    continue;
                                                }
                                            }

                                            IPolygon wayPolygon = new PolygonClass();
                                            comReleaser.ManageLifetime(wayPointCollection);

                                            wayPolygon.SpatialReference = downloadSpatialReference;

                                            IPointIDAware polygonIDAware = wayPolygon as IPointIDAware;
                                            polygonIDAware.PointIDAware = true;

                                            wayPointCollection = wayPolygon as IPointCollection;

                                            #region generate polygon geometry
                                            if (conserveMemory == false)
                                            {
                                                for (int ndIndex = 0; ndIndex < currentWay.nd.Length; ndIndex++)
                                                {
                                                    string ndID = currentWay.nd[ndIndex].@ref;
                                                    if (osmNodeDictionary.ContainsKey(ndID))
                                                    {
                                                        IPoint newPoint = new PointClass();
                                                        newPoint.X = osmNodeDictionary[ndID].Longitude;
                                                        newPoint.Y = osmNodeDictionary[ndID].Latitude;
                                                        newPoint.SpatialReference = wgs84;

                                                        if (shouldProject)
                                                        {
                                                            newPoint.Project(nativePolygonSpatialReference);
                                                        }

                                                        IPointIDAware idAware = newPoint as IPointIDAware;
                                                        idAware.PointIDAware = true;

                                                        newPoint.ID = osmNodeDictionary[ndID].pointObjectID;

                                                        wayPointCollection.AddPoint(newPoint, ref missingValue, ref missingValue);
                                                    }
                                                    else
                                                    {
                                                        message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedpolygon_node"), currentWay.id, ndID));
                                                        wayIsComplete = false;
                                                        break;
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                for (int pointIndex = 0; pointIndex < currentWay.nd.Length; pointIndex++)
                                                {
                                                    wayPointCollection.AddPoint(new PointClass());
                                                }

                                                List<string> idRequests = SplitOSMIDRequests(currentWay, 2);

                                                // build a list of node ids we can use to determine the point index in the line geometry
                                                // as well as a dictionary to determine the position in the list in case of duplicates nodes
                                                Dictionary<string, int> nodePositionDictionary = new Dictionary<string, int>(currentWay.nd.Length);
                                                List<string> nodeIDs = new List<string>(currentWay.nd.Length);

                                                foreach (nd wayNode in currentWay.nd)
                                                {
                                                    nodeIDs.Add(wayNode.@ref);

                                                    if (nodePositionDictionary.ContainsKey(wayNode.@ref) == false)
                                                    {
                                                        nodePositionDictionary.Add(wayNode.@ref, 0);
                                                    }
                                                }

                                                try
                                                {
                                                    osmIDQueryFilter.SubFields = osmPointFeatureClass.ShapeFieldName + "," + osmPointFeatureClass.Fields.get_Field(osmPointIDFieldIndex).Name + "," + osmPointFeatureClass.Fields.get_Field(osmWayRefCountFieldIndex).Name;
                                                }
                                                catch
                                                { }

                                                foreach (string osmIDRequest in idRequests)
                                                {
                                                    string idCompareString = osmIDRequest;

                                                    using (ComReleaser innercomReleaser = new ComReleaser())
                                                    {
                                                        osmIDQueryFilter.WhereClause = sqlPointOSMID + " IN " + osmIDRequest;
                                                        updatePointCursor = osmPointFeatureClass.Update(osmIDQueryFilter, false);
                                                        innercomReleaser.ManageLifetime(updatePointCursor);

                                                        IFeature nodeFeature = updatePointCursor.NextFeature();

                                                        while (nodeFeature != null)
                                                        {
                                                            // determine the index of the point in with respect to the node position
                                                            string nodeOSMIDString = Convert.ToString(nodeFeature.get_Value(osmPointIDFieldIndex));

                                                            idCompareString = idCompareString.Replace(nodeOSMIDString, String.Empty);

                                                            int nodePositionIndex = nodeIDs.IndexOf(nodeOSMIDString, nodePositionDictionary[nodeOSMIDString]);

                                                            // update the new position start search index
                                                            nodePositionDictionary[nodeOSMIDString] = nodePositionIndex + 1;

                                                            wayPointCollection.UpdatePoint(nodePositionIndex, (IPoint)nodeFeature.Shape);

                                                            // increase the reference counter
                                                            if (osmWayRefCountFieldIndex != -1)
                                                            {
                                                                nodeFeature.set_Value(osmWayRefCountFieldIndex, ((int)nodeFeature.get_Value(osmWayRefCountFieldIndex)) + 1);

                                                                updatePointCursor.UpdateFeature(nodeFeature);
                                                            }

                                                            if (nodeFeature != null)
                                                                Marshal.ReleaseComObject(nodeFeature);

                                                            nodeFeature = updatePointCursor.NextFeature();
                                                        }

                                                        idCompareString = CleanReportedNodes(idCompareString);

                                                        if (idCompareString.Length > 2)
                                                        {
                                                            message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_undeterminedpolygon_node"), currentWay.id, idCompareString));
                                                            wayIsComplete = false;
                                                        }
                                                    }
                                                }
                                            }
                                            #endregion

                                            if (wayIsComplete == false)
                                            {
                                                continue;
                                            }

                                            // remove the last point as OSM considers them to be coincident
                                            wayPointCollection.RemovePoints(wayPointCollection.PointCount - 1, 1);
                                            ((IPolygon)wayPointCollection).Close();

                                            featurePolygonBuffer.Shape = (IPolygon)wayPointCollection;
                                            featurePolygonBuffer.set_Value(osmPolygonIDFieldIndex, currentWay.id);
                                        }

                                        if (wayIsLine)
                                        {
                                            insertTags(osmLineDomainAttributeFieldIndices, osmLineDomainAttributeFieldLength, tagCollectionPolylineFieldIndex, featureLineBuffer, currentWay.tag);
                                        }
                                        else
                                        {
                                            insertTags(osmPolygonDomainAttributeFieldIndices, osmPolygonDomainAttributeFieldLength, tagCollectionPolygonFieldIndex, featurePolygonBuffer, currentWay.tag);
                                        }

                                        // store the administrative attributes
                                        // user, uid, version, changeset, timestamp, visible
                                        if (fastLoad == false)
                                        {
                                            if (!String.IsNullOrEmpty(currentWay.user))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmUserPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmUserPolylineFieldIndex, currentWay.user);
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmUserPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmUserPolygonFieldIndex, currentWay.user);
                                                    }
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.uid))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmUIDPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmUIDPolylineFieldIndex, Convert.ToInt32(currentWay.uid));
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmUIDPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmUIDPolygonFieldIndex, Convert.ToInt32(currentWay.uid));
                                                    }
                                                }
                                            }

                                            if (wayIsLine)
                                            {
                                                if (osmVisiblePolylineFieldIndex != -1)
                                                {
                                                    featureLineBuffer.set_Value(osmVisiblePolylineFieldIndex, currentWay.visible.ToString());
                                                }
                                            }
                                            else
                                            {
                                                if (osmVisiblePolygonFieldIndex != -1)
                                                {
                                                    featurePolygonBuffer.set_Value(osmVisiblePolygonFieldIndex, currentWay.visible.ToString());
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.version))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmVersionPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmVersionPolylineFieldIndex, Convert.ToInt32(currentWay.version));
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmVersionPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmVersionPolygonFieldIndex, Convert.ToInt32(currentWay.version));
                                                    }
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.changeset))
                                            {
                                                if (wayIsLine)
                                                {
                                                    if (osmChangesetPolylineFieldIndex != -1)
                                                    {
                                                        featureLineBuffer.set_Value(osmChangesetPolylineFieldIndex, Convert.ToInt32(currentWay.changeset));
                                                    }
                                                }
                                                else
                                                {
                                                    if (osmChangesetPolygonFieldIndex != -1)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmChangesetPolygonFieldIndex, Convert.ToInt32(currentWay.changeset));
                                                    }
                                                }
                                            }

                                            if (!String.IsNullOrEmpty(currentWay.timestamp))
                                            {
                                                try
                                                {
                                                    if (wayIsLine)
                                                    {
                                                        if (osmTimeStampPolylineFieldIndex != -1)
                                                        {
                                                            featureLineBuffer.set_Value(osmTimeStampPolylineFieldIndex, Convert.ToDateTime(currentWay.timestamp));
                                                        }
                                                    }
                                                    else
                                                    {
                                                        if (osmTimeStampPolygonFieldIndex != -1)
                                                        {
                                                            featurePolygonBuffer.set_Value(osmTimeStampPolygonFieldIndex, Convert.ToDateTime(currentWay.timestamp));
                                                        }
                                                    }
                                                }
                                                catch (Exception ex)
                                                {
                                                    message.AddWarning(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_invalidTimeFormat"), ex.Message));
                                                }
                                            }

                                            if (wayIsLine)
                                            {
                                                if (osmSupportingElementPolylineFieldIndex > -1)
                                                {
                                                    if (currentWay.tag == null)
                                                    {
                                                        featureLineBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "yes");
                                                    }
                                                    else
                                                    {
                                                        featureLineBuffer.set_Value(osmSupportingElementPolylineFieldIndex, "no");
                                                    }
                                                }
                                            }
                                            else
                                            {
                                                if (osmSupportingElementPolygonFieldIndex > -1)
                                                {
                                                    if (currentWay.tag == null)
                                                    {
                                                        featurePolygonBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "yes");
                                                    }
                                                    else
                                                    {
                                                        featurePolygonBuffer.set_Value(osmSupportingElementPolygonFieldIndex, "no");
                                                    }
                                                }
                                            }
                                        } // fast load

                                        try
                                        {
                                            if (wayIsLine)
                                            {
                                                insertLineCursor.InsertFeature(featureLineBuffer);
                                                lineIndexRebuildRequired = true;
                                            }
                                            else
                                            {
                                                insertPolygonCursor.InsertFeature(featurePolygonBuffer);
                                                polygonIndexRebuildRequired = true;
                                            }

                                            wayCount = wayCount + 1;

                                            if (stepProgressor != null)
                                            {
                                                stepProgressor.Position = wayCount;
                                            }

                                            if ((wayCount % 50000) == 0)
                                            {
                                                message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_waysloaded"), wayCount));
                                            }

                                        }
                                        catch (Exception ex)
                                        {
                                            message.AddWarning(ex.Message);
                                            message.AddWarning(currentwayString);
                                        }

                                    }
                                    catch (Exception ex)
                                    {
                                        System.Diagnostics.Debug.WriteLine(ex.Message);
                                        System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                                    }
                                    finally
                                    {
                                        if (featureLineBuffer != null)
                                        {
                                            Marshal.ReleaseComObject(featureLineBuffer);

                                            if (featureLineBuffer != null)
                                                featureLineBuffer = null;
                                        }

                                        if (featurePolygonBuffer != null)
                                        {
                                            Marshal.ReleaseComObject(featurePolygonBuffer);

                                            if (featurePolygonBuffer != null)
                                                featurePolygonBuffer = null;
                                        }

                                        currentWay = null;
                                    }

                                    if (TrackCancel.Continue() == false)
                                    {
                                        insertPolygonCursor.Flush();
                                        if (polygonFeatureLoad != null)
                                        {
                                            polygonFeatureLoad.LoadOnlyMode = false;
                                        }

                                        insertLineCursor.Flush();
                                        if (lineFeatureLoad != null)
                                        {
                                            lineFeatureLoad.LoadOnlyMode = false;
                                        }

                                        return missingWays;
                                    }
                                }
                            }
                        }

                        osmFileXmlReader.Close();

                        if (stepProgressor != null)
                        {
                            stepProgressor.Hide();
                        }

                        message.AddMessage(String.Format(_resourceManager.GetString("GPTools_OSMGPFileReader_waysloaded"), wayCount));

                        insertPolygonCursor.Flush();
                        if (polygonFeatureLoad != null)
                        {
                            polygonFeatureLoad.LoadOnlyMode = false;
                        }

                        insertLineCursor.Flush();
                        if (lineFeatureLoad != null)
                        {
                            lineFeatureLoad.LoadOnlyMode = false;
                        }
                    }
                }

                IGeoProcessor2 geoProcessor = new GeoProcessorClass();
                IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
                bool storedOriginal = geoProcessor.AddOutputsToMap;
                IVariantArray parameterArrary = null;
                IGeoProcessorResult2 gpResults2 = null;

                try
                {
                    geoProcessor.AddOutputsToMap = false;

                    if (lineIndexRebuildRequired)
                    {
                        IIndexes featureClassIndexes = osmLineFeatureClass.Indexes;
                        int indexPosition = -1;
                        featureClassIndexes.FindIndex("osmID_IDX", out indexPosition);

                        string fcLocation = GetLocationString(targetGPValue, osmLineFeatureClass);

                        if (indexPosition == -1)
                        {
                            message.AddMessage(_resourceManager.GetString("GPTools_buildinglineidx"));

                            // Addd index for osmid column
                            parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                            gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                        }

                        if (wayCount > 100)
                        {
                            // in this case we are dealing with a file geodatabase
                            if (lineFeatureLoad == null)
                            {
                                UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation);
                            }
                        }
                    }

                    if (polygonIndexRebuildRequired)
                    {
                        IIndexes featureClassIndexes = osmPolygonFeatureClass.Indexes;
                        int indexPosition = -1;
                        featureClassIndexes.FindIndex("osmID_IDX", out indexPosition);

                        string fcLocation = GetLocationString(targetGPValue, osmPolygonFeatureClass);

                        if (indexPosition == -1)
                        {
                            message.AddMessage(_resourceManager.GetString("GPTools_buildingpolygonidx"));

                            IGPValue polygonFeatureClassGPValue = gpUtilities3.MakeGPValueFromObject(osmPolygonFeatureClass);

                            if (polygonFeatureClassGPValue != null)
                            {
                                // Addd index for osmid column
                                parameterArrary = CreateAddIndexParameterArray(fcLocation, "OSMID", "osmID_IDX", "UNIQUE", "");
                                gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary, TrackCancel) as IGeoProcessorResult2;
                            }
                        }

                        if (wayCount > 100)
                        {
                            if (polygonFeatureLoad == null)
                            {
                                UpdateSpatialGridIndex(TrackCancel, message, geoProcessor, fcLocation);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    message.AddWarning(ex.Message);
                }
                finally
                {
                    geoProcessor.AddOutputsToMap = storedOriginal;

                    Marshal.FinalReleaseComObject(gpUtilities3);
                    Marshal.FinalReleaseComObject(geoProcessor);
                }
            }
            catch (Exception ex)
            {
                message.AddWarning(ex.Message);
            }
            finally
            {
                if (waySerializer != null)
                    waySerializer = null;

                if (osmFileXmlReader != null)
                    osmFileXmlReader = null;

                System.GC.Collect();
                System.GC.WaitForPendingFinalizers();
            }

            return missingWays;
        }