using Microsoft.SqlServer.Types;
using System.Data.SqlTypes;
public static void Main()
Console.WriteLine("@dbc Alternative2");
Console.WriteLine("------- Step 1: serialiization using datatable with SqlGeographyDTO------");
var xml=SerializeDataTable(dt2);
Console.WriteLine("Step2: DeSerialiization the same xml using datatable with SqlGeographyDTO");
var dt3=DeSerializeDataTable(xml);
Console.WriteLine("Writing data from the generated datatable");
public static void DumpTable(DataTable dt)
foreach (DataRow row in dt.Rows)
var geoDto = f1 as SqlGeographyDTO2;
Console.WriteLine("id: {0} |f1: {1} | Lat:{2} Long:{3}", ID, f1,geoDto.GetLat(),geoDto.GetLong());
public static string SerializeDataTable(DataTable dt)
var writer = new StringWriter();
dt.WriteXml(writer,XmlWriteMode.WriteSchema );
var xml=writer.ToString();
public static DataTable DeSerializeDataTable(string xml)
DataTable dt=new DataTable();
StringReader srXMLtext = new StringReader(xml);
static string GetXml(SqlGeography geo)
var g = (SqlGeographyDTO) geo;
return g.Geography.Value;
static DataTable GetGeoTable2()
DataTable dataTable = new DataTable("table");
dataTable.Columns.Add("f1", typeof(SqlGeographyDTO2));
dataTable.Columns.Add("id", typeof(int));
SqlGeography g= SqlGeography.Point(20, 10, 4326);
DataRow newRow = dataTable.NewRow();
newRow["f1"] = (SqlGeographyDTO2)g;
dataTable.Rows.Add(newRow);
g=SqlGeography.Point(30, 15, 4326);
newRow = dataTable.NewRow();
newRow["f1"] = (SqlGeographyDTO2)g;;
dataTable.Rows.Add(newRow);
public class SqlGeographyDTO
const int DefaultSRID = 4326;
public SqlInt32 STSrid { get; set; }
public SqlXml Geography { get; set; }
public static implicit operator SqlGeographyDTO(SqlGeography geography)
if (geography == null || geography.IsNull)
return new SqlGeographyDTO
STSrid = geography.STSrid,
Geography = geography.AsGml(),
public static implicit operator SqlGeography(SqlGeographyDTO dto)
return SqlGeography.Null;
var geography = SqlGeography.GeomFromGml(dto.Geography, dto.STSrid.IsNull ? DefaultSRID : dto.STSrid.Value);
public override string ToString()
public class SqlGeographyDTO2
const int DefaultSRID = 4326;
public int? STSrid { get; set; }
public string Geography { get; set; }
var text = new SqlChars(Geography);
var geo = SqlGeography.STPointFromText(text, (int)STSrid).Long.Value;
var text = new SqlChars(Geography);
var geo = SqlGeography.STPointFromText(text, (int)STSrid).Lat.Value;
public static implicit operator SqlGeographyDTO2(SqlGeography geography)
if (geography == null || geography.IsNull)
return new SqlGeographyDTO2
STSrid = geography.STSrid.IsNull ? (int?)null : geography.STSrid.Value,
Geography = geography.ToString(),
public static implicit operator SqlGeography(SqlGeographyDTO2 dto)
return SqlGeography.Null;
var geography = SqlGeography.STGeomFromText(new SqlChars(dto.Geography), dto.STSrid.GetValueOrDefault(DefaultSRID));
public override string ToString()