public static void ChangeCoordinateSystem(IGeodatabaseRelease igeodatabaseRelease_0, ISpatialReference ispatialReference_0, bool bool_0) { if (ispatialReference_0 != null) { bool geoDatasetPrecision = GeodatabaseTools.GetGeoDatasetPrecision(igeodatabaseRelease_0); IControlPrecision2 controlPrecision = ispatialReference_0 as IControlPrecision2; if (controlPrecision.IsHighPrecision != geoDatasetPrecision) { controlPrecision.IsHighPrecision = geoDatasetPrecision; double num; double num2; double num3; double num4; ispatialReference_0.GetDomain(out num, out num2, out num3, out num4); if (bool_0) { ISpatialReferenceResolution spatialReferenceResolution = ispatialReference_0 as ISpatialReferenceResolution; spatialReferenceResolution.ConstructFromHorizon(); spatialReferenceResolution.SetDefaultXYResolution(); ISpatialReferenceTolerance spatialReferenceTolerance = ispatialReference_0 as ISpatialReferenceTolerance; spatialReferenceTolerance.SetDefaultXYTolerance(); } } } }
private ISpatialReference GetSpatialReference(int xyCoordinateSystem) { const bool IsHighPrecision = true; ISpatialReference spatialReference; ISpatialReferenceFactory3 spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); spatialReference = spatialReferenceFactory.CreateSpatialReference(xyCoordinateSystem); IControlPrecision2 controlPrecision = spatialReference as IControlPrecision2; controlPrecision.IsHighPrecision = IsHighPrecision; ISpatialReferenceResolution spatialReferenceResolution = spatialReference as ISpatialReferenceResolution; spatialReferenceResolution.ConstructFromHorizon(); spatialReferenceResolution.SetDefaultXYResolution(); spatialReferenceResolution.SetDefaultZResolution(); spatialReferenceResolution.SetDefaultMResolution(); ISpatialReferenceTolerance spatialReferenceTolerance = spatialReference as ISpatialReferenceTolerance; spatialReferenceTolerance.SetDefaultXYTolerance(); spatialReferenceTolerance.SetDefaultZTolerance(); spatialReferenceTolerance.SetDefaultMTolerance(); return(spatialReference); }
/// <summary> /// 创建Dataset /// </summary> /// <param name="wsTarget"></param> /// <param name="pSpatialRef"></param> /// <returns></returns> protected virtual IFeatureDataset CreateFeatureDataset(IWorkspace wsTarget, ISpatialReference pSpatialRef) { if (wsTarget == null) { return(null); } try { if (pSpatialRef == null) { pSpatialRef = new UnknownCoordinateSystemClass(); ISpatialReferenceTolerance pSpatialTolerance = pSpatialRef as ISpatialReferenceTolerance; double dXYTolerance = pSpatialTolerance.XYTolerance; double dZTolerance = pSpatialTolerance.ZTolerance; ISpatialReferenceResolution pSpatialRefResolution = pSpatialRef as ISpatialReferenceResolution; pSpatialRefResolution.set_XYResolution(true, dXYTolerance * 0.1); pSpatialRefResolution.set_ZResolution(true, dZTolerance * 0.1); pSpatialRefResolution.MResolution = pSpatialTolerance.MTolerance * 0.1; } return(((IFeatureWorkspace)wsTarget).CreateFeatureDataset(COMMONCONST.Dataset_Name, pSpatialRef)); } catch (Exception ex) { SendMessage(enumMessageType.Exception, string.Format("创建Dataset时出错,信息:{0}", ex.Message)); return(null); } }
/// <summary> // 创建要素数据集 /// </summary> /// <param name="workspace"></param> /// <param name="code"></param> /// <param name="datasetName"></param> /// <returns></returns> public IFeatureDataset CreateFeatureClass(IWorkspace workspace, int code, string datasetName) { IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)workspace; //创建一个要素集创建一个投影 ISpatialReferenceFactory spatialRefFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialRefFactory.CreateProjectedCoordinateSystem(code); //确定是否支持高精度存储空间 Boolean supportsHighPrecision = false; IWorkspaceProperties workspaceProperties = (IWorkspaceProperties)workspace; IWorkspaceProperty workspaceProperty = workspaceProperties.get_Property (esriWorkspacePropertyGroupType.esriWorkspacePropertyGroup, (int)esriWorkspacePropertyType.esriWorkspacePropSupportsHighPrecisionStorage); if (workspaceProperty.IsSupported) { supportsHighPrecision = Convert.ToBoolean(workspaceProperty.PropertyValue); } //设置投影精度 IControlPrecision2 controlPrecision = (IControlPrecision2)spatialReference; controlPrecision.IsHighPrecision = supportsHighPrecision; //设置容差 ISpatialReferenceResolution spatialRefResolution = (ISpatialReferenceResolution)spatialReference; spatialRefResolution.ConstructFromHorizon(); spatialRefResolution.SetDefaultXYResolution(); ISpatialReferenceTolerance spatialRefTolerance = (ISpatialReferenceTolerance)spatialReference; spatialRefTolerance.SetDefaultXYTolerance(); //创建要素集 IFeatureDataset featureDataset = featureWorkspace.CreateFeatureDataset(datasetName, spatialReference); return(featureDataset); }
/// <summary> /// 创建要素集 20110919 xisheng /// </summary> /// <param name="feaworkspace">指定工作空间</param> /// <param name="datasetname">指定要素集名称</param> /// <param name="PrjPath">空间参考</param> /// <returns></returns> private static IFeatureDataset CreateFeatureDataset(IFeatureWorkspace feaworkspace, string datasetname, string PrjPath) { try { string spatialPath = PrjPath; ISpatialReferenceFactory pSpaReferenceFac = new SpatialReferenceEnvironmentClass(); //空间参考工厂 ISpatialReference pSpatialReference = null; //用来获得空间参考 if (File.Exists(spatialPath)) { pSpatialReference = pSpaReferenceFac.CreateESRISpatialReferenceFromPRJFile(spatialPath); } if (pSpatialReference == null) { pSpatialReference = new UnknownCoordinateSystemClass(); } //设置默认的Resolution ISpatialReferenceResolution pSpatiaprefRes = pSpatialReference as ISpatialReferenceResolution; pSpatiaprefRes.ConstructFromHorizon();//Defines the XY resolution and domain extent of this spatial reference based on the extent of its horizon pSpatiaprefRes.SetDefaultXYResolution(); pSpatiaprefRes.SetDefaultZResolution(); pSpatiaprefRes.SetDefaultMResolution(); //设置默认的Tolerence ISpatialReferenceTolerance pSpatialrefTole = pSpatiaprefRes as ISpatialReferenceTolerance; pSpatialrefTole.SetDefaultXYTolerance(); pSpatialrefTole.SetDefaultZTolerance(); pSpatialrefTole.SetDefaultMTolerance(); //创建数据集 IFeatureDataset pFeatureDataset = null;//定义数据集用来装载要素类 pFeatureDataset = feaworkspace.CreateFeatureDataset(datasetname, pSpatialReference); return(pFeatureDataset); } catch (Exception e) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(e, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(e, null, DateTime.Now); } //******************************************************************** return(null); } }
/// <summary> /// 根据某一图层的范围,创建mdb文件中的featuredataset及其空间范围 /// </summary> /// <param name="motherWs">要创建featuredataset的工作空间</param> /// <param name="pGeoDataset">featuredataset所要依据的空间参考和空间范围</param> /// 这个函数要改!! public static void CreateDatasetInWs(IWorkspace motherWs, IGeoDataset pGeoDataset, string datasetName) { try { ISpatialReference pSpatialRef = null; IFeatureDataset pFtDs = null; if (pGeoDataset != null) { pSpatialRef = pGeoDataset.SpatialReference; IControlPrecision2 controlPrecision2 = pSpatialRef as IControlPrecision2; if (!controlPrecision2.IsHighPrecision) { controlPrecision2.IsHighPrecision = true; } IEnvelope pEnv = pGeoDataset.Extent; pEnv.Expand(1.5, 1.5, true); pSpatialRef.SetDomain(pEnv.XMin, pEnv.XMax, pEnv.YMin, pEnv.YMax); ISpatialReferenceTolerance pSpatialTolerance = (ISpatialReferenceTolerance)pSpatialRef; double dXYTolerance = pSpatialTolerance.XYTolerance; double dZTolerance = pSpatialTolerance.ZTolerance; ISpatialReferenceResolution pSpatialRefResolution = (ISpatialReferenceResolution)pSpatialRef; pSpatialRefResolution.set_XYResolution(true, dXYTolerance * 0.1); pSpatialRefResolution.set_ZResolution(true, dZTolerance * 0.1); pSpatialRefResolution.MResolution = pSpatialTolerance.MTolerance * 0.1; pFtDs = ((IFeatureWorkspace)motherWs).CreateFeatureDataset(datasetName, pSpatialRef); } else { pSpatialRef = new UnknownCoordinateSystemClass(); ISpatialReferenceTolerance pSpatialTolerance = (ISpatialReferenceTolerance)pSpatialRef; double dXYTolerance = pSpatialTolerance.XYTolerance; double dZTolerance = pSpatialTolerance.ZTolerance; ISpatialReferenceResolution pSpatialRefResolution = (ISpatialReferenceResolution)pSpatialRef; pSpatialRefResolution.set_XYResolution(true, dXYTolerance * 0.1); pSpatialRefResolution.set_ZResolution(true, dZTolerance * 0.1); pSpatialRefResolution.MResolution = pSpatialTolerance.MTolerance * 0.1; pFtDs = ((IFeatureWorkspace)motherWs).CreateFeatureDataset(datasetName, pSpatialRef); } } catch (Exception exp) { Hy.Common.Utility.Log.OperationalLogManager.AppendMessage(exp.ToString()); } }
public IFeatureClass CreateFeatureClassToAccessDB(string featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace) { //创建字段集合 IFields pFields = new FieldsClass(); IFieldsEdit pFieldsEdit = (IFieldsEdit)pFields; //定义单个的字段 IField pField = new FieldClass(); IFieldEdit pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = "OID"; pFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; pFieldsEdit.AddField(pField); //为要素类创建几何定义和空间参考 IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit pGeoDefEdit = geometryDef as IGeometryDefEdit; pGeoDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; //指定创建的要素类的要素类型 ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_Beijing1954); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); pGeoDefEdit.SpatialReference_2 = spatialReference; //设置要素类的空间参考 //将几何字段添加到字段集合 IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; pFieldsEdit.AddField(geometryField); //创建字段name IField nameField = new FieldClass(); IFieldEdit nameFieldEdit = (IFieldEdit)nameField; nameFieldEdit.Name_2 = "Name"; nameFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; nameFieldEdit.Length_2 = 20; pFieldsEdit.AddField(nameField); IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, pFields, null, classExtensionUID, esriFeatureType.esriFTSimple, "Shape", ""); return(featureClass); }
public static ISpatialReference ConstructCoordinateSystem(IGeodatabaseRelease igeodatabaseRelease_0) { bool geoDatasetPrecision = GeodatabaseTools.GetGeoDatasetPrecision(igeodatabaseRelease_0); ISpatialReference spatialReference = new UnknownCoordinateSystem() as ISpatialReference; IControlPrecision2 controlPrecision = spatialReference as IControlPrecision2; controlPrecision.IsHighPrecision = geoDatasetPrecision; ISpatialReferenceResolution spatialReferenceResolution = spatialReference as ISpatialReferenceResolution; spatialReferenceResolution.ConstructFromHorizon(); spatialReferenceResolution.SetDefaultXYResolution(); ISpatialReferenceTolerance spatialReferenceTolerance = spatialReference as ISpatialReferenceTolerance; spatialReferenceTolerance.SetDefaultXYTolerance(); return(spatialReference); }
/// <summary> /// Creates the fields for the ESRI geodatabase featureclass from the spatialite table /// </summary> /// <returns>IFields to use when building the featureclass</returns> private IFields CreateFields() { IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; // Add an object ID field to the fields collection. This is mandatory for feature classes. IField oidField = new FieldClass(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = GetEsriGeometryType(); ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = CreateSpatialReference(); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); CreateSpatialiteFields(ref fieldsEdit); return(fields); }
/// <summary> /// 创建几何空间参考 /// </summary> /// <param name="LoadPath">空间参考文件</param> /// <param name="eError"></param> /// <returns></returns> public ISpatialReference GetSpatialRef(string LoadPath, out Exception eError) { eError = null; try { ISpatialReference pSR = null; ISpatialReferenceFactory pSpatialRefFac = new SpatialReferenceEnvironmentClass(); if (!File.Exists(LoadPath)) { //eError = new Exception("空间参考文件不存在!"); return(null); } pSR = pSpatialRefFac.CreateESRISpatialReferenceFromPRJFile(LoadPath); ISpatialReferenceResolution pSRR = pSR as ISpatialReferenceResolution; ISpatialReferenceTolerance pSRT = (ISpatialReferenceTolerance)pSR; IControlPrecision2 pSpatialPrecision = (IControlPrecision2)pSR; pSRR.ConstructFromHorizon();//Defines the XY resolution and domain extent of this spatial reference based on the extent of its horizon pSRR.SetDefaultXYResolution(); pSRT.SetDefaultXYTolerance(); return(pSR); } catch (Exception ex) { //******************************************************************* //guozheng added if (ModData.SysLog != null) { ModData.SysLog.Write(ex, null, DateTime.Now); } else { ModData.SysLog = new SysCommon.Log.clsWriteSystemFunctionLog(); ModData.SysLog.Write(ex, null, DateTime.Now); } //******************************************************************** eError = ex; return(null); } }
/// <summary> /// 建立featureclass /// </summary> /// <param name="featureClassName"></param> /// <returns></returns> public IFeatureClass CreateFC(string featureClassName) { if (pWorkspace == null) { throw new NullReferenceException("尚未建立Wokspace, " + nameof(pWorkspace) + " NullReference"); } IFeatureClass pFC = null; UID pCLSID = null; if (pCLSID == null) { pCLSID = new UID(); pCLSID.Value = "esriGeoDatabase.Feature"; } IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); // create the fields using the required fields method IFields fields = objectClassDescription.RequiredFields; IFieldsEdit fieldsEdit = (IFieldsEdit)fields; // Create a geometry definition (and spatial reference) for the feature class. // GeometryType=point and SpatialReference=WGS84 IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Set spatialReference for (int i = 0; i < fields.FieldCount; i++) { var pfield = fields.get_Field(i); if (pfield.Type == esriFieldType.esriFieldTypeGeometry) { var geometryField = pfield as IFieldEdit; geometryField.GeometryDef_2 = geometryDef; Console.WriteLine(pfield.GeometryDef.SpatialReference.Name); break; } } // create a user defined text field IField field = new FieldClass(); IFieldEdit fieldEdit = (IFieldEdit)field; // setup field properties fieldEdit.Name_2 = "SampleField"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit.IsNullable_2 = true; fieldEdit.AliasName_2 = "Sample Field Column"; fieldEdit.DefaultValue_2 = "test"; fieldEdit.Editable_2 = true; fieldEdit.Length_2 = 100; // add field to field collection fieldsEdit.AddField(field); fields = (IFields)fieldsEdit; String strShapeField = ""; // locate the shape field for (int j = 0; j < fields.FieldCount; j++) { if (fields.get_Field(j).Type == esriFieldType.esriFieldTypeGeometry) { strShapeField = fields.get_Field(j).Name; } } //create feature class in memory workspace pFC = pFeatureWorkspace.CreateFeatureClass(featureClassName, fields, pCLSID, null, esriFeatureType.esriFTSimple, strShapeField, null); return(pFC); }
/// <summary> /// 创建一个要素集 /// </summary> private void CreateFeatureClass() { string path = txt_org.Text; string PRJFile = txt_prj.Text; AccessWorkspaceFactory pAccessFact = new AccessWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWorkspace = pAccessFact.OpenFromFile(path, 0) as IFeatureWorkspace; ISpatialReferenceFactory2 Isp = new SpatialReferenceEnvironmentClass(); //创建一个空间参照的接口空间 ISpatialReference spatial = Isp.CreateESRISpatialReferenceFromPRJFile(PRJFile); //利用要素类的PRJ文件参照 ISpatialReferenceResolution pSRR = (ISpatialReferenceResolution)spatial; //设置分辨率 pSRR.SetDefaultXYResolution(); //设置默认XY值 ISpatialReferenceTolerance pSRT = (ISpatialReferenceTolerance)spatial; pSRT.SetDefaultXYTolerance();//设置默认容差值 IWorkspace space = pFeatureWorkspace as IWorkspace; IEnumDatasetName Dataset_name = space.get_DatasetNames(esriDatasetType.esriDTAny);//得到有多少个要素集合名字 Dataset_name.Reset(); IDatasetName Name_set = Dataset_name.Next(); while (Name_set != null) { if (Name_set.Name == "Geo_Topo_ice") { SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数据集已存在,不用创建!"); this.Close();//如果要创建的数据集已存在,就返回,并关闭窗体 return; } Name_set = Dataset_name.Next(); } IFeatureDataset pfd = pFeatureWorkspace.CreateFeatureDataset("Geo_Topo_ice", spatial); //创建一个要素集 IEnumDataset dst = space.get_Datasets(esriDatasetType.esriDTAny); //得到所有的要素类的一个集合 dst.Reset(); IDataset det = dst.Next(); _AppHk.OperatorTips = "开始创建对应的要素类..."; while (det != null) { #region 给要素集创建空的要素类 if (det.Type == esriDatasetType.esriDTFeatureClass) //判定是不是要素类 { string org_name = det.Name; //原始的名字 _AppHk.OperatorTips = "开始创建" + org_name + "要素类..."; IFeatureClass f_class = pFeatureWorkspace.OpenFeatureClass(org_name); //打开源要素类 det.Rename(org_name + "_t"); //把源要素类进行重命名 IFields Fieldset = new FieldsClass(); //建立一个字段集 IFieldsEdit sField = Fieldset as IFieldsEdit; //字段集 if (f_class.FeatureType != esriFeatureType.esriFTAnnotation) { //shape IGeometryDefEdit d_edit; //定义一个用来接收要素类的SHAPE类型 d_edit = new GeometryDefClass(); //实例一个操作类 d_edit.GeometryType_2 = f_class.ShapeType; //将源要素类的SHAPE赋值给我们要创建的几何类型 d_edit.SpatialReference_2 = spatial; //空间参考 string OID = f_class.OIDFieldName; //ODI名字 string SHAPE = f_class.ShapeFieldName; //SHAPE名字 //IFields Fieldset = new FieldsClass();//建立一个字段集 //IFieldsEdit sField = Fieldset as IFieldsEdit;//字段集 //创建要素类里的字段 int count = f_class.Fields.FieldCount;//确定有多少个字段 #region 创建字段 for (int n = 0; n < count; n++) { IField f_ield = f_class.Fields.get_Field(n); IFieldEdit fieldEdit = f_ield as IFieldEdit; //Annotate if (f_ield.Name == SHAPE) { //shape field fieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; //确定字段的类型 fieldEdit.GeometryDef_2 = d_edit; //把几何类型赋值给它 fieldEdit.Name_2 = SHAPE; //把几何类型SHPAE的名字赋值给它 f_ield = fieldEdit as IField; sField.AddField(f_ield); //加入要素集 } else if (f_ield.Name == OID) { //oid fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; //OID标识字段 fieldEdit.Name_2 = OID; //OID的名字 f_ield = fieldEdit as IField; sField.AddField(f_ield); //加入OID } else { //一般字段 fieldEdit.Name_2 = f_ield.Name; fieldEdit.Type_2 = f_ield.Type;//字段的类型 f_ield = fieldEdit as IField; sField.AddField(f_ield); } } #endregion Fieldset = sField as IFields; //将可编辑的字段集转成一般字段集 pfd.CreateFeatureClass(org_name, Fieldset, f_class.CLSID, null, esriFeatureType.esriFTSimple, SHAPE, ""); //给要素集中创建要素类 } else { createAnnoFeatureClass(org_name, pfd, pfd.Workspace as IFeatureWorkspace, sField, 2000); } det = dst.Next();//重新遍历下一个 } else { det = dst.Next();//重新遍历下一个 } #endregion } _AppHk.OperatorTips = "要素集合创建成功!"; GetValue(pFeatureWorkspace);//当对应的要素类建立好后,就开始给空要素类赋值 SysCommon.Error.ErrorHandle.ShowFrmErrorHandle("提示", "数据处理完成!"); this.Close(); }
protected override void OnMouseDown(MouseEventArgs arg) { IFeatureLayer pPointLayer = null; IFeatureLayer pLineLayer = null; IArray pParcelLayers = null; IFeatureLayer pControlLayer = null; IFeatureLayer pLinePointLayer = null; double dXYTol = 0.003; clsFabricUtils FabricUTILS = new clsFabricUtils(); IEditor pEd = (IEditor)ArcMap.Application.FindExtensionByName("esri object editor"); //first get the extension UID pUID = new UIDClass(); pUID.Value = "{114D685F-99B7-4B63-B09F-6D1A41A4DDC1}"; ICadastralExtensionManager2 pCadExtMan = (ICadastralExtensionManager2)ArcMap.Application.FindExtensionByCLSID(pUID); ICadastralEditor pCadEd = (ICadastralEditor)ArcMap.Application.FindExtensionByCLSID(pUID); //check if there is a Manual Mode "modify" job active =========== ICadastralPacketManager pCadPacMan = (ICadastralPacketManager)pCadExtMan; if (pCadPacMan.PacketOpen) { FabricUTILS.ExecuteCommand(m_CommUID); MessageBox.Show("This tool cannot be used when there is an open parcel, construction, or job.\r\nPlease complete or discard the open items, and try again."); return; } ICadastralFabric pCadFabric = null; //if we're in an edit session then grab the target fabric if (pEd.EditState == esriEditState.esriStateEditing) { pCadFabric = pCadEd.CadastralFabric; } else { FabricUTILS.ExecuteCommand(m_CommUID); MessageBox.Show("This tool works on a parcel fabric in an edit session.\r\nPlease start editing and try again."); return; } if (pCadFabric == null) {//find the first fabric in the map if (!FabricUTILS.GetFabricFromMap(ArcMap.Document.ActiveView.FocusMap, out pCadFabric)) { FabricUTILS.ExecuteCommand(m_CommUID); MessageBox.Show("No Parcel Fabric found in the map.\r\nPlease add a single fabric to the map, and try again."); return; } } IGeoDataset pGeoDS = (IGeoDataset)pCadFabric; ISpatialReferenceTolerance pSpatRefTol = (ISpatialReferenceTolerance)pGeoDS.SpatialReference; if (pSpatRefTol.XYToleranceValid == esriSRToleranceEnum.esriSRToleranceOK) { dXYTol = pSpatRefTol.XYTolerance; } IMouseCursor pMouseCursor = null; ISpatialFilter pSpatFilt = null; //spatial filter query hinging off the dragged rectangle selection IQueryFilter pQuFilter = null; //used for the non-spatial query for radial lines, as they have no geometry IRubberBand2 pRubberRect = null; IGeometryBag pGeomBag = null; ITopologicalOperator5 pUnionedPolyine = null; IPolygon pBufferedToolSelectGeometry = null; //geometry used to search for parents IFIDSet pLineFIDs = null; //the FIDSet used to collect the lines that'll be deleted IFIDSet pPointFIDs = null; // the FIDSet used to collect the points that'll be deleted IFIDSet pLinePointFIDs = null; // the FIDSet used to collect the line-points that'll be deleted List <int> pDeletedLinesPoints = new List <int>(); //list used to stage the ids for points that are referenced by lines List <int> pUsedPoints = new List <int>(); //list used to collect pointids that are referenced by existing lines List <int> CtrPointIDList = new List <int>(); //list for collecting the ids of center points List <int> pParcelsList = new List <int>(); //used only to avoid adding duplicates to IN clause string for, based on ties to radial lines List <int> pOrphanPointsList = new List <int>(); //list of orphan points defined from radial ines List <int> pPointsInsideBoxList = new List <int>(); //list of parcels that exist and that intersect the drag-box List <string> sFromToPair = new List <string>(); //list of from/to pairs for manging line points List <int> pLineToParcelIDRef = new List <int>(); //list of parcel id refs stored on lines IInvalidArea3 pInvArea = null; IFeatureClass pLines = null; IFeatureClass pPoints = null; IFeatureClass pParcels = null; IFeatureClass pLinePoints = null; IWorkspace pWS = null; try { #region define the rubber envelope geometry pRubberRect = new RubberEnvelopeClass(); IGeometry ToolSelectEnvelope = pRubberRect.TrackNew(ArcMap.Document.ActiveView.ScreenDisplay, null); if (ToolSelectEnvelope == null) { return; } ISegmentCollection pSegmentColl = new PolygonClass(); pSegmentColl.SetRectangle(ToolSelectEnvelope.Envelope); IPolygon ToolSelectGeometry = (IPolygon)pSegmentColl; if (pCadFabric == null) { return; } pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); #endregion FabricUTILS.GetFabricSubLayersFromFabric(ArcMap.Document.ActiveView.FocusMap, pCadFabric, out pPointLayer, out pLineLayer, out pParcelLayers, out pControlLayer, out pLinePointLayer); #region get tables and field indexes pLines = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLines); pPoints = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); pParcels = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); pLinePoints = (IFeatureClass)pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTLinePoints); string sPref = ""; string sSuff = ""; int iCtrPtFldIDX = pLines.FindField("CENTERPOINTID"); int iFromPtFldIDX = pLines.FindField("FROMPOINTID"); int iToPtFldIDX = pLines.FindField("TOPOINTID"); int iCatFldIDX = pLines.FindField("CATEGORY"); int iParcelIDX = pLines.FindField("PARCELID"); int iDistanceIDX = pLines.FindField("DISTANCE"); pWS = pLines.FeatureDataset.Workspace; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); pSpatFilt = new SpatialFilterClass(); pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatFilt.Geometry = ToolSelectGeometry; #endregion #region center point //need to make sure that center points are correctly handled for cases where the center point //is inside the select box, but the curve itself is not. The following is used to build an //IN CLAUSE for All the center points that are found within the tool's select geometry. int iIsCtrPtIDX = pPoints.FindField("CENTERPOINT"); int iCount = 0; int iCntCtrPoint = 0; string sCtrPntIDList1 = ""; IFeatureCursor pFeatCursPoints = pPoints.Search(pSpatFilt, false); IFeature pFeat7 = pFeatCursPoints.NextFeature(); while (pFeat7 != null) { iCount++; int iVal = -1; object Attr_val = pFeat7.get_Value(iIsCtrPtIDX); if (Attr_val != DBNull.Value) { iVal = Convert.ToInt32(pFeat7.get_Value(iIsCtrPtIDX)); } if (iVal == 1) { if (sCtrPntIDList1.Trim() == "") { sCtrPntIDList1 += pFeat7.OID.ToString(); } else { sCtrPntIDList1 += "," + pFeat7.OID.ToString(); } iCntCtrPoint++; } pPointsInsideBoxList.Add(pFeat7.OID); //used to check for orphan linepoints pOrphanPointsList.Add(pFeat7.OID); //this gets whittled down till only "pure" orphan points remain Marshal.ReleaseComObject(pFeat7); pFeat7 = pFeatCursPoints.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursPoints); #endregion #region create convex hull of lines //get the lines that intersect the search box and build a //polygon search geometry being the convex hull of those lines. IFeatureCursor pFeatCursLines = pLines.Search(pSpatFilt, false); pGeomBag = new GeometryBagClass(); IGeometryCollection pGeomColl = (IGeometryCollection)pGeomBag; IFeature pFeat1 = pFeatCursLines.NextFeature(); m_sDebug = "Add lines to Geometry Collection."; string sParcelRefOnLines = ""; object missing = Type.Missing; while (pFeat1 != null) { int iVal = (int)pFeat1.get_Value(iFromPtFldIDX); string sFromTo = iVal.ToString() + ":"; if (pOrphanPointsList.Contains(iVal)) //Does this need to be done...will remove fail if it's not there? { pOrphanPointsList.Remove(iVal); //does this need to be in the if block? } iVal = (int)pFeat1.get_Value(iToPtFldIDX); sFromTo += iVal.ToString(); if (pOrphanPointsList.Contains(iVal)) { pOrphanPointsList.Remove(iVal); } sFromToPair.Add(sFromTo); pGeomColl.AddGeometry(pFeat1.ShapeCopy, missing, missing); if (sParcelRefOnLines.Trim() == "") { sParcelRefOnLines = pFeat1.get_Value(iParcelIDX).ToString(); } else { sParcelRefOnLines += "," + pFeat1.get_Value(iParcelIDX).ToString(); } Marshal.ReleaseComObject(pFeat1); pFeat1 = pFeatCursLines.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursLines); #endregion #region Add Center Points for curves outside map extent if (iCntCtrPoint > 999) { throw new InvalidOperationException("The Delete Orphans tool works with smaller amounts of data." + Environment.NewLine + "Please try again, by selecting fewer fabric lines and points. (More than 1000 center points returned.)"); } //If there is no line geometry found, and there are also no points found, then nothing to do... if (pGeomColl.GeometryCount == 0 && iCount == 0) { return; } //Radial lines have no geometry so there is a special treatment for those; //that special treatment takes two forms, //1. if a circular arc is selected and it turns out that it is an orphan line, then we //need to take down its radial lines, and its center point as well. //2. if a center point is selected, we need to check if it's an orphan, by searching for its parent. //The parent parcel can easily be well beyond the query rectangle, so the original //search rectangle is buffered by the largest found radius distance, to make sure that all //parent parcels are "find-able." //The radial lines themselves are also needed; Get the radial lines from the Center Points //CtrPt is always TO point, so find lines CATEGORY = 4 AND TOPOINT IN () string sRadialLineListParcelID = ""; string sRadialLinesID = ""; string sRadialLinePoints = ""; double dRadiusBuff = 0; pQuFilter = new QueryFilterClass(); //Find all the radial lines based on the search query if (sCtrPntIDList1.Trim() != "") { pQuFilter.WhereClause = "CATEGORY = 4 AND TOPOINTID IN (" + sCtrPntIDList1 + ")"; //add all the *references* to Parcel ids for the radial lines, //and add the ID's of the lines IFeatureCursor pFeatCursLines8 = pLines.Search(pQuFilter, false); IFeature pFeat8 = pFeatCursLines8.NextFeature(); while (pFeat8 != null) { object Attr_val = pFeat8.get_Value(iDistanceIDX); double dVal = 0; if (Attr_val != DBNull.Value) { dVal = Convert.ToDouble(Attr_val); } dRadiusBuff = dRadiusBuff > dVal ? dRadiusBuff : dVal; int iVal = Convert.ToInt32(pFeat8.get_Value(iParcelIDX)); if (!pParcelsList.Contains(iVal)) { if (sRadialLineListParcelID.Trim() == "") { sRadialLineListParcelID += Convert.ToString(iVal); } else { sRadialLineListParcelID += "," + Convert.ToString(iVal); } } pParcelsList.Add(iVal); //pOrphanPointsList is used for "Pure Orphan point" detection //meaning that these are points that do not have ANY line, not even an orphan line. iVal = (int)pFeat8.get_Value(iFromPtFldIDX); if (pOrphanPointsList.Contains(iVal)) { pOrphanPointsList.Remove(iVal); } iVal = (int)pFeat8.get_Value(iToPtFldIDX); if (pOrphanPointsList.Contains(iVal)) { pOrphanPointsList.Remove(iVal); } if (sRadialLinesID.Trim() == "") { sRadialLinesID += Convert.ToString(iVal); } else { sRadialLinesID += "," + Convert.ToString(iVal); } //Add from point to list if (sRadialLinePoints.Trim() == "") { sRadialLinePoints += Convert.ToString(pFeat8.get_Value(iFromPtFldIDX)); } else { sRadialLinePoints += "," + Convert.ToString(pFeat8.get_Value(iFromPtFldIDX)); } //Add To point to list sRadialLinePoints += "," + Convert.ToString(pFeat8.get_Value(iToPtFldIDX)); Marshal.ReleaseComObject(pFeat8); pFeat8 = pFeatCursLines8.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursLines8); //create a polygon goeometry that is a buffer of the selection rectangle expanded //to the greatest radius of all the radial lines found. ITopologicalOperator topologicalOperator = (ITopologicalOperator)ToolSelectGeometry; pBufferedToolSelectGeometry = topologicalOperator.Buffer(dRadiusBuff) as IPolygon; } else { pQuFilter.WhereClause = ""; } #endregion #region OrphanLines if (pGeomColl.GeometryCount != 0) { pUnionedPolyine = new PolylineClass(); pUnionedPolyine.ConstructUnion((IEnumGeometry)pGeomBag); ITopologicalOperator pTopoOp = (ITopologicalOperator)pUnionedPolyine; IGeometry pConvexHull = pTopoOp.ConvexHull(); //With this convex hull, do a small buffer, //theis search geometry is used as a spatial query on the parcel polygons //and also on the parcel lines, to build IN Clauses pTopoOp = (ITopologicalOperator)pConvexHull; IGeometry pBufferedConvexHull = pTopoOp.Buffer(10 * dXYTol); if (pBufferedToolSelectGeometry != null) { pTopoOp = (ITopologicalOperator)pBufferedToolSelectGeometry; IGeometry pUnionPolygon = pTopoOp.Union(pBufferedConvexHull); pSpatFilt.Geometry = pUnionPolygon; } else { pSpatFilt.Geometry = pBufferedConvexHull; } } else { if (pQuFilter.WhereClause.Trim() == "" && pBufferedToolSelectGeometry == null) { pSpatFilt.Geometry = ToolSelectGeometry; } else { pSpatFilt.Geometry = pBufferedToolSelectGeometry; } } IColor pColor = new RgbColorClass(); pColor.RGB = System.Drawing.Color.Blue.ToArgb(); IScreenDisplay pScreenDisplay = ArcMap.Document.ActiveView.ScreenDisplay; FabricUTILS.FlashGeometry(pSpatFilt.Geometry, pScreenDisplay, pColor, 5, 100); pSpatFilt.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; m_sDebug = "Searching Parcels table."; pInvArea = new InvalidAreaClass(); IFeatureCursor pFeatCursParcels = pParcels.Search(pSpatFilt, false); IFeature pFeat2 = pFeatCursParcels.NextFeature(); string sParcelIDList = ""; iCount = 0; //create the "NOT IN" CLAUSE for parcels that exist in the DB and that are within the search area //Will be used as a search on lines to get the Orphan Lines while (pFeat2 != null) { iCount++; if (sParcelIDList.Trim() == "") { sParcelIDList += pFeat2.OID.ToString(); } else { sParcelIDList += "," + pFeat2.OID.ToString(); } Marshal.ReleaseComObject(pFeat2); if (iCount > 999) { break; } pFeat2 = pFeatCursParcels.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursParcels); //if we have more than 999 in clause tokens, there will be problems on Oracle. //Since this is an interactive tool, we expect it not to be used on a large amount of data. //for this reason, the following message is displayed if more than 999 parcels are returned in this query. //TODO: for the future this can be made to work on larger sets of data. if (iCount > 999) { throw new InvalidOperationException("The Delete Orphans tool works with smaller amounts of data." + Environment.NewLine + "Please try again, by selecting fewer fabric lines and points. (More than 1000 parcels returned.)"); } m_sDebug = "Building the used points list."; //This first pass contains all references to points found within the parent parcel search buffer //Later, points are removed from this list IFeatureCursor pFeatCursLargerLineSet = pLines.Search(pSpatFilt, false); IFeature pFeat3 = pFeatCursLargerLineSet.NextFeature(); while (pFeat3 != null) { iCount++; object Attr_val = pFeat3.get_Value(iCtrPtFldIDX); if (Attr_val != DBNull.Value) { pUsedPoints.Add(Convert.ToInt32(Attr_val)); //add center point } int iVal = (int)pFeat3.get_Value(iFromPtFldIDX); pUsedPoints.Add(iVal);//add from point iVal = (int)pFeat3.get_Value(iToPtFldIDX); pUsedPoints.Add(iVal);//add to point Marshal.ReleaseComObject(pFeat3); pFeat3 = pFeatCursLargerLineSet.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursLargerLineSet); //pUsedPoints list is at this stage, references to points for all lines found within the search area. //use the IN clause of the parcel ids to search for lines within //the original search box, and that are also orphans that do not have a parent parcel. pSpatFilt.WhereClause = ""; pSpatFilt.Geometry = ToolSelectGeometry; pSpatFilt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; pSpatFilt.SearchOrder = esriSearchOrder.esriSearchOrderSpatial; IFeatureCursor pFeatCursor = null; if (pGeomColl.GeometryCount == 0) { if (sParcelIDList.Trim().Length > 0 && sCtrPntIDList1.Trim().Length > 0) { pQuFilter.WhereClause = "(PARCELID NOT IN (" + sParcelIDList + ")) AND (CATEGORY = 4 AND TOPOINTID IN (" + sCtrPntIDList1 + "))"; pFeatCursor = pLines.Search(pQuFilter, false); } else if (sParcelIDList.Trim().Length == 0 && sCtrPntIDList1.Trim().Length > 0) { pQuFilter.WhereClause = "CATEGORY = 4 AND TOPOINTID IN (" + sCtrPntIDList1 + ")"; pFeatCursor = pLines.Search(pQuFilter, false); } } else {//do a spatial query if (sParcelIDList.Trim().Length > 0) { pSpatFilt.WhereClause = "PARCELID NOT IN (" + sParcelIDList + ")"; } else { pSpatFilt.WhereClause = ""; } pFeatCursor = pLines.Search(pSpatFilt, false); } m_sDebug = "Collecting lines to be deleted."; //start collecting the lines that need to be deleted iCount = 0; int iCtrPointCount = 0; string sCtrPointIDList = ""; string sLineParcelIDReference = ""; //Feature cursor is lines that are NOT IN the ParcelIDList if (pFeatCursor != null) { pLineFIDs = new FIDSetClass(); IFeature pFeat4 = pFeatCursor.NextFeature(); while (pFeat4 != null) { iCount++; pLineFIDs.Add(pFeat4.OID); int iParcRef = Convert.ToInt32(pFeat4.get_Value(iParcelIDX)); if (sLineParcelIDReference.Trim() == "") { sLineParcelIDReference = iParcRef.ToString(); } else { if (!pLineToParcelIDRef.Contains(iParcRef)) { sLineParcelIDReference += "," + iParcRef.ToString(); } } pLineToParcelIDRef.Add(iParcRef); pInvArea.Add((IObject)pFeat4); //now for this line, get it's points //first add the center point reference if there is one object Attr_val = pFeat4.get_Value(iCtrPtFldIDX); if (Attr_val != DBNull.Value) { iCtrPointCount++; int iCtrPointID = Convert.ToInt32(Attr_val); pDeletedLinesPoints.Add(iCtrPointID); //add this line's center point pUsedPoints.Remove(iCtrPointID); if (sCtrPointIDList.Trim() == "") { sCtrPointIDList = iCtrPointID.ToString(); } else { if (CtrPointIDList.Contains(iCtrPointID)) { iCtrPointCount--; } else { sCtrPointIDList += "," + iCtrPointID.ToString(); } } CtrPointIDList.Add(iCtrPointID);//to keep track of repeats } //and also add the FROM and TO point references if they exist int iVal = (int)pFeat4.get_Value(iFromPtFldIDX); pDeletedLinesPoints.Add(iVal);//add FROM point if (pGeomColl.GeometryCount > 0) { pUsedPoints.Remove(iVal); } iVal = (int)pFeat4.get_Value(iToPtFldIDX); pDeletedLinesPoints.Add(iVal);//add TO point if (pGeomColl.GeometryCount > 0) { pUsedPoints.Remove(iVal); } Marshal.ReleaseComObject(pFeat4); if (iCtrPointCount > 999) { break; } pFeat4 = pFeatCursor.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursor); } if (iCtrPointCount > 999) { throw new InvalidOperationException("The Delete Orphans tool works with smaller amounts of data." + Environment.NewLine + "Please try again, by selecting fewer fabric lines and points. (More than 1000 center points returned.)"); } m_sDebug = "Adding orphan radial lines to list."; if (sCtrPointIDList.Trim().Length > 0) { //add the Radial lines at each end of the curves using the collected CtrPtIDs //CtrPt is always TO point, so find lines CATEGORY = 4 AND TOPOINT IN () pQuFilter.WhereClause = "CATEGORY = 4 AND TOPOINTID IN (" + sCtrPointIDList + ")"; pFeatCursor = pLines.Search(pQuFilter, false); IFeature pFeat5 = pFeatCursor.NextFeature(); while (pFeat5 != null) { pLineFIDs.Add(pFeat5.OID); int iParcRef = Convert.ToInt32(pFeat5.get_Value(iParcelIDX)); pLineToParcelIDRef.Add(iParcRef); if (sLineParcelIDReference.Trim() == "") { sLineParcelIDReference = iParcRef.ToString(); } else { if (!pLineToParcelIDRef.Contains(iParcRef)) { sLineParcelIDReference += "," + iParcRef.ToString(); } } Marshal.ReleaseComObject(pFeat5); pFeat5 = pFeatCursor.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursor); } else { pQuFilter.WhereClause = ""; } //refine the DeletedLinesPoints list foreach (int i in pUsedPoints) { if (pDeletedLinesPoints.Contains(i)) { do { } while (pDeletedLinesPoints.Remove(i)); } } //add the points to a new FIDSet pPointFIDs = new FIDSetClass(); foreach (int i in pDeletedLinesPoints) { pPointFIDs.Add(i); } #endregion #region OrphanPoints //We already know which points to delete based on taking down the orphan lines. //We need to still add to the points FIDSet those points that are "pure" ophan points //as defined for the pOrphanPointsList variable. //and add the orphan points to the points FIDSet foreach (int i in pOrphanPointsList) { bool bFound = false; pPointFIDs.Find(i, out bFound); if (!bFound) { pPointFIDs.Add(i); } } #endregion #region orphan Line points //next check for orphan line-points //the line-point is deleted if there is no underlying point //or if the from and to point references do not exist. pSpatFilt.WhereClause = ""; pSpatFilt.Geometry = ToolSelectGeometry; IFeatureCursor pFeatCursLinePoints = pLinePoints.Search(pSpatFilt, false); IFeature pLPFeat = pFeatCursLinePoints.NextFeature(); int iLinePtPointIdIdx = pLinePoints.FindField("LINEPOINTID"); int iLinePtFromPtIdIdx = pLinePoints.FindField("FROMPOINTID"); int iLinePtToPtIdIdx = pLinePoints.FindField("TOPOINTID"); pLinePointFIDs = new FIDSetClass(); while (pLPFeat != null) { bool bExistsA = true; bool bExists1 = true; bool bExists2 = true; bool bExists3 = true; int iVal = (int)pLPFeat.get_Value(iLinePtPointIdIdx); pPointFIDs.Find(iVal, out bExists1); if (!pPointsInsideBoxList.Contains(iVal)) { bExistsA = false; } iVal = (int)pLPFeat.get_Value(iLinePtFromPtIdIdx); string sFrom = iVal.ToString(); pPointFIDs.Find(iVal, out bExists2); iVal = (int)pLPFeat.get_Value(iLinePtToPtIdIdx); string sTo = iVal.ToString(); pPointFIDs.Find(iVal, out bExists3); int iOID = pLPFeat.OID; if (bExists1 || bExists2 || bExists3) { pLinePointFIDs.Add(iOID); } if (!sFromToPair.Contains(sFrom + ":" + sTo) && !sFromToPair.Contains(sTo + ":" + sFrom)) { pLinePointFIDs.Find(iOID, out bExists1); if (!bExists1) { pLinePointFIDs.Add(iOID); } } //if (!bExistsA || !bExistsB || !bExistsC) if (!bExistsA) { bool bFound = true; pLinePointFIDs.Find(iOID, out bFound); if (!bFound) { pLinePointFIDs.Add(iOID); } } pPointsInsideBoxList.Contains(iVal); Marshal.ReleaseComObject(pLPFeat); pLPFeat = pFeatCursLinePoints.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursLinePoints); #endregion #region Refine the lines that are on the delete list //next step is to refine and double-check to make sure that the lines that are on the delete list //do not have a parcel record somewhere else (not spatially connected to the line) (example unjoined, or bad geom) string sFreshlyFoundParcels = ""; if (sLineParcelIDReference.Trim() != "") { pQuFilter.WhereClause = sPref + pParcels.OIDFieldName + sSuff + " IN (" + sLineParcelIDReference + ")"; pFeatCursor = pParcels.Search(pQuFilter, false); IFeature pFeat6 = pFeatCursor.NextFeature(); while (pFeat6 != null) { int iOID = pFeat6.OID; if (sFreshlyFoundParcels.Trim() == "") { sFreshlyFoundParcels = iOID.ToString(); } else { sFreshlyFoundParcels += "," + iOID.ToString(); } Marshal.ReleaseComObject(pFeat6); pFeat6 = pFeatCursor.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursor); if (sFreshlyFoundParcels.Trim() != "") { pQuFilter.WhereClause = "PARCELID IN (" + sFreshlyFoundParcels + ")"; pFeatCursor = pLines.Search(pQuFilter, false); IFeature pFeat9 = pFeatCursor.NextFeature(); while (pFeat9 != null) { int iOID = pFeat9.OID; bool bIsHere = false; pLineFIDs.Delete(iOID); int iVal = Convert.ToInt32(pFeat9.get_Value(iFromPtFldIDX)); pPointFIDs.Find(iVal, out bIsHere); if (bIsHere) { pPointFIDs.Delete(iVal); } iVal = Convert.ToInt32(pFeat9.get_Value(iToPtFldIDX)); pPointFIDs.Find(iVal, out bIsHere); if (bIsHere) { pPointFIDs.Delete(iVal); } Marshal.ReleaseComObject(pFeat9); pFeat9 = pFeatCursor.NextFeature(); } Marshal.FinalReleaseComObject(pFeatCursor); } } #endregion #region Make sure the points on the delete list are not part of a construction //For post 10.0, Make sure the points on the delete list are not part of a construction if they are then null geometry //pQuFilter.WhereClause=pLines.LengthField.Name + " = 0 AND CATEGORY <> 4"; //IFeatureCursor pFeatCursLines101 = pLines.Search(pQuFilter, false); //this would open a new cursor and do a query on the entire #endregion #region report results and do edits dlgReport Report = new dlgReport(); //Display the dialog System.Drawing.Color BackColorNow = Report.textBox1.BackColor; if (iCount == 0 && pPointFIDs.Count() == 0 && pLinePointFIDs.Count() == 0) { Report.textBox1.BackColor = System.Drawing.Color.LightGreen; Report.textBox1.Text = "Selected area has no orphan lines or points."; } else { int iCount1 = 0; int iCount2 = 0; int iCount3 = 0; if (pLineFIDs != null) { iCount1 = pLineFIDs.Count(); } if (pPointFIDs != null) { iCount2 = pPointFIDs.Count(); } if (pLinePointFIDs != null) { iCount3 = pLinePointFIDs.Count(); } iCount = iCount1 + iCount2 + iCount3; if (iCount > 0) { pEd.StartOperation(); FabricUTILS.DeleteRowsByFIDSet((ITable)pLines, pLineFIDs, null, null); FabricUTILS.DeleteRowsByFIDSet((ITable)pPoints, pPointFIDs, null, null); if (pPointFIDs.Count() > 0) { //now need to update the control points associated with any deleted points. ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)pCadFabric; ITable pControlTable = pCadFabric.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); int idxNameFldOnControl = pControlTable.FindField("POINTID"); string ControlNameFldName = pControlTable.Fields.get_Field(idxNameFldOnControl).Name; int i; List <int> pPointFIDList = new List <int>(); pPointFIDs.Reset(); pPointFIDs.Next(out i); while (i > -1) { pPointFIDList.Add(i); pPointFIDs.Next(out i); } List <string> InClausePointsNotConnectedToLines = FabricUTILS.InClauseFromOIDsList(pPointFIDList, 995); pQuFilter.WhereClause = ControlNameFldName + " IN (" + InClausePointsNotConnectedToLines[0] + ")"; pSchemaEd.ReleaseReadOnlyFields(pControlTable, esriCadastralFabricTable.esriCFTControl); //release safety-catch if (!FabricUTILS.ResetControlAssociations(pControlTable, pQuFilter, false)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);//set safety back on pEd.AbortOperation(); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl);//set safety back on } pQuFilter.WhereClause = ""; FabricUTILS.DeleteRowsByFIDSet((ITable)pLinePoints, pLinePointFIDs, null, null); pEd.StopOperation("Delete " + iCount.ToString() + " orphans"); Report.textBox1.Text = "Deleted:"; if (iCount1 > 0) { Report.textBox1.Text += Environment.NewLine + iCount1.ToString() + " orphaned lines"; } if (iCount2 > 0) { Report.textBox1.Text += Environment.NewLine + iCount2.ToString() + " orphaned points"; } if (iCount3 > 0) { Report.textBox1.Text += Environment.NewLine + iCount3.ToString() + " orphaned line points"; } } if (sFreshlyFoundParcels.Trim() != "") { if (Report.textBox1.Text.Trim() != "") { Report.textBox1.Text += Environment.NewLine; } Report.textBox1.Text += "Info: Line(s) that you selected are not directly" + Environment.NewLine + "touching a parent parcel geometry. Check parcels with OIDs:" + sFreshlyFoundParcels; } } IArea pArea = (IArea)ToolSelectGeometry; if (pArea.Area > 0) { SetDialogLocationAtPoint(Report, pArea.Centroid); } DialogResult pDialogResult = Report.ShowDialog(); Report.textBox1.BackColor = BackColorNow; pInvArea.Display = ArcMap.Document.ActiveView.ScreenDisplay; pInvArea.Invalidate((short)esriScreenCache.esriAllScreenCaches); if (pPointLayer != null) { ArcMap.Document.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, pPointLayer, ArcMap.Document.ActiveView.Extent); } #endregion } catch (Exception ex) { if (pEd != null) { pEd.AbortOperation(); } MessageBox.Show(ex.Message + Environment.NewLine + m_sDebug, "Delete Orphans Tool"); this.OnDeactivate(); } #region Final Cleanup finally { pDeletedLinesPoints.Clear(); pDeletedLinesPoints = null; pUsedPoints.Clear(); pUsedPoints = null; CtrPointIDList.Clear(); CtrPointIDList = null; pParcelsList.Clear(); pParcelsList = null; pOrphanPointsList.Clear(); pOrphanPointsList = null; pPointsInsideBoxList.Clear(); pPointsInsideBoxList = null; pLineToParcelIDRef.Clear(); pLineToParcelIDRef = null; sFromToPair.Clear(); sFromToPair = null; FabricUTILS = null; } #endregion }
/// <summary> /// 创建空间参考 /// </summary> /// <param name="headNode">VCT头节点</param> private ISpatialReference CreateProjection(HeadNode headNode) { try { string sPrjInfo = ""; //根据投影参数中的长半轴值,来判断是什么坐标系统(北京54,西安80,WGS-84,其他地方坐标系) //北京54 double dMajorAxis = headNode.MajorMax.Y; //读取参考椭球的名称 (名称,长半轴,扁率的倒数) string sProjection = headNode.Spheroid.Split(',')[0]; dMajorAxis = Math.Abs(dMajorAxis - 6378245); //if (fabs( m_dSemiMajorAxis - 6378245) < 0.0001) if (dMajorAxis < 0.0001) { sPrjInfo = string.Format("PROJCS[\"{0}\",GEOGCS[\"GCS_Beijing_1954\",DATUM[\"D_Beijing_1954\"" + ",SPHEROID[\"{1}\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," + "PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",{2}],PARAMETER[\"False_Northing\",0.0]," + "PARAMETER[\"Central_Meridian\",{3}],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0]," + "UNIT[\"Meter\",1.0]]", sProjection, "Gauss-Krueger", headNode.Excursion, headNode.Parametetor.OriginLongtitude); } //西安80 else { // sPrjInfo = string.Format("PROJCS["%s\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\",SPHEROID[\"%s\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",%s],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",%f],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]", m_strProjection, m_strSpheroid, sPianYi, m_lMeridian); sPrjInfo = string.Format("PROJCS[\"{0}\",GEOGCS[\"GCS_Xian_1980\",DATUM[\"D_Xian_1980\"," + "SPHEROID[\"{1}\",6378140.0,298.257]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]]," + "PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",{2}],PARAMETER[\"False_Northing\",0.0]," + "PARAMETER[\"Central_Meridian\",{3}],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0]," + "UNIT[\"Meter\",1.0]]", sProjection, "Gauss-Krueger", headNode.Parametetor.EastOffset, headNode.Parametetor.OriginLongtitude); } //将坐标信息写入到Prj文件 string sPrjFilename = Application.StartupPath + "tempPrj.prj"; FileStream fs = File.Create(sPrjFilename); StreamWriter sw = new StreamWriter(fs); sw.Write(sPrjInfo); sw.Close(); fs.Close(); //根据Prj文件生成空间参考 ISpatialReferenceFactory ipSpatialFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference pSpatialReference = ipSpatialFactory.CreateESRISpatialReferenceFromPRJFile(sPrjFilename); pSpatialReference.SetDomain(headNode.MajorMin.X,headNode.MajorMax.X,headNode.MajorMin.Y,headNode.MajorMax.Y);// //设置精度,防止cut失败 //设置六位小数精度。以保证导出时也是六位 ISpatialReferenceTolerance ipSrTolerance = pSpatialReference as ISpatialReferenceTolerance; ipSrTolerance.XYTolerance = 0.000001; ipSrTolerance.MTolerance = 0.001; ipSrTolerance.ZTolerance = 0.001; ISpatialReferenceResolution ipSrResolution = pSpatialReference as ISpatialReferenceResolution; ipSrResolution.MResolution = 0.001; ipSrResolution.set_XYResolution(true, 0.000001); ipSrResolution.set_ZResolution(true, 0.001); //删除生成的Prj文件 File.Delete(sPrjFilename); //ISpatialReference pSpatialReference; //ISpatialReferenceFactory pSpatialreferenceFactory; //pSpatialreferenceFactory = new SpatialReferenceEnvironmentClass(); //IGeographicCoordinateSystem pGeographicCoordinateSystem; //pGeographicCoordinateSystem = pSpatialreferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCS3Type.esriSRGeoCS_Xian1980); //pSpatialReference = pGeographicCoordinateSystem as ISpatialReference; //pSpatialReference.SetFalseOriginAndUnits(-180, -90, 1000000);// return pSpatialReference; } catch (Exception ex) { LogAPI.WriteLog("创建空间参考失败,系统默认创建空的空间参考!\r\n"); LogAPI.WriteErrorLog(ex); ISpatialReference pSpatialReference = new UnknownCoordinateSystemClass(); pSpatialReference.SetDomain(headNode.MajorMin.X, headNode.MajorMax.X, headNode.MajorMin.Y, headNode.MajorMax.Y);// return pSpatialReference; } }
//创建featureclass private IFeatureClass CreateFeatureClass(string name, IWorkspace pWorkspace, UID uidCLSID, UID uidCLSEXT, IGeometry pGeometry) { try { if (uidCLSID == null) { uidCLSID = new UIDClass(); uidCLSID.Value = "{52353152-891A-11D0-BEC6-00805F7C4268}"; } // 设置 uidCLSEXT (if Null) //uidCLSEXT == null; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; IField oidField = new FieldClass(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = pGeometry.GeometryType; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = pGeometry.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = pWorkspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); IFeatureClass targetFeatureclass = null; targetFeatureclass = pFeatureWorkspace.CreateFeatureClass("" + name + "", fields, uidCLSID, uidCLSEXT, esriFeatureType.esriFTSimple, "Shape", ""); return(targetFeatureclass); } catch (Exception ex) { if (ex.Message == "Cannot create a low precision dataset in a high precision database.") { MessageBox.Show("数据必须是ArcGis9.3的数据,请将数据处理成ArcGis9.2的数据!"); } } IFeatureClass featureclass = null; return(featureclass); }
/// <summary> /// shape图层入库 /// </summary> /// <param name="sourceworkspace"></param> /// <param name="targetworkspace"></param> /// <param name="nameOfsourceFeatureClass"></param> /// <param name="nameOftargetFeatureClass"></param> /// <returns></returns> public IFeatureClass ShapeFileIntoGDB(IWorkspace sourceworkspace, IWorkspace targetworkspace, string nameOfsourceFeatureClass, string nameOftargetFeatureClass) { try { //创建源工作空间 IDataset sourceWorkspaceDataset = (IDataset)sourceworkspace; IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName; //创建源数据集 IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass(); IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName; sourceDatasetName.WorkspaceName = sourceWorkspaceName; sourceDatasetName.Name = nameOfsourceFeatureClass; //创建目标工作空间 IDataset targetWorkspaceDataset = (IDataset)targetworkspace; IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName; //创建目标数据集 IFeatureClassName targetFeatureClassName = new FeatureClassNameClass(); IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName; targetDatasetName.WorkspaceName = targetWorkspaceName; targetDatasetName.Name = nameOftargetFeatureClass; //源数据集的字段集 IName sourceName = (IName)sourceFeatureClassName; IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open(); //验证字段 IFieldChecker fieldChecker = new FieldCheckerClass(); IFields targetFeatureClassFields; IFields sourceFeatureClassFields = sourceFeatureClass.Fields; IEnumFieldError enumFieldError; //设置验证的对象 fieldChecker.InputWorkspace = sourceworkspace; fieldChecker.ValidateWorkspace = targetworkspace; fieldChecker.Validate(sourceFeatureClassFields, out enumFieldError, out targetFeatureClassFields); //找到空间对象字段 IField geometryField; for (int i = 0; i < targetFeatureClassFields.FieldCount; i++) { if (targetFeatureClassFields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry) { geometryField = targetFeatureClassFields.get_Field(i); //得到空间字段的定义 IGeometryDef geometryDef = geometryField.GeometryDef; //得到空间字段的索引 IGeometryDefEdit targetFCGeometryDefEdit = (IGeometryDefEdit)geometryDef; targetFCGeometryDefEdit.GridCount_2 = 1; targetFCGeometryDefEdit.set_GridSize(0, 0); //targetFCGeometryDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = DataEditCommon.g_pMap.SpatialReference; //spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_20N); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); spatialReferenceResolution.SetDefaultXYResolution(); spatialReferenceResolution.SetDefaultZResolution(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetMinimumXYTolerance(); spatialReferenceTolerance.SetMinimumZTolerance(); double XMin, XMax, YMin, YMax, ZMin, ZMax, MinXYTolerance, MinZTolerance; XMin = 4054.3603997438; XMax = 78088.6926632544; YMin = 14424.8510028409; YMax = 59609.4812606697; ZMin = 30330.1483519995; ZMax = 38389.3283520005; //spatialReference.SetDomain(XMin, XMax, YMin, YMax); //spatialReference.SetZDomain(ZMin, ZMax); MinXYTolerance = 0.000000000008219; MinZTolerance = 0.000000000007629; //spatialReferenceTolerance.SetMinimumZTolerance( MinXYTolerance); //spatialReference.GetDomain(out XMin, out XMax, out YMin, out YMax); //spatialReference.GetZDomain(out ZMin, out ZMax); targetFCGeometryDefEdit.SpatialReference_2 = spatialReference; //开始导入 IQueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = ""; //导入所有的输入对象 IFeatureDataConverter featureDataConverter = new FeatureDataConverterClass(); IEnumInvalidObject enumInvalidObject = featureDataConverter.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0); break; } } //导入后数据集的字段集 IName targetName = (IName)targetFeatureClassName; IFeatureClass targetFeatureClass = (IFeatureClass)targetName.Open(); return(targetFeatureClass); } catch (Exception ex) { return(null); } }
private void OpenCADFile(string filePath, string outputFilePath) { try { Debug.WriteLine("Start Time: " + DateTime.Now.ToShortTimeString()); System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; String nameOfPath = System.IO.Path.GetDirectoryName(filePath); String nameOfCADFile = System.IO.Path.GetFileName(filePath); #region Open CAD Workspace from File Path //Set the workspace. ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWorkspaceFact = new ESRI.ArcGIS.DataSourcesFile.CadWorkspaceFactory(); ESRI.ArcGIS.Geodatabase.IWorkspaceFactory defaultWorkspaceFact = new FileGDBWorkspaceFactory(); //Open the workspace. ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = pWorkspaceFact.OpenFromFile(nameOfPath, 0); //Get the CADDrawingWorkspace. ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace pCadDwgWorkspace; pCadDwgWorkspace = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace)pWorkspace; //Open the CadDrawingDataset. ESRI.ArcGIS.DataSourcesFile.ICadDrawingDataset pCadDwgDataset; pCadDwgDataset = pCadDwgWorkspace.OpenCadDrawingDataset(nameOfCADFile); //Set the feature workspace. ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)pWorkspace; //Open the Feature Class. #endregion #region Getting Polygon, polylines, and annotation from Cad file ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polygon")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Plyline = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polyline")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Anno = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Annotation")); #endregion UID CLSID_def = new UIDClass(); CLSID_def.Value = "esriGeoDatabase.Feature"; #region Creating Layers from Feature Classes //Polygons ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer.FeatureClass = pFeatClass; pFeatLayer.Name = "Polygons"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer; //Annotation ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Anno = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Anno.FeatureClass = pFeatClass_Anno; pFeatLayer_Anno.Name = "Annotation"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Anno = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Anno; //Polylines ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Plyline = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Plyline.FeatureClass = pFeatClass_Plyline; pFeatLayer_Plyline.Name = "Polylines"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Plyline = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Plyline; #endregion #region Creating In-Memory workspace IWorkspaceFactory WF = new InMemoryWorkspaceFactory(); ESRI.ArcGIS.esriSystem.IName name = WF.Create("", "MyWorkspace", null, 0) as ESRI.ArcGIS.esriSystem.IName; IWorkspace inMemWorkspace = (IWorkspace)name.Open(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inMemWorkspace; #endregion #region Creating new Fields IObjectClassDescription objectClassDescription = new FeatureClassDescription(); // create the fields using the required fields method IFields exportFields = new Fields(); IFieldsEdit fieldsEdit = (IFieldsEdit)exportFields; //OID IField field = new Field(); IField oidField = new Field(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class IGeometryDef geometryDef = new GeometryDef(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; IGeoDataset dataSet = (IGeoDataset)pFeatClass.FeatureDataset; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment(); ISpatialReference spatialReference = dataSet.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new Field(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); #endregion #region Creating New Shapefile for Final output UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; //using the In-Memory Workspace created above IFeatureClass output = featureWorkspace.CreateFeatureClass("myPolygons", pFeatClass.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass polylines_cleaned = featureWorkspace.CreateFeatureClass("polylines_cleaned", pFeatClass_Plyline.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass annotation_cleaned = featureWorkspace.CreateFeatureClass("annotation_cleaned", pFeatClass_Anno.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); #endregion #region Appending features from CADWorkspaceFeatureClass to In-Memory FeatureClass Because Update cursor not in Cad workspace Geoprocessor GP = new Geoprocessor(); //Polylines ESRI.ArcGIS.DataManagementTools.Append append = new Append(); append.inputs = pFeatClass_Plyline; append.target = polylines_cleaned; GP.Execute(append, null); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Plyline); GC.Collect(); //Annotation append = new Append(); append.inputs = pFeatClass_Anno; append.target = annotation_cleaned; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Anno); GC.Collect(); //Polygons to output append = new Append(); append.inputs = pFeatClass; append.target = output; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass); GC.Collect(); #endregion #region Query Filter to Filter Layers string queryString = ""; //using the checked box list and comma seperated list to create where clause string //Adding Items from Check Box List foreach (var checkedItem in checkedListBox1.CheckedItems) { queryString = queryString + "Layer NOT LIKE '" + checkedItem.ToString() + "' AND "; } //Adding Items from Comma separated string if (textBox_commaSeparated.Text.Length > 0) { foreach (var item in textBox_commaSeparated.Text.Split(',')) { queryString = queryString + "Layer NOT LIKE '" + item.ToString() + "' AND "; } } //Removing Last 'AND' FROM queryString if (queryString.Length > 0) //if Atleast one item added { queryString = queryString.Remove(queryString.Length - 4); } IQueryFilter queryFilter = new QueryFilter(); queryFilter.SubFields = ""; if (queryString.Length > 0) { queryFilter.WhereClause = queryString; } else { queryFilter.WhereClause = "1=1"; } #endregion #region Removing Null Geometries string ignoreList = queryString.Replace("Layer NOT LIKE '", "").Replace("' AND ", ",").Replace("' ", ""); Debug.WriteLine("lines Count before:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From Polylines_cleaned IFeatureCursor updateCursor = polylines_cleaned.Update(new QueryFilter(), false); IFeature feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); //System.Runtime.InteropServices.Marshal.ReleaseComObject(feat); GC.Collect(); Debug.WriteLine("lines Count After:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From output Debug.WriteLine("polygons Count before:" + output.FeatureCount(new QueryFilter()).ToString()); updateCursor = output.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("polygons Count after:" + output.FeatureCount(new QueryFilter()).ToString()); //From Annotation Debug.WriteLine("Annotation Count before:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); updateCursor = annotation_cleaned.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("Annotation Count after:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); #endregion #region Convert lines feature class to feature Cursor IFeatureCursor linesFCursor = polylines_cleaned.Search(new QueryFilter(), false); #endregion #region Deleting all columns of polygons to match with output IFields _fieldsP = output.Fields; IFieldsEdit _fieldsEditP = (IFieldsEdit)_fieldsP; for (int i = 0; i < output.Fields.FieldCount; i++) { IField _field = output.Fields.get_Field(i); if (_field.Name != "Shape" && _field.Name != "FID") { output.DeleteField(_field); if (i < output.Fields.FieldCount) { i--; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsP); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEditP); GC.Collect(); #endregion #region Setting Envelop information IEnvelope envelop = new Envelope() as IEnvelope; IGeoDataset dataSetEnv = (IGeoDataset)pFeatClass_Plyline.FeatureDataset; envelop.SpatialReference = dataSet.SpatialReference; envelop.PutCoords(dataSet.Extent.XMin, dataSet.Extent.YMin, dataSet.Extent.XMax, dataSet.Extent.YMax); #endregion #region Construct Polygons from Lines Cursor (usting Feature Construct) IFeatureConstruction featureConstruct = new FeatureConstruction() as IFeatureConstruction; ISelectionSet selectionSet = null; //atureConstruct.ConstructPolygonsFromFeaturesFromCursor(null,output,envelop,false,false,linesFCursor,null,0.001,null); featureConstruct.AutoCompleteFromFeaturesFromCursor(output, envelop, linesFCursor, null, -1, null, out selectionSet); #endregion System.Runtime.InteropServices.Marshal.ReleaseComObject(featureConstruct); System.Runtime.InteropServices.Marshal.ReleaseComObject(linesFCursor); GC.Collect(); Debug.WriteLine("polygons Count after PolygonConstruct :" + output.FeatureCount(new QueryFilter()).ToString()); #region SPATIAL JOIN GP = new Geoprocessor(); ESRI.ArcGIS.AnalysisTools.SpatialJoin spatialJoin = new ESRI.ArcGIS.AnalysisTools.SpatialJoin(); spatialJoin.join_features = annotation_cleaned; spatialJoin.target_features = output; spatialJoin.join_operation = "JOIN_ONE_TO_MANY"; spatialJoin.join_type = "KEEP_ALL"; spatialJoin.match_option = "CONTAINS"; spatialJoin.out_feature_class = outputFilePath; GP.Execute(spatialJoin, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(annotation_cleaned); GC.Collect(); #endregion #region Remove All Fields of Annotation except Text ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory(); IFeatureWorkspace work = (IFeatureWorkspace)wsf.OpenFromFile(System.IO.Path.GetDirectoryName(outputFilePath), 0); IFeatureClass output_AfterJoin_FClasss = work.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(outputFilePath)); IFields _fields = output_AfterJoin_FClasss.Fields; IFieldsEdit _fieldsEdit = (IFieldsEdit)_fields; for (int i = 0; i < _fields.FieldCount; i++) { IField _field = output_AfterJoin_FClasss.Fields.get_Field(i); if (_field.Name != "Text_" && _field.Name != "Text" && _field.Name != "Shape" && _field.Name != "FID") { output_AfterJoin_FClasss.DeleteField(_field); i--; } else { if (field.Name == "Text_" || _field.Name == "Text") { IFieldEdit fieldEdit = (IFieldEdit)_field; fieldEdit.Name_2 = "PlotNumber"; fieldEdit.AliasName_2 = "PlotNumber"; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fields); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEdit); GC.Collect(); #endregion System.Windows.Forms.Cursor.Current = Cursors.Default; Debug.WriteLine("End Time: " + DateTime.Now.ToShortTimeString()); MessageBox.Show("Import Complete!"); } catch { MessageBox.Show("Error Importing. Something wrong with the CAD File"); } }
public void OnDblClick() { Editor.UniqueInstance.CheckOverlap = false; try { IFeatureLayer targetLayer = Editor.UniqueInstance.TargetLayer; object missing = Type.Missing; if (!this.m_IsUsed || (this.m_LineFeedback == null)) { return; } if (this.m_Step > 1) { IPolyline polyline = this.m_LineFeedback.Stop(); if (polyline == null) { this.Init(); return; } IFeatureClass featureClass = targetLayer.FeatureClass; if (featureClass == null) { this.Init(); return; } IGeoDataset dataset = featureClass as IGeoDataset; if (polyline.SpatialReference != dataset.SpatialReference) { polyline.Project(dataset.SpatialReference); polyline.SpatialReference = dataset.SpatialReference; } IGeometry inGeometry = polyline; GeometryBagClass lineSrc = new GeometryBagClass(); lineSrc.AddGeometry(inGeometry, ref missing, ref missing); targetLayer.Selectable = true; IDataset dataset2 = featureClass as IDataset; IWorkspace selectionWorkspace = dataset2.Workspace; IEnvelope extent = dataset.Extent; IInvalidArea invalidArea = new InvalidAreaClass(); IFeatureConstruction construction = new FeatureConstructionClass(); IFeatureSelection selection = targetLayer as IFeatureSelection; ISelectionSet selectionSet = selection.SelectionSet; Editor.UniqueInstance.SetArea = false; Editor.UniqueInstance.StartEditOperation(); ISpatialReferenceTolerance spatialReference = (ISpatialReferenceTolerance)dataset.SpatialReference; construction.AutoCompleteFromGeometries(featureClass, extent, lineSrc, invalidArea, spatialReference.XYTolerance, selectionWorkspace, out selectionSet); if ((selectionSet == null) || (selectionSet.Count < 1)) { Editor.UniqueInstance.AbortEditOperation(); } else { List <IFeature> pFeatureList = new List <IFeature>(); IEnumIDs iDs = selectionSet.IDs; iDs.Reset(); for (int i = iDs.Next(); i >= 0; i = iDs.Next()) { IFeature pFeature = featureClass.GetFeature(i); FeatureFuncs.SetFeatureArea(pFeature); pFeatureList.Add(pFeature); } if (selectionSet.Count == 1) { IFeature feature = pFeatureList[0]; selection.Clear(); selection.Add(feature); AttributeManager.AttributeAddHandleClass.AttributeAdd(ref feature); } else { AttributeManager.AttributeSplitHandleClass.AttributeSplit(null, ref pFeatureList); } Editor.UniqueInstance.StopEditOperation("AutoComplete"); } Editor.UniqueInstance.SetArea = true; this.m_hookHelper.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeoSelection | esriViewDrawPhase.esriViewGeography, null, this.m_hookHelper.ActiveView.Extent); } } catch (Exception exception) { this.mErrOpt.ErrorOperate(this.mSubSysName, "ShapeEdit.AutoComplete", "OnDblClick", exception.GetHashCode().ToString(), exception.Source, exception.Message, "", "", ""); } this.Init(); Editor.UniqueInstance.CheckOverlap = true; }
protected override void OnClick() { IApplication pApp; ICadastralFabric m_pCadaFab; IQueryFilter m_pQF; #region Get Fabric pApp = (IApplication)ArcMap.Application; if (pApp == null) { //if the app is null then could be running from ArcCatalog pApp = (IApplication)ArcCatalog.Application; } if (pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)pApp; stdole.IUnknown pUnk = null; try { pUnk = (stdole.IUnknown)pGXApp.SelectedObject.InternalObjectName.Open(); } catch (COMException ex) { if (ex.ErrorCode == (int)fdoError.FDO_E_DATASET_TYPE_NOT_SUPPORTED_IN_RELEASE || ex.ErrorCode == -2147220944) { MessageBox.Show("The dataset is not supported in this release.", "Could not open the dataset"); } else { MessageBox.Show(ex.ErrorCode.ToString(), "Could not open the dataset"); } return; } if (pUnk is ICadastralFabric) { m_pCadaFab = (ICadastralFabric)pUnk; } else { MessageBox.Show("Please select a parcel fabric and try again.", "Not a parcel fabric"); return; } #endregion IFeatureClass pFabricPointClass = (IFeatureClass)m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); IDataset pDS = (IDataset)pFabricPointClass; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; Utilities FabricUTILS = new Utilities(); FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) { return; } m_pQF = new QueryFilterClass(); m_pQF.WhereClause = ""; int iChangePointCount = 0; try { //next need to use an in clause to update the points, ... ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields((ITable)pFabricPointClass, esriCadastralFabricTable.esriCFTPoints); IGeoDataset pGeoDS = (IGeoDataset)pFabricPointClass; ISpatialReferenceTolerance pSRTol = (ISpatialReferenceTolerance)pGeoDS.SpatialReference; double dTolerance = pSRTol.XYTolerance; if (!UpdatePointXYFromGeometry((ITable)pFabricPointClass, m_pQF, (bIsUnVersioned || bIsFileBasedGDB), dTolerance, out iChangePointCount)) { FabricUTILS.AbortEditing(pWS); return; } FabricUTILS.StopEditing(pWS); pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); MessageBox.Show("Updated " + iChangePointCount.ToString() + " points that had coordinates different" + Environment.NewLine + "from their geometry by more than " + dTolerance.ToString("0.00000000").TrimEnd('0'), "Coordinate Inverse", MessageBoxButtons.OK, MessageBoxIcon.Information); } catch (Exception ex) { MessageBox.Show(ex.Message); FabricUTILS.AbortEditing(pWS); } finally { } }
// create feature class in file geodatabase #region "create feature class in file geodatabase" public static ESRI.ArcGIS.Geodatabase.IFeatureClass CreateFeatureClass(String featureClassName, UID classExtensionUID, IFeatureWorkspace featureWorkspace) { // check if the fc exist, if so rename it // Create a fields collection for the feature class. IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = (IFieldsEdit)fields; // Add an object ID field to the fields collection. This is mandatory for feature classes. IField oidField = new FieldClass(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OBJECTID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class. IGeometryDef geometryDef = new GeometryDefClass(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolyline; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass(); ISpatialReference spatialReference = spatialReferenceFactory.CreateProjectedCoordinateSystem((int)esriSRProjCSType.esriSRProjCS_NAD1983UTM_12N); ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new FieldClass(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); // Create a text field called "ADDRSYS_L" for the fields collection. IField addrSysLField = new FieldClass(); IFieldEdit addrSysLFieldEdit = (IFieldEdit)addrSysLField; addrSysLFieldEdit.Name_2 = "ADDRSYS_L"; addrSysLFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; addrSysLFieldEdit.Length_2 = 30; fieldsEdit.AddField(addrSysLField); // Create a text field called "ADDRSYS_R" for the fields collection. IField addrSysRField = new FieldClass(); IFieldEdit addrSysRFieldEdit = (IFieldEdit)addrSysRField; addrSysRFieldEdit.Name_2 = "ADDRSYS_R"; addrSysRFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; addrSysRFieldEdit.Length_2 = 30; fieldsEdit.AddField(addrSysRField); // Create a text field called "FROMADDR_L" for the fields collection. IField rangeL_Ffield = new FieldClass(); IFieldEdit rangeL_FfieldEdit = (IFieldEdit)rangeL_Ffield; rangeL_FfieldEdit.Name_2 = "FROMADDR_L"; rangeL_FfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeL_FfieldEdit.Precision_2 = 38; rangeL_FfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeL_Ffield); // Create a text field called "TOADDR_L" for the fields collection. IField rangeL_Tfield = new FieldClass(); IFieldEdit rangeL_TfieldEdit = (IFieldEdit)rangeL_Tfield; rangeL_TfieldEdit.Name_2 = "TOADDR_L"; rangeL_TfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeL_TfieldEdit.Precision_2 = 38; rangeL_TfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeL_Tfield); // Create a text field called "FROMADDR_R" for the fields collection. IField rangeR_Ffield = new FieldClass(); IFieldEdit rangeR_FfieldEdit = (IFieldEdit)rangeR_Ffield; rangeR_FfieldEdit.Name_2 = "FROMADDR_R"; rangeR_FfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeR_FfieldEdit.Precision_2 = 38; rangeR_FfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeR_Ffield); // Create a text field called "TOADDR_R" for the fields collection. IField rangeR_Tfield = new FieldClass(); IFieldEdit rangeR_TfieldEdit = (IFieldEdit)rangeR_Tfield; rangeR_TfieldEdit.Name_2 = "TOADDR_R"; rangeR_TfieldEdit.Type_2 = esriFieldType.esriFieldTypeDouble; rangeR_TfieldEdit.Precision_2 = 38; rangeR_TfieldEdit.Scale_2 = 8; fieldsEdit.AddField(rangeR_Tfield); // Create a text field called "PREDIR" for the fields collection. IField predirField = new FieldClass(); IFieldEdit predirFieldEdit = (IFieldEdit)predirField; predirFieldEdit.Name_2 = "PREDIR"; predirFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; predirFieldEdit.Length_2 = 1; fieldsEdit.AddField(predirField); // Create a text field called "NAME" for the fields collection. IField nameField = new FieldClass(); IFieldEdit nameFieldEdit = (IFieldEdit)nameField; nameFieldEdit.Name_2 = "NAME"; nameFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; nameFieldEdit.Length_2 = 30; fieldsEdit.AddField(nameField); // Create a text field called "POSTTYPE" for the fields collection. IField streettypeField = new FieldClass(); IFieldEdit streettypeFieldEdit = (IFieldEdit)streettypeField; streettypeFieldEdit.Name_2 = "POSTTYPE"; streettypeFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; streettypeFieldEdit.Length_2 = 4; fieldsEdit.AddField(streettypeField); // Create a text field called "POSTDIR" for the fields collection. IField sufdirField = new FieldClass(); IFieldEdit sufdirFieldEdit = (IFieldEdit)sufdirField; sufdirFieldEdit.Name_2 = "POSTDIR"; sufdirFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; sufdirFieldEdit.Length_2 = 2; fieldsEdit.AddField(sufdirField); // Create a text field called "ZIPCODE_L" for the fields collection. IField zipleftField = new FieldClass(); IFieldEdit zipleftFieldEdit = (IFieldEdit)zipleftField; zipleftFieldEdit.Name_2 = "ZIPCODE_L"; zipleftFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; zipleftFieldEdit.Length_2 = 5; fieldsEdit.AddField(zipleftField); // Create a text field called "ZIPCODE_R" for the fields collection. IField ziprightField = new FieldClass(); IFieldEdit ziprightFieldEdit = (IFieldEdit)ziprightField; ziprightFieldEdit.Name_2 = "ZIPCODE_R"; ziprightFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; ziprightFieldEdit.Length_2 = 5; fieldsEdit.AddField(ziprightField); // Create a text field called "GLOBALID_SGID" for the fields collection - to join to the table or sgid. IField globalidField = new FieldClass(); IFieldEdit globalidFieldEdit = (IFieldEdit)globalidField; globalidFieldEdit.Name_2 = "GLOBALID_SGID"; globalidFieldEdit.Type_2 = esriFieldType.esriFieldTypeString; // use string and not the globalid type b/c it might that might assign it's own unique global id and this is for joinging back to sgid globalidFieldEdit.Length_2 = 50; fieldsEdit.AddField(globalidField); // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = (IWorkspace)featureWorkspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. // Create the feature class. Note that the CLSID parameter is null - this indicates to use the // default CLSID, esriGeodatabase.Feature (acceptable in most cases for feature classes). IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, null, classExtensionUID, esriFeatureType.esriFTSimple, "Shape", ""); return(featureClass); }