public static Dictionary <string, object> GetAll(this Feature feature) { Dictionary <string, object> ret = new Dictionary <string, object>(); if (feature != null) { int fieldCount = feature.GetFieldCount(); for (int i = 0; i < fieldCount; i++) { FieldDefn fd = feature.GetFieldDefnRef(i); string key = fd.GetName(); object value = null; FieldType ft = fd.GetFieldType(); switch (ft) { case FieldType.OFTString: value = feature.GetFieldAsString(i); break; case FieldType.OFTReal: value = feature.GetFieldAsDouble(i); break; case FieldType.OFTInteger: value = feature.GetFieldAsInteger(i); break; } ret.Add(key, value); } } return(ret); }
private DataTable BuildSchemaTable() { _schemaTable = new DataTable("SchemaTable"); _schemaTable.Locale = CultureInfo.InvariantCulture; AddDataColumn(_schemaTable, SchemaTableColumn.ColumnName, typeof(string)); AddDataColumn(_schemaTable, SchemaTableColumn.ColumnOrdinal, typeof(int)); AddDataColumn(_schemaTable, SchemaTableColumn.ColumnSize, typeof(int), -1); AddDataColumn(_schemaTable, SchemaTableColumn.NumericPrecision, typeof(short)); AddDataColumn(_schemaTable, SchemaTableColumn.NumericScale, typeof(short)); AddDataColumn(_schemaTable, SchemaTableColumn.DataType, typeof(Type)); AddDataColumn(_schemaTable, SchemaTableColumn.ProviderType, typeof(int)); AddDataColumn(_schemaTable, SchemaTableColumn.IsLong, typeof(bool), false); AddDataColumn(_schemaTable, SchemaTableColumn.AllowDBNull, typeof(bool), true); AddDataColumn(_schemaTable, SchemaTableColumn.IsUnique, typeof(bool), false); AddDataColumn(_schemaTable, SchemaTableColumn.IsKey, typeof(bool), false); AddDataColumn(_schemaTable, SchemaTableColumn.BaseSchemaName, typeof(string)); AddDataColumn(_schemaTable, SchemaTableColumn.BaseTableName, typeof(string), String.Empty); AddDataColumn(_schemaTable, SchemaTableColumn.BaseColumnName, typeof(string)); AddDataRow(_schemaTable, GeometryFieldName, GeometryFieldOrdinal, 1, typeof(byte[]), true, false, false); AddDataRow(_schemaTable, FidFieldName, FidFieldOrdinal, 1, typeof(long), false, true, true); for (int i = 0; i < _iFieldCount; i++) { FieldDefn f = _ogrFeatureDefinition.GetFieldDefn(i); AddDataRow(_schemaTable, f.GetName(), i + 2, f.GetWidth(), TranslateOgrType(f.GetFieldType()), true, false, false); } _schemaTable.AcceptChanges(); return(_schemaTable); }
public static object Get(this Feature feature, string name) { int fieldCount = feature.GetFieldCount(); object ret = null; for (int i = 0; i < fieldCount; i++) { FieldDefn fd = feature.GetFieldDefnRef(i); if (fd.GetName() == name) { FieldType ft = fd.GetFieldType(); switch (ft) { case FieldType.OFTString: ret = feature.GetFieldAsString(i); break; case FieldType.OFTReal: ret = feature.GetFieldAsDouble(i); break; case FieldType.OFTInteger: ret = feature.GetFieldAsInteger(i); break; } } } return(ret); }
private static IList <Column> BuildSchemaTable(FeatureDefn ogrFeatureDefinition) { IList <Column> schema = new List <Column>(); for (int i = 0; i < ogrFeatureDefinition.GetFieldCount(); i++) { FieldDefn f = ogrFeatureDefinition.GetFieldDefn(i); schema.Add(new Column(f.GetName(), f.GetFieldType())); } return(schema); }
/// <summary> /// Reads the field types from the OgrFeatureDefinition -> OgrFieldDefinition /// </summary> /// <param name="fdt">FeatureDatatTable</param> /// <param name="oLayer">OgrLayer</param> private void readColumnDefinition(FeatureDataTable fdt, Layer oLayer) { using (FeatureDefn _OgrFeatureDefn = oLayer.GetLayerDefn()) { int iField; for (iField = 0; iField < _OgrFeatureDefn.GetFieldCount(); iField++) { using (FieldDefn _OgrFldDef = _OgrFeatureDefn.GetFieldDefn(iField)) { FieldType type; switch ((type = _OgrFldDef.GetFieldType())) { case FieldType.OFTInteger: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.Int32")); break; case FieldType.OFTReal: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.Double")); break; case FieldType.OFTString: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.String")); break; case FieldType.OFTWideString: fdt.Columns.Add(_OgrFldDef.GetName(), Type.GetType("System.String")); break; default: { //fdt.Columns.Add(_OgrFldDef.GetName(), System.Type.GetType("System.String")); Debug.WriteLine("Not supported type: " + type + " [" + _OgrFldDef.GetName() + "]"); break; } } } } } }
// the field names in shapefile have limit of 10 characteres private string getValidFieldName(FieldDefn fieldDefn) { string fieldName = fieldDefn.GetName(); //string valuname = fieldDefn.GetDefault(); //var valuname1 = fieldDefn.GetFieldType(); //var valuname2 = fieldDefn.GetJustify(); //string valuname3 = fieldDefn.GetTypeName(); //string valuname4 = fieldDefn.GetNameRef(); //var valuname5 = fieldDefn.GetSubType(); //var valuname6 = fieldDefn.GetType(); return(fieldName.Length > 10 ? fieldName.Substring(0, 10) : fieldName); }
/// <summary> /// Fetch the field names from a layer /// </summary> /// <param name="ogrLayer">the layer</param> /// <returns>Arraylist of strings</returns> private ArrayList GetFieldNames(Layer ogrLayer) { FeatureDefn featDef = ogrLayer.GetLayerDefn(); ArrayList fNames = new ArrayList(); for (int i = 0; i < featDef.GetFieldCount(); i++) { FieldDefn fieldDef = featDef.GetFieldDefn(i); fNames.Add(fieldDef.GetName()); } return(fNames); }
private FeatureDataTable CreateFeatureDataTableStructure() { var featureDataTable = new FeatureDataTable(); //reads the column definition of the layer/feature using (FeatureDefn ogrFeatureDefn = ogrLayer.GetLayerDefn()) { int iField; var ogrTypesAndCSharpTypesMapping = new Dictionary <FieldType, Type>(); ogrTypesAndCSharpTypesMapping[FieldType.OFTInteger] = typeof(int); ogrTypesAndCSharpTypesMapping[FieldType.OFTReal] = typeof(double); ogrTypesAndCSharpTypesMapping[FieldType.OFTString] = typeof(string); ogrTypesAndCSharpTypesMapping[FieldType.OFTWideString] = typeof(string); ogrTypesAndCSharpTypesMapping[FieldType.OFTDateTime] = typeof(DateTime); for (iField = 0; iField < ogrFeatureDefn.GetFieldCount(); iField++) { using (FieldDefn ogrFldDef = ogrFeatureDefn.GetFieldDefn(iField)) { if (ogrTypesAndCSharpTypesMapping.ContainsKey(ogrFldDef.GetFieldType())) { featureDataTable.Columns.Add(ogrFldDef.GetName(), ogrTypesAndCSharpTypesMapping[ogrFldDef.GetFieldType()]); } else { //fdt.Columns.Add(_OgrFldDef.GetName(), System.Type.GetType("System.String")); Debug.WriteLine("Not supported type: " + ogrFldDef.GetFieldType() + " [" + ogrFldDef.GetName() + "]"); break; } } } } return(featureDataTable); }
public List <string> GetTileNameFromShapefile(string shpfilepath) { string fieldname = "TileName"; bool gotit = false; List <string> tilenames = new List <string>(); DataSource ds1 = Ogr.Open(shpfilepath, 0); if (ds1 == null) { Console.WriteLine(" [-] Could not open {0}", shpfilepath); return(tilenames); } Layer newlayer = ds1.GetLayerByIndex(0); if (newlayer == null) { Console.WriteLine(" [-] Could not fetch layer."); ds1.Dispose(); return(tilenames); } newlayer.ResetReading(); FeatureDefn newfeaturedfn = newlayer.GetLayerDefn(); for (int i = 0; i < newfeaturedfn.GetFieldCount(); i++) { //find TileName field in provided shapefile FieldDefn fielddefn = newfeaturedfn.GetFieldDefn(i); if (fielddefn.GetName() == fieldname) { gotit = true; break; } } if (gotit == false) { Console.WriteLine(" [-] Could not find tile name field. Please provide shapefile with the attribute field TileName"); ds1.Dispose(); return(tilenames); } for (int i = 0; i < newlayer.GetFeatureCount(1); i++) { //return each string for TileName field in shapefile Feature newfeature = newlayer.GetFeature(i); string result = newfeature.GetFieldAsString(fieldname); tilenames.Add(result); } ds1.Dispose(); return(tilenames); }
public static bool ContainsKey(this Feature feature, string name) { int fieldCount = feature.GetFieldCount(); bool flag = false; for (int i = 0; i < fieldCount; i++) { FieldDefn fd = feature.GetFieldDefnRef(i); if (fd.GetName() == name) { flag = true; break; } } return(flag); }
private static void Details(string dataSetPath) { Driver fileGdbDriver = Ogr.GetDriverByName("OpenFileGDB"); DataSource dataSource = fileGdbDriver.Open(dataSetPath, 0); Layer layer = dataSource.GetLayerByIndex(0); string shapeType = layer.GetGeomType().ToString("G").Substring(3); Console.WriteLine($"Shape Type: {shapeType}"); SpatialReference spatialReference = layer.GetSpatialRef(); string projectionName = spatialReference.GetName(); Console.WriteLine($"Projection: {projectionName}"); using Envelope extent = new Envelope(); layer.GetExtent(extent, 0); var dataSetExtent = new { XMin = extent.MinX, XMax = extent.MaxX, YMin = extent.MinY, YMax = extent.MaxY, }; Console.WriteLine($"Extent: {JsonSerializer.Serialize(dataSetExtent, new JsonSerializerOptions { WriteIndented = true })}"); int featureCount = (int)layer.GetFeatureCount(0); Console.WriteLine($"Feature Count: {featureCount}"); List <dynamic> columns = new List <dynamic>(); FeatureDefn layerDefinition = layer.GetLayerDefn(); for (int j = 0; j < layerDefinition.GetFieldCount(); j++) { FieldDefn field = layerDefinition.GetFieldDefn(j); columns.Add(new { Name = field.GetName(), DataType = field.GetFieldTypeName(field.GetFieldType()), }); } Console.WriteLine($"Columns: {JsonSerializer.Serialize(columns, new JsonSerializerOptions { WriteIndented = true })}"); }
public static void Test2() { try { Ogr.RegisterAll(); string shapefile = @"C:\data\Links\Links.shp"; DataSource ds = Ogr.Open(shapefile, 0); Driver driver = ds.GetDriver(); int nLayerCount = ds.GetLayerCount();//1 for (int iLayer = 0; iLayer < nLayerCount; iLayer++) { Layer layer = ds.GetLayerByIndex(iLayer); string layerName = layer.GetName(); int fc = layer.GetFeatureCount(1); Envelope env = new Envelope(); layer.GetExtent(env, 1); //MessageBox.Show("test sr"); OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef(); string sr_wkt; sr.ExportToPrettyWkt(out sr_wkt, 1); layer.GetName(); FeatureDefn def = layer.GetLayerDefn(); def.GetName(); for (int iField = 0; iField < def.GetFieldCount(); iField++) { FieldDefn fdef = def.GetFieldDefn(iField); string fieldName = fdef.GetName(); //Id Name URL FieldType fieldType = fdef.GetFieldType(); //OFTInteger OFTString OFTString string fieldTypeName = fdef.GetFieldTypeName(fdef.GetFieldType()); //Integer String String int width = fdef.GetWidth(); //6 50 254 int precision = fdef.GetPrecision(); //0 0 0 } for (int fid = 0; fid < layer.GetFeatureCount(1); fid++) { Feature f = layer.GetFeature(fid); int id = f.GetFID(); int nFiledCount = f.GetFieldCount(); Geometry geom = f.GetGeometryRef(); // retrive geometry data //this.Geometrys.Add(geom); string geomName = geom.GetGeometryName(); //POINT string geomType = geom.GetGeometryType().ToString(); //wkbPoint Envelope geom_env = new Envelope(); geom.GetEnvelope(geom_env); // wkt string geom_wkt; geom.ExportToWkt(out geom_wkt);//"POINT (-63.490966216299803 46.66247022944782)" int wkbSize = geom.WkbSize(); if (wkbSize > 0) { // wkb byte[] geom_wkb = new byte[wkbSize]; geom.ExportToWkb(geom_wkb); string str_wkb = BitConverter.ToString(geom_wkb); // wkb--->wkt Geometry geom2 = Geometry.CreateFromWkb(geom_wkb); string geom2_wkt; geom2.ExportToWkt(out geom2_wkt); } f.Dispose(); } } } catch (Exception ex) { MessageBox.Show(ex.ToString()); return; } }
public override void ReinitializeMetaData() { base.ReinitializeMetaData(); //get default output IDTSOutput100 defaultOutput = null; this.GetErrorOutputInfo(ref errorOutputID, ref errorOutputIndex); foreach (IDTSOutput100 output in ComponentMetaData.OutputCollection) { if (output.ID != errorOutputID) { defaultOutput = output; } } if (this.isConnected) { defaultOutput.OutputColumnCollection.RemoveAll(); defaultOutput.ExternalMetadataColumnCollection.RemoveAll(); //get ogrlayer and layer definition Layer OGRLayer; bool isSQLLayer = (!(ComponentMetaData.CustomPropertyCollection["SQL Statement"].Value == null || ComponentMetaData.CustomPropertyCollection["SQL Statement"].Value.ToString() == string.Empty)); if (isSQLLayer) { OGRLayer = getSQLLayer(); } else { OGRLayer = getLayer(); } FeatureDefn OGRFeatureDef = OGRLayer.GetLayerDefn(); //for each field in ogrlayer add output column and external metadata int i = 0; while (i < OGRFeatureDef.GetFieldCount()) { //map OGR field type to SSIS data type FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(i); DataType BufferDataType = this.OGRTypeToBufferType(OGRFieldDef.GetFieldType()); int length = 0; int precision = OGRFieldDef.GetWidth(); int scale = OGRFieldDef.GetPrecision(); int codepage = 1252; switch (BufferDataType) { case DataType.DT_WSTR: length = precision; codepage = 0; precision = 0; scale = 0; //check for length == 0 if (length == 0) { //BufferDataType = DataType.DT_NTEXT; length = 4000; } break; default: length = 0; precision = 0; codepage = 0; scale = 0; break; } //create column metadata IDTSOutputColumn100 col = defaultOutput.OutputColumnCollection.New(); col.Name = OGRFieldDef.GetName(); col.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent; col.TruncationRowDisposition = DTSRowDisposition.RD_FailComponent; col.SetDataTypeProperties(BufferDataType, length, precision, scale, codepage); //create external metadata IDTSExternalMetadataColumn100 ecol = defaultOutput.ExternalMetadataColumnCollection.New(); ecol.Name = col.Name; ecol.DataType = col.DataType; ecol.Precision = col.Precision; ecol.Length = col.Length; ecol.Scale = col.Scale; ecol.CodePage = col.CodePage; col.ExternalMetadataColumnID = ecol.ID; i++; } //get geometry column string geomtryColumn = (OGRLayer.GetGeometryColumn() != "") ? OGRLayer.GetGeometryColumn() : "GEOMETRY"; //add geom output column IDTSOutputColumn100 geomCol = defaultOutput.OutputColumnCollection.New(); geomCol.Name = geomtryColumn; geomCol.ErrorRowDisposition = DTSRowDisposition.RD_FailComponent; geomCol.TruncationRowDisposition = DTSRowDisposition.RD_FailComponent; geomCol.SetDataTypeProperties(DataType.DT_IMAGE, 0, 0, 0, 0); //add geom external metadata IDTSExternalMetadataColumn100 egeomCol = defaultOutput.ExternalMetadataColumnCollection.New(); egeomCol.Name = geomCol.Name; egeomCol.DataType = geomCol.DataType; egeomCol.Precision = geomCol.Precision; egeomCol.Length = geomCol.Length; egeomCol.Scale = geomCol.Scale; egeomCol.CodePage = geomCol.CodePage; //map column metadata to external column metadata geomCol.ExternalMetadataColumnID = egeomCol.ID; //set geometry column custom property ComponentMetaData.CustomPropertyCollection["Geometry Column"].Value = geomtryColumn; if (isSQLLayer) { this.OGRDataSource.ReleaseResultSet(OGRLayer); } } }
/// <summary> /// Outputs the specified DotSpatial IFeatureLayer to an OGR layer /// </summary> /// <param name="pDrvNm">A name like KML, ESRI SHapefile or FileGDB etc.</param> /// <param name="pFLyr">A layer that implements the IFeatureLayer interface</param> /// <param name="pOPFn">The outputShapefileName of the output file</param> /// <param name="pSrcProj">The SRS of the source dataset</param> /// <param name="pTgtProj">The SRS of the output dataset</param> /// <param name="pHasTitle">A boolean flag that determines whether to create fieldAttributes special title field</param> /// <param name="pTitleFieldNames">A comma separated list of field names to be used in the special title field</param> /// <param name="pTitleFormat">The C# String.Format format of the special title field</param> /// <param name="pLCOpts">A string array of layer creation options in the form of OPTION=VALUE entries</param> /// <param name="pDSCOpts">A string of data source creation options in the form of OPTION=VALUE entries</param> /// <param name="pFieldMap">A dictionary of source and target field names to be translated on the source /// the title format field names and the special title field name all observe this field mapping.</param> /// <param name="pOnlyInFieldMap">If true, only writes fields that are included in the field-map</param> /// <returns>True on success, false on error</returns> /// <remarks> /// Presently implements special functions for KML that perhaps should be kept separate. /// </remarks> public static ReturnValue ExportFeatureLayerToOGR( string pDrvNm, IFeatureLayer pFLyr, string pOPFn, ProjectionInfo pSrcProj, ProjectionInfo pTgtProj, bool pHasTitle = false, string pTitleFieldNames = "", string pTitleFormat = "", List <string> pLCOpts = null, List <string> pDSCOpts = null, Dictionary <string, string> pFieldMap = null, bool pOnlyInFieldMap = false, bool pAppend = false) { var mReturnValue = new ReturnValue(true); //Check if data source and layer creation options are null and if so, create an empty list object for them pDSCOpts = (pDSCOpts != null) ? pDSCOpts : new List <string>(); pLCOpts = (pLCOpts != null) ? pLCOpts : new List <string>(); // May or may not be used, declared in any case; Dictionary <string, string> mTitleFieldValues = null; // Determine whether transformation is required bool mTransformRequired = (pSrcProj != pTgtProj) ? true : false; // Read the target SRS SpatialReference mTgtSRS = ExtFunctions.GetSpatialReferenceByEPSG(pTgtProj.AuthorityCode); // If transformation is needed, create fieldAttributes shared transformation object for the export if (mTransformRequired) { pFLyr.Projection = pSrcProj; pFLyr.Reproject(pTgtProj); } // Setup driver OSGeo.OGR.Driver drv = Ogr.GetDriverByName(pDrvNm); if (drv == null) { mReturnValue.AddMessage("Could not load driver", true); return(mReturnValue); } // Special handling of KML mFiles // Add special title name as datasource creation option if (pHasTitle && pDrvNm == "KML") { pDSCOpts.Add("NameField=" + ExtFunctions.TitleFieldName); } // Create fieldAttributes datasource DataSource ds = null; try { if (pAppend && (Directory.Exists(pOPFn) || File.Exists(pOPFn))) { ds = drv.Open(pOPFn, 1); } else { ds = drv.CreateDataSource(pOPFn, pDSCOpts.ToArray()); } if (ds == null) { mReturnValue.AddMessage("Could not create/open datasource"); return(mReturnValue); } } catch (Exception ex) { mReturnValue.AddMessage(ex.Message); return(mReturnValue); } // Find the geometry type of the source layer to determine output type wkbGeometryType mGeomType = DSGeomTypeToOgrGeomType(pFLyr.DataSet.FeatureType); if (mGeomType == wkbGeometryType.wkbNone) { mReturnValue.AddMessage("Could not parse geometry type of input layer"); return(mReturnValue); } // Create the new layer OSGeo.OGR.Layer l; if (pAppend && ds.HasLayer(pFLyr.LegendText.Replace(" ", "_"))) { l = ds.GetLayerByName(pFLyr.LegendText.Replace(" ", "_")); } else { l = ds.CreateLayer(pFLyr.LegendText, mTgtSRS, mGeomType, pLCOpts.ToArray()); } if (l == null) { mReturnValue.AddMessage("Failed to create file: "); return(mReturnValue); } // Create fieldAttributes list to hold the names of fields var mDataSourceFieldNames = new List <string>(); // Loop through all the fields foreach (DataColumn mDataColumn in pFLyr.DataSet.DataTable.Columns) { var mColType = DataTypeToOgrFieldType(mDataColumn.DataType); var mNewField = new FieldDefn(MapFieldName(mDataColumn.ColumnName, pFieldMap), mColType); if (mColType == FieldType.OFTString) { mNewField.SetWidth(mDataColumn.MaxLength); } if (pOnlyInFieldMap == false || (pOnlyInFieldMap && pFieldMap.Keys.Contains(mDataColumn.ColumnName))) { if (!pAppend || !l.HasField(mNewField.GetName())) { if (Ogr.OGRERR_NONE != l.CreateField(mNewField, 1)) { mReturnValue.AddMessage("Failed to add field: " + mDataColumn.ColumnName + " => " + MapFieldName(mDataColumn.ColumnName, pFieldMap)); return(mReturnValue); } } } mDataSourceFieldNames.Add(mNewField.GetName()); } // Add special title field, if the necessary information is present if (pHasTitle == true && !string.IsNullOrEmpty(pTitleFieldNames) && !string.IsNullOrEmpty(pTitleFormat) && !mDataSourceFieldNames.Contains(ExtFunctions.TitleFieldName)) { mTitleFieldValues = new Dictionary <string, string>(); var mTitleField = new FieldDefn(MapFieldName(TitleFieldName, pFieldMap), FieldType.OFTString); mTitleField.SetWidth(254); foreach (var mTitleFieldName in pTitleFieldNames.Split(',')) { mTitleFieldValues.Add(mTitleFieldName, ""); } l.CreateField(mTitleField, 1); } int createdFeatures = 0; // For each row in the source featureset for (int i = 0; i < pFLyr.DataSet.NumRows(); i++) { // Read the source feature IFeature mSrcFeature = pFLyr.DataSet.GetFeature(i); // Read and set the geometry on the new feature byte[] mSrcGeom = mSrcFeature.ToBinary(); var mFeature = new OSGeo.OGR.Feature(l.GetLayerDefn()); var mGeom = OSGeo.OGR.Geometry.CreateFromWkb(mSrcGeom); mFeature.SetGeometry(mGeom); // Set feature id mFeature.SetFID(i); // Handle fieldAttributes for (int j = 0; j < mDataSourceFieldNames.Count(); j++) { var mCurrentValue = mSrcFeature.DataRow[j]; if (pOnlyInFieldMap == false || (pOnlyInFieldMap && pFieldMap.Values.Contains(mDataSourceFieldNames[j]))) { if (mCurrentValue.GetType() == typeof(string)) { mFeature.SetField(mDataSourceFieldNames[j], Utilities.GetANSI((string)mCurrentValue)); } else if (mCurrentValue.GetType() == typeof(int)) { mFeature.SetField(mDataSourceFieldNames[j], (int)mCurrentValue); } else if (mCurrentValue.GetType() == typeof(double)) { mFeature.SetField(mDataSourceFieldNames[j], (double)mCurrentValue); } } if (pHasTitle && mTitleFieldValues.Keys.Contains(mDataSourceFieldNames[j])) { mTitleFieldValues[mDataSourceFieldNames[j]] = mCurrentValue.ToString(); } } // If title field is to be created, use field values collected above to construct fieldAttributes new string format // to go into the title-field if (pHasTitle == true) { var mTitleValue = string.Format(pTitleFormat, mTitleFieldValues.Values.ToArray <string>()); mFeature.SetField(MapFieldName(TitleFieldName, pFieldMap), Utilities.GetANSI(mTitleValue)); } // Create the feature try { l.CreateFeature(mFeature); createdFeatures++; } catch (Exception ex) { mReturnValue.AddMessage(ex.Message); mReturnValue.AddMessage("Tip: A datasource may appear read-only if the file location is inside a dropbox folder and the dropbox application is running"); } } if (mTransformRequired) { pFLyr.Reproject(pSrcProj); } // Dispose and cleanup l.Dispose(); ds.Dispose(); drv.Dispose(); mReturnValue.AddMessage(String.Format("Added {0} features to layer {1}", createdFeatures, pFLyr.LegendText)); return(mReturnValue); }
public override void ReinitializeMetaData() { base.ReinitializeMetaData(); IDTSInput100 input = ComponentMetaData.InputCollection[0]; if (!this.validExternalMetadata && this.isConnected) { input.ExternalMetadataColumnCollection.RemoveAll(); input.InputColumnCollection.RemoveAll(); this.validExternalMetadata = true; Layer OGRLayer = this.getLayer(); FeatureDefn OGRFeatureDef = OGRLayer.GetLayerDefn(); int i = 0; while (i < OGRFeatureDef.GetFieldCount()) { //map OGR field type to SSIS data type FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(i); DataType BufferDataType = this.OGRTypeToBufferType(OGRFieldDef.GetFieldType()); int length = 0; int precision = OGRFieldDef.GetWidth(); int scale = OGRFieldDef.GetPrecision(); int codepage = 1252; switch (BufferDataType) { case DataType.DT_WSTR: length = precision; codepage = 0; precision = 0; scale = 0; //check for length == 0 if (length == 0) { BufferDataType = DataType.DT_NTEXT; } break; default: length = 0; precision = 0; codepage = 0; scale = 0; break; } IDTSExternalMetadataColumn100 ecol = input.ExternalMetadataColumnCollection.New(); ecol.Name = OGRFieldDef.GetName(); ecol.DataType = BufferDataType; ecol.Length = length; ecol.Precision = precision; ecol.Scale = scale; ecol.CodePage = codepage; i++; } //get geometry column string geomtryColumn = (OGRLayer.GetGeometryColumn() != "") ? OGRLayer.GetGeometryColumn() : "GEOMETRY"; //Set OGRGeometry external metadata column IDTSExternalMetadataColumn100 egeomCol = input.ExternalMetadataColumnCollection.New(); egeomCol.Name = geomtryColumn; egeomCol.DataType = DataType.DT_IMAGE; egeomCol.Precision = 0; egeomCol.Length = 0; egeomCol.Scale = 0; egeomCol.CodePage = 0; //set geometry column custom property ComponentMetaData.CustomPropertyCollection["Geometry Column"].Value = geomtryColumn; } if (!ComponentMetaData.AreInputColumnsValid) { ComponentMetaData.RemoveInvalidInputColumns(); } }
/// <summary> /// Gerar um nome válido para o campo /// Os nomes dos campos em arquivos shapefile têm limite de 10 caracteres /// </summary> private string getValidFieldName(FieldDefn fieldDefn) { string fieldName = fieldDefn.GetName(); return(fieldName.Length > 10 ? fieldName.Substring(0, 10) : fieldName); }
static DataSet CreateTables(DataSource OGRDataSource, string MSSQLConnectionString) { // Create OSM ADO.NET DataSet DataSet OSMDataSet = new DataSet(); // Create SQL Tables for (int iLayer = 0; iLayer < OGRDataSource.GetLayerCount(); iLayer++) { Layer OGRLayer = OGRDataSource.GetLayerByIndex(iLayer); string layerName = OGRLayer.GetName(); // Construct CREATE TABLE statement StringBuilder SQLCreateCmd = new StringBuilder(); SQLCreateCmd.Append(string.Format("CREATE TABLE [{0}] (", layerName)); SQLCreateCmd.Append("[id] [INT] IDENTITY(1,1), "); FeatureDefn OGRLayerDef = OGRLayer.GetLayerDefn(); for (int iField = 0; iField < OGRLayerDef.GetFieldCount(); iField++) { FieldDefn OGRFieldDef = OGRLayerDef.GetFieldDefn(iField); SQLCreateCmd.Append(string.Format("[{0}] " + "[VARCHAR](MAX), ", OGRFieldDef.GetName())); } SQLCreateCmd.Append("[ogr_geometry] [GEOMETRY],"); SQLCreateCmd.Append("[ogr_geometry_area] [FLOAT]);"); //geometry_columns metadata string SQLGeometryColumnsCmd = string.Format(@"IF OBJECT_ID('dbo.geometry_columns') IS NOT NULL INSERT INTO [dbo].[geometry_columns] ([f_table_catalog],[f_table_schema],[f_table_name],[f_geometry_column],[coord_dimension],[srid],[geometry_type]) VALUES (DB_NAME(),SCHEMA_NAME(),'{0}','ogr_geometry',2,900913,'{1}')", layerName, OGRLayer.GetGeomType().ToString().Replace("wkb", "") ); // Construct SQL statement used to get table schema // We use this to set a DataTable object schema after we create the SQL table string SQLSchemaCmd = string.Format("SET FMTONLY ON; SELECT * FROM [{0}]; SET FMTONLY OFF;", layerName); // Execute SQL DataTable table = new DataTable(); using (SqlConnection con = new SqlConnection(MSSQLConnectionString)) { con.Open(); try { // Create SQL table using (SqlCommand cmd = new SqlCommand(SQLCreateCmd.ToString(), con)) { log(TraceLevel.Info, string.Format("Creating table {0}...", layerName)); cmd.ExecuteNonQuery(); } // Set DataTable object schema using (SqlDataAdapter da = new SqlDataAdapter(SQLSchemaCmd, con)) { da.FillSchema(table, SchemaType.Source); // Hack to set ogr_geometry datatable column to correct SQLGeometry type // http://msdn.microsoft.com/en-us/library/ms143179(v=sql.110).aspx#Y2686 // http://connect.microsoft.com/SQLServer/feedback/details/685654/invalidcastexception-retrieving-sqlgeography-column-in-ado-net-data-reader table.Columns["ogr_geometry"].DataType = typeof(SqlGeometry); // Add DataTable to OSM DataSet OSMDataSet.Tables.Add(table); } } catch (Exception e) { log(TraceLevel.Error, e.Message); Environment.Exit(1); } //insert geoemtry_columns record try { using (SqlCommand cmd = new SqlCommand(SQLGeometryColumnsCmd, con)) { log(TraceLevel.Info, string.Format("Update geometry_columns metadata for {0}...", layerName)); cmd.ExecuteNonQuery(); } } catch (Exception e) { log(TraceLevel.Warning, e.Message); } } } return(OSMDataSet); }
private void _load(bool leaveopen = false) { Open(); // Populate some important metadata Layer mLayer = _ds.GetLayerByIndex(0); FIDColumn = mLayer.GetFIDColumn(); LayerName = mLayer.GetName(); _geometryType = new GDalGeometryType(mLayer.GetGeomType()); // Get our FEATURE definitions Feature mFeat = mLayer.GetNextFeature(); while (mFeat != null) { Geometry geo = mFeat.GetGeometryRef(); if (geo == null) { Debug.WriteLine(String.Format("Warning: Null Geometry Detected: FID:{0}", mFeat.GetFID())); } else { int count = geo.GetGeometryCount(); if (count > 1) { if (_geometryType.SimpleType == SimpleTypes.Point || _geometryType.SimpleType == SimpleTypes.LineString) { Exception ex = new Exception("Multi-part geometries are detected in this file. This is not allowed."); ex.Data["File Path"] = GISFileInfo.FullName; ex.Data["Solution"] = "Remove all multipart features from this ShapeFile."; throw ex; } else { Debug.WriteLine(String.Format("Warning: Multipart feature detected: FID:{0}", mFeat.GetFID())); } } } Features.Add(mFeat.GetFID(), new VectorFeature(mFeat)); mFeat = mLayer.GetNextFeature(); } // Now get our FIELD definitions FeatureDefn mFeatDfn = mLayer.GetLayerDefn(); int iFldCnt = mFeatDfn.GetFieldCount(); for (int fldId = 0; fldId < iFldCnt; fldId++) { FieldDefn mFldDef = mFeatDfn.GetFieldDefn(fldId); Fields.Add(mFldDef.GetName(), new VectorField(mFldDef, fldId)); } // Spatial is way harder than it needs to be: OSGeo.OSR.SpatialReference sRef = mLayer.GetSpatialRef(); if (sRef == null) { Exception ex = new Exception("Feature class is missing spatial reference"); ex.Data["Path"] = GISFileInfo.FullName; throw ex; } string sRefstring = ""; sRef.ExportToWkt(out sRefstring); _Init(sRefstring); if (!leaveopen) { UnloadDS(); } }
public static List <string> OGRInfo(string datasourceFileLocation) { List <string> info = new List <string>(); Ogr.RegisterAll(); DataSource ds = Ogr.Open(datasourceFileLocation, 0); if (ds == null) { info.Add("Couldn not open vector data source."); return(info); } OSGeo.OGR.Driver drv = ds.GetDriver(); if (drv == null) { info.Add("Could not find driver to open vector data source."); return(info); } info.Add("Using driver: " + drv.GetName()); ///Iterating through layers for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++) { Layer layer = ds.GetLayerByIndex(iLayer); if (layer == null) { info.Add("Could not find layers in the vector data source."); return(info); } FeatureDefn def = layer.GetLayerDefn(); info.Add("Layer name: " + def.GetName()); info.Add("Feature count: " + layer.GetFeatureCount(1)); Envelope ext = new Envelope(); layer.GetExtent(ext, 1); info.Add("Extent: " + ext.MinX + ", " + ext.MinY + ", " + ext.MaxX + ", " + ext.MaxY); ///Reading the spatial reference OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef(); string srs_wkt = string.Empty; if (sr != null) { sr.ExportToPrettyWkt(out srs_wkt, 1); } else { srs_wkt = "(unknow)"; } info.Add("Layer SRS WKT: " + srs_wkt); ///Reading the fields info.Add("Field Names (type): "); for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++) { FieldDefn fdef = def.GetFieldDefn(iAttr); info.Add(fdef.GetName() + " (" + fdef.GetFieldTypeName(fdef.GetFieldType()) + ")"); } } ds.Dispose(); return(info); }
//----------------------------------------------------------------------------------- public void readPoint(ref Layer oLayer) { // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); Driver oDriver = null; DataSource oDS = null; Layer newLayer = null; initShp(ref oLayer, ref oDriver, ref oDS, ref newLayer, LAYER_TYPE.POINT); // 获取图层中的属性表表头并输出 string strInfo = "属性表结构信息:\n"; FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); FieldType type = oField.GetFieldType(); string fieldName = oField.GetName(); //为新图层创建属性 if (!fieldName.Equals("X坐标") && !fieldName.Equals("Y坐标")) { FieldDefn newField = new FieldDefn(fieldName, type); if (type == FieldType.OFTString) { newField.SetWidth(oField.GetWidth()); } newLayer.CreateField(newField, 1); } //获取图层属性信息 strInfo += string.Format("{0}:{1} ({2}.{3})\n", oField.GetNameRef(), oField.GetFieldTypeName(oField.GetFieldType()), oField.GetWidth(), oField.GetPrecision()); } FeatureDefn newDefn = newLayer.GetLayerDefn(); // 输出图层中的要素个数 strInfo += string.Format("要素个数 = {0}\n", oLayer.GetFeatureCount(0)); Feature oFeature = null; // 下面开始遍历图层中的要素 while ((oFeature = oLayer.GetNextFeature()) != null) { strInfo += string.Format("\n当前处理第{0}个: \n属性值:", oFeature.GetFID()); //为新图层创建要素 Feature oFeaturePoint = new Feature(newDefn); double pointX = 0.0; double pointY = 0.0; // 获取要素中的属性表内容 for (int iField = 0; iField < iFieldCount; iField++) { FieldDefn oFieldDefn = oDefn.GetFieldDefn(iField); FieldType type = oFieldDefn.GetFieldType(); string name = oFieldDefn.GetNameRef(); switch (type) { case FieldType.OFTString: IntPtr pchar = OGR_F_GetFieldAsString(Feature.getCPtr(oFeature), iField); string val = Marshal.PtrToStringAnsi(pchar); oFeaturePoint.SetField(name, val); break; case FieldType.OFTReal: if (!name.Equals("X坐标") && !name.Equals("Y坐标")) { oFeaturePoint.SetField(name, oFeature.GetFieldAsDouble(iField)); } switch (name) { case "X": pointX = oFeature.GetFieldAsDouble(iField); break; case "Y": pointY = oFeature.GetFieldAsDouble(iField); break; default: break; } break; case FieldType.OFTInteger: oFeaturePoint.SetField(iField, oFeature.GetFieldAsInteger(iField)); break; default: oFeaturePoint.SetField(iField, oFeature.GetFieldAsString(iField)); break; } } //填充要素几何信息 Geometry oGeometry = Geometry.CreateFromWkt(string.Format("POINT({0} {1})", pointX, pointY)); oFeaturePoint.SetGeometry(oGeometry); newLayer.CreateFeature(oFeaturePoint); } strInfo += "\n数据集关闭!"; oDS.Dispose(); }
private static void ReportFeature(Feature f, FeatureDefn def) { //string layerName = def.GetName();//Links int fid = f.GetFID(); //0 1 2 3...15 int nFieldCount = f.GetFieldCount(); //3 for (int iField = 0; iField < nFieldCount; iField++) { FieldDefn fdef = def.GetFieldDefn(iField); string fieldName = fdef.GetName(); //Id Name URL string fieldNameRef = fdef.GetNameRef(); //Id Name URL string fieldTypeName = fdef.GetFieldTypeName(fdef.GetFieldType()); //Integer String String if (f.IsFieldSet(iField)) { if (fdef.GetFieldType() == FieldType.OFTStringList) { string[] sList = f.GetFieldAsStringList(iField); foreach (string s in sList) { } } else if (fdef.GetFieldType() == FieldType.OFTIntegerList) { int count; int[] iList = f.GetFieldAsIntegerList(iField, out count); for (int i = 0; i < count; i++) { } } else if (fdef.GetFieldType() == FieldType.OFTRealList) { int count; double[] iList = f.GetFieldAsDoubleList(iField, out count); for (int i = 0; i < count; i++) { } } else if (fdef.GetFieldType() == FieldType.OFTString) { string strField = f.GetFieldAsString(iField); } else if (fdef.GetFieldType() == FieldType.OFTInteger) { int nField = f.GetFieldAsInteger(iField); } else if (fdef.GetFieldType() == FieldType.OFTReal) { double fField = f.GetFieldAsDouble(iField); } else { // other types } } } if (f.GetStyleString() != null) { string style = f.GetStyleString(); } // feature's geometry info Geometry geom = f.GetGeometryRef(); if (geom != null) { string geomName = geom.GetGeometryName(); //POINT string geomType = geom.GetGeometryType().ToString(); //wkbPoint int geometryCount = geom.GetGeometryCount(); //0 for (int i = 0; i < geometryCount; i++) { Geometry sub_geom = geom.GetGeometryRef(i); if (sub_geom != null) { string sub_geomName = sub_geom.GetGeometryName(); string sub_geomType = sub_geom.GetGeometryType().ToString(); } } Envelope env = new Envelope(); geom.GetEnvelope(env); string geom_wkt; geom.ExportToWkt(out geom_wkt);//POINT(-63.4,46.6) } }
private static void ReportLayer(Layer layer) { //layer info string layerName = layer.GetName(); //Links string layerName2 = layer.GetLayerDefn().GetName(); //Links int fc = layer.GetFeatureCount(1); //16 Envelope ext = new Envelope(); layer.GetExtent(ext, 1); /* -------------------------------------------------------------------- */ /* Reading the spatial reference */ /* -------------------------------------------------------------------- */ OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef(); string srs_wkt; if (sr != null) { sr.ExportToPrettyWkt(out srs_wkt, 1); } else { srs_wkt = "(unknown)"; } // feature definition FeatureDefn def = layer.GetLayerDefn(); //string layerName2 = def.GetName();//Links /* -------------------------------------------------------------------- */ /* Reading the fields */ /* -------------------------------------------------------------------- */ int nFieldCount = def.GetFieldCount();//3 for (int iField = 0; iField < nFieldCount; iField++) { // field definition FieldDefn fdef = def.GetFieldDefn(iField); // field info string fieldName = fdef.GetName(); //Id Name URL string fieldNameRef = fdef.GetNameRef(); // Id Name URL FieldType fieldType = fdef.GetFieldType(); //OFTInteger OFTString OFTString string fieldTypeName = fdef.GetFieldTypeName(fdef.GetFieldType()); //Integer String String int width = fdef.GetWidth(); //6 50 254 int precision = fdef.GetPrecision(); //0 0 0 } /* -------------------------------------------------------------------- */ /* Reading the shapes */ /* -------------------------------------------------------------------- */ for (int fid = 0; fid < layer.GetFeatureCount(1); fid++) { Feature f = layer.GetFeature(fid); ReportFeature(f, def); f.Dispose(); } //Feature f; //while ((f = layer.GetNextFeature()) != null) //{ // ReportFeature(f, def); // f.Dispose(); //} }
public void AppendField(FieldDefn field) //增加一个字段 { fields.Add(field.GetName(), field); }