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 void test(ref Layer oLayer) { // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); // 获取图层中的属性表表头并输出 string strInfo = "属性表结构信息:\n"; FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); strInfo += string.Format("{0}:{1} ({2}.{3})\n", oField.GetNameRef(), oField.GetFieldTypeName(oField.GetFieldType()), oField.GetWidth(), oField.GetPrecision()); } // 输出图层中的要素个数 strInfo += string.Format("要素个数 = {0}\n", oLayer.GetFeatureCount(0)); Feature oFeature = null; // 下面开始遍历图层中的要素 while ((oFeature = oLayer.GetNextFeature()) != null) { strInfo += string.Format("\n当前处理第{0}个: \n属性值:", oFeature.GetFID()); // 获取要素中的属性表内容 for (int iField = 0; iField < iFieldCount; iField++) { FieldDefn oFieldDefn = oDefn.GetFieldDefn(iField); FieldType type = oFieldDefn.GetFieldType(); switch (type) { case FieldType.OFTString: IntPtr pchar = OGR_F_GetFieldAsString(Feature.getCPtr(oFeature), iField); string val = Marshal.PtrToStringAnsi(pchar); strInfo += string.Format("{0}\t", val); break; case FieldType.OFTReal: strInfo += string.Format("{0}\t", oFeature.GetFieldAsDouble(iField)); break; case FieldType.OFTInteger: strInfo += string.Format("{0}\t", oFeature.GetFieldAsInteger(iField)); break; default: strInfo += string.Format("{0}\t", oFeature.GetFieldAsString(iField)); break; } } // 获取要素中的几何体 Geometry oGeometry = oFeature.GetGeometryRef(); // 为了演示,只输出一个要素信息 break; } strInfo += "\n数据集关闭!"; }
/// <summary> /// Gets the data type of the field. /// </summary> /// <param name="i">Index of the field.</param> /// <returns>The data type.</returns> public string GetDataTypeName(int i) { if (i == 1) { return(typeof(int).ToString()); } if (i == 0) { return(typeof(byte[]).ToString()); } return(_ogrFeatureDefinition.GetFieldDefn(i - 2).GetFieldType().ToString()); }
private Dictionary <string, Type> getShapeFields(out string errorMessage) { errorMessage = ""; Dictionary <string, Type> fields = new Dictionary <string, Type>(); try { DataSource ds = Ogr.Open(inputFile.FullName, 0); if (ds == null) { throw new Exception("Невозможно открыть файл"); } var layerCount = ds.GetLayerCount(); if (layerCount != 1) { throw new Exception("В файле должен быть ровно один слой"); } var layer = ds.GetLayerByIndex(0); FeatureDefn featDef = layer.GetLayerDefn(); var fc = featDef.GetFieldCount(); for (int i = 0; i < fc; i++) { var field = featDef.GetFieldDefn(i); fields.Add(field.GetNameRef(), convertType(field.GetFieldType())); } featDef.Dispose(); layer.Dispose(); ds.Dispose(); } catch (Exception ex) { errorMessage = ex.Message; } return(fields); }
private void cmbLayers_SelectedIndexChanged(object sender, EventArgs e) { cmbIdField.Items.Clear(); cmbNameField.Items.Clear(); if (cmbLayers.SelectedIndex > -1) { try { cmbNameField.Items.Add("<无>"); var layer = dataSourceSelector1.GetLayerByName(cmbLayers.SelectedItem.ToString()); FeatureDefn featureDefn = layer.GetLayerDefn(); for (int i = 0; i < featureDefn.GetFieldCount(); i++) { var fieldName = featureDefn.GetFieldDefn(i).GetName(); cmbNameField.Items.Add(fieldName); cmbIdField.Items.Add(fieldName); } if (cmbIdField.Items.Contains("XMID")) { cmbIdField.SelectedItem = "XMID"; if (cmbNameField.Items.Contains("XMMC")) { cmbNameField.SelectedItem = "XMMC"; } } } catch (Exception ex) { MessageBox.Show(ex.Message, Text, MessageBoxButtons.OK, MessageBoxIcon.Error); } } }
public bool getFields() { if (oLayer == null) { return(false); } mFiledList.Clear(); //获取图层的属性表结构 FeatureDefn oDefn = oLayer.GetLayerDefn(); int filedCount = oDefn.GetFieldCount(); for (int i = 0; i < filedCount; i++) { //获取指定序号的属性列 FieldDefn oField = oDefn.GetFieldDefn(i); if (oField != null) { //获取属性列名字 mFiledList.Add(oField.GetNameRef()); } } return(true); }
public void opiszWarstwe() { FeatureDefn def = this.layer.GetLayerDefn(); Console.WriteLine("Nazwa warstwy: " + def.GetName()); Console.WriteLine("Liczba obiektów: " + this.layer.GetFeatureCount(1)); Envelope ext = new Envelope(); layer.GetExtent(ext, 1); Console.WriteLine("Zasiêg: " + ext.MinX + "," + ext.MaxX + "," + ext.MinY + "," + ext.MaxY); SpatialReference sr = this.layer.GetSpatialRef(); string srs_wkt = "(unknown)"; if (sr != null) { sr.ExportToPrettyWkt(out srs_wkt, 1); } Console.WriteLine("Uk³ad przestrzenny warstwy: " + srs_wkt); Console.WriteLine("Definicje atrybutów:"); for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++) { FieldDefn fdef = def.GetFieldDefn(iAttr); Console.WriteLine(fdef.GetNameRef() + ": " + fdef.GetFieldTypeName(fdef.GetFieldType()) + " (" + fdef.GetWidth() + "." + fdef.GetPrecision() + ")"); } }
public static string ReportLayer(Layer layer) { string strInfomation = ""; FeatureDefn def = layer.GetLayerDefn(); strInfomation += ("Layer name: " + def.GetName()); strInfomation += ("Feature Count: " + layer.GetFeatureCount(1).ToString()); Envelope ext = new Envelope(); layer.GetExtent(ext, 1); strInfomation += ("Extent: " + ext.MinX.ToString() + "," + ext.MaxX.ToString() + "," + ext.MinY.ToString() + "," + ext.MaxY.ToString()); /* -------------------------------------------------------------------- */ /* 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)"; } strInfomation += ("Layer SRS WKT: " + srs_wkt); /* -------------------------------------------------------------------- */ /* Reading the fields */ /* -------------------------------------------------------------------- */ strInfomation += ("Field definition:"); for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++) { FieldDefn fdef = def.GetFieldDefn(iAttr); strInfomation += (fdef.GetNameRef() + ": " + fdef.GetFieldTypeName(fdef.GetFieldType()) + " (" + fdef.GetWidth().ToString() + "." + fdef.GetPrecision().ToString() + ")"); } /* -------------------------------------------------------------------- */ /* Reading the shapes */ /* -------------------------------------------------------------------- */ strInfomation += (""); Feature feat; while ((feat = layer.GetNextFeature()) != null) { strInfomation += ReportFeature(feat, def); feat.Dispose(); } return(strInfomation); }
public static IEnumerable <FieldDefn> FieldDefns(this FeatureDefn featureDefn) { var count = featureDefn.GetFieldCount(); for (int i = 0; i < count; i++) { yield return(featureDefn.GetFieldDefn(i)); } }
public override bool isExternalMetadataValid() { IDTSExternalMetadataColumnCollection100 exColumns = ComponentMetaData.InputCollection[0].ExternalMetadataColumnCollection; Layer OGRLayer = this.getLayer(); FeatureDefn OGRFeatureDef = OGRLayer.GetLayerDefn(); // Get Geometry column name string geomtryColumn = (OGRLayer.GetGeometryColumn() != "") ? OGRLayer.GetGeometryColumn() : "GEOMETRY"; //check for correct number of external metadata columns if (OGRFeatureDef.GetFieldCount() + 1 != exColumns.Count) { return(false); } //validate each external metadata column for (int i = 0; i < exColumns.Count; i++) { IDTSExternalMetadataColumn100 col = exColumns[i]; if (col.Name == geomtryColumn) { if (col.DataType != DataType.DT_IMAGE) { return(false); } // Check geometry column custom property against source if ((string)ComponentMetaData.CustomPropertyCollection["Geometry Column"].Value != geomtryColumn) { return(false); } } else { //check if ogr field exists by name int OGRFieldIndex = OGRFeatureDef.GetFieldIndex(col.Name); if (OGRFieldIndex == -1) { return(false); } //check if ogr column matches output column type FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(OGRFieldIndex); FieldType OGRFieldType = OGRFieldDef.GetFieldType(); if (this.OGRTypeToBufferType(OGRFieldType) != col.DataType) { //check for case where OFTString -> DT_NTEXT if (!(OGRFieldType == FieldType.OFTString && col.DataType == DataType.DT_NTEXT)) { return(false); } } } } return(true); }
public static MG_Feature AsFeature(Feature f) { FeatureDefn def = f.GetDefnRef(); MG_FieldSet fieldSet = AsFieldSet(def); MG_Feature mgFeature = new MG_Feature(fieldSet);//collect data // geometry Geometry g = f.GetGeometryRef(); MG_Geometry geometry = AsGeometry(g); string wkt = geometry.AsWKT(); // Test mgFeature.SetGeometry(geometry); //collect data // symbol string styleString = f.GetStyleString(); //f.SetStyleString(styleString); // attribute value MG_ValueSet valueSet = new MG_ValueSet(); int fid = f.GetFID(); int nFieldCount = f.GetFieldCount(); for (int iField = 0; iField < nFieldCount; iField++) { FieldDefn fdef = def.GetFieldDefn(iField); FieldType fieldType = fdef.GetFieldType();//OFTInteger OFTString OFTString MG_Value mgValue = new MG_Value(); mgValue.Index = iField;// collect data //collect data if (fieldType == FieldType.OFTString) { mgValue.Value = f.GetFieldAsString(iField); } else if (fieldType == FieldType.OFTInteger) { mgValue.Value = f.GetFieldAsInteger(iField); } else if (fieldType == FieldType.OFTReal) { mgValue.Value = f.GetFieldAsDouble(iField); } else if (fieldType == FieldType.OFTDateTime) { int year, month, day, hour, minute, second, flag; f.GetFieldAsDateTime(iField, out year, out month, out day, out hour, out minute, out second, out flag); mgValue.Value = new DateTime(year, month, day, hour, minute, second, flag); } valueSet.Add(mgValue); } mgFeature.ValueSet = valueSet;//collect data return(mgFeature); }
/// <summary> /// 获取图层中的全部字段 /// </summary> /// <param name="layer"></param> /// <returns></returns> public static List <FieldDefn> GetFields(this Layer layer) { var fields = new List <FieldDefn>(); FeatureDefn featureDefn = layer.GetLayerDefn(); for (int i = 0; i < featureDefn.GetFieldCount(); i++) { fields.Add(featureDefn.GetFieldDefn(i)); } return(fields); }
public static MG_FieldSet AsFieldSet(FeatureDefn f) { MG_FieldSet fieldSet = new MG_FieldSet(f.GetName());// name int count = f.GetFieldCount(); for (int i = 0; i < count; i++) { MG_Field field = AsField(f.GetFieldDefn(i)); fieldSet.Add(field); } return(fieldSet); }
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> /// 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); }
/// <summary> /// 获取所有列名 /// </summary> /// <param name="strVectorFile"></param> /// <returns></returns> public static List <string> getShapeFieldList(string strVectorFile) { List <string> list = new List <string>(); #region ReadShape { Gdal.AllRegister(); // 为了支持中文路径,请添加下面这句代码 OSGeo.GDAL.Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "NO"); // 为了使属性表字段支持中文,请添加下面这句 OSGeo.GDAL.Gdal.SetConfigOption("SHAPE_ENCODING", ""); // 注册所有的驱动 Ogr.RegisterAll(); //打开数据 DataSource ds = Ogr.Open(strVectorFile, 0); if (ds == null) { MessageBox.Show("打开文件【{0}】失败!,文件名中不能包含中文!", strVectorFile); return(list); } //MessageBox.Show("打开文件【{0}】成功!", strVectorFile); // 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个 int iLayerCount = ds.GetLayerCount(); // 获取第一个图层 Layer oLayer = ds.GetLayerByIndex(0); if (oLayer == null) { MessageBox.Show("获取第{0}个图层失败!\n", "0"); return(list); } // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空 oLayer.ResetReading(); FeatureDefn oDefn = oLayer.GetLayerDefn(); // 输出图层中的要素个数 int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); list.Add(oField.GetNameRef()); } } #endregion list.Sort(); return(list); }
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); }
/// <summary> /// 获取某条数据的字段内容 /// </summary> /// <param name="iIndex"></param> /// <param name="FeildStringList"></param> /// <returns></returns> public bool GetFeildContent(int iIndex, out List <string> FeildStringList) { FeildStringList = new List <string>(); Feature oFeature = null; if ((oFeature = oLayer.GetFeature(iIndex)) != null) { FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); // 查找字段属性 for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); string sFeildName = oField.GetNameRef(); #region 获取属性字段 FieldType Ftype = oFeature.GetFieldType(sFeildName); switch (Ftype) { case FieldType.OFTString: string sFValue = oFeature.GetFieldAsString(sFeildName); string sTempType = "string"; FeildStringList.Add(sFValue); break; case FieldType.OFTReal: double dFValue = oFeature.GetFieldAsDouble(sFeildName); sTempType = "float"; FeildStringList.Add(dFValue.ToString()); break; case FieldType.OFTInteger: int iFValue = oFeature.GetFieldAsInteger(sFeildName); sTempType = "int"; FeildStringList.Add(iFValue.ToString()); break; default: //sFValue = oFeature.GetFieldAsString(ChosenFeildIndex[iFeildIndex]); sTempType = "string"; break; } #endregion } } return(true); }
public static void ReportFeature(Feature feat, FeatureDefn def) { Console.WriteLine("Feature(" + def.GetName() + "): " + feat.GetFID()); for (int iField = 0; iField < feat.GetFieldCount(); iField++) { FieldDefn fdef = def.GetFieldDefn(iField); Console.Write(fdef.GetNameRef() + " (" + fdef.GetFieldTypeName(fdef.GetFieldType()) + ") = "); if (feat.IsFieldSet(iField)) { Console.WriteLine(feat.GetFieldAsString(iField)); } else { Console.WriteLine("(null)"); } } if (feat.GetStyleString() != null) { Console.WriteLine(" Style = " + feat.GetStyleString()); } Geometry geom = feat.GetGeometryRef(); if (geom != null) { Console.WriteLine(" " + geom.GetGeometryName() + "(" + geom.GetGeometryType() + ")"); } Envelope env = new Envelope(); geom.GetEnvelope(env); Console.WriteLine(" ENVELOPE: " + env.MinX + "," + env.MaxX + "," + env.MinY + "," + env.MaxY); string geom_wkt; geom.ExportToWkt(out geom_wkt); Console.WriteLine(" " + geom_wkt); Console.WriteLine(""); }
/// <summary>获取某条数据的字段内容 /// </summary> /// <param name="nIndex"></param> /// <param name="lstFeildString"></param> /// <param name="fileAttrEncoding">文件属性字段编码类型</param> /// <returns></returns> public virtual bool GetFeildContent(int nIndex, out Dictionary <string, string> dictFieldInfo, Encoding fileAttrEncoding) { _FileAttrEncoding = fileAttrEncoding; dictFieldInfo = new Dictionary <string, string>(); Feature oFeature = null; if ((oFeature = _Layer.GetFeature(nIndex)) != null) { FeatureDefn oDefn = _Layer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); // 查找字段属性 for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); string strFeildName = oField.GetNameRef(); string strValue = ""; #region 获取属性字段 FieldType Ftype = oFeature.GetFieldType(strFeildName); switch (Ftype) { case FieldType.OFTString: strValue = GetFieldAsStringNu(oFeature, strFeildName, _FileAttrEncoding); break; case FieldType.OFTReal: double dFValue = oFeature.GetFieldAsDouble(strFeildName); strValue = dFValue.ToString(); break; case FieldType.OFTInteger: int iFValue = oFeature.GetFieldAsInteger(strFeildName); strValue = iFValue.ToString(); break; default: break; } dictFieldInfo.Add(strFeildName, strValue); #endregion } } return(true); }
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 })}"); }
/// <summary> /// 获取某条数据的字段内容 /// </summary> /// <param name="iIndex"></param> /// <param name="FeildStringList"></param> /// <returns></returns> public string GetFeildContent(int iAttr, Feature oFeature) { //string tempType; string attribute = ""; if (oFeature != null) { FeatureDefn oDefn = oLayer.GetLayerDefn(); FieldDefn oField = oDefn.GetFieldDefn(iAttr); string sFeildName = oField.GetNameRef(); FieldType Ftype = oFeature.GetFieldType(sFeildName); switch (Ftype) { case FieldType.OFTString: string sFValue = oFeature.GetFieldAsString(sFeildName); //tempType = "string"; attribute = sFValue.ToString(); break; case FieldType.OFTReal: double dFValue = oFeature.GetFieldAsDouble(sFeildName); //tempType = "float"; attribute = dFValue.ToString(); break; case FieldType.OFTInteger: int iFValue = oFeature.GetFieldAsInteger(sFeildName); //tempType = "int"; attribute = iFValue.ToString(); break; default: //sFValue = oFeature.GetFieldAsString(ChosenFeildIndex[iFeildIndex]); //tempType = "string"; break; } } return(attribute); }
/// <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; } } } } } }
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); }
/// <summary>获取所有的属性字段 /// </summary> /// <returns></returns> public virtual bool GetFeilds() { if (null == _Layer) { return(false); } _Feilds.Clear(); wkbGeometryType oTempGeometryType = _Layer.GetGeomType(); FeatureDefn oDefn = _Layer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); if (null != oField) { _Feilds.Add(oField.GetNameRef(), oField.GetFieldType()); } } return(true); }
/// <summary> /// 获取所有的属性字段 /// </summary> /// <returns></returns> public void GetFeilds() { if (null == oLayer) { } m_FeildList.Clear(); wkbGeometryType oTempGeometryType = oLayer.GetGeomType(); List <string> TempstringList = new List <string>(); // FeatureDefn oDefn = oLayer.GetLayerDefn(); int iFieldCount = oDefn.GetFieldCount(); for (int iAttr = 0; iAttr < iFieldCount; iAttr++) { FieldDefn oField = oDefn.GetFieldDefn(iAttr); if (null != oField) { m_FeildList.Add(oField.GetNameRef()); } } string[] a = m_FeildList.ToArray(); }
//Checks if output metadata columns match ogrlayer source columns public override bool isMetadataValid() { //get default output IDTSOutput100 output = null; for (int i = 0; i < ComponentMetaData.OutputCollection.Count; i++) { if (!ComponentMetaData.OutputCollection[i].IsErrorOut) { output = ComponentMetaData.OutputCollection[i]; } } //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(); // Get Geometry column name string geomtryColumn = (OGRLayer.GetGeometryColumn() != "") ? OGRLayer.GetGeometryColumn() : "GEOMETRY"; // Begin checks bool isValid = true; if (OGRFeatureDef.GetFieldCount() + 1 == output.OutputColumnCollection.Count) { int i = 0; do { //check if ogr field exists by name IDTSOutputColumn100 col = output.OutputColumnCollection[i]; int OGRFieldIndex = OGRFeatureDef.GetFieldIndex(col.Name); if (OGRFieldIndex == -1) { //set isValid false if not geom column if ((col.Name != geomtryColumn) || (col.DataType != DataType.DT_IMAGE) || ((string)ComponentMetaData.CustomPropertyCollection["Geometry Column"].Value != geomtryColumn)) { isValid = false; } } else { //is isVaild to false if field types don't match FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(OGRFieldIndex); FieldType OGRFieldType = OGRFieldDef.GetFieldType(); if ((col.DataType != this.OGRTypeToBufferType(OGRFieldType)) && (!(OGRFieldType == FieldType.OFTString && col.DataType == DataType.DT_NTEXT))) // special case where lenth not provided by OFTString { isValid = false; } } i++; } while (isValid && i < output.OutputColumnCollection.Count); } else { isValid = false; } //Manualy call release on OGR layer sql result set if needed if (isSQLLayer) { this.OGRDataSource.ReleaseResultSet(OGRLayer); } return(isValid); }
public override void PrimeOutput(int outputs, int[] outputIDs, PipelineBuffer[] buffers) { //identify buffers PipelineBuffer errorBuffer = null; PipelineBuffer defaultBuffer = null; for (int x = 0; x < outputs; x++) { if (outputIDs[x] == errorOutputID) { errorBuffer = buffers[x]; } else { defaultBuffer = buffers[x]; } } //get ogrlayer and ogrlayer feature 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(); } Feature OGRFeature; FeatureDefn OGRFeatureDef = OGRLayer.GetLayerDefn(); //initialize columnInfo object columnInfo ci = new columnInfo(); //for each row in ogrlayer add row to output buffer while ((OGRFeature = OGRLayer.GetNextFeature()) != null) { try { defaultBuffer.AddRow(); //set buffer column values for (int i = 0; i < this.columnInformation.Count; i++) { ci = (columnInfo)this.columnInformation[i]; if (ci.geom) { Geometry geom = OGRFeature.GetGeometryRef(); if (geom != null) { byte[] geomBytes = new byte[geom.WkbSize()]; geom.ExportToWkb(geomBytes); defaultBuffer.AddBlobData(ci.bufferColumnIndex, geomBytes); } } else { int OGRFieldIndex = OGRFeatureDef.GetFieldIndex(ci.columnName); FieldDefn OGRFieldDef = OGRFeatureDef.GetFieldDefn(OGRFieldIndex); FieldType OGRFieldType = OGRFieldDef.GetFieldType(); //declare datetime variables int pnYear, pnMonth, pnDay, pnHour, pnMinute, pnTZFlag; float pnSecond; DateTime dt; TimeSpan ts; switch (OGRFieldType) { //case FieldType.OFTBinary: // break; case FieldType.OFTDate: OGRFeature.GetFieldAsDateTime(OGRFieldIndex, out pnYear, out pnMonth, out pnDay, out pnHour, out pnMinute, out pnSecond, out pnTZFlag); dt = new DateTime(pnYear, pnMonth, pnDay); defaultBuffer.SetDate(ci.bufferColumnIndex, dt); break; case FieldType.OFTDateTime: OGRFeature.GetFieldAsDateTime(OGRFieldIndex, out pnYear, out pnMonth, out pnDay, out pnHour, out pnMinute, out pnSecond, out pnTZFlag); dt = new DateTime(pnYear, pnMonth, pnDay, pnHour, pnMinute, (int)pnSecond); //set time zone? defaultBuffer.SetDateTime(ci.bufferColumnIndex, dt); break; case FieldType.OFTInteger: defaultBuffer.SetInt32(ci.bufferColumnIndex, OGRFeature.GetFieldAsInteger(OGRFieldIndex)); break; case FieldType.OFTInteger64: defaultBuffer.SetInt64(ci.bufferColumnIndex, OGRFeature.GetFieldAsInteger(OGRFieldIndex)); break; case FieldType.OFTReal: defaultBuffer.SetDouble(ci.bufferColumnIndex, OGRFeature.GetFieldAsDouble(OGRFieldIndex)); break; case FieldType.OFTTime: OGRFeature.GetFieldAsDateTime(OGRFieldIndex, out pnYear, out pnMonth, out pnDay, out pnHour, out pnMinute, out pnSecond, out pnTZFlag); ts = new TimeSpan(pnHour, pnMinute, (int)pnSecond); defaultBuffer.SetTime(ci.bufferColumnIndex, ts); break; case FieldType.OFTString: default: defaultBuffer.SetString(ci.bufferColumnIndex, OGRFeature.GetFieldAsString(OGRFieldIndex)); break; } } } } catch (Exception ex) { //redirect to error buffer if (ci.errorDisposition == DTSRowDisposition.RD_RedirectRow) { // Add a row to the error buffer. errorBuffer.AddRow(); // Set the error information. int errorCode = System.Runtime.InteropServices.Marshal.GetHRForException(ex); errorBuffer.SetErrorInfo(errorOutputID, errorCode, ci.lineageID); // Remove the row that was added to the default buffer. defaultBuffer.RemoveRow(); } //fail component else if (ci.errorDisposition == DTSRowDisposition.RD_FailComponent || ci.errorDisposition == DTSRowDisposition.RD_NotUsed) { ComponentMetaData.FireError(0, "primeoutput failure", ex.ToString(), string.Empty, 0, out cancel); throw; } } } //set end of rowset for buffers if (defaultBuffer != null) { defaultBuffer.SetEndOfRowset(); } if (errorBuffer != null) { errorBuffer.SetEndOfRowset(); } //clean up layer object if (isSQLLayer) { this.OGRDataSource.ReleaseResultSet(OGRLayer); } }
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); } } }
public static bool CovertRegion2Line(string path, string savePath) { try { OSGeo.OGR.Ogr.RegisterAll(); OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile"); if (dr == null) { Console.WriteLine("启动驱动失败!\n"); } OSGeo.OGR.DataSource ds = dr.Open(path, 0); int layerCount = ds.GetLayerCount(); OSGeo.OGR.Layer layer = ds.GetLayerByIndex(0); FeatureDefn fdf = layer.GetLayerDefn(); int fieldCount = fdf.GetFieldCount(); // 创建数据源 DataSource oDS = dr.CreateDataSource(savePath, null); if (oDS == null) { Console.WriteLine("创建矢量文件【%s】失败!\n", savePath); return(false); } OSGeo.OSR.SpatialReference srs = layer.GetSpatialRef(); // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定 Layer oLayer = oDS.CreateLayer("line", srs, OSGeo.OGR.wkbGeometryType.wkbMultiLineString, null); if (oLayer == null) { Console.WriteLine("图层创建失败!\n"); return(false); } for (int i = 0; i < fieldCount; i++) { FieldDefn fieldDefn = fdf.GetFieldDefn(i); oLayer.CreateField(fieldDefn, 1); } FeatureDefn oDefn = oLayer.GetLayerDefn(); OSGeo.OGR.Feature feat; while ((feat = layer.GetNextFeature()) != null) { Feature oFeatureMulty = new Feature(oDefn); OSGeo.OGR.Geometry geometry = feat.GetGeometryRef(); for (int i = 0; i < fieldCount; i++) { string value = feat.GetFieldAsString(i); oFeatureMulty.SetField(i, value); } OSGeo.OGR.wkbGeometryType goetype = geometry.GetGeometryType(); if (goetype == OSGeo.OGR.wkbGeometryType.wkbPolygon) { Geometry tempGeo = new Geometry(wkbGeometryType.wkbMultiLineString); int count = geometry.GetGeometryCount(); for (int j = 0; j < count; j++) { Geometry line = new Geometry(wkbGeometryType.wkbLinearRing); Geometry geo = geometry.GetGeometryRef(j); for (int i = 0; i < geo.GetPointCount(); i++) { double x = geo.GetX(i); double y = geo.GetY(i); line.AddPoint(x, y, 0); } tempGeo.AddGeometryDirectly(line); } oFeatureMulty.SetGeometry(tempGeo); } oLayer.SetFeature(oFeatureMulty); } oLayer.Dispose(); layer.Dispose(); oDS.Dispose(); ds.Dispose(); dr.Dispose(); } catch { } return(false); }