年度变更建库软件5.0版本
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1746 lines
88 KiB

using System;
using System.Collections.Generic;
//using System.Linq;
using System.Text;
using System.Data.SQLite;
using System.IO;
using System.Windows.Forms;
using System.Data;
using System.Threading;
//using ArcShapeFileDLL;
namespace Kingo.Mobile.Shape2KOTool.KoDataBase
{
//public delegate void MessageReport(string msg, int count = 0);
public class KODBFeatureLayer : IDisposable
{
public int LayerIndex { get; set; }
public object Tag { get; set; }
public event MessageReport Report;
public ISpatialDataSource SpatialDataSource { get; set; }
public string FeatureLayerName { get; set; }
public List<ShapeFieldInfo> FieldInfos { get; set; }
//public int RecordCount { get; set; }
public string OutputFileName { get; set; }
//public ArcSha MyProperty { get; set; }
//public double MinX { get; set; }
//public double MinY { get; set; }
//public double MaxX { get; set; }
//public double MaxY { get; set; }
public int WKID { get; set; }
public bool EncryptData { get; set; }
public int MinScale { get; set; }
public int MaxScale { get; set; }
public string DisplayField { get; set; }
public string LayerLabelName { get; set; }
public XSDClass.DEFeatureClassInfo DEFeatureClassInfo { get; set; }
public XSDClass.ItemInfo ItemInfo { get; set; }
public XSDClass.Renderer Render { get; set; }
public XSDClass.Renderer ItemInfoRender { get; set; }
public XSDClass.AdvancedDrawingInfo AdvDrawingInfo { get; set; }
public XSDClass.LabelingInfo LabelingInfo { get; set; }
public XSDClass.Symbol FeatureSymbol { get; set; }
//public ShapeFiles ShapeFile { get; set; }
//public string DisplayFieldName { get; set; }
//private XSDClass.ProjectedCoordinateSystem spatialReference = null;
public KODBFeatureLayer()
{
//RecordCount = 9998;
FeatureLayerName = "KOFDT";
OutputFileName = string.Format("{0}\\{1}.ko", Application.StartupPath, FeatureLayerName);
/*
FieldInfos = new List<ShapeFieldInfo>();
AdvDrawingInfo = new XSDClass.AdvancedDrawingInfo();
ItemInfo = new XSDClass.ItemInfo()
{
Id = 2
};*/
}
private void GetDEFeatureClassInfo(XSDClass.ProjectedCoordinateSystem spatialReference)
{
DEFeatureClassInfo = new XSDClass.DEFeatureClassInfo();
DEFeatureClassInfo.CatalogPath = string.Format(@"\main.{0}", FeatureLayerName);
DEFeatureClassInfo.Name = string.Format(@"main.{0}", FeatureLayerName);
DEFeatureClassInfo.Extent = new XSDClass.EnvelopeN()
{
SpatialReference = spatialReference,
XMax = this.SpatialDataSource.Extent.XMax,
XMin = this.SpatialDataSource.Extent.XMin,
YMax = this.SpatialDataSource.Extent.YMax,
YMin = this.SpatialDataSource.Extent.YMin
};
DEFeatureClassInfo.GPFieldInfoExs = new List<XSDClass.GPFieldInfoEx>();
XSDClass.GPFieldInfoEx objectid = new XSDClass.GPFieldInfoEx()
{
Name = "OBJECTID",
ModelName = "OBJECTID",
AliasName = "OBJECTID",
IsEditable = false,
IsNullable = false,
IsRequired = true,
FieldType = XSDClass.esriFieldType.esriFieldTypeOID
};
DEFeatureClassInfo.GPFieldInfoExs.Add(objectid);
foreach (ShapeFieldInfo item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
XSDClass.GPFieldInfoEx pGPFieldInfoEx = new XSDClass.GPFieldInfoEx()
{
Name = item.FieldName,
ModelName = item.FieldName,
AliasName = item.FieldAlias,
FieldType = XSDClass.CommonMethod.ConvertFromShpFieldType(item),
IsNullable = true
};
DEFeatureClassInfo.GPFieldInfoExs.Add(pGPFieldInfoEx);
}
XSDClass.GPFieldInfoEx st_area = new XSDClass.GPFieldInfoEx()
{
Name = "st_area(Shape)",
ModelName = "st_area(Shape)",
AliasName = "面积",
IsEditable = false,
IsNullable = false,
IsRequired = true,
FieldType = XSDClass.esriFieldType.esriFieldTypeDouble
};
DEFeatureClassInfo.GPFieldInfoExs.Add(st_area);
XSDClass.GPFieldInfoEx st_length = new XSDClass.GPFieldInfoEx()
{
Name = "st_perimeter(Shape)",
ModelName = "st_perimeter(Shape)",
AliasName = "周长",
IsEditable = false,
IsNullable = false,
IsRequired = true,
FieldType = XSDClass.esriFieldType.esriFieldTypeDouble
};
DEFeatureClassInfo.GPFieldInfoExs.Add(st_length);
DEFeatureClassInfo.SpatialReference = spatialReference;
}
private void GetItemInfo(int wkid)
{
ItemInfo = new XSDClass.ItemInfo();
ItemInfo.MaxScale = MaxScale;
ItemInfo.MinScale = MinScale;
ItemInfo.Name = FeatureLayerName;
ItemInfo.DisplayField = DisplayField == null ? "" : DisplayField;
ItemInfo.Extent.Xmax = SpatialDataSource.Extent.XMax;
ItemInfo.Extent.Xmin = SpatialDataSource.Extent.XMin;
ItemInfo.Extent.Ymax = SpatialDataSource.Extent.YMax;
ItemInfo.Extent.Ymin = SpatialDataSource.Extent.YMin;
ItemInfo.Extent.SpatialReference = new XSDClass.SpatialReference()
{
LatestWkid = wkid,
Wkid = wkid
};
//创建字段
ItemInfo.Fields = new List<XSDClass.Field>();
Kingo.Mobile.Shape2KOTool.XSDClass.FieldNomal objectid = new XSDClass.FieldNomal()
{
Alias = "OBJECTID",
Name = "OBJECTID",
Editable = false,
Nullable = false,
Type = XSDClass.esriFieldType.esriFieldTypeOID
};
ItemInfo.Fields.Add(objectid);
foreach (ShapeFieldInfo item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
XSDClass.esriFieldType fieldType = XSDClass.CommonMethod.ConvertFromShpFieldType(item);
Kingo.Mobile.Shape2KOTool.XSDClass.Field field = null;
if (fieldType == XSDClass.esriFieldType.esriFieldTypeString)
{
field = new XSDClass.FieldWithLength()
{
Length = item.FieldSize
};
}
else
{
field = new XSDClass.FieldNomal();
}
field.Alias = item.FieldAlias;
field.Editable = true;
field.Name = item.FieldName;
field.Nullable = true;
field.Type = fieldType;
ItemInfo.Fields.Add(field);
}
//创建Template,types
XSDClass.Template template = new XSDClass.Template()
{
Name = FeatureLayerName
};
template.Prototype.Attributes.Add("OBJECTID", 0);
foreach (ShapeFieldInfo item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
template.Prototype.Attributes.Add(item.FieldName, null);
}
ItemInfo.Templates.Add(template);
//创建DrawingInfo
XSDClass.SFSymbol pSFSymbol = new XSDClass.SFSymbol();
pSFSymbol.Color[0] = 249;
pSFSymbol.Color[1] = 250;
pSFSymbol.Color[2] = 205;
pSFSymbol.Color[3] = 255;
pSFSymbol.Style = XSDClass.esriSimpleFillStyle.esriSFSSolid;
//pSFSymbol.Outline.Style = XSDClass.esriSimpleLineStyle.esriSLSSolid;
pSFSymbol.Outline.Width = 0.4;
pSFSymbol.Outline.Color[0] = 110;
pSFSymbol.Outline.Color[1] = 110;
pSFSymbol.Outline.Color[2] = 110;
pSFSymbol.Outline.Color[3] = 255;
XSDClass.SimpleRenderer pSimpleRenderer = new XSDClass.SimpleRenderer();
pSimpleRenderer.Symbol = pSFSymbol;
ItemInfo.DrawingInfo.Renderer = pSimpleRenderer;
if (LabelingInfo != null)
{
ItemInfo.DrawingInfo.LabelingInfo = new List<XSDClass.LabelingInfo>();
ItemInfo.DrawingInfo.LabelingInfo.Add(LabelingInfo);
}
}
private void GetAdvancedDrawingInfo()
{
//AdvDrawingInfo = new XSDClass.AdvancedDrawingInfo();
//XSDClass.SimpleRenderer pSimpleRenderer = new XSDClass.SimpleRenderer();
//AdvDrawingInfo.DrawingInfo.Renderer = pSimpleRenderer;
//XSDClass.CIMSymbolReference pCIMSymbolReference = new XSDClass.CIMSymbolReference()
//{
// SymbolName = "Symbol_1"
//};
//pSimpleRenderer.Symbol = pCIMSymbolReference;
//XSDClass.CIMPolygonSymbol pCIMPolygonSymbol = new XSDClass.CIMPolygonSymbol();
//pCIMSymbolReference.Symbol = pCIMPolygonSymbol;
//XSDClass.CIMFilledStroke pCIMFilledStroke = new XSDClass.CIMFilledStroke();
//XSDClass.CIMSolidPattern pCIMSolidPattern = new XSDClass.CIMSolidPattern();
//pCIMSolidPattern.Color[0] = 110;
//pCIMSolidPattern.Color[1] = 110;
//pCIMSolidPattern.Color[2] = 110;
//pCIMSolidPattern.Color[3] = 255;
//pCIMFilledStroke.Pattern = pCIMSolidPattern;
//pCIMPolygonSymbol.SymbolLayers.Add(pCIMFilledStroke);
//XSDClass.CIMFill pCIMFill = new XSDClass.CIMFill();
//XSDClass.CIMSolidPattern pCIMSolidPattern2 = new XSDClass.CIMSolidPattern();
//pCIMSolidPattern2.Color[0] = 249;
//pCIMSolidPattern2.Color[1] = 250;
//pCIMSolidPattern2.Color[2] = 205;
//pCIMSolidPattern2.Color[3] = 255;
//pCIMFill.Pattern = pCIMSolidPattern2;
//pCIMPolygonSymbol.SymbolLayers.Add(pCIMFill);
//if (LabelingInfo != null)
//{
// AdvDrawingInfo.DrawingInfo.LabelingInfo = new List<XSDClass.LabelingInfo>();
// AdvDrawingInfo.DrawingInfo.LabelingInfo.Add(LabelingInfo);
//}
}
public void CreateFeatureLayer(int wkid)
{
Test();
return;
//try
//{
//TestGDB_Items();
//return;
string fileName = string.Format("{0}\\{1}.ko", Application.StartupPath, FeatureLayerName);
File.WriteAllBytes(fileName, Properties.Resources.kodatabase);
//SQLiteConnection sqlConnection = new SQLiteConnection(@"Data Source=D:\Users\Administrator\Desktop\杨江川\SQLiteSpy.db3");
//SQLiteConnection.CreateFile(fileName);
SQLiteConnection sqlConnection = new SQLiteConnection(@"Data Source=" + fileName);
sqlConnection.Open();
try
{
string sload = string.Format("SELECT load_extension('{0}\\stgeometry_sqlite.dll','SDE_SQL_funcs_init')", Application.StartupPath);
SQLiteCommand cmdload = new SQLiteCommand(sload, sqlConnection);
cmdload.ExecuteNonQuery();
SQLiteTransaction pTran = sqlConnection.BeginTransaction();
try
{
//DataTable dt= ExecuteQuery(sqlConnection, "select * from GDB_Items");
//TestGDB_Items(sqlConnection);
//创建空间索引(应该可以不要)
XSDClass.ProjectedCoordinateSystem spatialReference = null;
int srid = InsertSpatialReference(wkid, sqlConnection, out spatialReference);
//获取DEFeatureClassInfo的值
GetDEFeatureClassInfo(spatialReference);
//获取ItemInfo
GetItemInfo(wkid);
//获取AdvancedDrawingInfo
GetAdvancedDrawingInfo();
//创建空间表SELECT CreateOGCTables();
CreateSpatialTable(srid, sqlConnection);
//注册元数据
InsertMetaData(sqlConnection, srid);
InsertDataRecords(sqlConnection, srid);
//可能需要删除sqlite_sequence注册的表名,必须放到插入数据后,插入数据时又会自动生成对应的记录
//ExecuteScalar(sqlConnection, string.Format("delete from sqlite_sequence where name = '{0}'", FeatureLayerName));
//测试
//ALTER TABLE `table1` ADD `AAAA` VARCHAR( 10 ) NOT NULL ;
pTran.Commit();
}
//catch (Exception ex)
//{
// pTran.Rollback();
// throw;
//}
finally
{
pTran.Dispose();
}
}
//catch
//{
// throw;
//}
finally
{
sqlConnection.Close();
}
//插入数据
//}
//catch (Exception ex)
//{
// throw;
//}
}
private int InsertSpatialReference(int srid, SQLiteConnection conn, out XSDClass.ProjectedCoordinateSystem spatialReference)
{
try
{
string sqlSelect = "SELECT * FROM st_aux_spatial_reference_systems where auth_srid=" + srid.ToString();
SQLiteCommand cmd = new SQLiteCommand(sqlSelect, conn);
SQLiteDataReader objReader = cmd.ExecuteReader();
if (objReader.HasRows)
{
objReader.Read();
spatialReference = new XSDClass.ProjectedCoordinateSystem()
{
WKID = Convert.ToInt32(objReader.GetValue(2)),
LatestWKID = Convert.ToInt32(objReader.GetValue(2)),
WKT = objReader.GetValue(3).ToString(),
XOrigin = Convert.ToDouble(objReader.GetValue(4)),
YOrigin = Convert.ToDouble(objReader.GetValue(5)),
XYScale = Convert.ToDouble(objReader.GetValue(6)),
ZOrigin = Convert.ToDouble(objReader.GetValue(7)),
ZScale = Convert.ToDouble(objReader.GetValue(8)),
MOrigin = Convert.ToDouble(objReader.GetValue(9)),
MScale = Convert.ToDouble(objReader.GetValue(10)),
XYTolerance = Convert.ToDouble(objReader.GetValue(11)),
ZTolerance = Convert.ToDouble(objReader.GetValue(12)),
MTolerance = Convert.ToDouble(objReader.GetValue(13)),
HighPrecision = Convert.ToBoolean(Convert.ToInt32(objReader.GetValue(14)))
};
spatialReference.WKT = string.Format("{0},AUTHORITY[\"EPSG\",{1}]]", spatialReference.WKT.Remove(spatialReference.WKT.Length - 1), spatialReference.WKID);
int nSrid = Convert.ToInt32(objReader.GetValue(0));
objReader.Close();
return nSrid;
}
else
{
objReader.Close();
//string selectSrid = @"SELECT seq FROM sqlite_sequence where name='st_aux_spatial_reference_systems'";
//cmd.CommandText = selectSrid;
//int currentsrid = Convert.ToInt32(cmd.ExecuteScalar());
//currentsrid++;
//
//string updateSrid = string.Format(@"update sqlite_sequence set seq ={0} where name='st_aux_spatial_reference_systems'", currentsrid);
//cmd.CommandText = updateSrid;
//cmd.ExecuteNonQuery();
int currentsrid = GetSeqIDInSqlite_Sequence(conn, "st_aux_spatial_reference_systems");
//string insertSP = string.Format(@"insert into st_aux_spatial_reference_systems SELECT * FROM st_spatial_reference_systems where auth_srid={0};
//update st_aux_spatial_reference_systems set srid={1} where auth_srid={0};", srid, currentsrid);
string selectSql = string.Format("SELECT * FROM st_spatial_reference_systems where auth_srid={0}", srid);
cmd.CommandText = selectSql;
SQLiteDataReader reader = cmd.ExecuteReader();
reader.Read();
spatialReference = new XSDClass.ProjectedCoordinateSystem()
{
WKID = Convert.ToInt32(reader.GetValue(2)),
LatestWKID = Convert.ToInt32(reader.GetValue(2)),
WKT = reader.GetValue(3).ToString(),
XOrigin = Convert.ToDouble(reader.GetValue(4)),
YOrigin = Convert.ToDouble(reader.GetValue(5)),
XYScale = Convert.ToDouble(reader.GetValue(6)),
ZOrigin = Convert.ToDouble(reader.GetValue(7)),
ZScale = Convert.ToDouble(reader.GetValue(8)),
MOrigin = Convert.ToDouble(reader.GetValue(9)),
MScale = Convert.ToDouble(reader.GetValue(10)),
XYTolerance = Convert.ToDouble(reader.GetValue(11)),
ZTolerance = Convert.ToDouble(reader.GetValue(12)),
MTolerance = Convert.ToDouble(reader.GetValue(13)),
HighPrecision = Convert.ToBoolean(Convert.ToInt32(reader.GetValue(14)))
};
spatialReference.WKT = string.Format("{0},AUTHORITY[\"EPSG\",{1}]]", spatialReference.WKT.Remove(spatialReference.WKT.Length - 1), spatialReference.WKID);
//插入数据
string insertSql = string.Format("insert into st_aux_spatial_reference_systems values({0},'{1}',{2},'{3}',{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14})",
currentsrid,
reader.GetValue(1),
reader.GetValue(2),
reader.GetValue(3),
reader.GetValue(4),
reader.GetValue(5),
reader.GetValue(6),
reader.GetValue(7),
reader.GetValue(8),
reader.GetValue(9),
reader.GetValue(10),
reader.GetValue(11),
reader.GetValue(12),
reader.GetValue(13),
reader.GetValue(14)
);
reader.Close();
reader.Dispose();
cmd.CommandText = insertSql;
int resturt= cmd.ExecuteNonQuery();
return currentsrid;
/* SpatialRefrenceStruct srs = SpatialRefrenceStruct.GetAllData().Find(p => p.WKID == -1);
insertSql = string.Format("insert into st_aux_spatial_reference_systems values({0},'{1}',{2},'{3}',{4},{5},{6},{7},{8},{9},{10},{11},{12},{13},{14})",
currentsrid,
"EPSG",
srs.WKID,
srs.WKT,
srs.FalseX,
srs.FalseY,
srs.XYUnits,
srs.FalseZ,
srs.ZUnits,
srs.FalseM,
srs.MUnits,
srs.XYCluster_Tol,
srs.ZCluster_Tol,
srs.MCluster_Tol,
1
);*/
}
}
catch (Exception ex)
{
OnReport(string.Format("插入空间参考失败!原因:{0}", ex), -1);
spatialReference = null;// new XSDClass.ProjectedCoordinateSystem();
return -1;
}
}
private void CreateSpatialTable(int srid, SQLiteConnection conn)
{
SQLiteCommand cmd = new SQLiteCommand(conn);
StringBuilder sqlCreateTable = new StringBuilder();
sqlCreateTable.AppendFormat("CREATE TABLE {0} (OBJECTID integer primary key not null", FeatureLayerName);
// sqlCreateTable.AppendFormat("CREATE TABLE {0} (OBJECTID integer primary key not null, KReserved int16 check(typeof(KReserved) = 'integer' and KReserved >= -32768 and KReserved <= 32767) not null)", FeatureLayerName);
foreach (var item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
sqlCreateTable.AppendFormat(",{0} {1}", item.FieldName, XSDClass.CommonMethod.GetCreateSqlTypeFormShapeField(item));
}
sqlCreateTable.Append(")");
// string sqltst = @"CREATE TABLE KOFDT (OBJECTID integer primary key not null,
//DLMC text(60) check((typeof(DLMC) = 'text' or typeof(DLMC) = 'null') ))";
cmd.CommandText = sqlCreateTable.ToString();
//cmd.CommandText = sqltst;
int resturt = cmd.ExecuteNonQuery();
string sqlCreateShape = string.Format("SELECT AddGeometryColumn(null,'{0}','Shape',{1}, 'multipolygon','xy','null');", FeatureLayerName, srid);
cmd.CommandText = sqlCreateShape;
resturt= cmd.ExecuteNonQuery();
string sqlCreateSpatialIndex = string.Format("SELECT CreateSpatialIndex('main','{0}','Shape','rtreexy')", FeatureLayerName);
cmd.CommandText = sqlCreateSpatialIndex;
resturt = cmd.ExecuteNonQuery();
}
public static DataTable GetSpatialRefrenceSystemTable(SQLiteConnection conn)
{
//string sload = string.Format("SELECT load_extension('{0}\\stgeometry_sqlite.dll','SDE_SQL_funcs_init');", Application.StartupPath);
//DataSet ds = Kingo.Mobile.SQLiteHelper.ExecuteDataSet(sload+@"Data Source=D:\Users\Administrator\Desktop\杨江川\Counties.sqlite", "SELECT * FROM st_spatial_reference_systems", System.Data.CommandType.Text);
//SQLiteConnection sqlConnection = new SQLiteConnection(@"Data Source=D:\Users\Administrator\Desktop\杨江川\Counties.sqlite");
//sqlConnection.Open();
SQLiteCommand cmd = new SQLiteCommand(conn);
//cmd.CommandText = sload;
//cmd.ExecuteNonQuery();
cmd.CommandText = "SELECT * FROM st_spatial_reference_systems";
SQLiteDataAdapter sda = new SQLiteDataAdapter(cmd);
DataTable dt = new DataTable();
sda.Fill(dt);
sda.Dispose();
return dt;
}
private void InsertMetaData(SQLiteConnection conn, int srid)
{
//consolidationMapping_GDB
//FromWkspPath FromName ToName OBJECTID
//C:\Users\Administrator\Desktop\东营市测政点(新) Export_Output main.Export_Output 1
string insertSqlconsolidationMapping_GDB = string.Format(
@"insert into consolidationMapping_GDB values('E:\back\桌面\OfflineData','{0}','main.{0}',{1})",
FeatureLayerName,
GetGDB_RowidGeneratorsSeq(conn, "consolidationMapping_GDB"));
SQLiteCommand cmd = new SQLiteCommand(conn);
cmd.CommandText = insertSqlconsolidationMapping_GDB;
int resturt = cmd.ExecuteNonQuery();
//sqlite_sequence
int registration_id = GetSeqIDInSqlite_Sequence(conn, "GDB_TableRegistry");
//GDB_TableRegistry
//registration_id table_name rowid_column description object_flags registration_date minimum_id
//9 Export_Output_2 OBJECTID_1 16391 1404267848 1
string insertSqlGDB_TableRegistry = string.Format(
@"insert into GDB_TableRegistry values({0},'{1}','OBJECTID','',16391,{2},1)",
registration_id,
FeatureLayerName,
XSDClass.CommonMethod.UNIX_TIMESTAMP(DateTime.Now)
);
cmd.CommandText = insertSqlGDB_TableRegistry;
resturt = cmd.ExecuteNonQuery();
//GDB_RowidGenerators
//registration_id base_id num_ids last_id
//9 266 -1 266
string insertSqlGDB_RowidGenerators = string.Format(
@"insert into GDB_RowidGenerators values({0},{1},-1,{1})",
registration_id,
SpatialDataSource.RecordCount
);
cmd.CommandText = insertSqlGDB_RowidGenerators;
resturt = cmd.ExecuteNonQuery();
//GDB_Layers
//layer_id description table_name spatial_column eflags layer_mask minx miny maxx maxy minz minm maxz maxm cdate minimum_id srid base_layer_id
//3 Export_Output Shape 71303299 0 40455786.8818237 4087619.97360693 40460944.7805747 4089982.91920062 1407132840 1 300001 0
//eg.eflags值71303299为点的mask值 71565457为面的mask值
int layer_id = GetSeqIDInSqlite_Sequence(conn, "GDB_Layers");
string insertSqlGDB_Layers = string.Format(
@"insert into GDB_Layers values({0},null,'{1}','Shape',71565457,0,{2},{3},{4},{5},null,null,null,null,{6},1,{7},0)",
layer_id,
FeatureLayerName,
//minx miny maxx maxy
//MinX, MinY, MaxX, MaxY,
SpatialDataSource.Extent.XMin, SpatialDataSource.Extent.YMin, SpatialDataSource.Extent.XMax, SpatialDataSource.Extent.YMax,
XSDClass.CommonMethod.UNIX_TIMESTAMP(DateTime.Now),
srid
);
cmd.CommandText = insertSqlGDB_Layers;
resturt = cmd.ExecuteNonQuery();
//GDB_Items
//ObjectID UUID Type Name PhysicalName Path Url Properties Defaults DatasetSubtype1 DatasetSubtype2 DatasetInfo1 DatasetInfo2 Definition Documentation ItemInfo Shape
//5 {B18A6FCA-7844-42BE-87B5-78B294BC1DF8} {70737809-852C-4A03-9E22-2CECEA5B9BFA} main.Export_Output MAIN.EXPORT_OUTPUT \main.Export_Output 1 1 1 Shape <DEFeatureClassInfo xsi:type='typens:DEFeatureClassInfo' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xs='http://www.w3.org/2001/XMLSchema' xmlns:typens='http://www.esri.com/schemas/ArcGIS/10.1'><CatalogPath>\main.Export_Output</CatalogPath><Name>main.Export_Output</Name><ChildrenExpanded>false</ChildrenExpanded><DatasetType>esriDTFeatureClass</DatasetType><DSID>5</DSID><Versioned>false</Versioned><CanVersion>true</CanVersion><ConfigurationKeyword></ConfigurationKeyword><RequiredGeodatabaseClientVersion>10.0</RequiredGeodatabaseClientVersion><HasOID>true</HasOID><OIDFieldName>OBJECTID_1</OIDFieldName><GPFieldInfoExs xsi:type='typens:ArrayOfGPFieldInfoEx'><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>OBJECTID_1</Name><ModelName>OBJECTID_1</ModelName><FieldType>esriFieldTypeOID</FieldType><IsNullable>false</IsNullable><Required>true</Required><Editable>false</Editable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>OBJECTID</Name><ModelName>OBJECTID</ModelName><FieldType>esriFieldTypeInteger</FieldType><IsNullable>false</IsNullable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>NAME</Name><ModelName>NAME</ModelName><FieldType>esriFieldTypeString</FieldType><IsNullable>false</IsNullable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>HYDC</Name><ModelName>HYDC</ModelName><FieldType>esriFieldTypeString</FieldType><IsNullable>false</IsNullable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>TYPE</Name><ModelName>TYPE</ModelName><FieldType>esriFieldTypeString</FieldType><IsNullable>false</IsNullable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>ANGLE</Name><ModelName>ANGLE</ModelName><FieldType>esriFieldTypeDouble</FieldType><IsNullable>false</IsNullable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>GB</Name><ModelName>GB</ModelName><FieldType>esriFieldTypeInteger</FieldType><IsNullable>false</IsNullable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>ORIG_FID</Name><ModelName>ORIG_FID</ModelName><FieldType>esriFieldTypeInteger</FieldType><IsNullable>false</IsNullable></GPFieldInfoEx><GPFieldInfoEx xsi:type='typens:GPFieldInfoEx'><Name>Shape</Name><ModelName>Shape</ModelName><FieldType>esriFieldTypeGeometry</FieldType><IsNullable>false</IsNullable><Required>true</Required></GPFieldInfoEx></GPFieldInfoExs><CLSID>{52353152-891A-11D0-BEC6-00805F7C4268}</CLSID><EXTCLSID></EXTCLSID><RelationshipClassNames xsi:type='typens:Names'></RelationshipClassNames><AliasName></AliasName><ModelName></ModelName><HasGlobalID>false</HasGlobalID><GlobalIDFieldName></GlobalIDFieldName><RasterFieldName></RasterFieldName><ExtensionProperties xsi:type='typens:PropertySet'><PropertyArray xsi:type='typens:ArrayOfPropertySetProperty'></PropertyArray></ExtensionProperties><ControllerMemberships xsi:type='typens:ArrayOfControllerMembership'></ControllerMemberships><EditorTrackingEnabled>false</EditorTrackingEnabled><CreatorFieldName></CreatorFieldName><CreatedAtFieldName></CreatedAtFieldName><EditorFieldName></EditorFieldName><EditedAtFieldName></EditedAtFieldName><IsTimeInUTC>true</IsTimeInUTC><FeatureType>esriFTSimple</FeatureType><ShapeType>esriGeometryPoint</ShapeType><ShapeFieldName>Shape</ShapeFieldName><HasM>false</HasM><HasZ>false</HasZ><HasSpatialIndex>true</HasSpatialIndex><AreaFieldName></AreaFieldName><LengthFieldName></LengthFieldName><Extent xsi:type='typens:EnvelopeN'><XMin>NaN</XMin><YMin>NaN</YMin><XMax>NaN</XMax><YMax>NaN</YMax><SpatialReference xsi:type='typens:ProjectedCoordinateSystem'><WKT>PROJCS[&quot;CGCS_2000_3_Degree_GK_Zone_40&quot;,GEOGCS[&quot;GCS_CGCS_2000&quot;,DATUM[&quot;D_CGCS_2000&quot;,SPHEROID[&quot;CGCS_2000&quot;,6378137.0,298.257222101]],PRIMEM[&quot;Greenwich&quot;,0.0],UNIT[&quot;Degree&quot;,0.0174532925199433]],PROJECTION[&quot;Gauss_Kruger&quot;],PARAMETER[&quot;False_Easting&quot;,40500000.0],PARAMETER[&quot;False_Northing&quot;,0.0],PARAMETER[&quot;Central_Meridian&quot;,120.0],PARAMETER[&quot;Scale_Factor&quot;,1.0],PARAMETER[&quot;Latitude_Of_Origin&quot;,0.0],UNIT[&quot;Meter&quot;,1.0]]</WKT><XOrigin>34876800</XOrigin><YOrigin>-10002100</YOrigin><XYScale>9999.8040848168384</XYScale><ZOrigin>0</ZOrigin><ZScale>1</ZScale><MOrigin>0</MOrigin><MScale>1</MScale><XYTolerance>0.0010000020265579224</XYTolerance><ZTolerance>0.001</ZTolerance><MTolerance>0.001</MTolerance><HighPrecision>true</HighPrecision></SpatialReference></Extent><SpatialReference xsi:type='typens:ProjectedCoordinateSystem'><WKT>PROJCS[&quot;CGCS_2000_3_Degree_GK_Zone_40&quot;,GEOGCS[&quot;GCS_CGCS_2000&quot;,DATUM[&quot;D_CGCS_2000&quot;,SPHEROID[&quot;CGCS_2000&quot;,6378137.0,298.257222101]],PRIMEM[&quot;Greenwich&quot;,0.0],UNIT[&quot;Degree&quot;,0.0174532925199433]],PROJECTION[&quot;Gauss_Kruger&quot;],PARAMETER[&quot;False_Easting&quot;,40500000.0],PARAMETER[&quot;False_Northing&quot;,0.0],PARAMETER[&quot;Central_Meridian&quot;,120.0],PARAMETER[&quot;Scale_Factor&quot;,1.0],PARAMETER[&quot;Latitude_Of_Origin&quot;,0.0],UNIT[&quot;Meter&quot;,1.0]]</WKT><XOrigin>34876800</XOrigin><YOrigin>-10002100</YOrigin><XYScale>9999.8040848168384</XYScale><ZOrigin>0</ZOrigin><ZScale>1</ZScale><MOrigin>0</MOrigin><MScale>1</MScale><XYTolerance>0.0010000020265579224</XYTolerance><ZTolerance>0.001</ZTolerance><MTolerance>0.001</MTolerance><HighPrecision>true</HighPrecision></SpatialReference><ChangeTracked>false</ChangeTracked><FieldFilteringEnabled>false</FieldFilteringEnabled><FilteredFieldNames xsi:type='typens:Names'></FilteredFieldNames></DEFeatureClassInfo> Blob
//string sqltest = "select Shape from GDB_Items where objectid=5";
//cmd.CommandText = sqltest;
//object obj = cmd.ExecuteScalar();
int GDB_Items_ObjectID = GetGDB_RowidGeneratorsSeq(conn, "GDB_Items");
DEFeatureClassInfo.DSID = GDB_Items_ObjectID;
string uuid = ("{" + Guid.NewGuid().ToString().ToUpper() + "}").ToUpper();
string type = GetItemType(conn, "Feature Class");
//st_multipolygon('MULTIPOLYGON EMPTY',4326)
string insertSqlGDB_Items = string.Format(
@"insert into GDB_Items values({0},'{1}','{2}','main.{3}','MAIN.{4}','\main.{3}',null,1,null,1, 4,'Shape',null,'{5}',null,null,@Shape)",
GDB_Items_ObjectID,
uuid,
type,
FeatureLayerName,
FeatureLayerName.ToUpper(),
DEFeatureClassInfo.ToXml()
);
byte[] byteShape = new byte[18];
byteShape[0] = 100;
byteShape[1] = 230;
byteShape[2] = 16;
byteShape[8] = 24;
byteShape[14] = 1;
cmd.CommandText = insertSqlGDB_Items;
cmd.Parameters.Add(new System.Data.SQLite.SQLiteParameter(
"Shape", byteShape));
resturt = cmd.ExecuteNonQuery();
cmd.Parameters.Clear();
//GDB_ItemRelationships
//ObjectID UUID Type OriginID DestID Properties Attributes
//2 {736A174C-C8E5-4F3E-8853-34EADA6314D9} {DC78F1AB-34E4-43AC-BA47-1C4EABD0E7C7} {983EF65E-EFA7-49D5-A4A9-03A0D3F42BE6} {B18A6FCA-7844-42BE-87B5-78B294BC1DF8} 1
int GDB_ItemRelationships_ObjectID = GetGDB_RowidGeneratorsSeq(conn, "GDB_ItemRelationships");
string uuid2 = "{" + Guid.NewGuid().ToString().ToUpper() + "}";
string type2 = GetGDB_ItemRelationshipTypes(conn, "DatasetInFolder");
string OriginID = ExecuteScalar(conn, "select uuid from GDB_Items where name =='' or name is null").ToString();
string DestID = uuid;
string insertGDB_ItemRelationships = string.Format(
@"insert into GDB_ItemRelationships values({0},'{1}','{2}','{3}','{4}',1,null)",
GDB_ItemRelationships_ObjectID,
uuid2,
type2,
OriginID,
DestID
);
cmd.CommandText = insertGDB_ItemRelationships;
resturt = cmd.ExecuteNonQuery();
//GDB_ColumnRegistry
//table_name column_name sde_type column_size decimal_digits description object_flags object_id
//Export_Output OBJECTID 2 0 0
InsertDataToGDB_ColumnRegistry(conn, layer_id);
//GDB_ServiceItems
//OBJECTID DatasetName ItemType ItemId ItemInfo AdvancedDrawingInfo
//1 Export_Output 1 0 {"currentVersion":10.21,"id":0,"name":"Export_Output","type":"Feature Layer","description":"","copyrightText":"","defaultVisibility":true,"editFieldsInfo":null,"ownershipBasedAccessControlForFeatures":null,"syncCanReturnChanges":false,"relationships":[],"isDataVersioned":false,"supportsRollbackOnFailureParameter":true,"supportsStatistics":true,"supportsAdvancedQueries":true,"geometryType":"esriGeometryPoint","minScale":0,"maxScale":0,"extent":{"xmin":40455786.881823681,"ymin":4087619.9736069329,"xmax":40460944.780574746,"ymax":4089982.9192006234,"spatialReference":{"wkt":"PROJCS[\"CGCS_2000_3_Degree_GK_Zone_40\",GEOGCS[\"GCS_CGCS_2000\",DATUM[\"D_CGCS_2000\",SPHEROID[\"CGCS_2000\",6378137.0,298.257222101]],PRIMEM[\"Greenwich\",0.0],UNIT[\"Degree\",0.0174532925199433]],PROJECTION[\"Gauss_Kruger\"],PARAMETER[\"False_Easting\",40500000.0],PARAMETER[\"False_Northing\",0.0],PARAMETER[\"Central_Meridian\",120.0],PARAMETER[\"Scale_Factor\",1.0],PARAMETER[\"Latitude_Of_Origin\",0.0],UNIT[\"Meter\",1.0]]"}},"drawingInfo":{"renderer":{"type":"simple","symbol":{"type":"esriSMS","style":"esriSMSCircle","color":[0,77,140,255],"size":4,"angle":0,"xoffset":0,"yoffset":0,"outline":{"color":[0,0,0,255],"width":1}},"label":"","description":""},"transparency":0,"labelingInfo":null},"hasM":false,"hasZ":false,"allowGeometryUpdates":true,"hasAttachments":false,"htmlPopupType":"esriServerHTMLPopupTypeAsHTMLText","objectIdField":"OBJECTID_1","globalIdField":"","displayField":"NAME","typeIdField":"","fields":[{"name":"OBJECTID_1","type":"esriFieldTypeOID","alias":"OBJECTID_1","domain":null,"editable":false,"nullable":false},{"name":"OBJECTID","type":"esriFieldTypeInteger","alias":"OBJECTID","domain":null,"editable":true,"nullable":false},{"name":"NAME","type":"esriFieldTypeString","alias":"名称","domain":null,"editable":true,"nullable":false,"length":60},{"name":"HYDC","type":"esriFieldTypeString","alias":"HYDC","domain":null,"editable":true,"nullable":false,"length":8},{"name":"TYPE","type":"esriFieldTypeString","alias":"TYPE","domain":null,"editable":true,"nullable":false,"length":20},{"name":"ANGLE","type":"esriFieldTypeDouble","alias":"角度","domain":null,"editable":true,"nullable":false},{"name":"GB","type":"esriFieldTypeInteger","alias":"GB","domain":null,"editable":true,"nullable":false},{"name":"ORIG_FID","type":"esriFieldTypeInteger","alias":"ORIG_FID","domain":null,"editable":true,"nullable":false}],"types":[],"templates":[{"name":"Export_Output","description":"","prototype":{"attributes":{"ORIG_FID":0,"OBJECTID":0,"NAME":" ","HYDC":" ","TYPE":" ","ANGLE":0,"GB":0}},"drawingTool":"esriFeatureEditToolPoint"}],"maxRecordCount":1000,"supportedQueryFormats":"JSON, AMF","capabilities":"Query"} {"drawingInfo":{"renderer":{"type":"simple","symbol":{"type":"CIMSymbolReference","symbol":{"type":"CIMPointSymbol","symbolLayers":[{"type":"CIMSimpleMarker","enable":true,"colorLocked":false,"anchorPoint":{"x":0,"y":0},"anchorPointUnits":"Points","size":4,"dominantSizeAxis3D":"Z","fillColor":[0,77,140,255],"outlineColor":[0,0,0,255],"outlineWidth":1,"simpleMarkerType":"Circle"}],"anchorPoint":{"x":0,"y":0},"anchorPointUnits":"Points","scaleX":1},"symbolName":"Symbol_1"},"label":"","description":""},"transparency":0,"labelingInfo":null}}
int GDB_ServiceItems_OBJECTID = GetGDB_RowidGeneratorsSeq(conn, "GDB_ServiceItems");
//string DatasetName = FeatureLayerName;
string advDrawingInfo = string.Empty;
if (AdvDrawingInfo != null)
advDrawingInfo = AdvDrawingInfo.ToJson();
string insertGDB_ServiceItems = string.Format(
@"insert into GDB_ServiceItems values({0},'{1}',1,{2},'{3}','{4}')",
GDB_ServiceItems_OBJECTID,
FeatureLayerName,
ItemInfo.Id,
ItemInfo.ToJson(),
advDrawingInfo
);
cmd.CommandText = insertGDB_ServiceItems;
resturt = cmd.ExecuteNonQuery();
}
//注册表字段信息
private void InsertDataToGDB_ColumnRegistry(SQLiteConnection conn, int layerid)
{
//GDB_ColumnRegistry
//table_name column_name sde_type column_size decimal_digits description object_flags object_id
//Export_Output OBJECTID 2 0 0
StringBuilder sbInsert = new StringBuilder();
foreach (var item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
int sdeType = 5;
string column_size = "0";
int object_flags = 0;
//string object_id = "";
string decimal_digits = "";
#region sdeType
/*
1 = SE_INT16_TYPE—2-byte integer
2 = SE_INT32_TYPE—4-byte integer
3 = SE_FLOAT32_TYPE—4-byte float
4 = SE_FLOAT64_TYPE—8-byte float
5 = SE_STRING_TYPE—Null terminal character array
6 = SE_BLOB_TYPE—Variable length data
7 = SE_DATE_TYPE—Structured time date
8 = SE_SHAPE_TYPE—Shape geometry (SE_SHAPE)
9 = SE_RASTER_TYPE—Raster
10 = SE_XML_TYPE—XML document
11 = SE_INT64_TYPE—8-byte integer
12 = SE_UUID_TYPE—A universal unique ID
13 = SE_CLOB_TYPE—Character variable length data
14 = SE_NSTRING_TYPE—Unicode null terminal character array
15 = SE_NCLOB_TYPE—Unicode character large object
20 = SE_POINT_TYPE—Point user-defined type
21 = SE_CURVE_TYPE—Linestring user-defined type
22 = SE_LINESTRING_TYPE—Linestring user-defined type
23 = SE_SURFACE_TYPE—Polygon user-defined type
24 = SE_POLYGON_TYPE— Polygon user-defined type
25 = SE_GEOMETRYCOLLECTION_TYPE—Multipoint user-defined type
26 = SE_MULTISURFACE_TYPE—Linestring user-defined type
27 = SE_MULTICURVE_TYPE—Linestring user-defined type
28 = SE_MULTIPOINT_TYPE—Multipoint user-defined type
29 = SE_MULTILINESTRING_TYPE—Multilinestring user-defined type
30 = SE_MULTIPOLYGON_TYPE—Multipolygon user-defined type
31 = SE_GEOMETRY_TYPE—Geometry user-defined type
*/
#endregion
switch (item.FieldType)
{
case eFieldType.shpBoolean:
sdeType = 1;
break;
case eFieldType.shpInteger:
sdeType = 2;
break;
case eFieldType.shpLong:
sdeType = 11;
break;
case eFieldType.shpDate:
sdeType = 7;
object_flags = 4;
break;
case eFieldType.shpNumeric:
if (item.FieldDecimal == 0)
{
sdeType = 2;
}
else
{
sdeType = 4;
decimal_digits = "0";
}
break;
case eFieldType.shpSingle:
case eFieldType.shpFloat:
case eFieldType.shpDouble:
sdeType = 4;
decimal_digits = "0";
break;
case eFieldType.shpText:
sdeType = 5;
column_size = item.FieldSize.ToString();
break;
case eFieldType.shpMemo:
sdeType = 13;
break;
default:
sdeType = 5;
column_size = item.FieldSize.ToString();
break;
}
sbInsert.AppendFormat("insert into GDB_ColumnRegistry values('{0}','{1}',{2},'{3}','{4}','',{5},'');",
FeatureLayerName,
item.FieldName,
sdeType,
column_size,
decimal_digits,
object_flags
);
}
//table_name column_name sde_type column_size decimal_digits description object_flags object_id
//Export_Output OBJECTID 2 0 0
//objectid
sbInsert.AppendFormat("insert into GDB_ColumnRegistry values('{0}','OBJECTID',2,0,'','',3,'');",
FeatureLayerName
);
//KReserved
//sbInsert.AppendFormat("insert into GDB_ColumnRegistry values('{0}','KReserved',1,0,'','',0,'');",
// FeatureLayerName
//);
//shape
sbInsert.AppendFormat("insert into GDB_ColumnRegistry values('{0}','Shape',8,'','','',32772,{1});",
FeatureLayerName,
layerid
);
SQLiteCommand cmd = new SQLiteCommand(sbInsert.ToString(), conn);
//StringBuilder sbInsert = new StringBuilder();
//
int resturt = cmd.ExecuteNonQuery();
}
//插入数据
private void InsertDataRecords(SQLiteConnection conn, int srid)
{
SQLiteCommand cmd = new SQLiteCommand(conn);
SpatialDataSource.Open();
try
{
List<ShapeFieldInfo> fieldInfoList = FieldInfos.FindAll(x => x.FieldName == "TBMJ");
if (fieldInfoList == null || fieldInfoList.Count == 0)
{
string sql = string.Format("ALTER TABLE KOFDT ADD COLUMN {0} {1};", "TBMJ", "float64");
cmd.CommandText = sql;
cmd.ExecuteNonQuery();
ShapeFieldInfo pShapeFieldInfo = new ShapeFieldInfo();
pShapeFieldInfo.FieldName = "TBMJ";
pShapeFieldInfo.FieldAlias = "图斑面积";
pShapeFieldInfo.FieldType = eFieldType.shpDouble;
FieldInfos.Add(pShapeFieldInfo);
}
int objectid = 1;
while (!SpatialDataSource.EOF)
{
try
{
InsertOneRecord(conn, cmd, objectid, srid);
if (objectid % 10 == 0)
OnReport(string.Format("已处理{0}条记录!", objectid), objectid);
//if (objectid % 10000 == 0 && ptran != null)
//{
// ptran.Commit();
// ptran = conn.BeginTransaction();
// Console.WriteLine("ptran.Commit()");
//}
objectid++;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
finally
{
SpatialDataSource.Close();
}
}
private void InsertOneRecord(SQLiteConnection conn, SQLiteCommand cmd, int objectid, int srid)
{
DataRow dr = SpatialDataSource.GetNextRecord();
if (dr == null) return;
cmd.CommandText = CreateInsertSql(objectid, srid, dr);
int resturt = cmd.ExecuteNonQuery();
//dr.Delete();
//dr = null;
//cmd.CommandText = "";
}
private string CreateInsertSql(int objectid, int srid, DataRow dr)
{
StringBuilder sbField = new StringBuilder();
sbField.AppendFormat("insert into {0} (objectid,KReserved,shape", FeatureLayerName);
StringBuilder sbValue = new StringBuilder();
if (FeatureSymbol is XSDClass.FSymbol)//面
{
if (dr["shape"].ToString().StartsWith("POLYGON"))
{
sbValue.AppendFormat(" values({0},0,st_polygon ('{1}',{2})", objectid, dr["shape"], srid);
}
else
{
sbValue.AppendFormat(" values({0},0,st_multipolygon ('{1}',{2})", objectid, dr["shape"], srid);
}
}
else if (FeatureSymbol is XSDClass.MSymbol)//点
{
sbValue.AppendFormat(" values({0},0,st_point ('{1}',{2})", objectid, dr["shape"], srid);
}
else if (FeatureSymbol is XSDClass.LSymbol)
{
sbValue.AppendFormat(" values({0},0,st_multilinestring ('{1}',{2})", objectid, dr["shape"], srid);
}
foreach (ShapeFieldInfo item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid"
|| item.FieldName.ToLower() == "shape")
continue;
sbField.AppendFormat(",{0}", item.FieldName);
object value = dr[item.FieldName];
if (item.FieldName == "TBMJ" && value != null && string.IsNullOrEmpty( value.ToString()))
{
try
{
OSGeo.OGR.Geometry geo = OSGeo.OGR.Geometry.CreateFromWkt(dr["Shape"].ToString());
value = geo.GetArea();
}
catch
{ }
}
//sbValue.AppendFormat(",'{0}'", dr[item.FieldName]);
if (value != null && value.ToString().Trim() != string.Empty)
{
if (item.FieldType == eFieldType.shpDate)
{
sbValue.AppendFormat(",{0}", ((DateTime)value).Subtract(new DateTime(1900, 1, 1)).TotalDays + 2415020.5);
}
else
{
sbValue.AppendFormat(",'{0}'", value);
}
}
else
{
//object value = XSDClass.CommonMethod.GetShpFieldTypeDefaultValue(item.FieldType);
//if (value != null)
//{
// sbValue.AppendFormat(",'{0}'", value);
//}
//else
//{
sbValue.Append(",null");
//}
}
/*
ShapeField shapeField = null;
foreach (ShapeField field in ShapeFile.ShapeFields)
{
if (field.FieldName.ToLower() == item.FieldName.ToLower())
{
shapeField = field;
break;
}
}
if (shapeField == null)
continue;
sbField.AppendFormat(",{0}", item.FieldName);
if (shapeField.Value != null)
{
if (item.FieldType == ShapeFiles.eFieldType.shpDate)
{
sbValue.AppendFormat(",{0}", ((DateTime)shapeField.Value).Subtract(new DateTime(1900, 1, 1)).TotalDays + 2415020.5);
}
else
{
sbValue.AppendFormat(",'{0}'", shapeField.Value);
}
}
else
{
object value = XSDClass.CommonMethod.GetShpFieldTypeDefaultValue(item.FieldType);
if (value != null)
{
sbValue.AppendFormat(",'{0}'", value);
}
else
{
sbValue.Append(",null");
}
}*/
}
sbField.Append(")");
sbValue.Append(")");
return sbField.Append(sbValue).ToString();
}
private int GetSeqIDInSqlite_Sequence(SQLiteConnection conn, string tablename)
{
SQLiteCommand cmd = new SQLiteCommand(conn);
//sqlite_sequence
string selectseq = string.Format(@"SELECT seq FROM sqlite_sequence where name='{0}'", tablename);
cmd.CommandText = selectseq;
int currentseq = Convert.ToInt32(cmd.ExecuteScalar());
currentseq++;
string updateseq = string.Format(@"update sqlite_sequence set seq ={0} where name='{1}'", currentseq, tablename);
cmd.CommandText = updateseq;
int resturt = cmd.ExecuteNonQuery();
return currentseq;
}
private int GetGDB_RowidGeneratorsSeq(SQLiteConnection conn, string tablename)
{
SQLiteCommand cmd = new SQLiteCommand(conn);
//GDB_RowidGenerators
string selectseq = string.Format(@"SELECT t.base_id,t.registration_id FROM GDB_RowidGenerators t
left join GDB_TableRegistry p on t.registration_id = p.registration_id
where table_name = '{0}'", tablename);
cmd.CommandText = selectseq;
SQLiteDataReader dr = cmd.ExecuteReader();
dr.Read();
int base_id = Convert.ToInt32(dr.GetValue(0));
object registration_id = dr.GetValue(1);
dr.Close();
dr.Dispose();
int last_id = base_id;
base_id++;
string updateseq = string.Format(@"update GDB_RowidGenerators set base_id={0},last_id ={1} where registration_id='{2}'", base_id, last_id, registration_id);
cmd.CommandText = updateseq;
int resturt = cmd.ExecuteNonQuery();
return base_id;
}
private string GetItemType(SQLiteConnection conn, string typename)
{
//GDB_ItemTypes
//ObjectID UUID Name ParentTypeID
//22 {70737809-852C-4A03-9E22-2CECEA5B9BFA} Feature Class {D4912162-3413-476E-9DA4-2AEFBBC16939}
string selectsql = string.Format("select UUID from GDB_ItemTypes where Name='{0}'", typename);
//SQLiteCommand cmd = new SQLiteCommand(selectsql,conn);
return ExecuteScalar(conn, selectsql).ToString();
}
private string GetGDB_ItemRelationshipTypes(SQLiteConnection conn, string typename)
{
string selectsql = string.Format("select UUID from GDB_ItemRelationshipTypes where Name='{0}'", typename);
//SQLiteCommand cmd = new SQLiteCommand(selectsql, conn);
return ExecuteScalar(conn, selectsql).ToString();
}
private object ExecuteScalar(SQLiteConnection conn, string sqlTxt)
{
using (SQLiteCommand cmd = new SQLiteCommand(sqlTxt, conn))
{
return cmd.ExecuteScalar();
}
}
private void TestGDB_Items()
{
SQLiteConnection conn = new SQLiteConnection(@"Data Source=D:\Users\Administrator\Desktop\杨江川\offlinedata.db");
conn.Open();
try
{
//ObjectID UUID Type Name PhysicalName Path Url Properties Defaults DatasetSubtype1 DatasetSubtype2 DatasetInfo1 DatasetInfo2 Definition Documentation ItemInfo Shape
//8 {A4FC0FCF-5A8D-4924-BB83-D28BDBDB154A} {CD06BC3B-789D-4C51-AAFA-A467912B8965} main.consolidationMapping_GDB MAIN.CONSOLIDATIONMAPPING_GDB \main.consolidationMapping_GDB 1
SQLiteCommand cmd = new SQLiteCommand(conn);
//string sload = string.Format("SELECT load_extension('{0}\\stgeometry_sqlite.dll','SDE_SQL_funcs_init')", Application.StartupPath);
//cmd.CommandText = sload;
//cmd.ExecuteNonQuery();
string insertSqlGDB_Items = @"insert into GDB_Items values(12,'{A4FC0FCF-5A8D-4924-BB83-D28BDBDB154A}',
'{CD06BC3B-789D-4C51-AAFA-A467912B8965}','main.consolidationMapping_GDB2','MAIN.CONSOLIDATIONMAPPING_GDB2',
'\\main.consolidationMapping_GDB2',null,1,null,null,null,null,null,null,null,null,null)";
cmd.CommandText = insertSqlGDB_Items;
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
}
finally
{
conn.Close();
}
}
private DataTable ExecuteQuery(SQLiteConnection conn, string sql)
{
using (SQLiteDataAdapter sda = new SQLiteDataAdapter(sql, conn))
{
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
}
private void Test()
{
string fileName = string.Format("{0}\\{1}.ko", Application.StartupPath, "test");
File.WriteAllBytes(fileName, Properties.Resources.Template);
SQLiteConnection sqlConnection = new SQLiteConnection(@"Data Source=" + fileName);
sqlConnection.Open();
try
{
string sload = string.Format("SELECT load_extension('{0}\\stgeometry_sqlite.dll','SDE_SQL_funcs_init')", Application.StartupPath);
SQLiteCommand cmd = new SQLiteCommand(sload, sqlConnection);
cmd.ExecuteNonQuery();
SQLiteTransaction pTran = sqlConnection.BeginTransaction();
try
{
string stext = "select st_astext (shape) from GDB_Items where name='main.KOFDT'";
cmd.CommandText = stext;
object objShape = cmd.ExecuteScalar();
int oldSrid = 4326;
//改变一下空间参考
XSDClass.ProjectedCoordinateSystem spatialReference = null;
int newSrid = InsertSpatialReference(oldSrid, sqlConnection, out spatialReference);
//GDB_Layers
string sqlUpdateGDB_Layers = string.Format("update GDB_Layers set minx={0},miny={1},maxx={2},maxy={3},srid={4} where table_name='KOFDT'",
-180, -90, 180, 90, newSrid
);
cmd.CommandText = sqlUpdateGDB_Layers;
cmd.ExecuteNonQuery();
//更新一下图形
string updateShape = string.Format("update KOFDT set shape=st_multipolygon ('multipolygon {0}',{1})",
"(((90 45,90 -45,-90 -45,-90 45,90 45)))",
newSrid
);
cmd.CommandText = updateShape;
cmd.ExecuteNonQuery();
//测试增加字段
string alrtsql = "ALTER TABLE KOFDT ADD COLUMN QSDWDM text(19);";
alrtsql += "insert into GDB_ColumnRegistry values('KOFDT','QSDWDM',5,19,null,null,0,null);";
cmd.CommandText = alrtsql;
cmd.ExecuteNonQuery();
//测试三个类的方法是否可用
//Definition
string sql1 = "select Definition from GDB_Items where name='main.KOFDT'";
cmd.CommandText = sql1;
object obj1 = cmd.ExecuteScalar();
XSDClass.DEFeatureClassInfo pDEFeatureClassInfo = XSDClass.DEFeatureClassInfo.FromXml(obj1.ToString());
pDEFeatureClassInfo.GPFieldInfoExs.Add(new XSDClass.GPFieldInfoEx()
{
Name = "QSDWDM",
ModelName = "QSDWDM",
FieldType = XSDClass.esriFieldType.esriFieldTypeString,
IsNullable = true,
AliasName = "QSDWDM"
});
pDEFeatureClassInfo.SpatialReference = spatialReference;
pDEFeatureClassInfo.Extent.XMax = 180;
pDEFeatureClassInfo.Extent.XMin = -180;
pDEFeatureClassInfo.Extent.YMax = 90;
pDEFeatureClassInfo.Extent.YMin = -90;
pDEFeatureClassInfo.Extent.SpatialReference = spatialReference;
string xml1 = pDEFeatureClassInfo.ToXml();
sql1 = string.Format("update GDB_Items set Definition='{0}' where name='main.KOFDT'", xml1);
cmd.CommandText = sql1;
cmd.ExecuteNonQuery();
//ItemInfo
string sql2 = "select ItemInfo from GDB_ServiceItems where datasetname='KOFDT'";
cmd.CommandText = sql2;
object obj2 = cmd.ExecuteScalar();
XSDClass.ItemInfo pItemInfo = XSDClass.ItemInfo.FromJson(obj2.ToString());
pItemInfo.Fields.Add(new XSDClass.FieldWithLength()
{
Alias = "权属单位代码",
Name = "QSDWDM",
Length = 17,
Type = XSDClass.esriFieldType.esriFieldTypeString,
Nullable = true,
Editable = true
});
pItemInfo.Extent.Xmax = 180;
pItemInfo.Extent.Xmin = -180;
pItemInfo.Extent.Ymax = 90;
pItemInfo.Extent.Ymin = -90;
pItemInfo.Extent.SpatialReference = new XSDClass.SpatialReference()
{
LatestWkid = oldSrid,
Wkid = oldSrid
};
string json2 = pItemInfo.ToJson();
sql2 = string.Format("update GDB_ServiceItems set ItemInfo='{0}' where datasetname='KOFDT'", json2);
cmd.CommandText = sql2;
cmd.ExecuteNonQuery();
//AdvancedDrawingInfo
string sql3 = "select AdvancedDrawingInfo from GDB_ServiceItems where datasetname='KOFDT'";
cmd.CommandText = sql3;
object obj3 = cmd.ExecuteScalar();
string json3 = XSDClass.AdvancedDrawingInfo.FromJson(obj3.ToString()).ToJson();
sql3 = string.Format("update GDB_ServiceItems set AdvancedDrawingInfo='{0}' where datasetname='KOFDT'", json3);
cmd.CommandText = sql3;
cmd.ExecuteNonQuery();
pTran.Commit();
}
catch (Exception ex)
{
pTran.Rollback();
throw;
}
finally
{
pTran.Dispose();
}
}
finally
{
sqlConnection.Close();
}
}
private int ChangeSpatialRef(SQLiteConnection conn, int srid, out XSDClass.ProjectedCoordinateSystem spatialReference)
{
try
{
//XSDClass.ProjectedCoordinateSystem spatialReference = null;
int newSrid = InsertSpatialReference(srid, conn, out spatialReference);
//GDB_Layers
string sqlUpdateGDB_Layers = string.Format("update GDB_Layers set minx={0},miny={1},maxx={2},maxy={3},srid={4} where table_name='{5}'",
SpatialDataSource.Extent.XMin, SpatialDataSource.Extent.YMin, SpatialDataSource.Extent.XMax, SpatialDataSource.Extent.YMax,
newSrid, FeatureLayerName
);
SQLiteCommand cmd = new SQLiteCommand(sqlUpdateGDB_Layers, conn);
int result = cmd.ExecuteNonQuery();
return newSrid;
}
catch (Exception ex)
{
OnReport(string.Format("改变空间参考失败!原因:{0}", ex), -1);
spatialReference = null;// new XSDClass.ProjectedCoordinateSystem();
return -1;
}
}
private void AddFields(SQLiteConnection conn)
{
try
{
SQLiteCommand cmd = new SQLiteCommand(conn);
StringBuilder sqlAlterTable = new StringBuilder();
foreach (var item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
sqlAlterTable.AppendFormat("ALTER TABLE KOFDT ADD COLUMN {0} {1};", item.FieldName, XSDClass.CommonMethod.GetCreateSqlTypeFormShapeField(item));
int sdeType = 5;
string column_size = "0";
int object_flags = 0;
//string object_id = "";
string decimal_digits = "";
switch (item.FieldType)
{
case eFieldType.shpBoolean:
sdeType = 1;
break;
case eFieldType.shpInteger:
sdeType = 2;
break;
case eFieldType.shpLong:
sdeType = 11;
break;
case eFieldType.shpDate:
sdeType = 7;
object_flags = 4;
break;
case eFieldType.shpNumeric:
if (item.FieldDecimal == 0)
{
sdeType = 2;
}
else
{
sdeType = 4;
decimal_digits = "0";
}
break;
case eFieldType.shpSingle:
case eFieldType.shpFloat:
case eFieldType.shpDouble:
sdeType = 4;
decimal_digits = "0";
break;
case eFieldType.shpText:
sdeType = 5;
column_size = item.FieldSize.ToString();
break;
case eFieldType.shpMemo:
sdeType = 13;
break;
default:
sdeType = 5;
column_size = item.FieldSize.ToString();
break;
}
sqlAlterTable.AppendFormat("insert into GDB_ColumnRegistry values('{0}','{1}',{2},'{3}','{4}','',{5},'');",
FeatureLayerName,
item.FieldName,
sdeType,
column_size,
decimal_digits,
object_flags
);
}
cmd.CommandText = sqlAlterTable.ToString();
int result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
OnReport(string.Format("字段添加失败!原因:{0}", ex),-1);
}
}
private void UpdateGDB_Items_Definition(SQLiteConnection conn, XSDClass.ProjectedCoordinateSystem spatialReference)
{
//Definition
SQLiteCommand cmd = new SQLiteCommand(conn);
string sql1 =string.Format( "select Definition from GDB_Items where name='main.{0}'",FeatureLayerName);
cmd.CommandText = sql1;
object obj1 = cmd.ExecuteScalar();
XSDClass.DEFeatureClassInfo pDEFeatureClassInfo = XSDClass.DEFeatureClassInfo.FromXml(obj1.ToString());
//增加字段
foreach (var item in this.FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
pDEFeatureClassInfo.GPFieldInfoExs.Add(new XSDClass.GPFieldInfoEx()
{
Name = item.FieldName,
ModelName = item.FieldName,
FieldType = XSDClass.CommonMethod.ConvertFromShpFieldType(item),
IsNullable = true,
AliasName = item.FieldAlias
});
}
pDEFeatureClassInfo.SpatialReference = spatialReference;
pDEFeatureClassInfo.Extent.XMax = SpatialDataSource.Extent.XMax;
pDEFeatureClassInfo.Extent.XMin = SpatialDataSource.Extent.XMin;
pDEFeatureClassInfo.Extent.YMax = SpatialDataSource.Extent.YMax;
pDEFeatureClassInfo.Extent.YMin = SpatialDataSource.Extent.YMin;
pDEFeatureClassInfo.Extent.SpatialReference = spatialReference;
string xml1 = pDEFeatureClassInfo.ToXml();
sql1 = string.Format("update GDB_Items set Definition='{0}' where name='main.{1}'", xml1, FeatureLayerName);
cmd.CommandText = sql1;
int resturt = cmd.ExecuteNonQuery();
}
private void UpdateGDB_ServiceItems_ItemInfo(SQLiteConnection conn, int srid)
{
try
{
SQLiteCommand cmd = new SQLiteCommand(conn);
string sql2 = string.Format("select ItemInfo from GDB_ServiceItems where datasetname='{0}'", FeatureLayerName);
cmd.CommandText = sql2;
object obj2 = cmd.ExecuteScalar();
XSDClass.ItemInfo pItemInfo = XSDClass.ItemInfo.FromJson(obj2.ToString());
foreach (ShapeFieldInfo item in FieldInfos)
{
if (item.FieldName.ToLower() == "objectid")
continue;
XSDClass.esriFieldType fieldType = XSDClass.CommonMethod.ConvertFromShpFieldType(item);
Kingo.Mobile.Shape2KOTool.XSDClass.Field field = null;
if (fieldType == XSDClass.esriFieldType.esriFieldTypeString)
{
field = new XSDClass.FieldWithLength()
{
Length = item.FieldSize
};
}
else
{
field = new XSDClass.FieldNomal();
}
field.Alias = item.FieldAlias;
field.Editable = true;
field.Name = item.FieldName;
field.Nullable = true;
field.Type = fieldType;
if (pItemInfo.Fields.Find(p => p.Name == item.FieldName) == null)
pItemInfo.Fields.Add(field);
}
pItemInfo.Extent.Xmax = this.SpatialDataSource.Extent.XMax;
pItemInfo.Extent.Xmin = this.SpatialDataSource.Extent.XMin;
pItemInfo.Extent.Ymax = this.SpatialDataSource.Extent.YMax;
pItemInfo.Extent.Ymin = this.SpatialDataSource.Extent.YMin;
pItemInfo.Extent.SpatialReference = new XSDClass.SpatialReference()
{
LatestWkid = srid,
Wkid = srid,
wkt = pItemInfo.Extent.SpatialReference.wkt
};
pItemInfo.MaxScale = this.MaxScale;
pItemInfo.MinScale = this.MinScale;
if (LabelingInfo != null)
{
pItemInfo.DrawingInfo.LabelingInfo = new List<XSDClass.LabelingInfo>();
pItemInfo.DrawingInfo.LabelingInfo.Add(LabelingInfo);
}
//设置显示字段
pItemInfo.DisplayField = this.DisplayField;
//pItemInfo.DrawingInfo
//如果是唯一值渲染 则还要赋值ItemInfo中的types字段和typeIdField字段
if (this.Render is XSDClass.UniqueValueRenderer)
{
XSDClass.UniqueValueRenderer pUniqueValueRenderer = this.Render as XSDClass.UniqueValueRenderer;
pItemInfo.TypeIdField = pUniqueValueRenderer.Field1;
if (this.EncryptData)
{
//加密唯一值填充的的code值,如果当前字段是字符串
//pUniqueValueRenderer.Field1
cmd.CommandText = string.Format("select {0} from {1} where 1=0", pItemInfo.TypeIdField, this.FeatureLayerName);
using (SQLiteDataAdapter ada = new SQLiteDataAdapter(cmd))
{
DataSet ds = new DataSet();
ada.Fill(ds);
if (ds != null && ds.Tables.Count > 0)
{
if (ds.Tables[0].Columns[0].DataType.Equals(typeof(string)))
{
//加密字符串
foreach (var item in pUniqueValueRenderer.UniqueValueInfos)
{
item.Value = this.EnCode(item.Value);
}
}
}
}
}
}
//设置iteminfo的DrawingInfo样式
// pItemInfo.DrawingInfo.Renderer = this.Render;
pItemInfo.DrawingInfo.Renderer = this.ItemInfoRender;
//pItemInfo.DrawingInfo.LabelingInfo = null;
XSDClass.CommonMethod.BuildItemInfoTypes(pItemInfo);
string json2 = pItemInfo.ToJson();
sql2 = string.Format("update GDB_ServiceItems set ItemInfo='{0}' where datasetname='{1}'", json2, FeatureLayerName);
cmd.CommandText = sql2;
int result = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
OnReport(string.Format("修改GDB_ServiceItems的ItemInfo字段失败!原因:{0}", ex),-1);
}
}
private void UpdateGDB_ServiceItems_AdvancedDrawingInfo(SQLiteConnection conn)
{
SQLiteCommand cmd = new SQLiteCommand(conn);
string sql3 =string.Format( "select AdvancedDrawingInfo from GDB_ServiceItems where datasetname='{0}'",FeatureLayerName);
cmd.CommandText = sql3;
object obj3 = cmd.ExecuteScalar();
XSDClass.AdvancedDrawingInfo pAdvancedDrawingInfo = XSDClass.AdvancedDrawingInfo.FromJson(obj3.ToString());
//修改AdvancedDrawingInfo的样式
pAdvancedDrawingInfo.DrawingInfo.Renderer = XSDClass.CommonMethod.GetAdvDrawingInfoRender(this.Render);
if (LabelingInfo != null)
{
pAdvancedDrawingInfo.DrawingInfo.LabelingInfo = new List<XSDClass.LabelingInfo>();
pAdvancedDrawingInfo.DrawingInfo.LabelingInfo.Add(LabelingInfo);
}
string json3 = pAdvancedDrawingInfo.ToJson();
sql3 = string.Format("update GDB_ServiceItems set AdvancedDrawingInfo='{0}' where datasetname='{1}'", json3,FeatureLayerName);
cmd.CommandText = sql3;
int resturt = cmd.ExecuteNonQuery();
}
private void UpdateGDB_ServiceItems_AdvancedDrawingInfoNew(SQLiteConnection conn)
{
try
{
SQLiteCommand cmd = new SQLiteCommand(conn);
AdvancedDrawimgInfoManager ad = new AdvancedDrawimgInfoManager();
string json3 = ad.GetRenderer(this.Render, LabelingInfo);
//string json3 = ad.GetRenderer(this.Render, null);
string sql3 = string.Format("update GDB_ServiceItems set AdvancedDrawingInfo='{0}' where datasetname='{1}'", json3, FeatureLayerName);
cmd.CommandText = sql3;
int resturt = cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
OnReport(string.Format("修改GDB_ServiceItems的AdvancedDrawingInfo字段失败!原因:{0}", ex),-1);
}
}
System.Threading.Thread doWorkThread = null;
public void DoWork()
{
//CreateLayerUdp();
doWorkThread = new System.Threading.Thread(new System.Threading.ThreadStart(CreateLayerUdp));
doWorkThread.IsBackground = true;
doWorkThread.Priority = System.Threading.ThreadPriority.Highest;
doWorkThread.Start();
}
private void LoadSqlliteExtension(SQLiteConnection connectiont, string path)
{
try
{
string extensionPath = path;// string.Format("{0}\\stgeometry_sqlite.dll", @HostingEnvironment.ApplicationPhysicalPath + "bin");
connectiont.LoadExtension(extensionPath, "SDE_SQL_funcs_init");
}
catch (Exception ex)
{
throw ex;
}
}
public void CreateLayerUdp()
{
int wkid = this.WKID;
//string fileName = string.Format("{0}\\{1}.ko", Application.StartupPath, FeatureLayerName);
if (!System.IO.File.Exists(OutputFileName))
{
if (FeatureSymbol is XSDClass.FSymbol)
{
if (wkid == 0)
{
//临时处理宁波独立坐标系
File.WriteAllBytes(OutputFileName, Properties.Resources.TemplateNB);
}
else
{
File.WriteAllBytes(OutputFileName, Properties.Resources.Template);
}
}
else if (FeatureSymbol is XSDClass.MSymbol)
{
File.WriteAllBytes(OutputFileName, Properties.Resources.TemplatePoint);
}
else if (FeatureSymbol is XSDClass.LSymbol)
{
File.WriteAllBytes(OutputFileName, Properties.Resources.TemplateLine);
}
}
//File.Delete(fileName);
//File.WriteAllBytes(fileName, Properties.Resources.Template);
SQLiteConnection sqlConnection = new SQLiteConnection(@"Data Source=" + OutputFileName);
sqlConnection.Open();
try
{
string dllPath = Application.StartupPath + "\\stgeometry_sqlite.dll";
if (!File.Exists(dllPath))
{
dllPath = Environment.SystemDirectory + "\\stgeometry_sqlite.dll";
}
if (!File.Exists(dllPath))
{
//throw new Exception("未能加载sql扩展程序集,请检查!");
OnReport(string.Format( "未能加载sql扩展程序集,请检查软件运行目录下是否存在'{0}'!", "stgeometry_sqlite.dll"),-1);
return;
}
string sload = string.Format("SELECT load_extension('{0}','SDE_SQL_funcs_init')", dllPath);
LoadSqlliteExtension(sqlConnection, dllPath);
//SQLiteCommand cmdload = new SQLiteCommand(sload, sqlConnection);
//cmdload.ExecuteNonQuery();
SQLiteCommand cmdload = new SQLiteCommand(sqlConnection);
SQLiteTransaction pTran = sqlConnection.BeginTransaction();
try
{
int nSrid = 0;
XSDClass.ProjectedCoordinateSystem spatialReference = null;
if (wkid == 0)
{
nSrid = 300001;
}
else
{
//改变空间参考
nSrid = ChangeSpatialRef(sqlConnection, wkid, out spatialReference);
//增加字段
//修改GDB_Items的Definition字段
UpdateGDB_Items_Definition(sqlConnection, spatialReference);
}
AddFields(sqlConnection);
//修改GDB_ServiceItems的ItemInfo字段
UpdateGDB_ServiceItems_ItemInfo(sqlConnection, wkid);
//修改GDB_ServiceItems的AdvancedDrawingInfo字段
UpdateGDB_ServiceItems_AdvancedDrawingInfoNew(sqlConnection);
//清除原有数据
// cmdload.CommandText = "delete from KOFDT";
cmdload.CommandText = String.Format("delete from {0}", FeatureLayerName);
int resturt = cmdload.ExecuteNonQuery();
OnReport("更新元数据完成");
//开始插入数据
InsertDataRecords(sqlConnection, nSrid);
pTran.Commit();
if (this.EncryptData)
{
EncryptTable();
}
if (sqlConnection != null)
{
sqlConnection.Close();
sqlConnection.Dispose();
sqlConnection = null;
}
OnReport(string.Format("插入数据完成!"));
}
catch (Exception ex)
{
pTran.Rollback();
OnReport(string.Format("制作失败!原因:{0}", ex.Message));
//throw;
}
finally
{
pTran.Dispose();
}
}
catch (Exception ex)
{
OnReport(string.Format("制作失败!原因:{0}", ex.Message));
}
finally
{
if (sqlConnection != null)
{
sqlConnection.Close();
sqlConnection.Dispose();
sqlConnection = null;
}
GC.Collect();
}
}
public void Dispose()
{
//if (this.ShapeFile != null)
//{
// try
// {
// this.ShapeFile.CloseShape();
// this.ShapeFile.Dispose();
// }
// catch { }
//}
try
{
if (this.SpatialDataSource != null)
{
this.SpatialDataSource.Close();
}
if (this.doWorkThread != null)
{
try
{
this.doWorkThread.Abort();
}
catch { }
finally
{
this.doWorkThread = null;
}
}
}
catch
{
}
finally
{
GC.Collect();
}
}
private void OnReport(string msg, int count = 0)
{
if (Report != null)
Report(msg, count);
}
private void EncryptTable()
{
//string sConnStringSQLite = string.Format("Data Source={0}\\{1}.ko", Application.StartupPath, FeatureLayerName);
string sConnStringSQLite = string.Format("Data Source={0}", OutputFileName, FeatureLayerName);
string item = FeatureLayerName;
try
{
OnReport("开始加密表:" + item);
string sql = string.Format("select * from {0} where 1=0", item);
DataSet ds = SQLiteHelper.ExecuteDataSet(sConnStringSQLite, sql, CommandType.Text);
if (ds != null && ds.Tables.Count > 0)
{
DataTable dt = ds.Tables[0];
StringBuilder sqlSelect = new StringBuilder("select rowid");
StringBuilder sqlUpdata = new StringBuilder();
sqlUpdata.AppendFormat("update {0} set ", item);
int nOtherFields = 0;
foreach (DataColumn dc in dt.Columns)
{
if (dc.DataType.Equals(typeof(string)))
{
sqlSelect.AppendFormat(",{0}", dc.ColumnName);
sqlUpdata.AppendFormat("{0}=?,", dc.ColumnName);
nOtherFields++;
}
}
if (nOtherFields == 0)
return;
sqlSelect.AppendFormat(" from {0}", item);
sqlUpdata.Replace(",", " where rowid=?", sqlUpdata.Length - 1, 1);
//获取所有数据集
DataSet dsRecords = SQLiteHelper.ExecuteDataSet(sConnStringSQLite, sqlSelect.ToString(), CommandType.Text);
if (ds == null || ds.Tables.Count == 0 || dsRecords.Tables[0].Rows.Count == 0)
{
OnReport("表中无记录!", -1);
return;
}
DataTable dtRecords = dsRecords.Tables[0];
OnReport(string.Format("共{0}条记录需要加密", dtRecords.Rows.Count));
SQLiteConnection liteConn = new SQLiteConnection(sConnStringSQLite);
liteConn.Open();
try
{
SQLiteTransaction trans = liteConn.BeginTransaction();
try
{
SQLiteCommand cmdlite = new SQLiteCommand(sqlUpdata.ToString(), liteConn);
List<SQLiteParameter> parameters = new List<SQLiteParameter>();
for (int i = 0; i <= nOtherFields; i++)
{
parameters.Add(cmdlite.CreateParameter());
}
cmdlite.Parameters.AddRange(parameters.ToArray());
for (int i = 0; i < dtRecords.Rows.Count; i++)
{
DataRow dr = dtRecords.Rows[i];
foreach (DataColumn dc in dtRecords.Columns)
{
if (dc.Ordinal == 0 )
{
parameters[parameters.Count - 1].Value = dr[dc];
}
else if (dc.ColumnName.ToUpper() == this.LayerLabelName.ToUpper())
{
parameters[dc.Ordinal - 1].Value = dr[dc];
}
else
{
parameters[dc.Ordinal - 1].Value = EnCode(dr[dc]);
}
}
int resturt = cmdlite.ExecuteNonQuery();
if (i % 10000 == 0)
{
OnReport(string.Format("已加密{0}/{1}", i + 1, dtRecords.Rows.Count));
}
}
trans.Commit();
OnReport("数据已全部加密成功!", -1);
}
catch(Exception ex)
{
trans.Rollback();
throw;
}
finally
{
trans.Dispose();
}
}
finally
{
liteConn.Close();
liteConn.Dispose();
GC.Collect();
}
}
OnReport(string.Format("加密表:{0}结束。", item), -1);
}
catch (Exception ex)
{
OnReport(string.Format("加密表:{0}出现异常,异常信息为:{1}。", item, ex), -1);
}
}
private string EnCode(object value)
{
if (value == null)
return "";
string str = value.ToString();
if (string.IsNullOrEmpty(str))
return "";
string outStr = "";
foreach (char item in str)
{
outStr += (char)(item + 22);
}
return outStr;
}
private string DeCode(string str)
{
if (string.IsNullOrEmpty(str))
return "";
string outStr = "";
foreach (char item in str)
{
outStr += (char)(item - 22);
}
return outStr;
}
}
}