private static ITable CreateTable(IWorkspace2 workspace, string tableName, IFields fields) { UID uid = new UIDClass {Value = "esriGeoDatabase.Object"}; if (workspace == null) return null; IFeatureWorkspace featWorkspace = (IFeatureWorkspace) workspace; if (workspace.NameExists[esriDatasetType.esriDTTable, tableName]) { using (ComReleaser releaser = new ComReleaser()) { ITable table = featWorkspace.OpenTable(tableName); releaser.ManageLifetime(table); ((IDataset) table).Delete(); } } IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = workspace as IWorkspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); return featWorkspace.CreateTable(tableName, validatedFields, uid, null, string.Empty); }
// Konverterar raster till vektor. public IFeatureLayer convertRasterToVector(string outPath, string fileName) { IGeoDataset pLayerDataset = (IGeoDataset)dest; IConversionOp conversionOp = new RasterConversionOpClass(); IRasterAnalysisEnvironment env = (IRasterAnalysisEnvironment)conversionOp; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace workspace = workspaceFactory.OpenFromFile(outPath, 0); env.OutWorkspace = workspace; IWorkspaceFactory wsFactory = new ShapefileWorkspaceFactoryClass(); IWorkspace shapeWS = wsFactory.OpenFromFile(outPath, 0); IFeatureWorkspace fWorkspace = (IFeatureWorkspace)wsFactory.OpenFromFile(outPath, 0); IWorkspace2 workTemp = (IWorkspace2)fWorkspace; if (workTemp.NameExists[esriDatasetType.esriDTFeatureClass, fileName]) { IDataset dataset = (IDataset)fWorkspace.OpenFeatureClass(fileName); dataset.Delete(); } IGeoDataset featPolClassOut = conversionOp.RasterDataToPolygonFeatureData(pLayerDataset, shapeWS, fileName + ".shp", true); IFeatureClass fClass = fWorkspace.OpenFeatureClass(fileName); IFeatureLayer fLayer = new FeatureLayerClass(); fLayer.FeatureClass = fClass; fLayer.Name = fClass.AliasName; fLayer.Visible = true; map.AddLayer(fLayer); return(fLayer); }
private static Dictionary <LayerTypeEnum, ILayer> GetLayers(ArcSceneArguments layers, IObjectFactory objFactory) { var preparedLayers = new Dictionary <LayerTypeEnum, ILayer>(); Type rasterLayerType = typeof(RasterLayerClass); string typeRasterLayerID = rasterLayerType.GUID.ToString("B"); var elevationRasterLayer = (IRasterLayer)objFactory.Create(typeRasterLayerID); elevationRasterLayer.CreateFromFilePath(layers.DemLayer); preparedLayers.Add(LayerTypeEnum.Raster, elevationRasterLayer); Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.FileGDBWorkspaceFactory"); string typeFactoryID = factoryType.GUID.ToString("B"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)objFactory.Create(typeFactoryID); IWorkspace2 workspace = (IWorkspace2)workspaceFactory.OpenFromFile(_profileGdb, 0); if (!string.IsNullOrEmpty(layers.Line3DLayer)) { preparedLayers.Add(LayerTypeEnum.LineFeature, CreateFeatureLayer(layers.Line3DLayer, workspace, objFactory)); preparedLayers.Add(LayerTypeEnum.PointFeature, CreateFeatureLayer(layers.Point3DLayer, workspace, objFactory)); var polygon3DLayer = CreateFeatureLayer(layers.Polygon3DLayer, workspace, objFactory); var polygonLayerEffects = (ILayerEffects)polygon3DLayer; polygonLayerEffects.Transparency = 50; preparedLayers.Add(LayerTypeEnum.PolygonFeature, polygon3DLayer); } Marshal.ReleaseComObject(workspaceFactory); return(preparedLayers); }
public static IDatasetContainer3 GetDatasetContainer(IFeatureWorkspace featureWorkspace, string fdName) { IDatasetContainer3 datasetContainer = null; if (featureWorkspace is IWorkspace2) { IWorkspace2 workspace = featureWorkspace as IWorkspace2; bool fdExists = workspace.get_NameExists(esriDatasetType.esriDTFeatureDataset, fdName); if (!fdExists) { throw new Exception("Feature Dataset does not exist."); } } IFeatureDatasetExtensionContainer fdExtensionContainer = (IFeatureDatasetExtensionContainer)featureWorkspace.OpenFeatureDataset(fdName); datasetContainer = (IDatasetContainer3)fdExtensionContainer.FindExtension(esriDatasetType.esriDTNetworkDataset); if (datasetContainer == null) { throw new Exception("NATestNetworkDataset: dataset container should not be null"); } return(datasetContainer); }
private void GenerateTempStorage(string featureClassName, IFields fields, esriGeometryType type) { IWorkspaceEdit workspaceEdit = (IWorkspaceEdit)calcWorkspace; workspaceEdit.StartEditing(true); workspaceEdit.StartEditOperation(); IWorkspace2 wsp2 = (IWorkspace2)calcWorkspace; IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)calcWorkspace; if (!wsp2.get_NameExists(esriDatasetType.esriDTFeatureClass, featureClassName)) { IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; if (fields == null) { fields = ocDescription.RequiredFields; int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(shapeFieldIndex); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.HasZ_2 = true; geometryDefEdit.GeometryType_2 = type; geometryDefEdit.SpatialReference_2 = ArcMapInstance.Document.FocusMap.SpatialReference; } IFeatureClass featureClass = featureWorkspace.CreateFeatureClass(featureClassName, fields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "shape", ""); } workspaceEdit.StopEditOperation(); workspaceEdit.StopEditing(true); }
public bool DeleteTemporarSource(string resultTable, string lineFeatureClass) { IWorkspace2 wsp2 = (IWorkspace2)calcWorkspace; IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)calcWorkspace; try { var datasets = calcWorkspace.get_Datasets(esriDatasetType.esriDTTable); IDataset tabledataset = datasets.Next(); if (tabledataset != null) { while (tabledataset != null) { if (!tabledataset.Name.Equals(resultTable)) { tabledataset = datasets.Next(); continue; } if (!tabledataset.CanDelete()) { throw new MilSpaceCanotDeletePrifileCalcTable(resultTable, MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection); } tabledataset.Delete(); break; } } //Delete temprorary Feature class (Profile lites) datasets = calcWorkspace.get_Datasets(esriDatasetType.esriDTFeatureClass); if (tabledataset != null) { while (tabledataset != null) { if (!tabledataset.Name.Equals(lineFeatureClass)) { tabledataset = datasets.Next(); continue; } if (!tabledataset.CanDelete()) { throw new MilSpaceCanotDeletePrifileCalcTable(lineFeatureClass, MilSpaceConfiguration.ConnectionProperty.TemporaryGDBConnection); } tabledataset.Delete(); break; } } return(true); } catch (MilSpaceCanotDeletePrifileCalcTable ex) { //TODO: add logging throw; } catch (Exception ex) { //TODO: add logging } return(false); }
public bool CheckOut(IWorkspace source, string dir, string dbname, string template, IPolygon area, string taskName, string dept) { m_message = ""; //检查文件是否已经存在 string mdbpath = dir + @"\" + dbname + ".mdb"; bool isExist = File.Exists(mdbpath); if (isExist) { File.Delete(mdbpath); } Type factoryType = Type.GetTypeFromProgID( "esriDataSourcesGDB.AccessWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IWorkspaceName workspaceName = workspaceFactory.Create(dir, dbname, null, 0); IWorkspace workspace = workspaceFactory.OpenFromFile(mdbpath, 0); //导入库结构 IGdbXmlImport importer = new GdbImporterClass(); IEnumNameMapping mapping = null; bool isConflict = false; isConflict = importer.GenerateNameMapping(template, workspace, out mapping); importer.ImportWorkspace(template, mapping, workspace, true); IDataset ds = workspace as IDataset; List <String> fcNames = new List <string>(); Util.GetAllFeatureClassNames(ds, ref fcNames); IFeatureWorkspace source_ws = source as IFeatureWorkspace; IFeatureWorkspace target_ws = workspace as IFeatureWorkspace; IWorkspaceEdit wse = target_ws as IWorkspaceEdit; foreach (string fcname in fcNames) { IWorkspace2 source_ws2 = source_ws as IWorkspace2; if (!source_ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, fcname)) { continue; } IFeatureClass source_fc = source_ws.OpenFeatureClass(fcname); IFeatureClass target_fc = target_ws.OpenFeatureClass(fcname); AddSyncFields(target_fc); ISpatialFilter filter = new SpatialFilterClass(); filter.Geometry = area as IGeometry; filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; wse.StartEditing(false); IFeatureCursor target_cur = target_fc.Insert(true); IFeatureBuffer buffer = target_fc.CreateFeatureBuffer(); IFeatureCursor source_cur = source_fc.Search(filter, true); IFeature source_fea = source_cur.NextFeature(); while (source_fea != null) { buffer.set_Value(target_fc.FindField("SyncID"), source_fea.OID); for (int i = 0; i < source_fc.Fields.FieldCount; i++) { IField source_field = source_fc.Fields.get_Field(i); if (source_field.Name != source_fc.OIDFieldName) { int target_field_index = target_fc.FindField(source_field.Name); if (target_field_index != -1) { object source_value = source_fea.get_Value(source_fc.FindField(source_field.Name)); buffer.set_Value(target_field_index, source_value); } } } target_cur.InsertFeature(buffer); source_fea = source_cur.NextFeature(); } target_cur.Flush(); wse.StopEditing(true); } IFeatureClass log_fc = source_ws.OpenFeatureClass("TaskLog"); IWorkspaceEdit source_wse = source_ws as IWorkspaceEdit; source_wse.StartEditing(false); IFeature log_fea = log_fc.CreateFeature(); log_fea.set_Value(log_fc.FindField("CheckOutDate"), DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")); log_fea.set_Value(log_fc.FindField("TaskName"), taskName); log_fea.set_Value(log_fc.FindField("Dept"), dept); log_fea.set_Value(log_fc.FindField("Status"), Task.TaskManager.CHECKOUT_STATUS); log_fea.Shape = area; log_fea.Store(); source_wse.StopEditing(true); return(true); }
public static string GetUniqueFeatureClassName(string name, IWorkspace2 workspace) { //ToDo: This works to get a unique name but it's goobery, need to implement recursion here... try { IFieldChecker fieldChecker = new FieldChecker(); string fcName; fieldChecker.ValidateTableName(name, out fcName); int i = 1; while(workspace.get_NameExists(esriDatasetType.esriDTFeatureClass, fcName)) { fcName = fcName + i; i++; } return fcName; } catch { return ""; } }
//将mdb中要素类转换复制到GDB数据库中 private void ImportMDBToGDB(string file, string outfilename) { m_success = false;//初始化 try { string filepath = file.Substring(0, file.LastIndexOf("---")); string filename = file.Substring(file.LastIndexOf("-") + 1); //打开mdb文件所在的工作空间 ESRI.ArcGIS.Geodatabase.IWorkspaceFactory wf = new AccessWorkspaceFactory(); IFeatureWorkspace pFeatureWorkspaceMDB = wf.OpenFromFile(@filepath, 0) as IFeatureWorkspace; IWorkspace pWorkspaceMDB = pFeatureWorkspaceMDB as IWorkspace; // 创建源工作空间名称 IDataset sourceWorkspaceDataset = (IDataset)pWorkspaceMDB; IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName; //创建源数据集名称 //IFeatureClassName sourceFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass(); IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName; sourceDatasetName.WorkspaceName = sourceWorkspaceName; sourceDatasetName.Name = filename; //打开存在的工作空间,作为导入的空间 IWorkspaceFactory Pwf = new FileGDBWorkspaceFactoryClass(); //IWorkspace pWorkspaceGDB = Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0); //IWorkspace2 pWorkspace2 = (IWorkspace2)(Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0)); IWorkspace pWorkspaceGDB = GetWorkspace(comboBoxSource.Text); if (pWorkspaceGDB == null) { m_strErr = "数据源未找到"; m_success = false; return; } string username = GetSourceUser(comboBoxSource.Text); if (username.Trim() != "") { outfilename = username + "." + outfilename; } IWorkspace2 pWorkspace2 = pWorkspaceGDB as IWorkspace2; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspaceGDB; //创建目标工作空间名称 IDataset targetWorkspaceDataset = (IDataset)pWorkspaceGDB; IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName; //创建目标数据集名称 // IFeatureClassName targetFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; //判断要素是否存在,若存在将删除源文件 if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, outfilename)) { if (m_newfile == true) { IFeatureClass tmpfeatureclass; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(outfilename); IDataset set = tmpfeatureclass as IDataset; fdr.DeleteSql(filename); set.CanDelete(); set.Delete(); } else { m_strErr = "存在相同文件名"; m_success = false; return; } } IFeatureClassName targetFeatureClassName = new FeatureClassNameClass(); IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName; targetDatasetName.WorkspaceName = targetWorkspaceName; targetDatasetName.Name = outfilename; //打开输入的要素类以得到字段定义 ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName; IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();//打开源要素类 //验证字段名称,因为你正在不同类型的工作空间之间进行数据转换 //IFieldChecker fieldChecker = serverContext.CreateObject("esriGeoDatabase.FieldChecker") as IFieldChecker; IFieldChecker fieldChecker = new FieldCheckerClass(); IFields sourceFeatureClassFields = sourceFeatureClass.Fields; IFields targetFeatureClassFields; IEnumFieldError enumFieldError; //最重要的设置输入和验证工作空间 fieldChecker.InputWorkspace = pWorkspaceMDB; fieldChecker.ValidateWorkspace = pWorkspaceGDB; 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 targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef; targetFCGeoDefEdit.GridCount_2 = 1; targetFCGeoDefEdit.set_GridSize(0, 0); //允许ArcGIS为数据加载确定一个有效的格网大小 targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference; //转换要素类中所有的要素 //IQueryFilter queryFilter = serverContext.CreateObject("esriGeoDatabase.QueryFilter") as IQueryFilter; ; QueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = ""; //加载要素类 //IFeatureDataConverter fctofc = serverContext.CreateObject("esriGeoDatabase.FeatureDataConverter") as IFeatureDataConverter; if (InsertIntoDatabase(outfilename))//更新数据库 { IFeatureDataConverter fctofc = new FeatureDataConverterClass(); IEnumInvalidObject enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, null, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0); } } } m_success = true; } catch { m_success = false; m_strErr = ""; } }
public static bool Exist(IWorkspace workspace, string featureClassName) { IWorkspace2 pWorkspace2 = workspace as IWorkspace2; return(pWorkspace2 != null && pWorkspace2.NameExists[esriDatasetType.esriDTFeatureClass, featureClassName]); }
/// <summary> /// 将GDB的数据入到SDE中 xisheng 20110919 /// </summary> private void ImportGDBToSDE(string file, string outfilename, out int featurecount) { m_success = false;//初始化 try { string filepath = file.Substring(0, file.LastIndexOf("---")); string filename = file.Substring(file.LastIndexOf("-") + 1); //打开mdb文件所在的工作空间 ESRI.ArcGIS.Geodatabase.IWorkspaceFactory wf = new FileGDBWorkspaceFactory(); IFeatureWorkspace pFeatureWorkspaceGDB = wf.OpenFromFile(@filepath, 0) as IFeatureWorkspace; IWorkspace pWorkspaceGDB = pFeatureWorkspaceGDB as IWorkspace; // 创建源工作空间名称 IDataset sourceWorkspaceDataset = (IDataset)pFeatureWorkspaceGDB; IWorkspaceName sourceWorkspaceName = (IWorkspaceName)sourceWorkspaceDataset.FullName; //创建源数据集名称 //IFeatureClassName sourceFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; IFeatureClassName sourceFeatureClassName = new FeatureClassNameClass(); IDatasetName sourceDatasetName = (IDatasetName)sourceFeatureClassName; sourceDatasetName.WorkspaceName = sourceWorkspaceName; sourceDatasetName.Name = filename; //打开存在的工作空间,作为导入的空间; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pTargetworkspace; //创建目标工作空间名称 IDataset targetWorkspaceDataset = (IDataset)pTargetworkspace; IWorkspaceName targetWorkspaceName = (IWorkspaceName)targetWorkspaceDataset.FullName; IWorkspace2 pWorkspace2 = pTargetworkspace as IWorkspace2; IFeatureDataset tmpfeaturedataset; //创建目标数据集名称 // IFeatureClassName targetFeatureClassName = serverContext.CreateObject("esriGeoDatabase.FeatureClassName") as IFeatureClassName; //判断要素是否存在,若存在将删除源文件 if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureDataset, textBox.Text)) { tmpfeaturedataset = pFeatureWorkspace.OpenFeatureDataset(textBox.Text); if (text_prj.Text != "") { IGeoDatasetSchemaEdit pgeodataset = tmpfeaturedataset as IGeoDatasetSchemaEdit; if (pgeodataset.CanAlterSpatialReference) { pgeodataset.AlterSpatialReference(GetSpatialReferenceformFile(text_prj.Text)); } } } else { tmpfeaturedataset = CreateFeatureDataset(pTargetworkspace as IFeatureWorkspace, textBox.Text, text_prj.Text); } if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, outfilename)) { IFeatureClass tmpfeatureclass; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(outfilename); IDataset tempset = tmpfeatureclass as IDataset; tempset.Delete(); } IFeatureClassName targetFeatureClassName = new FeatureClassNameClass(); IDatasetName targetDatasetName = (IDatasetName)targetFeatureClassName; targetDatasetName.WorkspaceName = targetWorkspaceName; targetDatasetName.Name = outfilename; //目标数据集 IFeatureDatasetName outfeaturedatasetname = tmpfeaturedataset.FullName as IFeatureDatasetName; //打开输入的要素类以得到字段定义 ESRI.ArcGIS.esriSystem.IName sourceName = (ESRI.ArcGIS.esriSystem.IName)sourceFeatureClassName; IFeatureClass sourceFeatureClass = (IFeatureClass)sourceName.Open();//打开源要素类 //验证字段名称,因为你正在不同类型的工作空间之间进行数据转换 //IFieldChecker fieldChecker = serverContext.CreateObject("esriGeoDatabase.FieldChecker") as IFieldChecker; IFieldChecker fieldChecker = new FieldCheckerClass(); IFields sourceFeatureClassFields = sourceFeatureClass.Fields; IFields targetFeatureClassFields; IEnumFieldError enumFieldError; //最重要的设置输入和验证工作空间 fieldChecker.InputWorkspace = pWorkspaceGDB; fieldChecker.ValidateWorkspace = pTargetworkspace; 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 targetFCGeoDefEdit = (IGeometryDefEdit)geometryDef; targetFCGeoDefEdit.GridCount_2 = 1; targetFCGeoDefEdit.set_GridSize(0, 0); //允许ArcGIS为数据加载确定一个有效的格网大小 targetFCGeoDefEdit.SpatialReference_2 = geometryField.GeometryDef.SpatialReference; //转换要素类中所有的要素 //IQueryFilter queryFilter = serverContext.CreateObject("esriGeoDatabase.QueryFilter") as IQueryFilter; ; QueryFilter queryFilter = new QueryFilterClass(); queryFilter.WhereClause = ""; //加载要素类 //IFeatureDataConverter fctofc = serverContext.CreateObject("esriGeoDatabase.FeatureDataConverter") as IFeatureDataConverter; IFeatureDataConverter fctofc = new FeatureDataConverterClass(); IEnumInvalidObject enumErrors = fctofc.ConvertFeatureClass(sourceFeatureClassName, queryFilter, outfeaturedatasetname, targetFeatureClassName, geometryDef, targetFeatureClassFields, "", 1000, 0); } } featurecount = sourceFeatureClass.FeatureCount(null); m_success = true; } catch (Exception ee) { m_success = false; m_strErr = ee.Message; featurecount = 0; } }
//初始化数据库 创建数据集体 private IDataset CreateDatasetByS(IDataset pDataset, IWorkspace pWks, string strTagDatasetName, ref string strError) { IGeoDataset pGeoDataS = pDataset as IGeoDataset; IWorkspace2 pWks2 = pWks as IWorkspace2; IFeatureWorkspace pFeaWks = pWks as IFeatureWorkspace; IDataset pTagDataset = null; if (!pWks2.get_NameExists(esriDatasetType.esriDTFeatureDataset, strTagDatasetName)) { pTagDataset = pFeaWks.CreateFeatureDataset(strTagDatasetName, pGeoDataS.SpatialReference); } else { pTagDataset = pFeaWks.OpenFeatureDataset(strTagDatasetName); } if (pTagDataset == null) { return(null); } IEnumDataset pEnumSubFeaCls = pDataset.Subsets; IDataset pSubDataset = pEnumSubFeaCls.Next(); while (pSubDataset != null) { IFeatureClass pSubFeaCls = pSubDataset as IFeatureClass; if (pSubFeaCls == null) { pSubDataset = pEnumSubFeaCls.Next(); continue; } string[] strSubNames = pSubDataset.Name.Split('.'); string strSubName = strSubNames[strSubNames.GetLength(0) - 1]; if (pWks2.get_NameExists(esriDatasetType.esriDTFeatureClass, strSubName)) { IFeatureClass pTagCls = pFeaWks.OpenFeatureClass(strSubName); if (pTagCls.FeatureDataset != null) { string[] strTagFeaClsNames = pTagCls.FeatureDataset.Name.Split('.'); string strTagFeaClsName = strTagFeaClsNames[strTagFeaClsNames.GetLength(0) - 1]; if (strTagFeaClsName.ToUpper() == strTagDatasetName.ToUpper()) { pSubDataset = pEnumSubFeaCls.Next(); continue;//已经存在 继续 } else { strError = strError + Environment.NewLine + strSubName + " 不在指定的数据集下"; } } else { strError = strError + Environment.NewLine + strSubName; } } else { //创建要素 IFeatureDataset pTagFeaDataset = pTagDataset as IFeatureDataset; IFeatureClass pTagsubCls = CreateFeatureClass(strSubName, pSubFeaCls, pTagFeaDataset, pTagFeaDataset.Workspace as IFeatureWorkspace); if (pTagsubCls == null) { strError = strError + Environment.NewLine + strSubName + ":要素类创建失败"; pSubDataset = pEnumSubFeaCls.Next();//yjl20110815 continue; } //如果是注记 if (pTagsubCls.FeatureType == esriFeatureType.esriFTAnnotation) { CopyAnnoPropertyToFC(pSubFeaCls, pTagsubCls); } } pSubDataset = pEnumSubFeaCls.Next(); } return(pTagDataset); }
private bool ExportLayers(IMapDocument mapDoc, string strGdbName, bool bLayerSpatial) { //打开GDB工作空间 ClsGDBDataCommon cls = new ClsGDBDataCommon(); //IWorkspace wks = (IWorkspace)cls.OpenFromFileGDB(strGdbName); IWorkspace2 wksFeature = (IWorkspace2)cls.OpenFromFileGDB(strGdbName); if (wksFeature == null) { return(false); } IWorkspaceFactory pWSF = new RasterWorkspaceFactoryClass(); IWorkspace wksRaster = pWSF.OpenFromFile(System.IO.Path.GetDirectoryName(mapDoc.DocumentFilename), 0); if (wksRaster == null) { return(false); } for (int i = 0; i < mapDoc.MapCount; i++) { IMap map = mapDoc.get_Map(i); if (map == null) { continue; } ILayer layer = null; IEnumLayer pEnumLayer = map.get_Layers(null, true); pEnumLayer.Reset(); while ((layer = pEnumLayer.Next()) != null) { //只导出可见图层 if (chkExportVisible.Checked == true) { if (layer.Visible == false) { map.DeleteLayer(layer); continue; } } this.labelExport.Text = "导出:" + layer.Name; this.labelExport.Refresh(); if (layer is IFeatureLayer) { IFeatureClass featureClassNew = CopyFeatureClassToWorkspace(map, layer, wksFeature, bLayerSpatial); if (featureClassNew != null) { //拷贝完成重设数据源 cls.SetdataSourceOfFeatureLayer(layer, featureClassNew); } else { continue; } } else if (layer is IRasterLayer) { IRasterDataset rasterDatasetNew = CopyRasterToWorkspace(map, layer, wksRaster, bLayerSpatial); if (rasterDatasetNew != null) { //拷贝完成重设数据源 IRasterLayer rasterLayer = layer as IRasterLayer; rasterLayer.CreateFromDataset(rasterDatasetNew); } else { continue; } } } } this.labelExport.Text = "导出完成!"; return(true); }
/// <summary> /// creates a new featrue class /// </summary> /// <param name="wks">the workspace to create from</param> /// <param name="polyFtrClsName">name of the feature class</param> /// <param name="atrflds">name of the fields</param> /// <param name="geoType">the geotype</param> /// <param name="sr">spatial reference</param> /// <returns>newly created featureclass</returns> public IFeatureClass createFeatureClass(IWorkspace2 wks, string polyFtrClsName, IFields atrflds, esriGeometryType geoType, ISpatialReference sr) { IFeatureClass tFtr = null; try { IFeatureWorkspace ftrWks = (IFeatureWorkspace)wks; polyFtrClsName = getSafeOutputNameNonRaster((IWorkspace)wks, polyFtrClsName); IFeatureClassDescription fcDescription = new FeatureClassDescriptionClass(); IObjectClassDescription ocDescription = (IObjectClassDescription)fcDescription; IFields fields = ocDescription.RequiredFields; if (atrflds != null) { IFieldsEdit fieldsEdit = (IFieldsEdit)fields; for (int i = 0; i < atrflds.FieldCount; i++) { IField fld = atrflds.get_Field(i); IField nFld = new FieldClass(); IFieldEdit nFldE = (IFieldEdit)nFld; nFldE.Name_2 = fld.Name; if (fld.Type != esriFieldType.esriFieldTypeOID) { nFldE.Type_2 = fld.Type; fieldsEdit.AddField(nFld); } } } // Find the shape field in the required fields and modify its GeometryDef to// use point geometry and to set the spatial reference.int shapeFieldIndex = fields.FindField(fcDescription.ShapeFieldName); IField field = fields.get_Field(fields.FindField(fcDescription.ShapeFieldName)); IGeometryDef geometryDef = field.GeometryDef; IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = geoType; geometryDefEdit.SpatialReference_2 = sr; // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = (IWorkspace)wks; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); tFtr = ftrWks.CreateFeatureClass(polyFtrClsName, validatedFields, ocDescription.InstanceCLSID, ocDescription.ClassExtensionCLSID, esriFeatureType.esriFTSimple, fcDescription.ShapeFieldName, ""); } catch(Exception e) { Console.WriteLine("Error: " + e.ToString()); } return tFtr; }
//not used static bool ifGDBExist(IWorkspace2 ws2, string gdb) { return ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, gdb); }
public static void ExtractSelectFeatureFormFeatureCursor(string string_0, IFeatureCursor ifeatureCursor_0, IFeatureWorkspace ifeatureWorkspace_0, IGeometry igeometry_0) { IEnumFieldError enumFieldError; IFields field; string str; string string0; int num; if (ifeatureCursor_0 != null) { IFields fields = ifeatureCursor_0.Fields; IFieldChecker fieldCheckerClass = new FieldChecker() { ValidateWorkspace = ifeatureWorkspace_0 as IWorkspace }; fieldCheckerClass.Validate(fields, out enumFieldError, out field); char chr = string_0[0]; if ((chr < '0' ? false : chr <= '9')) { string_0 = string.Concat("A", string_0); } fieldCheckerClass.ValidateTableName(string_0, out str); string name = ""; int num1 = 0; while (true) { if (num1 < field.FieldCount) { IField field1 = field.Field[num1]; if (field1.Type == esriFieldType.esriFieldTypeGeometry) { name = field1.Name; IGeometryDef geometryDef = field1.GeometryDef; ISpatialReference spatialReference = geometryDef.SpatialReference; SpatialReferenctOperator.ChangeCoordinateSystem(ifeatureWorkspace_0 as IGeodatabaseRelease, spatialReference, false); (geometryDef as IGeometryDefEdit).SpatialReference_2 = spatialReference; (field1 as IFieldEdit).GeometryDef_2 = geometryDef; break; } else { num1++; } } else { break; } } string_0 = str; if (((ifeatureWorkspace_0 as IWorkspace).Type == esriWorkspaceType.esriLocalDatabaseWorkspace ? false : (ifeatureWorkspace_0 as IWorkspace).Type != esriWorkspaceType.esriRemoteDatabaseWorkspace)) { string str1 = string.Concat((ifeatureWorkspace_0 as IWorkspace).PathName, "\\", string_0); string0 = string.Concat(str1, ".shp"); num = 1; while (File.Exists(string0)) { string0 = string.Concat(str1, "_", num.ToString(), ".shp"); num++; } string_0 = System.IO.Path.GetFileNameWithoutExtension(string0); } else { IWorkspace2 ifeatureWorkspace0 = ifeatureWorkspace_0 as IWorkspace2; string0 = string_0; num = 1; while (ifeatureWorkspace0.NameExists[esriDatasetType.esriDTFeatureClass, string0]) { string0 = string.Concat(string_0, "_", num.ToString()); num++; } string_0 = string0; } try { IFeatureClass featureClass = ifeatureWorkspace_0.CreateFeatureClass(string_0, field, null, null, esriFeatureType.esriFTSimple, name, ""); IFeature feature = ifeatureCursor_0.NextFeature(); IFeatureCursor featureCursor = featureClass.Insert(true); IFeatureBuffer featureBuffer = featureClass.CreateFeatureBuffer(); while (feature != null) { if (feature.Shape != null) { Clip.InsertFeature(featureCursor, featureBuffer, field, feature, feature.Shape, igeometry_0); } feature = ifeatureCursor_0.NextFeature(); } featureCursor.Flush(); Marshal.ReleaseComObject(featureClass); featureClass = null; Marshal.ReleaseComObject(featureBuffer); featureBuffer = null; Marshal.ReleaseComObject(featureCursor); featureCursor = null; } catch { } Marshal.ReleaseComObject(ifeatureCursor_0); ifeatureCursor_0 = null; } }
protected override void OnClick() { m_pApp = (IApplication)ArcMap.Application; if (m_pApp == null) { //if the app is null then could be running from ArcCatalog m_pApp = (IApplication)ArcCatalog.Application; } if (m_pApp == null) { MessageBox.Show("Could not access the application.", "No Application found"); return; } IGxApplication pGXApp = (IGxApplication)m_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; } IMouseCursor pMouseCursor = new MouseCursorClass(); pMouseCursor.SetCursor(2); clsFabricUtils FabricUTILS = new clsFabricUtils(); IProgressDialog2 pProgressorDialog = null; ITable pTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTParcels); IDataset pDS = (IDataset)pTable; IWorkspace pWS = pDS.Workspace; bool bIsFileBasedGDB = true; bool bIsUnVersioned = true; FabricUTILS.GetFabricPlatform(pWS, m_pCadaFab, out bIsFileBasedGDB, out bIsUnVersioned); if (!bIsFileBasedGDB && !bIsUnVersioned) { MessageBox.Show("Truncate operates on non-versioned fabrics." + Environment.NewLine + "Please unversion the fabric and try again.", "Tables are versioned"); return; } //Do a Start and Stop editing to make sure truncate it not running within an edit session if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } FabricUTILS.StopEditing(pWS); dlgTruncate pTruncateDialog = new dlgTruncate(); IArray TableArray = new ESRI.ArcGIS.esriSystem.ArrayClass(); pTruncateDialog.TheFabric = m_pCadaFab; pTruncateDialog.TheTableArray = TableArray; //Display the dialog DialogResult pDialogResult = pTruncateDialog.ShowDialog(); if (pDialogResult != DialogResult.OK) { pTruncateDialog = null; if (TableArray != null) { TableArray.RemoveAll(); } return; } m_pProgressorDialogFact = new ProgressDialogFactoryClass(); m_pTrackCancel = new CancelTrackerClass(); m_pStepProgressor = m_pProgressorDialogFact.Create(m_pTrackCancel, m_pApp.hWnd); pProgressorDialog = (IProgressDialog2)m_pStepProgressor; m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = pTruncateDialog.DropRowCount; m_pStepProgressor.StepValue = 1; pProgressorDialog.Animation = ESRI.ArcGIS.Framework.esriProgressAnimationTypes.esriProgressSpiral; bool bSuccess = false; int iControlRowCount = 0; //look in registry to get flag on whether to run truncate on standard tables, or to delete by row. string sDesktopVers = FabricUTILS.GetDesktopVersionFromRegistry(); if (sDesktopVers.Trim() == "") { sDesktopVers = "Desktop10.0"; } else { sDesktopVers = "Desktop" + sDesktopVers; } bool bDeleteTablesByRowInsteadOfTruncate = false; string sValues = FabricUTILS.ReadFromRegistry(RegistryHive.CurrentUser, "Software\\ESRI\\" + sDesktopVers + "\\ArcMap\\Cadastral", "AddIn.DeleteFabricRecords_Truncate"); if (sValues.Trim().ToLower() == "deletebytruncateonstandardtables" || bIsFileBasedGDB) { bDeleteTablesByRowInsteadOfTruncate = false; } if (sValues.Trim().ToLower() == "deletebyrowonstandardtables") { bDeleteTablesByRowInsteadOfTruncate = true; } if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { // get the control point count ITable pControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); iControlRowCount = pControlTable.RowCount(null); } try { //Work on the table array pTable = null; m_pFIDSet = new FIDSetClass(); for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) ...redundant { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; //Following code uses the truncate method //*** if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { ITableWrite2 pTableWr = (ITableWrite2)pTable; m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; int RowCnt = pTable.RowCount(null); pTableWr.Truncate(); m_pStepProgressor.MaxRange -= RowCnt; //now re-insert the default plan string sName = pDataSet.Name.ToUpper().Trim(); if (sName.EndsWith("_PLANS")) { int idxPlanName = pTable.FindField("Name"); int idxPlanDescription = pTable.FindField("Description"); int idxPlanAngleUnits = pTable.FindField("AngleUnits"); int idxPlanAreaUnits = pTable.FindField("AreaUnits"); int idxPlanDistanceUnits = pTable.FindField("DistanceUnits"); int idxPlanDirectionFormat = pTable.FindField("DirectionFormat"); int idxPlanLineParameters = pTable.FindField("LineParameters"); int idxPlanCombinedGridFactor = pTable.FindField("CombinedGridFactor"); int idxPlanTrueMidBrg = pTable.FindField("TrueMidBrg"); int idxPlanAccuracy = pTable.FindField("Accuracy"); int idxPlanInternalAngles = pTable.FindField("InternalAngles"); ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pTable.CreateRowBuffer(); double dOneMeterEquals = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); bool bIsMetric = (dOneMeterEquals == 1); //write category 1 pRowBuff.set_Value(idxPlanName, "<map>"); pRowBuff.set_Value(idxPlanDescription, "System default plan"); pRowBuff.set_Value(idxPlanAngleUnits, 3); // if (bIsMetric) { pRowBuff.set_Value(idxPlanAreaUnits, 5); pRowBuff.set_Value(idxPlanDistanceUnits, 9001); pRowBuff.set_Value(idxPlanDirectionFormat, 1); } else { pRowBuff.set_Value(idxPlanAreaUnits, 4); pRowBuff.set_Value(idxPlanDistanceUnits, 9003); pRowBuff.set_Value(idxPlanDirectionFormat, 4); } pRowBuff.set_Value(idxPlanLineParameters, 4); pRowBuff.set_Value(idxPlanCombinedGridFactor, 1); //pRowBuff.set_Value(idxPlanTrueMidBrg, 1); pRowBuff.set_Value(idxPlanAccuracy, 4); pRowBuff.set_Value(idxPlanInternalAngles, 0); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } } } } } catch (COMException ex) { MessageBox.Show(ex.Message + ": " + Convert.ToString(ex.ErrorCode)); Cleanup(pProgressorDialog, pMouseCursor); return; } //do the loop again, this time within the edit transaction and using the delete function for the chosen tables try { //Start an Edit Transaction if (!FabricUTILS.StartEditing(pWS, bIsUnVersioned)) {//if start editing fails then bail Cleanup(pProgressorDialog, pMouseCursor); return; } for (int i = 0; i <= TableArray.Count - 1; i++) { //if (TableArray.get_Element(i) is ITable) { pTable = (ITable)TableArray.get_Element(i); IDataset pDataSet = (IDataset)pTable; if (pTable is IFeatureClass || !bDeleteTablesByRowInsteadOfTruncate) { } else { //The following code is in place to workaround a limitation of truncate for fabric classes //without a shapefield. It uses an alternative method for removing all the rows //with the Delete function. //General note: This method could be used exclusively, without needing the truncate method. //One advantage is that it allows the option to cancel the whole //operation using the cancel tracker. Truncate is faster, but is problematic if //the truncate fails, and leaves a partially deleted fabric. For example, if the //lines table is deleted but the points table truncate fails, the fabric would be in a //corrupt state. //**** m_pFIDSet.SetEmpty(); string sName = pDataSet.Name.ToUpper().Trim(); m_pStepProgressor.Message = "Loading rows from " + pDataSet.Name; if (sName.EndsWith("_PLANS")) {//for Plans table make sure the default plan is not deleted IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); string sFieldName = "NAME"; //pQF.WhereClause = sPref + sFieldName + sSuff + " <> '<map>'"; pQF.WhereClause = sFieldName + " <> '<map>'"; if (!BuildFIDSetFromTable(pTable, pQF, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } else { if (!BuildFIDSetFromTable(pTable, null, ref m_pFIDSet)) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } if (m_pFIDSet.Count() == 0) { continue; } m_pStepProgressor.Message = "Deleting all rows in " + pDataSet.Name; bSuccess = FabricUTILS.DeleteRowsUnversioned(pWS, pTable, m_pFIDSet, m_pStepProgressor, m_pTrackCancel); if (!bSuccess) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } } } } //now need to Fix control-to-point associations if one table was truncated //and the other was not if (pTruncateDialog.TruncateControl && !pTruncateDialog.TruncateParcelsLinesPoints) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); ITable PointTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.Message = "Resetting control associations on points...please wait."; int idxFld = PointTable.FindField("NAME"); string sFieldName = PointTable.Fields.get_Field(idxFld).Name; //NAME IS NOT NULL AND (NAME <>'' OR NAME <>' ') //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND (" + // sPref + sFieldName + sSuff + "<>'' OR " + sPref + sFieldName + sSuff + " <>' ')"; //pQF.WhereClause = sFieldName + " IS NOT NULL AND (" + sFieldName + "<>'' OR " + sFieldName + " <>' ')"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " > ''"; //changed 1/14/2016 ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(PointTable, esriCadastralFabricTable.esriCFTPoints); m_pStepProgressor.MinRange = 0; m_pStepProgressor.MaxRange = iControlRowCount; if (!ResetPointAssociations(PointTable, pQF, true, m_pStepProgressor, m_pTrackCancel)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTPoints); } else if (pTruncateDialog.TruncateParcelsLinesPoints && !pTruncateDialog.TruncateControl) { IQueryFilter pQF = new QueryFilterClass(); string sPref; string sSuff; ISQLSyntax pSQLSyntax = (ISQLSyntax)pWS; sPref = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierPrefix); sSuff = pSQLSyntax.GetSpecialCharacter(esriSQLSpecialCharacters.esriSQL_DelimitedIdentifierSuffix); //POINTID >=0 AND POINTID IS NOT NULL m_pStepProgressor.Message = "Resetting associations on control points...please wait."; ITable ControlTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTControl); int idxFld = ControlTable.FindField("POINTID"); string sFieldName = ControlTable.Fields.get_Field(idxFld).Name; //pQF.WhereClause = sPref + sFieldName + sSuff + " IS NOT NULL AND " + // sPref + sFieldName + sSuff + " >=0"; pQF.WhereClause = sFieldName + " IS NOT NULL AND " + sFieldName + " >=0"; ICadastralFabricSchemaEdit2 pSchemaEd = (ICadastralFabricSchemaEdit2)m_pCadaFab; pSchemaEd.ReleaseReadOnlyFields(ControlTable, esriCadastralFabricTable.esriCFTControl); if (!FabricUTILS.ResetControlAssociations(ControlTable, null, true)) { pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); return; } pSchemaEd.ResetReadOnlyFields(esriCadastralFabricTable.esriCFTControl); } //now need to re-assign default accuracy table values, if the option was checked if (pTruncateDialog.ResetAccuracyTableDefaults) { double dCat1 = FabricUTILS.ConvertMetersToFabricUnits(0.001, m_pCadaFab); double dCat2 = FabricUTILS.ConvertMetersToFabricUnits(0.01, m_pCadaFab); double dCat3 = FabricUTILS.ConvertMetersToFabricUnits(0.02, m_pCadaFab); double dCat4 = FabricUTILS.ConvertMetersToFabricUnits(0.05, m_pCadaFab); double dCat5 = FabricUTILS.ConvertMetersToFabricUnits(0.2, m_pCadaFab); double dCat6 = FabricUTILS.ConvertMetersToFabricUnits(1, m_pCadaFab); double dCat7 = FabricUTILS.ConvertMetersToFabricUnits(10, m_pCadaFab); ITable pAccTable = m_pCadaFab.get_CadastralTable(esriCadastralFabricTable.esriCFTAccuracy); int idxBrgSD = pAccTable.FindField("BrgSD"); int idxDistSD = pAccTable.FindField("DistSD"); int idxPPM = pAccTable.FindField("PPM"); int idxCategory = pAccTable.FindField("Category"); int idxDescription = pAccTable.FindField("Description"); ITableWrite2 pTableWr = (ITableWrite2)pAccTable; ICursor pCur = pTableWr.InsertRows(false); IRowBuffer pRowBuff = pAccTable.CreateRowBuffer(); //write category 1 pRowBuff.set_Value(idxCategory, 1); pRowBuff.set_Value(idxBrgSD, 5); pRowBuff.set_Value(idxDistSD, dCat1); pRowBuff.set_Value(idxPPM, 5); pRowBuff.set_Value(idxDescription, "1 - Highest"); pCur.InsertRow(pRowBuff); //write category 2 pRowBuff.set_Value(idxCategory, 2); pRowBuff.set_Value(idxBrgSD, 30); pRowBuff.set_Value(idxDistSD, dCat2); pRowBuff.set_Value(idxPPM, 25); pRowBuff.set_Value(idxDescription, "2 - After 1980"); pCur.InsertRow(pRowBuff); //write category 3 pRowBuff.set_Value(idxCategory, 3); pRowBuff.set_Value(idxBrgSD, 60); pRowBuff.set_Value(idxDistSD, dCat3); pRowBuff.set_Value(idxPPM, 50); pRowBuff.set_Value(idxDescription, "3 - 1908 to 1980"); pCur.InsertRow(pRowBuff); //write category 4 pRowBuff.set_Value(idxCategory, 4); pRowBuff.set_Value(idxBrgSD, 120); pRowBuff.set_Value(idxDistSD, dCat4); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "4 - 1881 to 1907"); pCur.InsertRow(pRowBuff); //write category 5 pRowBuff.set_Value(idxCategory, 5); pRowBuff.set_Value(idxBrgSD, 300); pRowBuff.set_Value(idxDistSD, dCat5); pRowBuff.set_Value(idxPPM, 125); pRowBuff.set_Value(idxDescription, "5 - Before 1881"); pCur.InsertRow(pRowBuff); //write category 6 pRowBuff.set_Value(idxCategory, 6); pRowBuff.set_Value(idxBrgSD, 3600); pRowBuff.set_Value(idxDistSD, dCat6); pRowBuff.set_Value(idxPPM, 1000); pRowBuff.set_Value(idxDescription, "6 - 1800"); pCur.InsertRow(pRowBuff); //write category 7 pRowBuff.set_Value(idxCategory, 7); pRowBuff.set_Value(idxBrgSD, 6000); pRowBuff.set_Value(idxDistSD, dCat7); pRowBuff.set_Value(idxPPM, 5000); pRowBuff.set_Value(idxDescription, "7 - Lowest"); pCur.InsertRow(pRowBuff); pCur.Flush(); if (pRowBuff != null) { Marshal.ReleaseComObject(pRowBuff); } if (pCur != null) { Marshal.ReleaseComObject(pCur); } } //now need to cleanup the IDSequence table if ALL the tables were truncated if (pTruncateDialog.TruncateControl && pTruncateDialog.TruncateParcelsLinesPoints && pTruncateDialog.TruncateJobs && pTruncateDialog.TruncateAdjustments) { IWorkspace2 pWS2 = (IWorkspace2)pWS; IDataset TheFabricDS = (IDataset)m_pCadaFab; string sFabricName = TheFabricDS.Name; string sName = sFabricName + "_IDSequencer"; bool bExists = pWS2.get_NameExists(esriDatasetType.esriDTTable, sName); IFeatureWorkspace pFWS = (IFeatureWorkspace)pWS; ITable pSequencerTable; if (bExists) { pSequencerTable = pFWS.OpenTable(sName); IFIDSet pFIDSet = new FIDSetClass(); if (BuildFIDSetFromTable(pSequencerTable, null, ref pFIDSet)) { FabricUTILS.DeleteRowsUnversioned(pWS, pSequencerTable, pFIDSet, null, null); } } } Cleanup(pProgressorDialog, pMouseCursor); if (TableArray != null) { TableArray.RemoveAll(); } FabricUTILS.StopEditing(pWS); } catch (Exception ex) { FabricUTILS.AbortEditing(pWS); Cleanup(pProgressorDialog, pMouseCursor); MessageBox.Show(Convert.ToString(ex.Message)); } }
public override bool Pretreat() { try { //SendMessage(enumMessageType.RuleError, "正在准备数据"); IFeatureWorkspace fws = m_TopoWorkspace as IFeatureWorkspace; IWorkspace2 ws2 = m_TopoWorkspace as IWorkspace2; IFeatureClassContainer fClassContainer = this.m_Topology as IFeatureClassContainer; IEnumFeatureClass enFeatureClass = fClassContainer.Classes; IFeatureClass fClass = enFeatureClass.Next(); IFeatureClass fClassRefer = null; bool isAdded = false; while (fClass != null) { IDataset ds = fClass as IDataset; if (ds.Name == m_LayerName) { isAdded = true; break; } fClass = enFeatureClass.Next(); } if (!isAdded) { if (!ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, m_LayerName)) { SendMessage(enumMessageType.RuleError, string.Format("图层{0}导入拓扑库失败,无法检查", this.m_psRuleParas.arraySeledLayers[0])); return(false); } fClass = fws.OpenFeatureClass(m_LayerName); this.m_Topology.AddClass(fClass as IClass, 1, m_psRuleParas.arrayRanks[0], 1, false); } if (this.m_psRuleParas.arraySeledLayers.Count > 1) { enFeatureClass.Reset(); fClassRefer = enFeatureClass.Next(); isAdded = false; while (fClass != null) { IDataset ds = fClassRefer as IDataset; if (ds.Name == m_ReferLayerName) { isAdded = true; break; } fClassRefer = enFeatureClass.Next(); } if (!isAdded) { if (!ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, m_ReferLayerName)) { SendMessage(enumMessageType.RuleError, string.Format("图层{0}不存在,无法检查", this.m_psRuleParas.arraySeledLayers[1])); return(false); } fClassRefer = fws.OpenFeatureClass(m_ReferLayerName); this.m_Topology.AddClass(fClass as IClass, 1, m_psRuleParas.arrayRanks[1], 1, false); } } m_TopologylRule = new TopologyRuleClass(); m_TopologylRule.Name = m_psRuleParas.arrayRules[0].strRuleAliasName; m_TopologylRule.OriginClassID = fClass.ObjectClassID; if (fClassRefer != null) { m_TopologylRule.DestinationClassID = fClassRefer.ObjectClassID; } m_TopologylRule.AllOriginSubtypes = true; m_TopologylRule.AllDestinationSubtypes = true; m_TopologylRule.TopologyRuleType = GetTopologyTypeByName(m_psRuleParas.arrayRules[0].strTopoRuleName); (this.m_Topology as ITopologyRuleContainer).AddRule(m_TopologylRule); return(true); } catch (Exception exp) { SendMessage(enumMessageType.PretreatmentError, "加入到拓扑时出错,信息:" + exp.Message); SendMessage(enumMessageType.Exception, exp.ToString()); return(false); } }
protected bool InWorkspace(IWorkspace2 wksp2, esriDatasetType type, String name) { ISQLSyntax sqlSyntax = (ISQLSyntax)wksp2; String fqname = sqlSyntax.QualifyTableName(_dbName, _ownerName, name); bool result = true; IWorkspace workspace = wksp2 as IWorkspace; if (wksp2.get_NameExists(type, fqname)) { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Exists check: " + fqname, "PASS"); } else { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Exists check: " + fqname, "FAIL"); return false; } return result; }
public static IFeatureClass CreateFeatureClassInPGDB(IWorkspace2 workspace, IFeatureDataset featureDataset, string featureClassName, IFields fields, UID CLSID, UID CLSEXT, string strConfigKeyword, esriGeometryType esriGeometryType) { if (featureClassName == "") return null; // name was not passed in ESRI.ArcGIS.Geodatabase.IFeatureClass featureClass; ESRI.ArcGIS.Geodatabase.IFeatureWorkspace featureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)workspace; // Explicit Cast if (workspace.get_NameExists(ESRI.ArcGIS.Geodatabase.esriDatasetType.esriDTFeatureClass, featureClassName)) //feature class with that name already exists { featureClass = featureWorkspace.OpenFeatureClass(featureClassName); return featureClass; } // assign the class id value if not assigned if (CLSID == null) { CLSID = new ESRI.ArcGIS.esriSystem.UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; } ESRI.ArcGIS.Geodatabase.IObjectClassDescription objectClassDescription = new ESRI.ArcGIS.Geodatabase.FeatureClassDescriptionClass(); // if a fields collection is not passed in then supply our own if (fields == null) { // create the fields using the required fields method fields = objectClassDescription.RequiredFields; ESRI.ArcGIS.Geodatabase.IFieldsEdit fieldsEdit = (ESRI.ArcGIS.Geodatabase.IFieldsEdit)fields; // Explicit Cast ESRI.ArcGIS.Geodatabase.IField field = new ESRI.ArcGIS.Geodatabase.FieldClass(); // create a user defined text field ESRI.ArcGIS.Geodatabase.IFieldEdit fieldEdit = (ESRI.ArcGIS.Geodatabase.IFieldEdit)field; // Explicit Cast // setup field properties fieldEdit.Name_2 = "SampleField"; fieldEdit.Type_2 = ESRI.ArcGIS.Geodatabase.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 = (ESRI.ArcGIS.Geodatabase.IFields)fieldsEdit; // Explicit Cast } System.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; ((IGeometryDefEdit)fields.get_Field(j).GeometryDef).GeometryType_2 = esriGeometryType; } } // Use IFieldChecker to create a validated fields collection. ESRI.ArcGIS.Geodatabase.IFieldChecker fieldChecker = new ESRI.ArcGIS.Geodatabase.FieldCheckerClass(); ESRI.ArcGIS.Geodatabase.IEnumFieldError enumFieldError = null; ESRI.ArcGIS.Geodatabase.IFields validatedFields = null; fieldChecker.ValidateWorkspace = (ESRI.ArcGIS.Geodatabase.IWorkspace)workspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. // finally create and return the feature class if (featureDataset == null)// if no feature dataset passed in, create at the workspace level { featureClass = featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, CLSID, CLSEXT, ESRI.ArcGIS.Geodatabase.esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword); } else { featureClass = featureDataset.CreateFeatureClass(featureClassName, validatedFields, CLSID, CLSEXT, ESRI.ArcGIS.Geodatabase.esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword); } return featureClass; }
protected override void OnClick() { try { if (this.pGxApp.Selection.Count != 1) { return; } IGxObject pGxObject = this.pGxApp.SelectedObject; if (!(pGxObject is IGxDataset)) { return; } IGxDataset pGxDataset = pGxObject as IGxDataset; if (pGxDataset == null) { return; } if (((pGxObject as IGxDataset).Type) != esriDatasetType.esriDTFeatureDataset) { MessageBox.Show("Select a Feature Dataset!", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation); return; } IFeatureDataset fDataset = pGxDataset.Dataset as IFeatureDataset; IWorkspace2 workspace = fDataset.Workspace as IWorkspace2; IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; DialogResult dialogResult = MessageBox.Show($@"Remove custom extension for all Feature Classes in {fDataset.Name}", "Attention", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (dialogResult == DialogResult.Yes) { IEnumDataset enumDataset = fDataset.Subsets; IDataset dataset = enumDataset.Next(); IObjectClassDescription ocDescriptionAnnotation = new AnnotationFeatureClassDescriptionClass(); IObjectClassDescription ocDescriptionDimension = new DimensionClassDescriptionClass(); while (dataset != null) { if (dataset is IClass) { IClass pClass = dataset as IClass; if (pClass.EXTCLSID != null) { if ((pClass.EXTCLSID.Value.ToString().ToLower() != ocDescriptionAnnotation.ClassExtensionCLSID.Value.ToString().ToLower()) && (pClass.EXTCLSID.SubType != ocDescriptionAnnotation.ClassExtensionCLSID.SubType) && (pClass.EXTCLSID.Value.ToString().ToLower() != ocDescriptionDimension.ClassExtensionCLSID.Value.ToString().ToLower()) && (pClass.EXTCLSID.SubType != ocDescriptionDimension.ClassExtensionCLSID.SubType)) { clsGenericStudioAT.RemoveClsExt(pClass); } } } dataset = enumDataset.Next(); } MessageBox.Show("All Extension removed!", "Ok", MessageBoxButtons.OK, MessageBoxIcon.Information); } } catch (Exception errore) { MessageBox.Show(errore.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); throw; } }
/// <summary> /// /// </summary> /// <param name="outName"></param> /// <param name="isDissolved"></param> /// <returns></returns> public static IFeatureClass CreateOutputFc(string outPath, IFeatureClass inputFc, bool isDissolved) { IFeatureWorkspace fws = getWorkspace(outPath); //Debug.WriteLine(outPath); //Debug.WriteLine((fws as IWorkspace).PathName); IFeatureClass fc = null; string[] pathParts = outPath.Split('\\'); string outName = pathParts[pathParts.Length - 1]; string featDatasetName = null; IFeatureDataset featDs = null; if (pathParts.Length > 3) { if (pathParts[pathParts.Length - 3].ToLower().IndexOf(".gdb") > -1) { featDatasetName = pathParts[pathParts.Length - 2]; } } if (featDatasetName == null) { IWorkspace2 ws2 = fws as IWorkspace2; if (ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, outName)) { IDataset dsExist = (IDataset)((IFeatureWorkspace)ws2).OpenFeatureClass(outName); deleteFeatureClass(dsExist); } } else { IEnumDataset enumFds = (fws as IWorkspace).get_Datasets(esriDatasetType.esriDTFeatureDataset); IDataset _fds; while ((_fds = enumFds.Next()) != null) { if (_fds.Name == featDatasetName) { featDs = (IFeatureDataset)_fds; IEnumDataset enumFcs = featDs.Subsets; IDataset ids; while ((ids = enumFcs.Next()) != null) { if (ids.Name.ToLower() == outName.ToLower()) { deleteFeatureClass(ids); break; } } break; } } } IFields fields = GetCurveAreaFields(outName.IndexOf(".shp") > -1, isDissolved, ((IGeoDataset)inputFc).SpatialReference); try { if (featDs == null) { fc = fws.CreateFeatureClass(outName, fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "SHAPE", ""); } else { fc = featDs.CreateFeatureClass(outName, fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "SHAPE", ""); } } catch (System.Runtime.InteropServices.COMException ex) { string errorMessage = "Could not create output feature class:\n"; if (featDs == null) { errorMessage += System.IO.Path.Combine((fws as IWorkspace).PathName, outName) + "\n"; } else { errorMessage += System.IO.Path.Combine((fws as IWorkspace).PathName, featDs.Name, outName) + "\n"; } errorMessage += ex.Message; throw new System.IO.IOException(errorMessage); } return(fc); }
string m_strErr; //错误信息提醒 //SHP数据入库到GDB数据库的方法 private void ImportFeatureClassToNewWorkSpace(string filename, string outfilename) { //try //{ m_success = false; //初始化 string ImportShapeFileName = filename; string ExportFileShortName = outfilename; if (ImportShapeFileName == "") { return; } string ImportFileShortName = System.IO.Path.GetFileNameWithoutExtension(ImportShapeFileName); string ImportFilePath = System.IO.Path.GetDirectoryName(ImportShapeFileName); //打开存在的工作空间,作为导入的空间 IWorkspaceFactory Pwf = new FileGDBWorkspaceFactoryClass(); //IWorkspace pWorkspace = Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0); // IWorkspace2 pWorkspace2 =(IWorkspace2)(Pwf.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0)); IWorkspace pWorkspace = GetWorkspace(comboBoxSource.Text); if (pWorkspace == null) { m_strErr = "数据源未找到"; m_success = false; return; } string username = GetSourceUser(comboBoxSource.Text); if (username.Trim() != "") { ExportFileShortName = username + "." + ExportFileShortName; } IWorkspace2 pWorkspace2 = pWorkspace as IWorkspace2; //判断要素是否存在,若存在将删除源文件 if (pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, ExportFileShortName)) { if (m_newfile == true) { IFeatureClass tmpfeatureclass; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pWorkspace; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(ExportFileShortName); IDataset set = tmpfeatureclass as IDataset; fdr.DeleteSql(ExportFileShortName); set.CanDelete(); set.Delete(); } else { //MessageBox.Show("存在相同文件名", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); m_strErr = "存在相同文件名"; m_success = false; return; } } IWorkspaceName pInWorkspaceName; IFeatureDatasetName pOutFeatureDSName; IFeatureClassName pInFeatureClassName; IDatasetName pInDatasetName; IFeatureClassName pOutFeatureClassName; IDatasetName pOutDatasetName; long iCounter; IFields pOutFields, pInFields; IFieldChecker pFieldChecker; IField pGeoField; IGeometryDef pOutGeometryDef; IGeometryDefEdit pOutGeometryDefEdit; IName pName; IFeatureClass pInFeatureClass; IFeatureDataConverter pShpToClsConverter; IEnumFieldError pEnumFieldError = null; //得到一个输入SHP文件的工作空间, pInWorkspaceName = new WorkspaceNameClass(); pInWorkspaceName.PathName = ImportFilePath; pInWorkspaceName.WorkspaceFactoryProgID = "esriCore.ShapefileWorkspaceFactory.1"; //创建一个新的要素类名称,目的是为了以来PNAME接口的OPEN方法打开SHP文件 pInFeatureClassName = new FeatureClassNameClass(); pInDatasetName = (IDatasetName)pInFeatureClassName; pInDatasetName.Name = ImportFileShortName; pInDatasetName.WorkspaceName = pInWorkspaceName; //打开一个SHP文件,将要读取它的字段集合 pName = (IName)pInFeatureClassName; pInFeatureClass = (IFeatureClass)pName.Open(); //通过FIELDCHECKER检查字段的合法性,为输入要素类获得字段集合 pInFields = pInFeatureClass.Fields; pFieldChecker = new FieldChecker(); pFieldChecker.Validate(pInFields, out pEnumFieldError, out pOutFields); //通过循环查找几何字段 pGeoField = null; for (iCounter = 0; iCounter < pOutFields.FieldCount; iCounter++) { if (pOutFields.get_Field((int)iCounter).Type == esriFieldType.esriFieldTypeGeometry) { pGeoField = pOutFields.get_Field((int)iCounter); break; } } //得到几何字段的几何定义 pOutGeometryDef = pGeoField.GeometryDef; //设置几何字段的空间参考和网格 pOutGeometryDefEdit = (IGeometryDefEdit)pOutGeometryDef; pOutGeometryDefEdit.GridCount_2 = 1; pOutGeometryDefEdit.set_GridSize(0, 1500000); //创建一个新的要素类名称作为可用的参数 pOutFeatureClassName = new FeatureClassNameClass(); pOutDatasetName = (IDatasetName)pOutFeatureClassName; pOutDatasetName.Name = ExportFileShortName; //创建一个新的数据集名称作为可用的参数 pOutFeatureDSName = (IFeatureDatasetName) new FeatureDatasetName(); //如果参数的值是NULL,说明要创建独立要素类 //创建一个不存在的要素集合pFDN,通过它将IFeatureClassName和工作空间连接起来,而ConvertFeatureClass函数并不使用该变量作为参数, IFeatureDatasetName pFDN = new FeatureDatasetNameClass(); IDatasetName pDN = (IDatasetName)pFDN; IDataset pDS = (IDataset)pWorkspace; pDN.WorkspaceName = (IWorkspaceName)pDS.FullName; pOutFeatureClassName.FeatureDatasetName = (IDatasetName)pFDN; //将pOutFeatureDSName设置为Null,将它做为参数给ConvertFeatureClass函数,因为IFeatureClassName本身已经和工作空间关联了,生成的 //要素类在工作空间的根目录下,即独立要素类 pOutFeatureDSName = null; //开始导入 if (InsertIntoDatabase(ExportFileShortName)) { pShpToClsConverter = new FeatureDataConverterClass(); pShpToClsConverter.ConvertFeatureClass(pInFeatureClassName, null, pOutFeatureDSName, pOutFeatureClassName, pOutGeometryDef, pOutFields, "", 1000, 0); //MessageBox.Show("导入成功", "提示"); m_success = true; } //} //catch //{ // m_success = false; //} }
private void btn_Del_Click(object sender, EventArgs e) { bool flag = false; foreach (DataGridViewRow row in dataGridView.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { flag = true; } } if (!flag) { MessageBox.Show("没有选中行,无法删除", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } DialogResult result = MessageBox.Show("是否确定删除!", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question); if (result == DialogResult.Yes) { foreach (DataGridViewRow row in dataGridView.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { string cellvalue = row.Cells[1].Value.ToString().Trim(); IWorkspace pWorkspace = GetWorkspace(comboBoxSource.Text); if (pWorkspace == null) { MessageBox.Show("数据源空间不存在!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } IWorkspace2 pWorkspace2 = (IWorkspace2)pWorkspace; // if (pWorkspace2.get_NameExists(esriDatasetType.esriDTRasterDataset, cellvalue)) { IEnumDataset enumDataset = pWorkspace.get_Datasets(esriDatasetType.esriDTRasterCatalog) as IEnumDataset; IDataset dataset = enumDataset.Next(); while (dataset != null) { if (dataset.Name.Trim() == comboBoxCatalog.Text.Trim()) { ITable pTable = dataset as ITable; //IRasterCatalog irastercatalog = (IRasterCatalog)dataset; ICursor pCursor = pTable.Search(null, false); IRow pRow = pCursor.NextRow(); while (pRow != null) { if (pRow.get_Value(pRow.Fields.FindField("Name")).ToString() == cellvalue) { this.Cursor = Cursors.WaitCursor; pRow.Delete();//如果相等则删除 this.Cursor = Cursors.Default; } pRow = pCursor.NextRow(); } } dataset = enumDataset.Next(); } } } } dataGridView.Rows.Clear(); LoadDataGridView();//重新加载数据 MessageBox.Show("删除数据成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } }
public bool CheckIn(IWorkspace store, string versionName, string dbpath, string gridFeatureClass, string gridCodeFieldName) { //创建子版本 IVersion ver_store = store as IVersion; IVersion new_version = ver_store.CreateVersion(versionName); new_version.Access = esriVersionAccess.esriVersionAccessPublic; IFeatureWorkspace target_ws = new_version as IFeatureWorkspace; IWorkspaceEdit2 wse = target_ws as IWorkspaceEdit2; //删除TaskGridLog ITable grid_tbl = target_ws.OpenTable("TaskGridLog"); IQueryFilter grid_filter = new QueryFilterClass(); grid_filter.WhereClause = "TaskName = '" + versionName + "'"; wse.StartEditing(false); grid_tbl.DeleteSearchedRows(grid_filter); wse.StopEditing(true); //删除CheckItem IQueryFilter checkItems_filter = new QueryFilterClass(); checkItems_filter.WhereClause = "versionName = '" + versionName + "'"; ITable checkItems = target_ws.OpenTable("CheckItemPtn"); checkItems.DeleteSearchedRows(checkItems_filter); checkItems = target_ws.OpenTable("CheckItemLn"); checkItems.DeleteSearchedRows(checkItems_filter); checkItems = target_ws.OpenTable("CheckItemPoly"); checkItems.DeleteSearchedRows(checkItems_filter); IFeatureClass grid_fc = target_ws.OpenFeatureClass(gridFeatureClass); int gridCodeFld_idx = grid_fc.FindField(gridCodeFieldName); Dictionary <string, int[]> updateGridCodes = new Dictionary <string, int[]>(); ISpatialFilter gridFilter = new SpatialFilter(); gridFilter.GeometryField = grid_fc.ShapeFieldName; gridFilter.AddField(gridCodeFieldName); gridFilter.SpatialRel = esriSpatialRelEnum.esriSpatialRelIntersects; //总更新网格面积 double totalUpdateGridsArea = 0; double totalUpdateGrids = 0; double totalUpdateItems = 0; double totalAddItems = 0; double totalDeleteItems = 0; wse.StartEditing(true); try { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IWorkspace source = workspaceFactory.OpenFromFile(dbpath, 0); IDataset ds = source as IDataset; List <String> fcNames = new List <string>(); Util.GetAllFeatureClassNames(ds, ref fcNames); IFeatureWorkspace source_ws = source as IFeatureWorkspace; foreach (string fcname in fcNames) { IWorkspace2 target_ws2 = target_ws as IWorkspace2; if (!target_ws2.get_NameExists(esriDatasetType.esriDTFeatureClass, fcname)) { continue; } IFeatureClass source_fc = source_ws.OpenFeatureClass(fcname); IFeatureClass target_fc = target_ws.OpenFeatureClass(fcname); int syncid_idx = source_fc.FindField("SyncID"); Dictionary <int, int> field_idxs = new Dictionary <int, int>(); for (int i = 0; i < source_fc.Fields.FieldCount; i++) { IField source_field = source_fc.Fields.get_Field(i); if (source_field.Name == "SyncID") { continue; } if (source_field.Name == "SyncTimeStamp") { continue; } if (source_field.Name == "SyncStatus") { continue; } if (source_field.Name == "SyncEditable") { continue; } if (source_field.Name == source_fc.OIDFieldName) { continue; } int j = target_fc.FindField(source_field.Name); if (j != -1) { field_idxs.Add(i, j); } } string checkItemName; switch (target_fc.ShapeType) { case esriGeometryType.esriGeometryPoint: checkItemName = "CheckItemPtn"; break; case esriGeometryType.esriGeometryPolyline: checkItemName = "CheckItemLn"; break; case esriGeometryType.esriGeometryPolygon: checkItemName = "CheckItemPoly"; break; default: checkItemName = "CheckItemPoly"; break; } IFeatureClass checkItem_fc = target_ws.OpenFeatureClass(checkItemName); int checkItem_f1 = checkItem_fc.FindField("FeatureClassName"); int checkItem_f2 = checkItem_fc.FindField("FeatureID"); int checkItem_f3 = checkItem_fc.FindField("VersionName"); int checkItem_f4 = checkItem_fc.FindField(checkItem_fc.ShapeFieldName); IGeoDataset checkItem_gds = checkItem_fc as IGeoDataset; //同步更新 wse.StartEditOperation(); IQueryFilter filter = new QueryFilterClass(); filter.WhereClause = "[SyncStatus]='U'"; IFeatureCursor source_cur = source_fc.Search(filter, false); IFeature source_fea = source_cur.NextFeature(); while (source_fea != null) { int id = Convert.ToInt32(source_fea.get_Value(syncid_idx)); IFeature target_fea = target_fc.GetFeature(id); foreach (KeyValuePair <int, int> field_idx in field_idxs) { target_fea.set_Value(field_idx.Value, source_fea.get_Value(field_idx.Key)); } target_fea.Store(); //添加check item IFeature checkItem_fea = checkItem_fc.CreateFeature(); checkItem_fea.set_Value(checkItem_f1, fcname); checkItem_fea.set_Value(checkItem_f2, id); checkItem_fea.set_Value(checkItem_f3, versionName); IGeometry shape = target_fea.ShapeCopy; shape.Project(checkItem_gds.SpatialReference); checkItem_fea.set_Value(checkItem_f4, shape); checkItem_fea.Store(); //添加TaskGridLog gridFilter.Geometry = target_fea.Shape; IFeatureCursor grid_cur = grid_fc.Search(gridFilter, true); IFeature grid_fea = grid_cur.NextFeature(); while (grid_fea != null) { string gridid = grid_fea.get_Value(gridCodeFld_idx).ToString(); if (updateGridCodes.ContainsKey(gridid)) { updateGridCodes[gridid][0] += 1; } else { int[] c = new int[2] { 1, 0 }; updateGridCodes.Add(gridid, c); } IArea area = grid_fea.Shape as IArea; totalUpdateGridsArea += area.Area; grid_fea = grid_cur.NextFeature(); } totalUpdateItems += 1; source_fea = source_cur.NextFeature(); } wse.StopEditOperation(); //同步删除 wse.StartEditOperation(); List <int> lst_del = new List <int>(); TaskManager tm = TaskManager.GetInstance(); ISpatialFilter target_filter = new SpatialFilterClass(); target_filter.Geometry = tm.GetTaskLocation(versionName); target_filter.SpatialRel = esriSpatialRelEnum.esriSpatialRelContains; target_filter.SubFields = ""; using (ComReleaser comReleaser = new ComReleaser()) { IFeatureCursor target_fea_cur = target_fc.Search(target_filter, false); comReleaser.ManageLifetime(target_fea_cur); IFeature target_fea_del = target_fea_cur.NextFeature(); while (target_fea_del != null) { filter = new QueryFilterClass(); filter.WhereClause = "[SyncID]=" + target_fea_del.OID.ToString(); using (ComReleaser comReleaser2 = new ComReleaser()) { IFeatureCursor source_cur_del = source_fc.Search(filter, true); comReleaser2.ManageLifetime(source_cur_del); source_fea = source_cur_del.NextFeature(); if (source_fea == null) { lst_del.Add(target_fea_del.OID); totalDeleteItems += 1; } } target_fea_del = target_fea_cur.NextFeature(); } } foreach (int id in lst_del) { IFeature target_fea_del = target_fc.GetFeature(id); target_fea_del.Delete(); } wse.StopEditOperation(); //同步新建 wse.StartEditOperation(); filter = new QueryFilterClass(); filter.WhereClause = "[SyncID] is null"; source_cur = source_fc.Search(filter, false); source_fea = source_cur.NextFeature(); while (source_fea != null) { IFeature target_fea = target_fc.CreateFeature(); foreach (KeyValuePair <int, int> field_idx in field_idxs) { target_fea.set_Value(field_idx.Value, source_fea.get_Value(field_idx.Key)); } target_fea.Store(); //添加check item IFeature checkItem_fea = checkItem_fc.CreateFeature(); checkItem_fea.set_Value(checkItem_f1, fcname); checkItem_fea.set_Value(checkItem_f2, target_fea.OID); checkItem_fea.set_Value(checkItem_f3, versionName); IGeometry shape = target_fea.ShapeCopy; shape.Project(checkItem_gds.SpatialReference); checkItem_fea.set_Value(checkItem_f4, shape); checkItem_fea.Store(); //添加TaskGridLog gridFilter.Geometry = target_fea.Shape; IFeatureCursor grid_cur = grid_fc.Search(gridFilter, true); IFeature grid_fea = grid_cur.NextFeature(); while (grid_fea != null) { string gridid = grid_fea.get_Value(gridCodeFld_idx).ToString(); if (updateGridCodes.ContainsKey(gridid)) { updateGridCodes[gridid][1] += 1; } else { int[] c = new int[2] { 0, 1 }; updateGridCodes.Add(gridid, c); } IArea area = grid_fea.Shape as IArea; totalUpdateGridsArea += area.Area; grid_fea = grid_cur.NextFeature(); } totalAddItems += 1; source_fea = source_cur.NextFeature(); } wse.StopEditOperation(); } //添加TaskGridLog wse.StartEditOperation(); using (ComReleaser comR = new ComReleaser()) { ICursor tgl_cur = grid_tbl.Insert(true); IRowBuffer tgl_rowBF = grid_tbl.CreateRowBuffer(); comR.ManageLifetime(tgl_rowBF); comR.ManageLifetime(tgl_cur); foreach (string gridcode in updateGridCodes.Keys) { tgl_rowBF.set_Value(1, versionName); tgl_rowBF.set_Value(2, gridcode); tgl_rowBF.set_Value(4, updateGridCodes[gridcode][1]); tgl_rowBF.set_Value(5, updateGridCodes[gridcode][0]); tgl_cur.InsertRow(tgl_rowBF); } tgl_cur.Flush(); } wse.StopEditOperation(); //设置Task的内容更新信息 totalUpdateGrids = updateGridCodes.Keys.Count; wse.StartEditOperation(); IFeatureClass task_fc = target_ws.OpenFeatureClass("TaskLog"); IQueryFilter task_filter = new QueryFilterClass(); task_filter.WhereClause = "TaskName = '" + versionName + "'"; IFeatureCursor cur = task_fc.Update(task_filter, true); IFeature task_fea = cur.NextFeature(); if (task_fea != null) { task_fea.set_Value(task_fc.FindField("totalAddItems"), totalAddItems); task_fea.set_Value(task_fc.FindField("totalUpdateItems"), totalUpdateItems); task_fea.set_Value(task_fc.FindField("totalDeleteItems"), totalDeleteItems); task_fea.set_Value(task_fc.FindField("totalGrids"), totalUpdateGrids); task_fea.set_Value(task_fc.FindField("totalGridsArea"), totalUpdateGridsArea); task_fea.Store(); } wse.StopEditOperation(); } catch (Exception ex) { return(false); } finally { wse.StopEditing(true); } return(true); }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { IGPUtilities3 gpUtilities3 = new GPUtilitiesClass(); OSMToolHelper osmToolHelper = new OSMToolHelper(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPEnvironment configKeyword = OSMToolHelper.getEnvironment(envMgr, "configKeyword"); IGPString gpString = configKeyword.Value as IGPString; string storageKeyword = String.Empty; if (gpString != null) { storageKeyword = gpString.Value; } IGPParameter osmFileParameter = paramvalues.get_Element(0) as IGPParameter; IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue; IGPParameter loadSuperRelationParameter = paramvalues.get_Element(1) as IGPParameter; IGPBoolean loadSuperRelationGPValue = gpUtilities3.UnpackGPValue(loadSuperRelationParameter) as IGPBoolean; IGPParameter osmSourceLineFeatureClassParameter = paramvalues.get_Element(2) as IGPParameter; IGPValue osmSourceLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmSourceLineFeatureClassParameter) as IGPValue; IGPParameter osmSourcePolygonFeatureClassParameter = paramvalues.get_Element(3) as IGPParameter; IGPValue osmSourcePolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmSourcePolygonFeatureClassParameter) as IGPValue; IGPParameter osmTargetLineFeatureClassParameter = paramvalues.get_Element(6) as IGPParameter; IGPValue osmTargetLineFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmTargetLineFeatureClassParameter) as IGPValue; IName workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetLineFeatureClassGPValue.GetAsText()); IWorkspace2 lineFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] lineFCNameElements = osmTargetLineFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmLineFeatureClass = null; IGPParameter tagLineCollectionParameter = paramvalues.get_Element(4) as IGPParameter; IGPMultiValue tagLineCollectionGPValue = gpUtilities3.UnpackGPValue(tagLineCollectionParameter) as IGPMultiValue; List <String> lineTagstoExtract = null; if (tagLineCollectionGPValue.Count > 0) { lineTagstoExtract = new List <string>(); for (int valueIndex = 0; valueIndex < tagLineCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagLineCollectionGPValue.get_Value(valueIndex).GetAsText(); lineTagstoExtract.Add(nameOfTag); } } else { lineTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // lines try { osmLineFeatureClass = osmToolHelper.CreateSmallLineFeatureClass(lineFeatureWorkspace, lineFCNameElements[lineFCNameElements.Length - 1], storageKeyword, "", "", lineTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmLineFeatureClass == null) { return; } IGPParameter osmTargetPolygonFeatureClassParameter = paramvalues.get_Element(7) as IGPParameter; IGPValue osmTargetPolygonFeatureClassGPValue = gpUtilities3.UnpackGPValue(osmTargetPolygonFeatureClassParameter) as IGPValue; workspaceName = gpUtilities3.CreateParentFromCatalogPath(osmTargetPolygonFeatureClassGPValue.GetAsText()); IWorkspace2 polygonFeatureWorkspace = workspaceName.Open() as IWorkspace2; string[] polygonFCNameElements = osmTargetPolygonFeatureClassGPValue.GetAsText().Split(System.IO.Path.DirectorySeparatorChar); IFeatureClass osmPolygonFeatureClass = null; IGPParameter tagPolygonCollectionParameter = paramvalues.get_Element(5) as IGPParameter; IGPMultiValue tagPolygonCollectionGPValue = gpUtilities3.UnpackGPValue(tagPolygonCollectionParameter) as IGPMultiValue; List <String> polygonTagstoExtract = null; if (tagPolygonCollectionGPValue.Count > 0) { polygonTagstoExtract = new List <string>(); for (int valueIndex = 0; valueIndex < tagPolygonCollectionGPValue.Count; valueIndex++) { string nameOfTag = tagPolygonCollectionGPValue.get_Value(valueIndex).GetAsText(); polygonTagstoExtract.Add(nameOfTag); } } else { polygonTagstoExtract = OSMToolHelper.OSMSmallFeatureClassFields(); } // polygons try { osmPolygonFeatureClass = osmToolHelper.CreateSmallPolygonFeatureClass(polygonFeatureWorkspace, polygonFCNameElements[polygonFCNameElements.Length - 1], storageKeyword, "", "", polygonTagstoExtract); } catch (Exception ex) { message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message)); return; } if (osmPolygonFeatureClass == null) { return; } ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass); ComReleaser.ReleaseCOMObject(osmLineFeatureClass); string[] gdbComponents = new string[polygonFCNameElements.Length - 1]; System.Array.Copy(lineFCNameElements, gdbComponents, lineFCNameElements.Length - 1); string fileGDBLocation = String.Join(System.IO.Path.DirectorySeparatorChar.ToString(), gdbComponents); osmToolHelper.smallLoadOSMRelations(osmFileLocationString.GetAsText(), osmSourceLineFeatureClassGPValue.GetAsText(), osmSourcePolygonFeatureClassGPValue.GetAsText(), osmTargetLineFeatureClassGPValue.GetAsText(), osmTargetPolygonFeatureClassGPValue.GetAsText(), lineTagstoExtract, polygonTagstoExtract, loadSuperRelationGPValue.Value); }
public List <string> CheckDataSchema(string template, string dbpath) { List <string> msgs = new List <string>(); try { Type factoryType = Type.GetTypeFromProgID("esriDataSourcesGDB.AccessWorkspaceFactory"); IWorkspaceFactory workspaceFactory = (IWorkspaceFactory)Activator.CreateInstance (factoryType); IFeatureWorkspace source_fws = workspaceFactory.OpenFromFile(dbpath, 0) as IFeatureWorkspace; IScratchWorkspaceFactory target_wsf = new FileGDBScratchWorkspaceFactoryClass(); IWorkspace target_ws = target_wsf.CreateNewScratchWorkspace(); IGdbXmlImport importer = new GdbImporterClass(); IEnumNameMapping mapping = null; bool isConflict = false; isConflict = importer.GenerateNameMapping(template, target_ws, out mapping); importer.ImportWorkspace(template, mapping, target_ws, true); IDataset ds = target_ws as IDataset; List <String> fcNames = new List <string>(); Util.GetAllFeatureClassNames(ds, ref fcNames); IFeatureWorkspace target_fws = target_ws as IFeatureWorkspace; IWorkspace2 source_ws = source_fws as IWorkspace2; foreach (string fcName in fcNames) { if (!source_ws.get_NameExists(esriDatasetType.esriDTFeatureClass, fcName)) { msgs.Add(string.Format("数据源中丢失图层:{0}", fcName)); continue; } IFeatureClass source_fc = source_fws.OpenFeatureClass(fcName); IFeatureClass target_fc = target_fws.OpenFeatureClass(fcName); for (int i = 0; i < target_fc.Fields.FieldCount; i++) { IField fld = target_fc.Fields.get_Field(i); if (fcName == target_fc.OIDFieldName) { continue; } int source_fld_idx = source_fc.FindField(fld.Name); if (source_fld_idx == -1) { msgs.Add(string.Format("数据源中丢失字段{0}", fld.Name)); } else { IField source_fld = source_fc.Fields.get_Field(source_fld_idx); if (source_fld.Type != fld.Type) { msgs.Add(string.Format("数据源中字段{0}类型不正确", fld.Name)); } if (source_fld.Length != fld.Length) { msgs.Add(string.Format("数据源中字段{0}长度不正确", fld.Name)); } if (source_fld.Precision != fld.Precision) { msgs.Add(string.Format("数据源中字段{0}精度不正确", fld.Name)); } } } if (source_fc.FindField("SyncID") == -1) { msgs.Add(@"数据源中丢失系统字段SyncID"); } if (source_fc.FindField("SyncTimeStamp") == -1) { msgs.Add(@"数据源中丢失系统字段SyncTimeStamp"); } if (source_fc.FindField("SyncStatus") == -1) { msgs.Add(@"数据源中丢失系统字段SyncStatus"); } if (source_fc.FindField("SyncEditable") == -1) { msgs.Add(@"数据源中丢失系统字段SyncEditable"); } } } catch { } return(msgs); }
/// <summary> /// 复制导入要素(ConvertFeatureDataset) /// </summary> /// <param name="pDataSet"></param> /// <param name="strFeatFileDir"></param> /// <param name="strFeatFileName"></param> /// <param name="strOutName"></param> /// <param name="isWorkspace"></param> public void FeatureClassToFeatureClass(IDataset pDataSet, string strFeatFileDir, string strFeatFileName, string strOutName, bool isWorkspace) { try { IWorkspaceFactory pWSF = new ESRI.ArcGIS.DataSourcesFile.ShapefileWorkspaceFactoryClass(); IFeatureWorkspace pFeatureWK = (IFeatureWorkspace)pWSF.OpenFromFile(strFeatFileDir, 0); IFeatureClass pInFeatureClass = pFeatureWK.OpenFeatureClass(strFeatFileName); if (pInFeatureClass == null || pDataSet == null) { MessageBox.Show("创建失败"); return; } IFeatureClassName pInFeatureclassName; IDataset pIndataset = (IDataset)pInFeatureClass; pInFeatureclassName = (IFeatureClassName)pIndataset.FullName; //如果名称已存在 IWorkspace2 pWS2 = null; if (isWorkspace) { pWS2 = pDataSet as IWorkspace2; } else { pWS2 = pDataSet.Workspace as IWorkspace2; } if (pWS2.get_NameExists(esriDatasetType.esriDTFeatureClass, strOutName)) { MessageBoxResult result = MessageBox.Show(null, "矢量文件名 " + strOutName + " 在数据库中已存在!" + "/r是否覆盖?", "相同文件名", MessageBoxButton.YesNo, MessageBoxImage.Information, MessageBoxResult.Yes); //覆盖原矢量要素 if (result == MessageBoxResult.Yes) { IFeatureWorkspace pFWS = (IFeatureWorkspace)pWS2; IDataset pDataset = pFWS.OpenFeatureClass(strOutName) as IDataset; pDataset.Delete(); pDataset = null; } } IFields pInFields, pOutFields; IFieldChecker pFieldChecker = new FieldCheckerClass(); IEnumFieldError pError; pInFields = pInFeatureClass.Fields; pFieldChecker.Validate(pInFields, out pError, out pOutFields); IField geoField = null; for (int i = 0; i < pOutFields.FieldCount; i++) { IField pField = pOutFields.get_Field(i); if (pField.Type == esriFieldType.esriFieldTypeOID) { IFieldEdit pFieldEdit = (IFieldEdit)pField; pFieldEdit.Name_2 = pField.AliasName; } if (pField.Type == esriFieldType.esriFieldTypeGeometry) { geoField = pField; break; } } IGeometryDef geometryDef = geoField.GeometryDef; IFeatureDataConverter one2another = new FeatureDataConverterClass(); IFeatureClassName pOutFeatureClassName = new FeatureClassNameClass(); IDatasetName pOutDatasetName = (IDatasetName)pOutFeatureClassName; if (isWorkspace) { pOutDatasetName.WorkspaceName = (IWorkspaceName)pDataSet.FullName; } else { pOutDatasetName.WorkspaceName = (IWorkspaceName)((IDataset)pDataSet.Workspace).FullName; } pOutDatasetName.Name = strOutName; if (isWorkspace) { one2another.ConvertFeatureClass(pInFeatureclassName, null, null, pOutFeatureClassName, geometryDef, pOutFields, "", 1000, 0); } else { IFeatureDataset pFeatDS = (IFeatureDataset)pDataSet; IFeatureDatasetName pOutFeatDSName = pFeatDS.FullName as IFeatureDatasetName; one2another.ConvertFeatureClass(pInFeatureclassName, null, pOutFeatDSName, pOutFeatureClassName, geometryDef, pOutFields, "", 1000, 0); pOutFeatDSName = null; pFeatDS = null; } } catch (Exception ex) { MessageBox.Show(ex.Message); return; } }
private void btnOK_Click(object sender, EventArgs e) { if ((m_MatchedFCName != "") && (m_WorkspacePath != "")) { //判断选择字段是否对应 for (int i = 0; i < dataGridViewX1.RowCount; i++) { DataGridViewCheckBoxCell dgvCheckBoxCell1 = dataGridViewX1[0, i] as DataGridViewCheckBoxCell; if (Convert.ToBoolean(dgvCheckBoxCell1.Value) == true)//判断是否进行属性匹配,若进行,必须选取对应字段 { if (this.dataGridViewX1[2, i].Value == null) { MessageBoxEx.Show("所选字段没有完全对应,请重新检查!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } } IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactory(); IWorkspace2 workspace = pWorkspaceFactory.OpenFromFile(m_WorkspacePath, 0) as IWorkspace2; IFeatureWorkspace featureWorkspace = workspace as IFeatureWorkspace; ITable table = null; IFields fields = null; if (m_TUFeatCls.ShapeType == esriGeometryType.esriGeometryPolygon) { if (workspace.get_NameExists(esriDatasetType.esriDTTable, "MatchedPolygonFCSetting")) { table = featureWorkspace.OpenTable("MatchedPolygonFCSetting"); } else { fields = CreateMatchedPolygonFCSettingFields(workspace); UID uid = new UIDClass(); uid.Value = "esriGeoDatabase.Object"; IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError = null; IFields validatedFields = null; fieldChecker.ValidateWorkspace = (IWorkspace)workspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); table = featureWorkspace.CreateTable("MatchedPolygonFCSetting", validatedFields, uid, null, ""); } } IWorkspaceEdit pWorkspaceEdit = featureWorkspace as IWorkspaceEdit; pWorkspaceEdit.StartEditing(true); pWorkspaceEdit.StartEditOperation(); //Collection<string> pCol = new Collection<string>(); Dictionary <string, int> pDic = new Dictionary <string, int>(); string tempFieldsName = ""; DataGridViewCheckBoxCell dgvCheckBoxCell = new DataGridViewCheckBoxCell(); //查看是否MatchedFCName是否存在,当前为工作层 int index = table.FindField("MatchedFCName"); ICursor pCursor = table.Search(null, false); IRow pRow = pCursor.NextRow(); while (pRow != null) { if (pRow.get_Value(index).ToString() != "") { pDic.Add(pRow.get_Value(index).ToString(), pRow.OID); } pRow = pCursor.NextRow(); } if (this.tabControl1.Tabs[0].Visible) { if (!pDic.ContainsKey(m_MatchedFCName)) { IRow tempRow = table.CreateRow(); tempRow.set_Value(index, m_MatchedFCName); tempRow.set_Value(tempRow.Fields.FindField("FCSettingID"), table.RowCount(null) - 1); if (this.radioButtonCenter.Checked == true) { tempRow.set_Value(tempRow.Fields.FindField("Center"), 1);//权重为一 tempRow.set_Value(tempRow.Fields.FindField("CenterNum"), this.txtCenterNum.Text); //tempRow.set_Value(tempRow.Fields.FindField("CenterWT"), this.txtCenterWT.Text); } else { tempRow.set_Value(tempRow.Fields.FindField("Center"), 0); } if (this.radioButtonArea.Checked == true) { tempRow.set_Value(tempRow.Fields.FindField("Area"), 1); tempRow.set_Value(tempRow.Fields.FindField("AreaNum"), this.txtAreaNum.Text); //tempRow.set_Value(tempRow.Fields.FindField("AreaWT"), this.txtAreaWT.Text); } else { tempRow.set_Value(tempRow.Fields.FindField("Area"), 0); } if (this.radioButtonShape.Checked == true) { tempRow.set_Value(tempRow.Fields.FindField("SP"), 1); tempRow.set_Value(tempRow.Fields.FindField("SPNum"), this.txtSPNum.Text); //tempRow.set_Value(tempRow.Fields.FindField("SPWT"), this.txtSPWT.Text); } else { tempRow.set_Value(tempRow.Fields.FindField("SP"), 0); } //修改属性!!!!!!!!!!!!!!!!!!!!! tempRow.set_Value(tempRow.Fields.FindField("Attribute"), 1); for (int i = 0; i < dataGridViewX1.RowCount; i++) { dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell; if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true) { if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper()) { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";"; } else { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")"; } } } if (tempFieldsName == "") { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0); MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1); tempRow.set_Value(tempRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim()); } IDataset dataset = m_TUFeatCls as IDataset; if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name)) { tempRow.set_Value(tempRow.Fields.FindField("SourceFCName"), dataset.Name); tempRow.set_Value(tempRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]); tempRow.set_Value(tempRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath); } tempRow.Store(); } else { IRow tRow = table.GetRow(pDic[m_MatchedFCName]); if (this.radioButtonCenter.Checked == true) { tRow.set_Value(tRow.Fields.FindField("Center"), 1); tRow.set_Value(tRow.Fields.FindField("CenterNum"), this.txtCenterNum.Text); //tRow.set_Value(tRow.Fields.FindField("CenterWT"), this.txtCenterWT.Text); } else { tRow.set_Value(tRow.Fields.FindField("Center"), 0); tRow.set_Value(tRow.Fields.FindField("CenterNum"), 0); } if (this.radioButtonArea.Checked == true) { tRow.set_Value(tRow.Fields.FindField("Area"), 1); tRow.set_Value(tRow.Fields.FindField("AreaNum"), this.txtAreaNum.Text); //tRow.set_Value(tRow.Fields.FindField("AreaWT"), this.txtAreaWT.Text); } else { tRow.set_Value(tRow.Fields.FindField("Area"), 0); tRow.set_Value(tRow.Fields.FindField("AreaNum"), 0); } if (this.radioButtonShape.Checked == true) { tRow.set_Value(tRow.Fields.FindField("SP"), 1); tRow.set_Value(tRow.Fields.FindField("SPNum"), this.txtSPNum.Text); //tRow.set_Value(tRow.Fields.FindField("SPWT"), this.txtSPWT.Text); } else { tRow.set_Value(tRow.Fields.FindField("SP"), 0); tRow.set_Value(tRow.Fields.FindField("SPNum"), 0); } //修改属性!!!!!!!!!!!! tRow.set_Value(tRow.Fields.FindField("Attribute"), 1); for (int i = 0; i < dataGridViewX1.RowCount; i++) { dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell; if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true) { if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper()) { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";"; } else { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")"; } } } if (tempFieldsName == "") { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0); MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1); tRow.set_Value(tRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim()); } IDataset dataset = m_TUFeatCls as IDataset; if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name)) { tRow.set_Value(tRow.Fields.FindField("SourceFCName"), dataset.Name); tRow.set_Value(tRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]); tRow.set_Value(tRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath); } tRow.Store(); } } else if (this.tabControl1.Tabs[1].Visible) { if (!pDic.ContainsKey(m_MatchedFCName)) { IRow tempRow = table.CreateRow(); tempRow.set_Value(index, m_MatchedFCName); tempRow.set_Value(tempRow.Fields.FindField("FCSettingID"), table.RowCount(null) - 1); tempRow.set_Value(tempRow.Fields.FindField("Top"), 1); if (this.comboBoxExBuffer.Text != "") { tempRow.set_Value(tempRow.Fields.FindField("Buffer"), this.comboBoxExBuffer.Text); } else { MessageBox.Show("请选择缓冲区半径!"); return; } //修改属性!!!!!!!!!!!! tempRow.set_Value(tempRow.Fields.FindField("Attribute"), 1); for (int i = 0; i < dataGridViewX1.RowCount; i++) { dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell; if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true) { if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper()) { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";"; } else { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")"; } } } if (tempFieldsName == "") { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0); MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1); tempRow.set_Value(tempRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim()); } IDataset dataset = m_TUFeatCls as IDataset; if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name)) { tempRow.set_Value(tempRow.Fields.FindField("SourceFCName"), dataset.Name); tempRow.set_Value(tempRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]); tempRow.set_Value(tempRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath); } tempRow.Store(); } else { IRow tRow = table.GetRow(pDic[m_MatchedFCName]); tRow.set_Value(tRow.Fields.FindField("Top"), 1); if (this.comboBoxExBuffer.Text != "") { tRow.set_Value(tRow.Fields.FindField("Buffer"), this.comboBoxExBuffer.Text); } else { MessageBoxEx.Show("请选择缓冲区半径!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } //修改属性!!!!!!!!!!!! tRow.set_Value(tRow.Fields.FindField("Attribute"), 1); for (int i = 0; i < dataGridViewX1.RowCount; i++) { dgvCheckBoxCell = dataGridViewX1[0, i] as DataGridViewCheckBoxCell; if (Convert.ToBoolean(dgvCheckBoxCell.Value) == true) { if (this.dataGridViewX1[1, i].Value.ToString().ToUpper() == this.dataGridViewX1[2, i].Value.ToString().ToUpper()) { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + ";"; } else { tempFieldsName = tempFieldsName + dataGridViewX1[1, i].Value.ToString() + "(" + dataGridViewX1[2, i].Value.ToString() + ")"; } } } if (tempFieldsName == "") { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 0); MessageBoxEx.Show("没有选择属性匹配对应字段!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { //tRow.set_Value(tRow.Fields.FindField("Attribute"), 1); tRow.set_Value(tRow.Fields.FindField("MatchedFields"), tempFieldsName.Trim()); } IDataset dataset = m_TUFeatCls as IDataset; if (ClsDeclare.g_SourceFeatClsPathDic.ContainsKey(dataset.Name)) { tRow.set_Value(tRow.Fields.FindField("SourceFCName"), dataset.Name); tRow.set_Value(tRow.Fields.FindField("SourcePath"), ClsDeclare.g_SourceFeatClsPathDic[dataset.Name]); tRow.set_Value(tRow.Fields.FindField("WorkspacePath"), ClsDeclare.g_WorkspacePath); } tRow.Store(); } } pWorkspaceEdit.StopEditOperation(); pWorkspaceEdit.StopEditing(true); } m_dgvCell.Value = "已设置"; this.Close(); return; }
private IFields CreateMatchedPolygonFCSettingFields(IWorkspace2 workspace) { IObjectClassDescription objectClassDescription = new ObjectClassDescriptionClass(); IFields fields = new FieldsClass(); IFieldsEdit fieldsEdit = fields as IFieldsEdit; fields = objectClassDescription.RequiredFields; IField field = new FieldClass(); IFieldEdit fieldEdit = field as IFieldEdit; fieldEdit.Name_2 = "OBJECTID"; fieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldEdit.IsNullable_2 = false; fieldsEdit.AddField(field); IField field16 = new FieldClass(); IFieldEdit fieldEdit16 = field16 as IFieldEdit; fieldEdit16.Name_2 = "SourceFCName"; fieldEdit16.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit16.IsNullable_2 = false; fieldEdit16.AliasName_2 = "源图层名称"; fieldsEdit.AddField(field16); IField field17 = new FieldClass(); IFieldEdit fieldEdit17 = field17 as IFieldEdit; fieldEdit17.Name_2 = "SourcePath"; fieldEdit17.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit17.IsNullable_2 = false; fieldEdit17.AliasName_2 = "源图层路径"; fieldsEdit.AddField(field17); IField field1 = new FieldClass(); IFieldEdit fieldEdit1 = field1 as IFieldEdit; fieldEdit1.Name_2 = "MatchedFCName"; fieldEdit1.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit1.IsNullable_2 = false; fieldEdit1.AliasName_2 = "更新图层名"; fieldsEdit.AddField(field1); IField field18 = new FieldClass(); IFieldEdit fieldEdit18 = field18 as IFieldEdit; fieldEdit18.Name_2 = "WorkspacePath"; fieldEdit18.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit18.IsNullable_2 = false; fieldEdit18.AliasName_2 = "工作区路径"; fieldsEdit.AddField(field18); IField field2 = new FieldClass(); IFieldEdit fieldEdit2 = field2 as IFieldEdit; fieldEdit2.Name_2 = "FCSettingID"; fieldEdit2.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit2.IsNullable_2 = false; fieldEdit2.AliasName_2 = "参数ID"; fieldsEdit.AddField(field2); IField field3 = new FieldClass(); IFieldEdit fieldEdit3 = field3 as IFieldEdit; fieldEdit3.Name_2 = "Center"; fieldEdit3.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit3.AliasName_2 = "重心点匹配"; fieldEdit3.IsNullable_2 = true; fieldsEdit.AddField(field3); IField field4 = new FieldClass(); IFieldEdit fieldEdit4 = field4 as IFieldEdit; fieldEdit4.Name_2 = "CenterNum"; fieldEdit4.Type_2 = esriFieldType.esriFieldTypeDouble; fieldEdit4.AliasName_2 = "重心点阈值"; fieldEdit4.IsNullable_2 = true; fieldsEdit.AddField(field4); //IField field5 = new FieldClass(); //IFieldEdit fieldEdit5 = field5 as IFieldEdit; //fieldEdit5.Name_2 = "CenterWT"; //fieldEdit5.Type_2 = esriFieldType.esriFieldTypeDouble; //fieldEdit5.AliasName_2 = "重心点权重"; //fieldEdit5.IsNullable_2 = true; //fieldsEdit.AddField(field5); IField field6 = new FieldClass(); IFieldEdit fieldEdit6 = field6 as IFieldEdit; fieldEdit6.Name_2 = "Area"; fieldEdit6.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit6.AliasName_2 = "面积匹配"; fieldEdit6.IsNullable_2 = true; fieldsEdit.AddField(field6); IField field7 = new FieldClass(); IFieldEdit fieldEdit7 = field7 as IFieldEdit; fieldEdit7.Name_2 = "AreaNum"; fieldEdit7.Type_2 = esriFieldType.esriFieldTypeDouble; fieldEdit7.AliasName_2 = "面积阈值"; fieldEdit7.IsNullable_2 = true; fieldsEdit.AddField(field7); //IField field8 = new FieldClass(); //IFieldEdit fieldEdit8 = field8 as IFieldEdit; //fieldEdit8.Name_2 = "AreaWT"; //fieldEdit8.Type_2 = esriFieldType.esriFieldTypeDouble; //fieldEdit8.AliasName_2 = "面积权重"; //fieldEdit8.IsNullable_2 = true; //fieldsEdit.AddField(field8); IField field9 = new FieldClass(); IFieldEdit fieldEdit9 = field9 as IFieldEdit; fieldEdit9.Name_2 = "SP"; fieldEdit9.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit9.AliasName_2 = "形状匹配"; fieldEdit9.IsNullable_2 = true; fieldsEdit.AddField(field9); IField field10 = new FieldClass(); IFieldEdit fieldEdit10 = field10 as IFieldEdit; fieldEdit10.Name_2 = "SPNum"; fieldEdit10.Type_2 = esriFieldType.esriFieldTypeDouble; fieldEdit10.AliasName_2 = "形状阈值"; fieldEdit10.IsNullable_2 = true; fieldsEdit.AddField(field10); //IField field11 = new FieldClass(); //IFieldEdit fieldEdit11 = field11 as IFieldEdit; //fieldEdit11.Name_2 = "SPWT"; //fieldEdit11.Type_2 = esriFieldType.esriFieldTypeDouble; //fieldEdit11.AliasName_2 = "形状权重"; //fieldEdit11.IsNullable_2 = true; //fieldsEdit.AddField(field11); IField field12 = new FieldClass(); IFieldEdit fieldEdit12 = field12 as IFieldEdit; fieldEdit12.Name_2 = "Top"; fieldEdit12.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit12.AliasName_2 = "拓扑匹配"; fieldEdit12.IsNullable_2 = true; fieldsEdit.AddField(field12); IField field13 = new FieldClass(); IFieldEdit fieldEdit13 = field13 as IFieldEdit; fieldEdit13.Name_2 = "Buffer"; fieldEdit13.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit13.AliasName_2 = "拓扑缓冲区半径"; fieldEdit13.IsNullable_2 = true; fieldsEdit.AddField(field13); IField field14 = new FieldClass(); IFieldEdit fieldEdit14 = field14 as IFieldEdit; fieldEdit14.Name_2 = "Attribute"; fieldEdit14.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit14.AliasName_2 = "属性匹配"; fieldEdit14.IsNullable_2 = true; fieldsEdit.AddField(field14); IField field15 = new FieldClass(); IFieldEdit fieldEdit15 = field15 as IFieldEdit; fieldEdit15.Name_2 = "MatchedFields"; fieldEdit15.Type_2 = esriFieldType.esriFieldTypeString; fieldEdit15.AliasName_2 = "匹配属性字段"; fieldEdit15.IsNullable_2 = true; fieldsEdit.AddField(field15); IField field19 = new FieldClass(); IFieldEdit fieldEdit19 = field19 as IFieldEdit; fieldEdit19.Name_2 = "Voronoi"; fieldEdit19.Type_2 = esriFieldType.esriFieldTypeInteger; fieldEdit19.AliasName_2 = "泰森多边形"; fieldEdit19.IsNullable_2 = true; fieldsEdit.AddField(field19); fields = fieldsEdit as IFieldsEdit; return(fields); }
//下载为MDB文件 private void btn_ExportNDB_Click(object sender, EventArgs e) { pWorkspace = GetWorkspace(comboBoxSource.Text); if (pWorkspace == null) { MessageBox.Show("数据源空间不存在", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } bool flag = false; //获取模板路径 string sourcefilename = Application.StartupPath + "\\..\\Template\\DATATEMPLATE.mdb"; foreach (DataGridViewRow row in datagwSource.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { flag = true; } } if (!flag) { MessageBox.Show("没有选中行!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); return; } SysCommon.CProgress vProgress = new SysCommon.CProgress("正在下载数据,请稍后"); try { if (File.Exists(sourcefilename))//原模板存在 { SaveFileDialog dlg = new SaveFileDialog(); dlg.Filter = "MDB数据|*.mdb"; dlg.OverwritePrompt = false; dlg.Title = "保存到MDB"; DialogResult result = MessageBox.Show("下载是否去掉前缀?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Information); if (dlg.ShowDialog() == DialogResult.OK) { //初始化进度条 vProgress.EnableCancel = false; vProgress.ShowDescription = false; vProgress.FakeProgress = true; vProgress.TopMost = true; vProgress.ShowProgress(); Application.DoEvents(); //IWorkspaceFactory pWorkspaceFactory = new FileGDBWorkspaceFactoryClass(); //pWorkspace = (IWorkspace)(pWorkspaceFactory.OpenFromFile(GetSourcePath(comboBoxSource.Text), 0)); //如果存在mdb,替换文件,则复制模板到指定路径 //如果存在mdb,不替换,则追加到这个文件 File.Copy(sourcefilename, dlg.FileName, true); string cellvalue = ""; IWorkspaceFactory Pwf = new AccessWorkspaceFactoryClass(); IWorkspace pws = (IWorkspace)(Pwf.OpenFromFile(dlg.FileName, 0)); IWorkspace2 pws2 = (IWorkspace2)pws; foreach (DataGridViewRow row in datagwSource.Rows) { if ((bool)row.Cells[0].EditedFormattedValue == true) { cellvalue = row.Cells[1].Value.ToString().Trim(); if (cellvalue.Contains(".")) { cellvalue = cellvalue.Substring(cellvalue.LastIndexOf(".") + 1); } if (result == DialogResult.Yes) { cellvalue = cellvalue.Substring(15); //去掉前缀 } pws2 = (IWorkspace2)pws; if (pws2.get_NameExists(esriDatasetType.esriDTFeatureClass, cellvalue)) { IFeatureClass tmpfeatureclass; IFeatureWorkspace pFeatureWorkspace = (IFeatureWorkspace)pws; tmpfeatureclass = pFeatureWorkspace.OpenFeatureClass(cellvalue); IDataset set = tmpfeatureclass as IDataset; set.CanDelete(); set.Delete(); flag = true; } IFeatureDataConverter_ConvertFeatureClass(pWorkspace, pws, row.Cells[1].Value.ToString().Trim(), cellvalue); } } vProgress.Close(); MessageBox.Show("下载成功", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Activate(); } } } catch (Exception ex) { vProgress.Close(); MessageBox.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); this.Activate(); } }
/// <summary> /// Raster图层导入到数据库 /// </summary> /// <param name="dbWorkspace">数据库</param> /// <param name="strRasterFileDir">本地栅格图层路径</param> /// <param name="strRasterFileName">本地栅格图层名称</param> /// <param name="strOutName">数据库栅格图层名称</param> /// <returns></returns> public IRasterDataset RasterFileIntoGDB(IWorkspace dbWorkspace, string strRasterFileDir, string strRasterFileName, string strOutName) { IWorkspace pSdeWorkSpace = dbWorkspace; try { //判断是否有重名现象 IWorkspace2 pWS2 = pSdeWorkSpace as IWorkspace2; //如果名称已存在 if (pWS2.get_NameExists(esriDatasetType.esriDTRasterDataset, strOutName)) { DialogResult result; result = MessageBox.Show("栅格文件名 " + strOutName + " 在数据库中已存在!" + "\r是否覆盖?", "相同文件名", MessageBoxButtons.YesNo, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1); //覆盖原栅格要素 if (result == DialogResult.Yes) { IRasterWorkspaceEx pRWs = pSdeWorkSpace as IRasterWorkspaceEx; IDataset pDataset = pRWs.OpenRasterDataset(strOutName) as IDataset; pDataset.Delete(); pDataset = null; } else if (result == DialogResult.No) { //不覆盖,则退出for循环,忽略这个要素,转入下一个要素的导入 return(null); } } IWorkspaceFactory pRasterWsFac = new RasterWorkspaceFactoryClass(); IWorkspace pWs = pRasterWsFac.OpenFromFile(strRasterFileDir, 0); IRasterDataset pRasterDs = null; IRasterWorkspace pRasterWs; if (!(pWs is IRasterWorkspace)) { MessageBox.Show("错误信息:" + strRasterFileDir + "不是栅格工作空间。"); return(null); } pRasterWs = pWs as IRasterWorkspace; pRasterDs = pRasterWs.OpenRasterDataset(strRasterFileName); ISaveAs2 saveAs2 = (ISaveAs2)pRasterDs; IRasterStorageDef rasterStorageDef = new RasterStorageDefClass(); IRasterStorageDef2 rasterStorageDef2 = (IRasterStorageDef2)rasterStorageDef; rasterStorageDef2.CompressionType = esriRasterCompressionType.esriRasterCompressionJPEG2000; rasterStorageDef2.CompressionQuality = 50; rasterStorageDef2.Tiled = true; rasterStorageDef2.TileHeight = 128; rasterStorageDef2.TileWidth = 128; saveAs2.SaveAsRasterDataset(strOutName, pSdeWorkSpace, "JP2", rasterStorageDef2); return(pRasterDs); } catch (Exception ex) { MessageBox.Show("错误信息:" + ex.Message); return(null); } }
public static void Project(IFeatureClass ifeatureClass_0, ISpatialReference ispatialReference_0, IFeatureDatasetName ifeatureDatasetName_0, string string_0, double double_0) { string str2; double num3; double num4; double num5; double num6; IEnumFieldError error; IFields fields2; IWorkspace workspace = ((IDataset)ifeatureClass_0).Workspace; IFeatureDataConverter converter = new FeatureDataConverterClass(); IWorkspaceName name = new WorkspaceNameClass { ConnectionProperties = workspace.ConnectionProperties, WorkspaceFactoryProgID = workspace.WorkspaceFactory.GetClassID().Value.ToString() }; IWorkspaceName workspaceName = (ifeatureDatasetName_0 as IDatasetName).WorkspaceName; IDatasetName name3 = new FeatureClassNameClass(); string aliasName = ifeatureClass_0.AliasName; int index = aliasName.LastIndexOf("."); if (index != -1) { aliasName = aliasName.Substring(index + 1); } name3.Name = aliasName; name3.WorkspaceName = name; IWorkspace2 workspace2 = (workspaceName as IName).Open() as IWorkspace2; IDatasetName name4 = new FeatureClassNameClass { WorkspaceName = workspaceName }; (name4 as IFeatureClassName).FeatureDatasetName = ifeatureDatasetName_0 as IDatasetName; IFieldChecker checker = new FieldCheckerClass { ValidateWorkspace = workspace2 as IWorkspace }; string[] strArray = string_0.Split(new char[] { '.' }); string_0 = strArray[strArray.Length - 1] + "_Project"; checker.ValidateTableName(string_0, out str2); string str3 = str2; int num2 = 1; if ((workspaceName.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace) || (workspaceName.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)) { while (workspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, str3)) { str3 = str2 + "_" + num2.ToString(); num2++; } } else if (workspaceName.Type == esriWorkspaceType.esriFileSystemWorkspace) { while (File.Exists(str3 + ".shp")) { str3 = str2 + "_" + num2.ToString(); num2++; } } name4.Name = str3; IFields inputField = new FieldsClass(); index = ifeatureClass_0.Fields.FindField(ifeatureClass_0.ShapeFieldName); IField field = ifeatureClass_0.Fields.get_Field(index); IGeometryDef geometryDef = field.GeometryDef; ISpatialReference spatialReference = geometryDef.SpatialReference; ispatialReference_0.GetDomain(out num3, out num4, out num5, out num6); ((IGeometryDefEdit)geometryDef).GridCount_2 = 1; ((IGeometryDefEdit)geometryDef).set_GridSize(0, double_0); ((IGeometryDefEdit)geometryDef).SpatialReference_2 = ispatialReference_0; ((IFieldEdit)field).GeometryDef_2 = geometryDef; for (int i = 0; i < ifeatureClass_0.Fields.FieldCount; i++) { if (i == index) { ((IFieldsEdit)inputField).AddField(field); } else { IField field2 = ifeatureClass_0.Fields.get_Field(i); ((IFieldsEdit)inputField).AddField(field2); } } checker.Validate(inputField, out error, out fields2); if (m_pfrm != null) { m_pfrm.FeatureProgress = converter; } try { converter.ConvertFeatureClass((IFeatureClassName)name3, null, ifeatureDatasetName_0, (IFeatureClassName)name4, geometryDef, fields2, "", 1000, 0); } catch (Exception exception) { MessageBox.Show(exception.Message); } }
public static void Project(IFeatureClass ifeatureClass_0, ISpatialReference ispatialReference_0, IFeatureDatasetName ifeatureDatasetName_0, string string_0, double double_0) { IWorkspace workspace = ((IDataset)ifeatureClass_0).Workspace; IFeatureDataConverter featureDataConverter = new FeatureDataConverter(); IWorkspaceName workspaceName = new WorkspaceName() as IWorkspaceName; workspaceName.ConnectionProperties = workspace.ConnectionProperties; workspaceName.WorkspaceFactoryProgID = workspace.WorkspaceFactory.GetClassID().Value.ToString(); IWorkspaceName workspaceName2 = (ifeatureDatasetName_0 as IDatasetName).WorkspaceName; IDatasetName datasetName = new FeatureClassName() as IDatasetName; string text = ifeatureClass_0.AliasName; int num = text.LastIndexOf("."); if (num != -1) { text = text.Substring(num + 1); } datasetName.Name = text; datasetName.WorkspaceName = workspaceName; IWorkspace2 workspace2 = (workspaceName2 as IName).Open() as IWorkspace2; IDatasetName datasetName2 = new FeatureClassName() as IDatasetName; datasetName2.WorkspaceName = workspaceName2; (datasetName2 as IFeatureClassName).FeatureDatasetName = (ifeatureDatasetName_0 as IDatasetName); IFieldChecker fieldChecker = new FieldChecker(); fieldChecker.ValidateWorkspace = (workspace2 as IWorkspace); string[] array = string_0.Split(new char[] { '.' }); string_0 = array[array.Length - 1] + "_Project"; string text2; fieldChecker.ValidateTableName(string_0, out text2); string text3 = text2; int num2 = 1; if (workspaceName2.Type == esriWorkspaceType.esriRemoteDatabaseWorkspace || workspaceName2.Type == esriWorkspaceType.esriLocalDatabaseWorkspace) { while (workspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, text3)) { text3 = text2 + "_" + num2.ToString(); num2++; } } else if (workspaceName2.Type == esriWorkspaceType.esriFileSystemWorkspace) { while (System.IO.File.Exists(text3 + ".shp")) { text3 = text2 + "_" + num2.ToString(); num2++; } } datasetName2.Name = text3; IFields fields = new ESRI.ArcGIS.Geodatabase.Fields() as IFields; num = ifeatureClass_0.Fields.FindField(ifeatureClass_0.ShapeFieldName); IField field = ifeatureClass_0.Fields.get_Field(num); IGeometryDef geometryDef = field.GeometryDef; ISpatialReference arg_1D9_0 = geometryDef.SpatialReference; double num3; double num4; double num5; double num6; ispatialReference_0.GetDomain(out num3, out num4, out num5, out num6); ((IGeometryDefEdit)geometryDef).GridCount_2 = 1; ((IGeometryDefEdit)geometryDef).set_GridSize(0, double_0); ((IGeometryDefEdit)geometryDef).SpatialReference_2 = ispatialReference_0; ((IFieldEdit)field).GeometryDef_2 = geometryDef; for (int i = 0; i < ifeatureClass_0.Fields.FieldCount; i++) { if (i == num) { ((IFieldsEdit)fields).AddField(field); } else { IField field2 = ifeatureClass_0.Fields.get_Field(i); ((IFieldsEdit)fields).AddField(field2); } } IEnumFieldError enumFieldError; IFields outputFields; fieldChecker.Validate(fields, out enumFieldError, out outputFields); if (SRLibCommonFunc.m_pfrm != null) { SRLibCommonFunc.m_pfrm.FeatureProgress = featureDataConverter; } try { featureDataConverter.ConvertFeatureClass((IFeatureClassName)datasetName, null, ifeatureDatasetName_0, (IFeatureClassName)datasetName2, geometryDef, outputFields, "", 1000, 0); } catch (System.Exception ex) { System.Windows.Forms.MessageBox.Show(ex.Message); } }
//** 功能描述: 获得要素类,如果已经存在的话,则直接打开,否则进行创建 //** 参数列表: pFeatWorkspace (IFeatureWorkspace) // sFeatClsName (String) // pFields (IFields) 某个要素类的字段 // pSpatialRefer (ISpatialReference)'如果需要改变创建的要素类的空间参考的话,就改变 // pDicField 更改字段的名称,key里边放的是原字段名称,item放的是目标字段名称 public static IFeatureClass CreatOrOpenFeatClsByName(ref IFeatureWorkspace pFeatWorkspace, string sFeatClsName, ref IFields pFields, ISpatialReference pSpatialRefer, Dictionary <string, string> pDicField) { IFeatureClass functionReturnValue = default(IFeatureClass); IFeatureClass pFeatCls = default(IFeatureClass); //Dim pGeoDataset As ESRI.ArcGIS.Geodatabase.IGeoDataset IFields pDesFields = default(IFields); IWorkspace2 pWorkspace2 = default(IWorkspace2); IWorkspace pWorkspace = default(IWorkspace); bool bHasExsit = false; IDataset pDataset = default(IDataset); try { //首选判断该数据集是否存在 if (pFeatWorkspace == null) { functionReturnValue = null; return(functionReturnValue); } pWorkspace = (IWorkspace)pFeatWorkspace; ////印骅 20081113 判断shapefile是否存在 if (pWorkspace.Type == esriWorkspaceType.esriFileSystemWorkspace) { bHasExsit = File.Exists(pWorkspace.PathName + "\\" + sFeatClsName + ".shp") && File.Exists(pWorkspace.PathName + "\\" + sFeatClsName + ".shx") && File.Exists(pWorkspace.PathName + "\\" + sFeatClsName + ".dbf"); } else { pWorkspace2 = (IWorkspace2)pFeatWorkspace; bHasExsit = pWorkspace2.get_NameExists(esriDatasetType.esriDTFeatureClass, sFeatClsName); pFeatWorkspace = (IFeatureWorkspace)pWorkspace2; } if (bHasExsit == false) { pDesFields = GetFieldsByFields(pFields, ref pSpatialRefer, pDicField); IFeatureDataset pFeatureDataset = null; esriFeatureType pEnumFeatType = esriFeatureType.esriFTSimple; pFeatCls = CreateFeatCls(ref sFeatClsName, ref pFeatWorkspace, pDesFields, ref pFeatureDataset, ref pEnumFeatType, "shape"); } else { //因为在获取工作空间的时候已经删除了空间内可能存在的要素集和要素类,所以下面的语句实际上永远不会被执行 yh //如果要找的要素类存在的话,则打开 pFeatCls = pFeatWorkspace.OpenFeatureClass(sFeatClsName); pDataset = (IDataset)pFeatCls; if (pDataset.CanDelete()) { pDataset.Delete(); } //重新创建要素类 pDesFields = GetFieldsByFields(pFields, ref pSpatialRefer, pDicField); IFeatureDataset pFeatureDataset = null; esriFeatureType pEnumFeatType = esriFeatureType.esriFTSimple; pFeatCls = CreateFeatCls(ref sFeatClsName, ref pFeatWorkspace, pDesFields, ref pFeatureDataset, ref pEnumFeatType, "shape"); } functionReturnValue = pFeatCls; return(functionReturnValue); } catch (Exception ex) { MessageBoxEx.Show(ex.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information); functionReturnValue = null; } return(functionReturnValue); }
private void simpleButton1_Click(object sender, EventArgs e) { if (Validate(true) == false) { return; } object createLoc; IWorkspace2 workspace2 = null; IObjectDataset dataset = _database.Datasets.FirstOrDefault(c => c.Name == cmbTemplate.SelectedItem.ToString()); if (dataset == null) { return; } IGxDatabase pDataset = txtDB.Tag as IGxDatabase; IWorkspace workspace = ((IGxObject)pDataset).InternalObjectName.Open(); workspace2 = workspace as IWorkspace2; string namePre = txtPreName.Text.Trim(); string nameNext = txtNameNext.Text.Trim(); string aliasPre = txtAliasPre.Text.Trim(); string aliasNext = txtAliasNext.Text.Trim(); if (!chkNamePre.Checked) { namePre = ""; aliasPre = ""; } if (!chkNameNext.Checked) { nameNext = ""; aliasNext = ""; } string dsName = CombineName(dataset.BaseName, namePre, nameNext); if (workspace == null) { return; } if (workspace2.NameExists[esriDatasetType.esriDTFeatureDataset, dsName]) { MessageService.Current.Warn("该名称已经存在,请重新输入!"); return; } ISpatialReference pSpatialReference = _map.SpatialReference; IFeatureDataset pNewDataset = WorkspaceOperator.CreateFeatureDataSet(workspace, dsName, pSpatialReference) as IFeatureDataset; string dsAliasName = CombineName(dataset.AliasName, aliasPre, aliasNext); //(pNewDataset as IClassSchemaEdit).AlterAliasName(dsAliasName); foreach (int selectedItem in chkFeatureClasses.CheckedIndices) { IObjectTemplate template = _templates[selectedItem]; string fcName = CombineName(template.BaseName, namePre, nameNext); string fcAliasName = CombineName(template.AliasName, aliasPre, aliasNext); if (template.FeatureType == esriFeatureType.esriFTAnnotation) { WorkspaceOperator.CreateAnnoFeatureClass(fcName, pNewDataset, 1000); } else { IFieldsEdit pFieldsEdit = new FieldsClass() as IFieldsEdit; IField pField = FieldHelper.CreateOIDField(); if (pFieldsEdit.FindField(pField.Name) < 0) { pFieldsEdit.AddField(pField); } pField = FieldHelper.CreateGeometryField(template.GeometryType, _map.SpatialReference); if (pFieldsEdit.FindField(pField.Name) < 0) { pFieldsEdit.AddField(pField); } string keyName = ""; foreach (YTField ytField in template.Fields) { pField = ytField.CreateField(); if (pFieldsEdit.FindField(pField.Name) < 0) { pFieldsEdit.AddField(pField); } if (ytField.IsKey) { keyName = ytField.Name; } } IFeatureClass pClass = WorkspaceOperator.CreateFeatureClass(pNewDataset, fcName, pSpatialReference, template.FeatureType, template.GeometryType, (IFields)pFieldsEdit, null, null, ""); (pClass as IClassSchemaEdit).AlterAliasName(fcAliasName); if (pClass == null) { MessageService.Current.Info(fcName + "创建失败!"); continue; } } } MapHelper.AddDataset(_map as IBasicMap, pNewDataset, dsAliasName); MessageService.Current.Info("创建成功层!"); DialogResult = DialogResult.OK; }
///<summary>Simple helper to create a featureclass in a geodatabase.</summary> /// ///<param name="workspace">An IWorkspace2 interface</param> ///<param name="featureDataset">An IFeatureDataset interface or Nothing</param> ///<param name="featureClassName">A System.String that contains the name of the feature class to open or create. Example: "states"</param> ///<param name="fields">An IFields interface</param> ///<param name="clsid">A UID value or Nothing. Example "esriGeoDatabase.Feature" or Nothing</param> ///<param name="clsext">A UID value or Nothing (this is the class extension if you want to reference a class extension when creating the feature class).</param> ///<param name="strConfigKeyword">An empty System.String or RDBMS table string for ArcSDE. Example: "myTable" or ""</param> /// ///<returns>An IFeatureClass interface or a Nothing</returns> /// ///<remarks> /// (1) If a 'featureClassName' already exists in the workspace a reference to that feature class /// object will be returned. /// (2) If an IFeatureDataset is passed in for the 'featureDataset' argument the feature class /// will be created in the dataset. If a Nothing is passed in for the 'featureDataset' /// argument the feature class will be created in the workspace. /// (3) When creating a feature class in a dataset the spatial reference is inherited /// from the dataset object. /// (4) If an IFields interface is supplied for the 'fields' collection it will be used to create the /// table. If a Nothing value is supplied for the 'fields' collection, a table will be created using /// default values in the method. /// (5) The 'strConfigurationKeyword' parameter allows the application to control the physical layout /// for this table in the underlying RDBMSfor example, in the case of an Oracle database, the /// configuration keyword controls the tablespace in which the table is created, the initial and /// next extents, and other properties. The 'strConfigurationKeywords' for an ArcSDE instance are /// set up by the ArcSDE data administrator, the list of available keywords supported by a workspace /// may be obtained using the IWorkspaceConfiguration interface. For more information on configuration /// keywords, refer to the ArcSDE documentation. When not using an ArcSDE table use an empty /// string (ex: ""). ///</remarks> internal IFeatureClass CreateFeatureClass(IWorkspace2 workspace, IFeatureDataset featureDataset, string featureClassName, IFields fields, ESRI.ArcGIS.esriSystem.UID clsid, ESRI.ArcGIS.esriSystem.UID clsext, string strConfigKeyword) { if (string.IsNullOrEmpty(featureClassName)) return null; IFeatureClass featureClass; var featureWorkspace = (IFeatureWorkspace)workspace; // Cast may throw exception if (workspace.NameExists[esriDatasetType.esriDTFeatureClass, featureClassName]) //feature class with that name already exists { featureClass = featureWorkspace.OpenFeatureClass(featureClassName); return featureClass; } // assign the class id value if not assigned if (clsid == null) { clsid = new ESRI.ArcGIS.esriSystem.UIDClass { Value = "esriGeoDatabase.Feature" }; //Works for shapefiles as well } IObjectClassDescription objectClassDescription = new FeatureClassDescriptionClass(); // if a fields collection is not passed in then supply our own if (fields == null) { // create the fields using the required fields method fields = objectClassDescription.RequiredFields; var fieldsEdit = (IFieldsEdit)fields; // Explicit Cast IField field = new FieldClass(); // create a user defined text field var fieldEdit = (IFieldEdit)field; // Explicit Cast // 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 = fieldsEdit; } string strShapeField = ""; // locate the shape field for (int j = 0; j < fields.FieldCount; j++) { if (fields.Field[j].Type != esriFieldType.esriFieldTypeGeometry) continue; strShapeField = fields.Field[j].Name; break; } // Use IFieldChecker to create a validated fields collection. IFieldChecker fieldChecker = new FieldCheckerClass(); IEnumFieldError enumFieldError; IFields validatedFields; fieldChecker.ValidateWorkspace = (IWorkspace)workspace; fieldChecker.Validate(fields, out enumFieldError, out validatedFields); // The enumFieldError enumerator can be inspected at this point to determine // which fields were modified during validation. // finally create and return the feature class featureClass = featureDataset == null ? featureWorkspace.CreateFeatureClass(featureClassName, validatedFields, clsid, clsext, esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword) : featureDataset.CreateFeatureClass(featureClassName, validatedFields, clsid, clsext, esriFeatureType.esriFTSimple, strShapeField, strConfigKeyword); return featureClass; }
protected bool InWorkspace(IWorkspace2 wksp2, esriDatasetType type, String name) { bool result = true; IWorkspace workspace = wksp2 as IWorkspace; if (wksp2.get_NameExists(type, name)) { _logHelper.addLogEntry(DateTime.Now.ToString(), "INFO", "Exists check: " + name, "PASS"); } else { _logHelper.addLogEntry(DateTime.Now.ToString(), "ERROR", "Exists check: " + name, "FAIL"); return false; } return result; }