public static void AddDefaultField(FieldEdit.ClassType classType_0, IFieldsEdit ifieldsEdit_0) { IObjectClassDescription objectClassDescriptionClass = new ObjectClassDescription(); switch (classType_0) { case FieldEdit.ClassType.Table: { objectClassDescriptionClass = new ObjectClassDescription(); break; } case FieldEdit.ClassType.FeatureClass: { objectClassDescriptionClass = new FeatureClassDescription(); break; } } IFields requiredFields = objectClassDescriptionClass.RequiredFields; for (int i = 0; i < requiredFields.FieldCount; i++) { ifieldsEdit_0.AddField(requiredFields.Field[i]); } }
protected override async void OnClick() { var selectedLayer = MapView.Active.GetSelectedLayers().FirstOrDefault(); if (selectedLayer == null || !(selectedLayer is FeatureLayer)) { MessageBox.Show("You have to select a feature layer. The selected layer's database connection is then used to create the new FeatureClass."); return; } var selectedFeatureLayer = selectedLayer as FeatureLayer; await QueuedTask.Run(() => { var selectedLayerTable = selectedFeatureLayer.GetTable(); var stringFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheString", FieldType.String); var intFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheInteger", FieldType.Integer); var dblFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheDouble", FieldType.Double) { Precision = 9, Scale = 5 }; var dateFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheDate", FieldType.Date); using (var geoDb = selectedLayerTable.GetDatastore() as Geodatabase) { var fcName = selectedLayerTable.GetName(); try { FeatureClassDefinition originalFeatureClassDefinition = geoDb.GetDefinition <FeatureClassDefinition>(fcName); FeatureClassDescription originalFeatureClassDescription = new FeatureClassDescription(originalFeatureClassDefinition); // Assemble a list of all of new field descriptions var fieldDescriptions = new List <ArcGIS.Core.Data.DDL.FieldDescription>() { stringFieldDescription, intFieldDescription, dblFieldDescription, dateFieldDescription }; // Create a FeatureClassDescription object to describe the feature class to create var fcDescription = new FeatureClassDescription(fcName, fieldDescriptions, originalFeatureClassDescription.ShapeDescription); // Create a SchemaBuilder object SchemaBuilder schemaBuilder = new SchemaBuilder(geoDb); // Add the modification to the feature class to our list of DDL tasks schemaBuilder.Modify(fcDescription); // Execute the DDL bool success = schemaBuilder.Build(); } catch (Exception ex) { MessageBox.Show($@"Exception: {ex}"); } } }); }
public IFeatureClass CreateFeatureClass(IGeometry igeometry_0) { IFeatureClass featureClass; try { IFeatureClassDescription featureClassDescriptionClass = new FeatureClassDescription() as IFeatureClassDescription; IFields requiredFields = (featureClassDescriptionClass as IObjectClassDescription).RequiredFields; IField field = requiredFields.Field[requiredFields.FindField(featureClassDescriptionClass.ShapeFieldName)]; IGeometryDef geometryDef = field.GeometryDef; if ( !(igeometry_0.GeometryType == esriGeometryType.esriGeometryMultipoint ? false : igeometry_0.GeometryType != esriGeometryType.esriGeometryPoint)) { (geometryDef as IGeometryDefEdit).GeometryType_2 = igeometry_0.GeometryType; } else if ((igeometry_0.GeometryType == esriGeometryType.esriGeometryPolygon ? false : igeometry_0.GeometryType != esriGeometryType.esriGeometryPolyline)) { featureClass = null; return(featureClass); } else { (geometryDef as IGeometryDefEdit).GeometryType_2 = igeometry_0.GeometryType; } if (igeometry_0.SpatialReference != null) { igeometry_0.SpatialReference = igeometry_0.SpatialReference; } (field as IFieldEdit).GeometryDef_2 = geometryDef; if (this.iworkspaceName_0 == null) { this.CreateTempDB(); } IWorkspace workspace = (this.iworkspaceName_0 as IName).Open() as IWorkspace; string str = "tempfc"; IFeatureClass featureClass1 = (workspace as IFeatureWorkspace).CreateFeatureClass(str, requiredFields, (featureClassDescriptionClass as IObjectClassDescription).InstanceCLSID, (featureClassDescriptionClass as IObjectClassDescription).ClassExtensionCLSID, esriFeatureType.esriFTSimple, featureClassDescriptionClass.ShapeFieldName, ""); this.AddGeometry(featureClass1, igeometry_0); featureClass = featureClass1; return(featureClass); } catch { } featureClass = null; return(featureClass); }
public IFeatureClass CreateFeatureClass(IGeometry igeometry_0) { IFeatureClass result; try { IFeatureClassDescription featureClassDescription = new FeatureClassDescription() as IFeatureClassDescription; IFields requiredFields = (featureClassDescription as IObjectClassDescription).RequiredFields; int index = requiredFields.FindField(featureClassDescription.ShapeFieldName); IField field = requiredFields.get_Field(index); IGeometryDef geometryDef = field.GeometryDef; if (igeometry_0.GeometryType == esriGeometryType.esriGeometryMultipoint || igeometry_0.GeometryType == esriGeometryType.esriGeometryPoint) { (geometryDef as IGeometryDefEdit).GeometryType_2 = igeometry_0.GeometryType; } else { if (igeometry_0.GeometryType != esriGeometryType.esriGeometryPolygon && igeometry_0.GeometryType != esriGeometryType.esriGeometryPolyline) { result = null; return(result); } (geometryDef as IGeometryDefEdit).GeometryType_2 = igeometry_0.GeometryType; } if (igeometry_0.SpatialReference != null) { igeometry_0.SpatialReference = igeometry_0.SpatialReference; } (field as IFieldEdit).GeometryDef_2 = geometryDef; if (this.iworkspaceName_0 == null) { this.CreateTempDB(); } IWorkspace workspace = (this.iworkspaceName_0 as IName).Open() as IWorkspace; string name = "tempfc"; IFeatureClass featureClass = (workspace as IFeatureWorkspace).CreateFeatureClass(name, requiredFields, (featureClassDescription as IObjectClassDescription).InstanceCLSID, (featureClassDescription as IObjectClassDescription).ClassExtensionCLSID, esriFeatureType.esriFTSimple, featureClassDescription.ShapeFieldName, ""); this.AddGeometry(featureClass, igeometry_0); result = featureClass; return(result); } catch { } result = null; return(result); }
private static ITable CreateTable(object container, string name, string oidField, bool isSpatial, esriGeometryType geometryType, ISpatialReference spatialReference, List <IField> customFields) { var i = (isSpatial ? 2 : 1); IFields fields = new Fields(); var fieldsEdit = (IFieldsEdit)fields; fieldsEdit.FieldCount_2 = i + customFields.Count; fieldsEdit.Field_2[0] = GetOIDField(oidField); if (isSpatial) { fieldsEdit.Field_2[1] = GetShapeField(geometryType, spatialReference); } foreach (var field in customFields) { fieldsEdit.Field_2[i++] = field; } IObjectClassDescription ocDesc = new FeatureClassDescription(); var fws = container as IFeatureWorkspace; if (fws != null) { return(isSpatial ? fws.CreateFeatureClass(name, fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "Shape", "") as ITable : fws.CreateTable(name, fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, "")); } var fds = container as IFeatureDataset; if (fds != null) { return(fds.CreateFeatureClass(name, fields, ocDesc.InstanceCLSID, ocDesc.ClassExtensionCLSID, esriFeatureType.esriFTSimple, "Shape", "") as ITable); } throw new Exception("An unexpected error has occurred."); }
private IFeatureClass method_1(string string_0, int int_0, IntPtr intptr_0, IFeatureWorkspace ifeatureWorkspace_0, out bool bool_0) { IEnumFieldError enumFieldError; IFields field; IFeatureClass featureClass; bool_0 = false; try { IFeatureClass featureClass1 = null; string fileNameWithoutExtension = System.IO.Path.GetFileNameWithoutExtension(string_0); IFeatureClassDescription featureClassDescriptionClass = new FeatureClassDescription() as IFeatureClassDescription; string shapeFieldName = featureClassDescriptionClass.ShapeFieldName; IFields requiredFields = (featureClassDescriptionClass as IObjectClassDescription).RequiredFields; this.AddTabField(requiredFields as IFieldsEdit, intptr_0); this.AddTabField(int_0, requiredFields as IFieldsEdit); IFields field1 = requiredFields; IFieldChecker fieldCheckerClass = new FieldChecker() { ValidateWorkspace = ifeatureWorkspace_0 as IWorkspace }; fieldCheckerClass.Validate(field1, out enumFieldError, out field); IFieldEdit fieldEdit = field.Field[field.FindField(shapeFieldName)] as IFieldEdit; IGeometryDefEdit geometryDef = fieldEdit.GeometryDef as IGeometryDefEdit; if (this.ispatialReference_0 == null) { string str = TabRead._mitab_c_get_coordsys_xml(intptr_0); if (str == null) { this.ispatialReference_0 = geometryDef.SpatialReference; } else if (str.Length <= 0) { this.ispatialReference_0 = geometryDef.SpatialReference; } else { string str1 = string.Concat(System.IO.Path.GetTempPath(), "\\temp.prj"); StreamWriter streamWriter = new StreamWriter(str1); try { streamWriter.Write(str); } finally { if (streamWriter != null) { ((IDisposable)streamWriter).Dispose(); } } try { this.ispatialReference_0 = (new SpatialReferenceEnvironment()).CreateESRISpatialReferenceFromPRJFile(str1); } catch { this.ispatialReference_0 = geometryDef.SpatialReference; } try { File.Delete(str1); } catch { } } double num = 0; double num1 = 0; double num2 = 0; double num3 = 0; TabRead._mitab_c_get_mif_bounds(intptr_0, ref num, ref num1, ref num2, ref num3); SpatialReferenctOperator.ChangeCoordinateSystem(ifeatureWorkspace_0 as IGeodatabaseRelease, this.ispatialReference_0, false); num = num - 10; num1 = num1 + 10; num2 = num2 - 10; num3 = num3 + 10; this.ispatialReference_0.SetDomain(num, num1, num2, num3); } geometryDef.SpatialReference_2 = this.ispatialReference_0; TabRead._mitab_c_get_feature_count_bytype(intptr_0, int_0); switch (int_0) { case 1: case 2: case 3: { fileNameWithoutExtension = string.Concat(fileNameWithoutExtension, "_Point"); fileNameWithoutExtension = this.method_0(ifeatureWorkspace_0 as IWorkspace, fileNameWithoutExtension); geometryDef.GeometryType_2 = esriGeometryType.esriGeometryPoint; fieldEdit.GeometryDef_2 = geometryDef; featureClass1 = ifeatureWorkspace_0.CreateFeatureClass(fileNameWithoutExtension, field, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); break; } case 4: { fileNameWithoutExtension = string.Concat(fileNameWithoutExtension, "_Anno_Point"); fileNameWithoutExtension = this.method_0(ifeatureWorkspace_0 as IWorkspace, fileNameWithoutExtension); geometryDef.GeometryType_2 = esriGeometryType.esriGeometryPoint; fieldEdit.GeometryDef_2 = geometryDef; featureClass1 = ifeatureWorkspace_0.CreateFeatureClass(fileNameWithoutExtension, field, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); break; } case 5: case 6: { fileNameWithoutExtension = string.Concat(fileNameWithoutExtension, "_Line"); fileNameWithoutExtension = this.method_0(ifeatureWorkspace_0 as IWorkspace, fileNameWithoutExtension); geometryDef.GeometryType_2 = esriGeometryType.esriGeometryPolyline; fieldEdit.GeometryDef_2 = geometryDef; featureClass1 = ifeatureWorkspace_0.CreateFeatureClass(fileNameWithoutExtension, field, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); break; } case 7: { fileNameWithoutExtension = string.Concat(fileNameWithoutExtension, "_Polygon"); fileNameWithoutExtension = this.method_0(ifeatureWorkspace_0 as IWorkspace, fileNameWithoutExtension); geometryDef.GeometryType_2 = esriGeometryType.esriGeometryPolygon; fieldEdit.GeometryDef_2 = geometryDef; featureClass1 = ifeatureWorkspace_0.CreateFeatureClass(fileNameWithoutExtension, field, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); break; } case 8: case 9: { featureClass = null; return(featureClass); } case 10: { fileNameWithoutExtension = string.Concat(fileNameWithoutExtension, "_MultiPoint"); fileNameWithoutExtension = this.method_0(ifeatureWorkspace_0 as IWorkspace, fileNameWithoutExtension); geometryDef.GeometryType_2 = esriGeometryType.esriGeometryMultipoint; fieldEdit.GeometryDef_2 = geometryDef; featureClass1 = ifeatureWorkspace_0.CreateFeatureClass(fileNameWithoutExtension, field, null, null, esriFeatureType.esriFTSimple, shapeFieldName, ""); break; } default: { featureClass = null; return(featureClass); } } featureClass = featureClass1; return(featureClass); } catch (Exception exception) { Logger.Current.Error("", exception, ""); bool_0 = true; } featureClass = null; return(featureClass); }
private IFeatureClass CreateFeatureClassFromGeometry(IGeometry pGeometry, IFeatureWorkspace pOutFeatWorkspace, int wkid) { // thanks to http://bcdcspatial.blogspot.co.uk/2011/12/some-random-arcobjects-that-make.html // which was the only place i could find an answer to the problem I was having - the last // argument to createfeatureclass is null NOT an empty string try { IFields tFields = new FieldsClass() as IFields; IFieldsEdit tFieldsEdit = (IFieldsEdit)tFields; IField tShpFld = new Field(); IFieldEdit tShpEd = (IFieldEdit)tShpFld; tShpEd.Type_2 = esriFieldType.esriFieldTypeGeometry; tShpEd.Name_2 = "Shape"; IGeometryDef tGeomDef = new GeometryDef(); IGeometryDefEdit tGdEdit = (IGeometryDefEdit)tGeomDef; tGdEdit.GeometryType_2 = pGeometry.GeometryType; ISpatialReferenceFactory2 tSRFac = new SpatialReferenceEnvironment() as ISpatialReferenceFactory2; ISpatialReference tSpatRef = tSRFac.CreateSpatialReference(wkid); ISpatialReferenceResolution tSpatRefRes = (ISpatialReferenceResolution)tSpatRef; tSpatRefRes.ConstructFromHorizon(); tGdEdit.SpatialReference_2 = tSpatRef; tShpEd.GeometryDef_2 = tGeomDef; tFieldsEdit.AddField(tShpFld); IObjectClassDescription tOCDesc = new FeatureClassDescription(); for (int i = 0; i < tOCDesc.RequiredFields.FieldCount; i++) { IField tField = tOCDesc.RequiredFields.get_Field(i); if (tFieldsEdit.FindField(tField.Name) == -1) { tFieldsEdit.AddField(tField); } } string tFCName = "tmp" + Guid.NewGuid().ToString("N"); IFeatureClass tFC = pOutFeatWorkspace.CreateFeatureClass( tFCName, tFields, null, null, esriFeatureType.esriFTSimple, "Shape", null); IFeature tGeomAsFeature = tFC.CreateFeature(); tGeomAsFeature.Shape = pGeometry; tGeomAsFeature.Store(); return tFC; } catch (Exception e) { Console.WriteLine(e.Message); logger.LogMessage(ServerLogger.msgType.error, "CreateFeatureClassFromGeometry", 99, "Could not create feature class " + e.Message + e.Source + e.StackTrace); throw e; } }
protected override async void OnClick() { var selectedLayer = MapView.Active.GetSelectedLayers().FirstOrDefault(); if (selectedLayer == null || !(selectedLayer is FeatureLayer)) { MessageBox.Show("You have to select a feature layer. The selected layer's database connection is then used to create the new FeatureClass."); return; } var selectedFeatureLayer = selectedLayer as FeatureLayer; await QueuedTask.Run(() => { var selectedLayerTable = selectedFeatureLayer.GetTable(); var testName = $@"Point{DateTime.Now:HHmmss}"; var hasZ = false; var hasM = false; // Create a ShapeDescription object var shapeDescription = new ShapeDescription(GeometryType.Point, SpatialReferences.WebMercator) { HasM = hasM, HasZ = hasZ }; var objectIDFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("ObjectID", FieldType.OID); var stringFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheString", FieldType.String); var intFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheInteger", FieldType.Integer); var dblFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheDouble", FieldType.Double) { Precision = 9, Scale = 5 }; var dateFieldDescription = new ArcGIS.Core.Data.DDL.FieldDescription("TheDate", FieldType.Date); using (var geoDb = selectedLayerTable.GetDatastore() as Geodatabase) { var fcName = $@"{testName}"; try { // Assemble a list of all of our field descriptions var fieldDescriptions = new List <ArcGIS.Core.Data.DDL.FieldDescription>() { objectIDFieldDescription, stringFieldDescription, intFieldDescription, dblFieldDescription, dateFieldDescription }; // Create a FeatureClassDescription object to describe the feature class // that we want to create var fcDescription = new FeatureClassDescription(fcName, fieldDescriptions, shapeDescription); // Create a SchemaBuilder object SchemaBuilder schemaBuilder = new SchemaBuilder(geoDb); // Add the creation of the new feature class to our list of DDL tasks schemaBuilder.Create(fcDescription); // Execute the DDL bool success = schemaBuilder.Build(); } catch (Exception ex) { MessageBox.Show($@"Exception: {ex}"); } } }); }
private void OpenCADFile(string filePath, string outputFilePath) { try { Debug.WriteLine("Start Time: " + DateTime.Now.ToShortTimeString()); System.Windows.Forms.Cursor.Current = Cursors.WaitCursor; String nameOfPath = System.IO.Path.GetDirectoryName(filePath); String nameOfCADFile = System.IO.Path.GetFileName(filePath); #region Open CAD Workspace from File Path //Set the workspace. ESRI.ArcGIS.Geodatabase.IWorkspaceFactory pWorkspaceFact = new ESRI.ArcGIS.DataSourcesFile.CadWorkspaceFactory(); ESRI.ArcGIS.Geodatabase.IWorkspaceFactory defaultWorkspaceFact = new FileGDBWorkspaceFactory(); //Open the workspace. ESRI.ArcGIS.Geodatabase.IWorkspace pWorkspace = pWorkspaceFact.OpenFromFile(nameOfPath, 0); //Get the CADDrawingWorkspace. ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace pCadDwgWorkspace; pCadDwgWorkspace = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingWorkspace)pWorkspace; //Open the CadDrawingDataset. ESRI.ArcGIS.DataSourcesFile.ICadDrawingDataset pCadDwgDataset; pCadDwgDataset = pCadDwgWorkspace.OpenCadDrawingDataset(nameOfCADFile); //Set the feature workspace. ESRI.ArcGIS.Geodatabase.IFeatureWorkspace pFeatureWorkspace = (ESRI.ArcGIS.Geodatabase.IFeatureWorkspace)pWorkspace; //Open the Feature Class. #endregion #region Getting Polygon, polylines, and annotation from Cad file ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polygon")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Plyline = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Polyline")); ESRI.ArcGIS.Geodatabase.IFeatureClass pFeatClass_Anno = pFeatureWorkspace.OpenFeatureClass(System.String.Concat(nameOfCADFile, ":Annotation")); #endregion UID CLSID_def = new UIDClass(); CLSID_def.Value = "esriGeoDatabase.Feature"; #region Creating Layers from Feature Classes //Polygons ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer.FeatureClass = pFeatClass; pFeatLayer.Name = "Polygons"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer; //Annotation ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Anno = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Anno.FeatureClass = pFeatClass_Anno; pFeatLayer_Anno.Name = "Annotation"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Anno = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Anno; //Polylines ESRI.ArcGIS.Carto.IFeatureLayer pFeatLayer_Plyline = new ESRI.ArcGIS.Carto.CadFeatureLayer() as ESRI.ArcGIS.Carto.IFeatureLayer; pFeatLayer_Plyline.FeatureClass = pFeatClass_Plyline; pFeatLayer_Plyline.Name = "Polylines"; ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers pCadDwgLayers_Plyline = (ESRI.ArcGIS.DataSourcesFile.ICadDrawingLayers)pFeatLayer_Plyline; #endregion #region Creating In-Memory workspace IWorkspaceFactory WF = new InMemoryWorkspaceFactory(); ESRI.ArcGIS.esriSystem.IName name = WF.Create("", "MyWorkspace", null, 0) as ESRI.ArcGIS.esriSystem.IName; IWorkspace inMemWorkspace = (IWorkspace)name.Open(); IFeatureWorkspace featureWorkspace = (IFeatureWorkspace)inMemWorkspace; #endregion #region Creating new Fields IObjectClassDescription objectClassDescription = new FeatureClassDescription(); // create the fields using the required fields method IFields exportFields = new Fields(); IFieldsEdit fieldsEdit = (IFieldsEdit)exportFields; //OID IField field = new Field(); IField oidField = new Field(); IFieldEdit oidFieldEdit = (IFieldEdit)oidField; oidFieldEdit.Name_2 = "OID"; oidFieldEdit.Type_2 = esriFieldType.esriFieldTypeOID; fieldsEdit.AddField(oidField); // Create a geometry definition (and spatial reference) for the feature class IGeometryDef geometryDef = new GeometryDef(); IGeometryDefEdit geometryDefEdit = (IGeometryDefEdit)geometryDef; geometryDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPolygon; IGeoDataset dataSet = (IGeoDataset)pFeatClass.FeatureDataset; ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironment(); ISpatialReference spatialReference = dataSet.SpatialReference; ISpatialReferenceResolution spatialReferenceResolution = (ISpatialReferenceResolution)spatialReference; spatialReferenceResolution.ConstructFromHorizon(); ISpatialReferenceTolerance spatialReferenceTolerance = (ISpatialReferenceTolerance)spatialReference; spatialReferenceTolerance.SetDefaultXYTolerance(); geometryDefEdit.SpatialReference_2 = spatialReference; // Add a geometry field to the fields collection. This is where the geometry definition is applied. IField geometryField = new Field(); IFieldEdit geometryFieldEdit = (IFieldEdit)geometryField; geometryFieldEdit.Name_2 = "Shape"; geometryFieldEdit.Type_2 = esriFieldType.esriFieldTypeGeometry; geometryFieldEdit.GeometryDef_2 = geometryDef; fieldsEdit.AddField(geometryField); #endregion #region Creating New Shapefile for Final output UID CLSID = new UIDClass(); CLSID.Value = "esriGeoDatabase.Feature"; //using the In-Memory Workspace created above IFeatureClass output = featureWorkspace.CreateFeatureClass("myPolygons", pFeatClass.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass polylines_cleaned = featureWorkspace.CreateFeatureClass("polylines_cleaned", pFeatClass_Plyline.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); IFeatureClass annotation_cleaned = featureWorkspace.CreateFeatureClass("annotation_cleaned", pFeatClass_Anno.Fields, CLSID, null, esriFeatureType.esriFTSimple, "Shape", null); #endregion #region Appending features from CADWorkspaceFeatureClass to In-Memory FeatureClass Because Update cursor not in Cad workspace Geoprocessor GP = new Geoprocessor(); //Polylines ESRI.ArcGIS.DataManagementTools.Append append = new Append(); append.inputs = pFeatClass_Plyline; append.target = polylines_cleaned; GP.Execute(append, null); //System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Plyline); GC.Collect(); //Annotation append = new Append(); append.inputs = pFeatClass_Anno; append.target = annotation_cleaned; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass_Anno); GC.Collect(); //Polygons to output append = new Append(); append.inputs = pFeatClass; append.target = output; GP.Execute(append, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(pFeatClass); GC.Collect(); #endregion #region Query Filter to Filter Layers string queryString = ""; //using the checked box list and comma seperated list to create where clause string //Adding Items from Check Box List foreach (var checkedItem in checkedListBox1.CheckedItems) { queryString = queryString + "Layer NOT LIKE '" + checkedItem.ToString() + "' AND "; } //Adding Items from Comma separated string if (textBox_commaSeparated.Text.Length > 0) { foreach (var item in textBox_commaSeparated.Text.Split(',')) { queryString = queryString + "Layer NOT LIKE '" + item.ToString() + "' AND "; } } //Removing Last 'AND' FROM queryString if (queryString.Length > 0) //if Atleast one item added { queryString = queryString.Remove(queryString.Length - 4); } IQueryFilter queryFilter = new QueryFilter(); queryFilter.SubFields = ""; if (queryString.Length > 0) { queryFilter.WhereClause = queryString; } else { queryFilter.WhereClause = "1=1"; } #endregion #region Removing Null Geometries string ignoreList = queryString.Replace("Layer NOT LIKE '", "").Replace("' AND ", ",").Replace("' ", ""); Debug.WriteLine("lines Count before:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From Polylines_cleaned IFeatureCursor updateCursor = polylines_cleaned.Update(new QueryFilter(), false); IFeature feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); //System.Runtime.InteropServices.Marshal.ReleaseComObject(feat); GC.Collect(); Debug.WriteLine("lines Count After:" + polylines_cleaned.FeatureCount(new QueryFilter()).ToString()); //From output Debug.WriteLine("polygons Count before:" + output.FeatureCount(new QueryFilter()).ToString()); updateCursor = output.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("polygons Count after:" + output.FeatureCount(new QueryFilter()).ToString()); //From Annotation Debug.WriteLine("Annotation Count before:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); updateCursor = annotation_cleaned.Update(new QueryFilter(), false); feat = updateCursor.NextFeature(); while (feat != null) { string lyr = Convert.ToString(feat.get_Value(feat.Fields.FindField("Layer"))); lyr = lyr.ToUpper(); if (feat.Shape.IsEmpty || ignoreList.ToUpper().Split(',').ToList <string>().Any(l => lyr.Contains(l))) { updateCursor.DeleteFeature(); } feat = updateCursor.NextFeature(); } System.Runtime.InteropServices.Marshal.ReleaseComObject(updateCursor); GC.Collect(); Debug.WriteLine("Annotation Count after:" + annotation_cleaned.FeatureCount(new QueryFilter()).ToString()); #endregion #region Convert lines feature class to feature Cursor IFeatureCursor linesFCursor = polylines_cleaned.Search(new QueryFilter(), false); #endregion #region Deleting all columns of polygons to match with output IFields _fieldsP = output.Fields; IFieldsEdit _fieldsEditP = (IFieldsEdit)_fieldsP; for (int i = 0; i < output.Fields.FieldCount; i++) { IField _field = output.Fields.get_Field(i); if (_field.Name != "Shape" && _field.Name != "FID") { output.DeleteField(_field); if (i < output.Fields.FieldCount) { i--; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsP); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEditP); GC.Collect(); #endregion #region Setting Envelop information IEnvelope envelop = new Envelope() as IEnvelope; IGeoDataset dataSetEnv = (IGeoDataset)pFeatClass_Plyline.FeatureDataset; envelop.SpatialReference = dataSet.SpatialReference; envelop.PutCoords(dataSet.Extent.XMin, dataSet.Extent.YMin, dataSet.Extent.XMax, dataSet.Extent.YMax); #endregion #region Construct Polygons from Lines Cursor (usting Feature Construct) IFeatureConstruction featureConstruct = new FeatureConstruction() as IFeatureConstruction; ISelectionSet selectionSet = null; //atureConstruct.ConstructPolygonsFromFeaturesFromCursor(null,output,envelop,false,false,linesFCursor,null,0.001,null); featureConstruct.AutoCompleteFromFeaturesFromCursor(output, envelop, linesFCursor, null, -1, null, out selectionSet); #endregion System.Runtime.InteropServices.Marshal.ReleaseComObject(featureConstruct); System.Runtime.InteropServices.Marshal.ReleaseComObject(linesFCursor); GC.Collect(); Debug.WriteLine("polygons Count after PolygonConstruct :" + output.FeatureCount(new QueryFilter()).ToString()); #region SPATIAL JOIN GP = new Geoprocessor(); ESRI.ArcGIS.AnalysisTools.SpatialJoin spatialJoin = new ESRI.ArcGIS.AnalysisTools.SpatialJoin(); spatialJoin.join_features = annotation_cleaned; spatialJoin.target_features = output; spatialJoin.join_operation = "JOIN_ONE_TO_MANY"; spatialJoin.join_type = "KEEP_ALL"; spatialJoin.match_option = "CONTAINS"; spatialJoin.out_feature_class = outputFilePath; GP.Execute(spatialJoin, null); System.Runtime.InteropServices.Marshal.ReleaseComObject(annotation_cleaned); GC.Collect(); #endregion #region Remove All Fields of Annotation except Text ShapefileWorkspaceFactory wsf = new ShapefileWorkspaceFactory(); IFeatureWorkspace work = (IFeatureWorkspace)wsf.OpenFromFile(System.IO.Path.GetDirectoryName(outputFilePath), 0); IFeatureClass output_AfterJoin_FClasss = work.OpenFeatureClass(System.IO.Path.GetFileNameWithoutExtension(outputFilePath)); IFields _fields = output_AfterJoin_FClasss.Fields; IFieldsEdit _fieldsEdit = (IFieldsEdit)_fields; for (int i = 0; i < _fields.FieldCount; i++) { IField _field = output_AfterJoin_FClasss.Fields.get_Field(i); if (_field.Name != "Text_" && _field.Name != "Text" && _field.Name != "Shape" && _field.Name != "FID") { output_AfterJoin_FClasss.DeleteField(_field); i--; } else { if (field.Name == "Text_" || _field.Name == "Text") { IFieldEdit fieldEdit = (IFieldEdit)_field; fieldEdit.Name_2 = "PlotNumber"; fieldEdit.AliasName_2 = "PlotNumber"; } } } System.Runtime.InteropServices.Marshal.ReleaseComObject(_fields); System.Runtime.InteropServices.Marshal.ReleaseComObject(_fieldsEdit); GC.Collect(); #endregion System.Windows.Forms.Cursor.Current = Cursors.Default; Debug.WriteLine("End Time: " + DateTime.Now.ToShortTimeString()); MessageBox.Show("Import Complete!"); } catch { MessageBox.Show("Error Importing. Something wrong with the CAD File"); } }
private IFeatureClass CreateFeatureClass(string Name, IFeatureWorkspace FeatureWorkspace) { //The feature that will be returned IFeatureClass featureClassCreated; //Create the filed for the histogram and the fields to be created in the future class IObjectClassDescription objectClassDescription = new FeatureClassDescription(); IFields fields = objectClassDescription.RequiredFields; IFieldsEdit fieldsEdit = fields as IFieldsEdit; IField field = new Field(); IFieldEdit fieldEdit = field as IFieldEdit; fieldEdit.AliasName_2 = "HistoField"; fieldEdit.Name_2 = "HistoField"; fieldEdit.Editable_2 = true; fieldEdit.Type_2 = esriFieldType.esriFieldTypeInteger; fieldsEdit.AddField(field); fields = fieldsEdit as IFields; //Create and assugn a CLSID UID CLSID = new UIDClass(); CLSID.Value = "esriGeodatabase.Feature"; string strShapeField = ""; //Find the geometry field and then set the spatial reference and the geometry type. for (int i = 0; i < fields.FieldCount; i++) { if (fields.get_Field(i).Type == esriFieldType.esriFieldTypeGeometry) { strShapeField = fields.get_Field(i).Name; IGeometryDef geomDef = fields.get_Field(i).GeometryDef; IGeometryDefEdit geomDefEdit = (IGeometryDefEdit)geomDef; geomDefEdit.SpatialReference_2 = getSpatialReference(4326); geomDefEdit.GeometryType_2 = esriGeometryType.esriGeometryPoint; break; } } //If the file exists, overwrite it, otherwise create a new one. if (((IWorkspace2)FeatureWorkspace).NameExists[esriDatasetType.esriDTFeatureClass, Name]) { IDataset dataset = FeatureWorkspace.OpenFeatureClass(Name) as IDataset; dataset.Delete(); featureClassCreated = FeatureWorkspace.CreateFeatureClass(Name, fields, CLSID, null, esriFeatureType.esriFTSimple, strShapeField, ""); } else { featureClassCreated = FeatureWorkspace.CreateFeatureClass(Name, fields, CLSID, null, esriFeatureType.esriFTSimple, strShapeField, ""); } return featureClassCreated; }