//添加点实体 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); }
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); } }
/// <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(); }
//函数号: //函数名: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); }
public void Write([NotNull] IRow importExceptionRow, DateTime importDate, [NotNull] string originValue, Guid lineageGuid, string versionOriginValue, string statusValue) { if (_insertCursor == null) { _insertCursor = _targetTable.Insert(true); _rowBuffer = _targetTable.CreateRowBuffer(); _featureBuffer = _rowBuffer as IFeatureBuffer; } IRowBuffer buffer = Assert.NotNull(_rowBuffer); TransferAttributes(importExceptionRow, buffer); WriteText(buffer, _originFieldIndex, originValue); buffer.Value[_versionBeginDateFieldIndex] = importDate; buffer.Value[_versionEndDateFieldIndex] = DBNull.Value; buffer.Value[_versionUuidFieldIndex] = GetNewVersionUuid(); WriteText(buffer, _versionOriginFieldIndex, versionOriginValue); buffer.Value[_lineageUuidFieldIndex] = ExceptionObjectUtils.FormatGuid(lineageGuid); buffer.Value[_statusFieldIndex] = statusValue; if (_featureBuffer != null) { _featureBuffer.Shape = ((IFeature)importExceptionRow).ShapeCopy; } _insertCursor?.InsertRow(buffer); }
/// <summary> /// 为要素添填充属性 /// </summary> /// <param name="featureBuffer">要素缓存</param> /// <param name="feature">待填充的要素</param> private static void AddFields(IFeatureBuffer featureBuffer, IFeature feature) { IRowBuffer rowBuffer = (IRowBuffer)featureBuffer; IFields fieldsNew = rowBuffer.Fields; int i; int intFieldIndex; IFields fields = feature.Fields; IField field; for (i = 0; i < fieldsNew.FieldCount; i++) { field = fieldsNew.get_Field(i); // if (field.Editable == true && (field.Type != esriFieldType.esriFieldTypeGeometry) && (field.Type != esriFieldType.esriFieldTypeOID) // && (field.Name != "SHAPE_Length") && (field.Name != "SHAPE_Area")) if (field.Editable == true) { intFieldIndex = feature.Fields.FindField(field.Name); if (intFieldIndex != -1) { featureBuffer.set_Value(i, feature.get_Value(intFieldIndex)); } } } }
/// <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(); }
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(); }
/// <summary> /// /// </summary> /// <param name="pobjectShapeEb"></param> /// <param name="pstrFieldNameLt"></param> /// <param name="pobjectValueLtLt"></param> /// <remarks>it should be ok if pobjectShapeEb is null or empty</remarks> private void CommitFeatures(IEnumerable <object> pobjectShapeEb, List <string> pstrFieldNameLt = null, List <List <object> > pobjectValueLtLt = null) { var pFeatureClass = this.pFeatureLayer.FeatureClass; if (pobjectShapeEb != null) { var intIndexLt = GenerateIndexLt(pstrFieldNameLt, pFeatureClass); IFeatureBuffer pFeatureBuffer = pFeatureClass.CreateFeatureBuffer(); IFeature pFeature = pFeatureBuffer as IFeature; IFeatureCursor pFeatureCursor = pFeatureClass.Insert(true); int intCount = 0; foreach (var pobjectShape in pobjectShapeEb) { List <object> pobjectValueLt = null; if (pobjectValueLtLt != null) { pobjectValueLt = pobjectValueLtLt[intCount]; } InsertOneFeature(pFeatureCursor, pFeatureBuffer, pFeature, pobjectShape, intIndexLt, pstrFieldNameLt, pobjectValueLt); intCount++; } pFeatureCursor.Flush(); } }
private void method_0(IFeatureCursor ifeatureCursor_0, IFeatureBuffer ifeatureBuffer_0, IFields ifields_0, IFeature ifeature_0) { IFields fields = ifeatureBuffer_0.Fields; IFields field = ifeature_0.Fields; for (int i = 0; i < field.FieldCount; i++) { IField field1 = field.Field[i]; if ((field1.Type == esriFieldType.esriFieldTypeGeometry || field1.Type == esriFieldType.esriFieldTypeOID ? false : field1.Editable)) { int value = fields.FindField(ifields_0.Field[i].Name); try { ifeatureBuffer_0.Value[value] = ifeature_0.Value[i]; } catch (Exception exception) { Logger.Current.Error("", exception, ""); } } } ifeatureBuffer_0.Shape = ifeature_0.ShapeCopy; ifeatureCursor_0.InsertFeature(ifeatureBuffer_0); }
/// <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(); } }
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#庐山真面目,让你感觉到可以这样写 }
//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(); } }
/// <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(); }
/// <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); }
/// <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); }
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; }
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); } }
public virtual ZhFeatureBuffer CreateZhFeatureBuffer() { IFeatureBuffer fb = this.FeatureClass.CreateFeatureBuffer(); ZhFeatureBuffer zhfb = new ZhFeatureBuffer(fb); return(zhfb); }
private void InsertFeature(IFeatureCursor inCurr, IFeatureBuffer inBuff, IFeature origF, IGeometry inGeo) { mLog.Debug("inside insert feature"); IField tmpField; IFields fieldColl; //object Missing = Type.Missing; fieldColl = origF.Fields; mLog.Debug("this feature has " + fieldColl.FieldCount.ToString() + " fields to work with"); for (int i = 0; i < fieldColl.FieldCount; i++) { tmpField = fieldColl.get_Field(i); mLog.Debug("this field is " + tmpField.Name); mLog.Debug("this field type is " + tmpField.VarType.ToString()); if (tmpField.Type != esriFieldType.esriFieldTypeGeometry && tmpField.Type != esriFieldType.esriFieldTypeOID && tmpField.Editable) { mLog.Debug(inBuff.get_Value(i).ToString()); mLog.Debug("seting the value to " + origF.get_Value(i)); inBuff.set_Value(i, origF.get_Value(i)); } } inBuff.Shape = inGeo; inCurr.InsertFeature(inBuff); inCurr.Flush(); }
/// <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); }
/// <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(); //游标移动 } }
/// <summary> /// Will copy the features from the original feature to the destination feature /// </summary> /// <param name="homeRow"> /// Feature that will receive the new row /// </param> /// <param name="rowToBeCombined"> /// Original row that will be copied /// </param> private static void AddFields(ref IFeatureBuffer homeRow, IFeature rowToBeCombined) { // Copy the attributes of the orig feature the new feature var fieldsNew = rowToBeCombined.Fields; var fields = homeRow.Fields; homeRow.Shape = rowToBeCombined.ShapeCopy; // Iterate through the fields and copy them as applicable. for (var i = 0; i <= fields.FieldCount - 1; i++) { var field = fields.Field[i]; // if the field to be copied is any of the below fields skip it. if ((field.Type == esriFieldType.esriFieldTypeOID) || string.Equals(field.Name, "Shape_Length", StringComparison.OrdinalIgnoreCase)) { continue; } var intFieldIndex = fieldsNew.FindField(field.Name); var origFieldIndex = fields.FindField(field.Name); if (intFieldIndex != -1 && origFieldIndex != -1) { homeRow.Value[origFieldIndex] = rowToBeCombined.Value[intFieldIndex]; } } }
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(); }
/// <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); } }
public void Write(IFeatureBuffer a_FeatureBuffer) { foreach ( var a_PropertyInfo in this.GetType() .GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.GetProperty)) { var a_ColumnAttribute = (ColumnAttribute) a_PropertyInfo.GetCustomAttributes(typeof(ColumnAttribute), false).FirstOrDefault(); if (a_ColumnAttribute == null) { continue; } var a_FieldIndex = a_FeatureBuffer.Fields.FindField(a_ColumnAttribute.Name); if (a_FieldIndex == -1) { throw new ArgumentException( string.Format( "Field {0}(property {1}) not found", a_ColumnAttribute.Name, a_PropertyInfo.Name)); } if (a_FeatureBuffer.Fields.Field[a_FieldIndex].Editable) { a_FeatureBuffer.Value[a_FieldIndex] = a_PropertyInfo.GetValue(this, null); } } if (Shape != null) { a_FeatureBuffer.Shape = Shape; } }
//不剪裁输出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; }
private void processFieldMapping(IFeature sourceFeature, IFeatureBuffer targetFeatureBuffer) { if ((sourceFeature == null) || (targetFeatureBuffer == null)) { return; } try { foreach (string outputFieldName in OutputFieldToInputField.Keys) { string inputFieldName = OutputFieldToInputField[outputFieldName]; if (!String.IsNullOrEmpty(outputFieldName) && !String.IsNullOrEmpty(inputFieldName)) { int sourceIndex = sourceFeature.Fields.FindField(inputFieldName); int targetIndex = targetFeatureBuffer.Fields.FindField(outputFieldName); if (sourceIndex >= 0 && targetIndex >= 0) { IField sourceField = sourceFeature.Fields.get_Field(sourceIndex); object sourceValue = sourceFeature.get_Value(sourceIndex); if (sourceValue == null) { continue; } if (sourceField.Type == esriFieldType.esriFieldTypeString) { if (String.IsNullOrEmpty(sourceValue as string)) { continue; } } IField targetField = targetFeatureBuffer.Fields.get_Field(targetIndex); try { if (targetField.Editable) { targetFeatureBuffer.set_Value(targetIndex, sourceValue); } else { System.Diagnostics.Debug.WriteLine("Field: " + targetField.Name + " not editable."); } } catch (Exception ex2) { Console.WriteLine(ex2); } } } } } catch (Exception ex) { Console.WriteLine(ex); } }
/// <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); }
public static void SetFieldValue(this IFeatureBuffer a_Feature, string a_FieldName, object a_Value) { var a_FieldIndex = a_Feature.Fields.FindField(a_FieldName); if (a_FieldIndex == -1) { throw new Exception(string.Format("Field '{0}' not found", a_FieldName)); } a_Feature.Value[a_FieldIndex] = a_Value; }
public static void CleanUpSignpostFeatureValues(IFeatureBuffer featureBuffer, int lastValidBranchNum, int lastValidTowardNum, int[] outBranchXFI, int[] outBranchXDirFI, int[] outBranchXLngFI, int[] outTowardXFI, int[] outTowardXLngFI) { // set unused sequence number values to null (our row buffer may still // have junk at the end) for (int i = lastValidBranchNum + 1; i < SignpostUtilities.MaxBranchCount; i++) { featureBuffer.set_Value(outBranchXFI[i], null); featureBuffer.set_Value(outBranchXDirFI[i], null); featureBuffer.set_Value(outBranchXLngFI[i], null); } for (int i = lastValidTowardNum + 1; i < SignpostUtilities.MaxBranchCount; i++) { featureBuffer.set_Value(outTowardXFI[i], null); featureBuffer.set_Value(outTowardXLngFI[i], null); } }
public object InsertFeature(IFeatureBuffer Buffer) { return null; }
private static void CopyFields(IFeature from, IFeatureBuffer to) { for (var i = 0; i < to.Fields.FieldCount; i++) { var fld = to.Fields.Field[i]; var fldName = fld.Name.ToUpper(); if (ReservedFields.Contains(fldName) == false) { var idx = from.Fields.FindField(fld.Name); if (idx > -1) { var val = from.get_Value(idx); if (val != null) { Console.WriteLine(string.Format("Fieldname:{0}", fldName)); Console.WriteLine(string.Format("Val:{0}", val)); to.set_Value(i, val); Console.WriteLine(string.Format("i:{0}", i)); } } } } }
private static void CopyFields(IFeature from, IFeatureBuffer to) { for (var i = 0; i < to.Fields.FieldCount; i++) { var fld = from.Fields.Field[i]; var fldName = fld.Name.ToUpper(); if (ReservedFields.Contains(fldName) == false) { var idx = from.Fields.FindField(fld.Name); if (idx > -1) { to.set_Value(i, from.get_Value(idx)); } } } }
private static void CopyValues(IFeatureBuffer buff, Dictionary<string, string> values) { for (var i = 0; i < buff.Fields.FieldCount; i++) { var fld = buff.Fields.Field[i]; if(values.ContainsKey(fld.Name) == false) continue; var o = values[fld.Name]; if (string.IsNullOrEmpty(o)) { if(fld.Type == esriFieldType.esriFieldTypeString) { buff.set_Value(i, o); } else { buff.set_Value(i, DBNull.Value); } } else { switch (fld.Type) { case esriFieldType.esriFieldTypeDate: buff.set_Value(i, Convert.ToDateTime(o)); break; case esriFieldType.esriFieldTypeDouble: buff.set_Value(i, Convert.ToDouble(o)); break; case esriFieldType.esriFieldTypeInteger: buff.set_Value(i, Convert.ToInt32(o)); break; case esriFieldType.esriFieldTypeSingle: buff.set_Value(i, Convert.ToSingle(o)); break; case esriFieldType.esriFieldTypeString: buff.set_Value(i, o.ToString()); break; default: throw new NotSupportedException(string.Format("不支持赋值类型'{0}'到字段", fld.Type)); } } } }
private void processSidc(IRepresentationClass repClass, IFeatureBuffer targetFeatureBuffer, string sidc) { if ((symbolCreator == null) || (repClass == null) || (targetFeatureBuffer == null)) { Console.WriteLine("Failed to initialize - could not create RepRule for SIDC: " + sidc); return; } if (!symbolCreator.Initialized) { Console.WriteLine("SymbolCreator is not initialized - can't look up SIDCs/symbols"); return; } int ruleIdIndex = targetFeatureBuffer.Fields.FindField(MilitaryFeatureClassHelper.RULE_FIELD_NAME1); if (ruleIdIndex < 0) // *2* different rule field names, need to check for both ruleIdIndex = targetFeatureBuffer.Fields.FindField(MilitaryFeatureClassHelper.RULE_FIELD_NAME2); if (ruleIdIndex < 0) { Console.WriteLine("Could not find field:{0}/{1} in output", MilitaryFeatureClassHelper.RULE_FIELD_NAME1, MilitaryFeatureClassHelper.RULE_FIELD_NAME2); return; } int repRuleId = getRepRuleIdForSidc(repClass, sidc); if (repRuleId < 0) repRuleId = addRepRuleIdForSidc(repClass, sidc); if (repRuleId < 0) { Console.WriteLine("Could not create RepRule for SIDC: " + sidc); return; } object o = repRuleId; targetFeatureBuffer.set_Value(ruleIdIndex, o); }
private void processMiscellaneousFields(IFeatureBuffer targetFeatureBuffer, string sidc) { if ((symbolCreator == null) || (targetFeatureBuffer == null)) return; // Set required field UniqueDesignation if empty int indexUD = targetFeatureBuffer.Fields.FindField(MilitaryFeatureClassHelper.UNIQUE_ID_FIELD_NAME); if (indexUD >= 0) { object oUD = targetFeatureBuffer.get_Value(indexUD); string s = oUD.ToString(); // if its null or hasn't changed, set it if ((lastUniqueDesignation == s) || (oUD == null) || (oUD == DBNull.Value) || (s.Length == 0)) { string newUniqueDesignation = symbolCreator.GetGenericSymbolName(sidc); // Apparently if you set a string field to a size larger than allowed it throws an exception // so don't let this happen IField uidField = targetFeatureBuffer.Fields.get_Field(indexUD); if (uidField != null) { int maxUidLength = uidField.Length; if (newUniqueDesignation.Length > maxUidLength) newUniqueDesignation = newUniqueDesignation.Substring(0, maxUidLength); } targetFeatureBuffer.set_Value(indexUD, newUniqueDesignation); lastUniqueDesignation = newUniqueDesignation; } } // Set Echelon field int indexEch = targetFeatureBuffer.Fields.FindField(MilitaryFeatureClassHelper.ECHELON_FIELD); if ((indexEch >= 0) && (symbolCreator.HasValidEchelon(sidc))) { object oEch = targetFeatureBuffer.get_Value(indexEch); if ((oEch == DBNull.Value) || (oEch.ToString().Length == 0)) // if it's empty { int ech = symbolCreator.GetEchelonOrdinal(sidc); oEch = (object)ech; targetFeatureBuffer.set_Value(indexEch, oEch); lastEchelon = ech; } else { // if its not empty, it may be because of the previous value/state of the featurebuffer // so we need to check the case when it hasn't changed int ech = (int)oEch; if (ech == lastEchelon) { ech = symbolCreator.GetEchelonOrdinal(sidc); oEch = (object)ech; targetFeatureBuffer.set_Value(indexEch, oEch); lastEchelon = ech; } } } // Set Country Code field int indexCC = targetFeatureBuffer.Fields.FindField(MilitaryFeatureClassHelper.COUNTRY_FIELD); if (indexCC >= 0) { object oCC = targetFeatureBuffer.get_Value(indexCC); string s = oCC.ToString(); // if its null or hasn't changed, set it if ((lastCountryCode == s) || (oCC == null) || (oCC == DBNull.Value) || (s.Length == 0)) { string countryCode = symbolCreator.GetCountryCode(sidc); targetFeatureBuffer.set_Value(indexCC, countryCode); lastCountryCode = countryCode; } } }
private void processFieldMapping(IFeature sourceFeature, IFeatureBuffer targetFeatureBuffer) { if ((sourceFeature == null) || (targetFeatureBuffer == null)) return; try { foreach (string outputFieldName in OutputFieldToInputField.Keys) { string inputFieldName = OutputFieldToInputField[outputFieldName]; if (!String.IsNullOrEmpty(outputFieldName) && !String.IsNullOrEmpty(inputFieldName)) { int sourceIndex = sourceFeature.Fields.FindField(inputFieldName); int targetIndex = targetFeatureBuffer.Fields.FindField(outputFieldName); if (sourceIndex >= 0 && targetIndex >= 0) { IField sourceField = sourceFeature.Fields.get_Field(sourceIndex); object sourceValue = sourceFeature.get_Value(sourceIndex); if (sourceValue == null) { continue; } if (sourceField.Type == esriFieldType.esriFieldTypeString) { if (String.IsNullOrEmpty(sourceValue as string)) { continue; } } IField targetField = targetFeatureBuffer.Fields.get_Field(targetIndex); try { if (targetField.Editable) { targetFeatureBuffer.set_Value(targetIndex, sourceValue); } else { System.Diagnostics.Debug.WriteLine("Field: " + targetField.Name + " not editable."); } } catch (Exception ex2) { Console.WriteLine(ex2); } } } } } catch (Exception ex) { Console.WriteLine(ex); } }
void ICopyFeatures.AddFields(IFeatureBuffer featureBuffer, IFeature feature) { // Copy the attributes of the orig feature the new feature IRowBuffer rowBuffer = (IRowBuffer)featureBuffer; IFields fieldsNew = rowBuffer.Fields; IFields fields = feature.Fields; for (int i = 0; i <= fields.FieldCount - 1; i++) { IField field = fields.get_Field(i); if ((field.Type != esriFieldType.esriFieldTypeGeometry) && (field.Type != esriFieldType.esriFieldTypeOID)) { int intFieldIndex = fieldsNew.FindField(field.Name); if (intFieldIndex != -1) { featureBuffer.set_Value(intFieldIndex, feature.get_Value(i)); } } } }
public static void SetFeatureValue(IFeatureBuffer pFea, string pField, object pValue) { SetRowValue(pFea as IRow, pField, pValue); }
/// <summary> /// Geometry��Zֵ��Mֵ���� /// </summary> /// <params name="feature"></params> /// <params name="geometry"></params> /// <params name="zValue"></params> public static void ZMValue(IFeatureBuffer feature, IGeometry geometry) { //���ж�ͼ��Ҫ���Ƿ���Zֵ int index; index = feature.Fields.FindField(GIS_Const.FIELD_SHAPE); if (index < 0) return; IGeometryDef pGeometryDef; pGeometryDef = feature.Fields.get_Field(index).GeometryDef as IGeometryDef; MakeZMValue(pGeometryDef, geometry); }