Browse Source

implement csv getData

master
jkpete 9 months ago
parent
commit
5315e625f6
  1. 76
      Example/UsingTest/Script/EGSaveTest.cs
  2. 43
      addons/EGFramework/Module/SaveTools/EGCsvSave.cs
  3. 26
      addons/EGFramework/Module/SaveTools/EGSqlite.cs

76
Example/UsingTest/Script/EGSaveTest.cs

@ -20,10 +20,24 @@ namespace EGFramework.Examples.Test{ @@ -20,10 +20,24 @@ namespace EGFramework.Examples.Test{
// // this.EGSave().SetObject(CardPath1,"Customer3",new Customer() { Name = "Terry" });
// Customer customer = this.EGSave().GetObject<Customer>(CardPath1,"Customer3");
// GD.Print("ReadName is "+customer.Name);
EGCsvSave csvSave = new EGCsvSave();
csvSave.InitSaveFile("SaveData/TestCsv.csv");
string[] group = {"7","MyTestData"};
csvSave.WriteLine(group);
Customer testData = csvSave.GetData<Customer>("",1);
GD.Print("Name = "+testData.Name +" || ID = "+testData.Id);
// GD.Print(typeof(Customer));
// Type type = typeof(Customer);
// foreach(PropertyInfo property in type.GetProperties()){
// GD.Print(property.Name);
// CsvParamAttribute csvParam = property.GetCustomAttribute<CsvParamAttribute>();
// if(csvParam != null){
// GD.Print("["+csvParam._name+"]");
// }
// }
// foreach(FieldInfo property in type.GetFields()){
// GD.Print(property.Name);
// }
}
public void TestSqlite(){
@ -38,62 +52,6 @@ namespace EGFramework.Examples.Test{ @@ -38,62 +52,6 @@ namespace EGFramework.Examples.Test{
// Godot.GD.Print(properties.Count() + " Readed ");
}
public void TestLiteDB(){
// 打开数据库 (如果不存在自动创建)
using(var db = new LiteDatabase("SaveData/DefaultLiteDBData.db"))
{
// 获取一个集合 (如果不存在创建)
LiteCollection<Customer> col = (LiteCollection<Customer>)db.GetCollection<Customer>("customers");
GD.Print(col);
// // 创建新顾客实例
// var customer = new Customer
// {
// Id = 200,
// Name = "Alexander King",
// Phones = new string[] { "8000-0000", "9000-0000" },
// IsActive = true
// };
// // 插入新顾客文档 (Id 自增)
// for (int i = 0; i < 10000; i++)
// {
// customer.Id ++;
// col.Insert(customer);
// }
// // 更新集合中的一个文档
// customer.Name = "Joana Doe";
// col.Update(customer);
// // 使用文档的 Name 属性为文档建立索引
// col.EnsureIndex(x => x.Name);
// 使用 LINQ 查询文档
// var results = col.Find(x => x.Name.StartsWith("Al"));
// GD.Print("Find:"+results.Count());
// string ids = "";
// foreach(var item in results){
// ids += "["+item.Id.ToString()+"]";
// }
// GD.Print(ids);
// // 让我们创建在电话号码字段上创建一个索引 (使用表达式). 它是一个多键值索引
// //col.EnsureIndex(x => x.Phones, "$.Phones[*]");
// col.EnsureIndex(x => x.Phones);
// // 现在我们可以查询电话号码
// var r = col.FindOne(x => x.Phones.Contains("8888-5555"));\
// Test Other
// ILiteCollection<SqliteBackpackItem> col = db.GetCollection<SqliteBackpackItem>("SqliteBackpackItem");
// var item = new SqliteBackpackItem{
// ItemID = 10,
// ItemCount = 1,
// BackpackID = 1,
// };
// for (int i = 0; i < 100; i++)
// {
// col.Insert(item);
// }
}
}
}
public struct SqliteBackpackItem{
public int Id { get; set; }
@ -104,7 +62,9 @@ namespace EGFramework.Examples.Test{ @@ -104,7 +62,9 @@ namespace EGFramework.Examples.Test{
public class Customer
{
[CsvParam("ID")]
public int Id { get; set; }
[CsvParam("Name")]
public string Name { get; set; }
public string[] Phones { get; set; }
public bool IsActive { get; set; }

43
addons/EGFramework/Module/SaveTools/EGCsvSave.cs

@ -5,6 +5,7 @@ using System.IO; @@ -5,6 +5,7 @@ using System.IO;
using System.Linq;
using System.Linq.Expressions;
using System.Threading.Tasks;
using Godot;
namespace EGFramework
{
@ -13,7 +14,7 @@ namespace EGFramework @@ -13,7 +14,7 @@ namespace EGFramework
public Encoding StringEncoding { set; get; } = Encoding.UTF8;
private string DefaultPath { set; get; }
private List<string[]> CsvDataBlock { get; set; }
private string[] CsvDataHeader;
private Dictionary<string,int> CsvDataHeader = new Dictionary<string,int>();
private string ReadText { set; get; }
public void InitSaveFile(string path)
{
@ -47,8 +48,8 @@ namespace EGFramework @@ -47,8 +48,8 @@ namespace EGFramework
FileStream fileStream = File.Create(path);
string writeText = "";
string headerText = "";
foreach(string headers in CsvDataHeader){
headerText+=headers + ",";
foreach(string headStr in CsvDataHeader.Keys){
headerText+=headStr + ",";
}
headerText = headerText.Remove(headerText.Length-1,1);
writeText = headerText + "\n";
@ -74,10 +75,15 @@ namespace EGFramework @@ -74,10 +75,15 @@ namespace EGFramework
}
}
public List<string[]> GetCSVDataBlockFromText(string text,out string[] header){
public List<string[]> GetCSVDataBlockFromText(string text,out Dictionary<string,int> header){
List<string[]> csvBlock = new List<string[]>();
string[] lineData = text.Split('\n');
header = lineData[0].Split(',');
string[] headerStr = lineData[0].Split(',');
header = new Dictionary<string,int>();
for (int i = 0; i < headerStr.Length; i++)
{
header.Add(headerStr[i],i);
}
for (int lineID = 0; lineID < lineData.Length; lineID++)
{
if (lineID!=0){
@ -106,7 +112,28 @@ namespace EGFramework @@ -106,7 +112,28 @@ namespace EGFramework
}
public TData GetData<TData>(string dataKey, object id) where TData : new()
{
throw new NotImplementedException();
TData data = new TData();
int dataID = 0;
if(id.GetType()==typeof(int)){
dataID = (int)id;
}else if(int.TryParse(id.ToString() ,out dataID)){
throw new Exception("Id cannot be convert to int!");
}
if(dataID>=CsvDataBlock.Count()){
throw new IndexOutOfRangeException("Parameter index is out of range.");
}
foreach(PropertyInfo property in data.GetType().GetProperties()){
CsvParamAttribute csvParam = property.GetCustomAttribute<CsvParamAttribute>();
if(csvParam != null && CsvDataHeader.ContainsKey(csvParam._name)){
string valueStr = CsvDataBlock[dataID][CsvDataHeader[csvParam._name]];
if(property.PropertyType==typeof(string)){
property.SetValue(data,valueStr);
}else{
property.SetValue(data,Convert.ChangeType(valueStr,property.PropertyType));
}
}
}
return data;
}
public IEnumerable<TData> GetAll<TData>(string dataKey) where TData : new()
{
@ -119,9 +146,11 @@ namespace EGFramework @@ -119,9 +146,11 @@ namespace EGFramework
}
}
[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field)]
public class CsvParamAttribute: Attribute{
public string _name { set; get; }
public CsvParamAttribute(string name){
this._name = name;
}
}
}

26
addons/EGFramework/Module/SaveTools/EGSqlite.cs

@ -80,12 +80,12 @@ namespace EGFramework{ @@ -80,12 +80,12 @@ namespace EGFramework{
{
string sqlCommand = "CREATE TABLE " + typeof(TData).Name;
sqlCommand += "(\"ID\" INTEGER NOT NULL UNIQUE,";
var properties = typeof(TData).GetFields();
var properties = typeof(TData).GetProperties();
Godot.GD.Print(properties.Count() + " Readed ");
foreach(var property in properties){
if(property.FieldType == typeof(int) || property.FieldType == typeof(bool) || property.FieldType.IsEnum){
if(property.PropertyType == typeof(int) || property.PropertyType == typeof(bool) || property.PropertyType.IsEnum){
sqlCommand += "\"" + property.Name + "\" INTEGER" + " NOT NULL,";
}else if(property.FieldType == typeof(double) || property.FieldType == typeof(float)){
}else if(property.PropertyType == typeof(double) || property.PropertyType == typeof(float)){
sqlCommand += "\"" + property.Name + "\" REAL" + " NOT NULL,";
}
else{
@ -135,15 +135,15 @@ namespace EGFramework{ @@ -135,15 +135,15 @@ namespace EGFramework{
try
{
string sqlCommand = "INSERT INTO " + typeof(TData).Name;
var properties = typeof(TData).GetFields();
var properties = typeof(TData).GetProperties();
Dictionary<string,object> dataParams = new Dictionary<string, object>();
foreach(var property in properties){
dataParams.Add(property.Name,property.GetValue(data));
if(property.FieldType==typeof(bool) || property.FieldType.IsEnum){
if(property.PropertyType==typeof(bool) || property.PropertyType.IsEnum){
// If property is bool type , save data to data base should be 0 or 1 instead of false or true;
// If property is Enum type , then transform data to int;
dataParams[property.Name] = System.Convert.ToInt32(dataParams[property.Name]);
}else if(property.FieldType.IsClass || property.FieldType.IsValueType && !property.FieldType.IsPrimitive && property.FieldType != typeof(string)){
}else if(property.PropertyType.IsClass || property.PropertyType.IsValueType && !property.PropertyType.IsPrimitive && property.PropertyType != typeof(string)){
dataParams[property.Name] = JsonConvert.SerializeObject(dataParams[property.Name]);
}
}
@ -188,23 +188,23 @@ namespace EGFramework{ @@ -188,23 +188,23 @@ namespace EGFramework{
string sqlCommand = "SELECT * FROM " + typeof(TData).Name;
SqliteCommand selectCommand = new SqliteCommand(sqlCommand,SqliteConn);
SqliteDataReader reader = selectCommand.ExecuteReader();
var properties = typeof(TData).GetFields();
var properties = typeof(TData).GetProperties();
while (reader.Read())
{
TData dataRow = new TData();
foreach(var property in properties){
if(property.FieldType == reader[property.Name].GetType()){
if(property.PropertyType == reader[property.Name].GetType()){
property.SetValue(dataRow,reader[property.Name]);
}else if(property.FieldType.IsEnum){
object propertyEnum = Enum.Parse(property.FieldType,reader[property.Name].ToString());
}else if(property.PropertyType.IsEnum){
object propertyEnum = Enum.Parse(property.PropertyType,reader[property.Name].ToString());
property.SetValue(dataRow,propertyEnum);
}
else if(property.FieldType.IsPrimitive) {
object propertyObject = System.Convert.ChangeType(reader[property.Name],property.FieldType);
else if(property.PropertyType.IsPrimitive) {
object propertyObject = System.Convert.ChangeType(reader[property.Name],property.PropertyType);
property.SetValue(dataRow,propertyObject);
}else{
object classObject = JsonConvert.DeserializeObject(reader[property.Name].ToString(),property.FieldType);
object classObject = JsonConvert.DeserializeObject(reader[property.Name].ToString(),property.PropertyType);
property.SetValue(dataRow,classObject);
}
}

Loading…
Cancel
Save