diff --git a/src/SharpConnect.Data/Accessories/IndentTextWriter.cs b/src/SharpConnect.Data/Accessories/IndentTextWriter.cs deleted file mode 100644 index e3faa3e..0000000 --- a/src/SharpConnect.Data/Accessories/IndentTextWriter.cs +++ /dev/null @@ -1,109 +0,0 @@ -//MIT, 2016-2017, EngineKit -using System.Text; -namespace SharpConnect.Data -{ - class IndentTextWriter - { - StringBuilder stBuilder; - int indentLevel; - const string defaultTabString = "\t"; - string newLine = "\r\n"; - public IndentTextWriter(StringBuilder stBuilder) - { - this.stBuilder = stBuilder; - } - public StringBuilder InnterStringBuilder - { - get - { - return this.stBuilder; - } - } - public void Append(string str) - { - stBuilder.Append(str); - } - public void Append(char c) - { - stBuilder.Append(c); - } - public void OutputTabs() - { - for (int i = 0; i < indentLevel; i++) - { - stBuilder.Append(defaultTabString); - } - } - - public void CloseLine() - { - stBuilder.Append(newLine); - OutputTabs(); - } - - public void CloseLine(string str) - { - - stBuilder.Append(str); - stBuilder.Append(newLine); - OutputTabs(); - } - - public void CloseLineFinal(string str) - { - stBuilder.Append(str); - - } - public void CloseLine(char c) - { - - stBuilder.Append(c); - stBuilder.Append(newLine); - OutputTabs(); - } - - public void CloseLineNoTab(string str) - { - stBuilder.Append(str); - stBuilder.Append(newLine); - } - public void CloseLineNoTab() - { - stBuilder.Append(newLine); - } - - public void CloseLineNoTab(char c) - { - stBuilder.Append(c); - stBuilder.Append(newLine); - } - - - public string NewLine - { - get - { - return newLine; - } - set - { - newLine = value; - } - } - - public int IndentLevel - { - get - { - return indentLevel; - } - set - { - indentLevel = value; - } - } - - - } - -} \ No newline at end of file diff --git a/src/SharpConnect.Data/Accessories/SimpleBinaryWriter.cs b/src/SharpConnect.Data/Accessories/SimpleBinaryWriter.cs deleted file mode 100644 index 8202270..0000000 --- a/src/SharpConnect.Data/Accessories/SimpleBinaryWriter.cs +++ /dev/null @@ -1,766 +0,0 @@ -////This contains some code from dotnet framework reference source -////with MIT license -////------------------------------------- -////2016,MIT EngineKit -////and -////The MIT License(MIT) -////Copyright(c) Microsoft Corporation -////------------------------------------- - -//using System; -//using System.Text; -//using System.IO; -//namespace SharpConnect.Data -//{ - -// public class SimpleBinaryWriter -// { -// Stream outStream = null; -// byte[] buffer = new byte[16]; -// public SimpleBinaryWriter(Stream stream) -// { -// this.outStream = stream; -// } - -// public void Flush() -// { -// this.outStream.Flush(); -// } -// public void Close() -// { - -// outStream.Flush(); -// outStream = null; -// buffer = null; -//#if DEBUG - -// if (dbug_EnableLog) -// { -// dbugClose(); -// } -//#endif -// } - -// public void Write(byte[] buffer) -// { - -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (byte[" + buffer.Length + "]:"); -// } -//#endif -// outStream.Write(buffer, 0, buffer.Length); -// } - -// public void Write(char[] utf8Char) -// { -// Write(Encoding.UTF8.GetBytes(utf8Char)); -// } -// public void Write(int data) -// { - -// this.buffer[0] = (byte)data; -// this.buffer[1] = (byte)(data >> 8); -// this.buffer[2] = (byte)(data >> 16); -// this.buffer[3] = (byte)(data >> 24); - -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (int):" + data); -// } -//#endif - -// outStream.Write(this.buffer, 0, 4); -// } -// public void Write(uint data) -// { -// this.buffer[0] = (byte)data; -// this.buffer[1] = (byte)(data >> 8); -// this.buffer[2] = (byte)(data >> 16); -// this.buffer[3] = (byte)(data >> 24); -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (uint):" + data); -// } -//#endif - -// outStream.Write(this.buffer, 0, 4); -// } -// public unsafe void Write(double value) -// { -// ulong num = *((ulong*)&value); -// this.buffer[0] = (byte)num; -// this.buffer[1] = (byte)(num >> 8); -// this.buffer[2] = (byte)(num >> 0x10); -// this.buffer[3] = (byte)(num >> 0x18); -// this.buffer[4] = (byte)(num >> 0x20); -// this.buffer[5] = (byte)(num >> 40); -// this.buffer[6] = (byte)(num >> 0x30); -// this.buffer[7] = (byte)(num >> 0x38); - -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (double):" + value); -// } -//#endif - -// this.outStream.Write(this.buffer, 0, 8); -// } -// public unsafe void Write(float value) -// { -// uint num = *((uint*)&value); -// this.buffer[0] = (byte)num; -// this.buffer[1] = (byte)(num >> 8); -// this.buffer[2] = (byte)(num >> 0x10); -// this.buffer[3] = (byte)(num >> 0x18); -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (float):" + value); -// } -//#endif -// this.outStream.Write(this.buffer, 0, 4); -// } -// public void Write(long data) -// { -// this.buffer[0] = (byte)data; -// this.buffer[1] = (byte)(data >> 8); -// this.buffer[2] = (byte)(data >> 16); -// this.buffer[3] = (byte)(data >> 24); -// this.buffer[4] = (byte)(data >> 32); -// this.buffer[5] = (byte)(data >> 40); -// this.buffer[6] = (byte)(data >> 48); -// this.buffer[7] = (byte)(data >> 56); -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (long):" + data); -// } -//#endif -// outStream.Write(this.buffer, 0, 8); -// } -// public void Write(ulong data) -// { -// this.buffer[0] = (byte)data; -// this.buffer[1] = (byte)(data >> 8); -// this.buffer[2] = (byte)(data >> 16); -// this.buffer[3] = (byte)(data >> 24); -// this.buffer[4] = (byte)(data >> 32); -// this.buffer[5] = (byte)(data >> 40); -// this.buffer[6] = (byte)(data >> 48); -// this.buffer[7] = (byte)(data >> 56); -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (ulong):" + data); -// } -//#endif -// outStream.Write(this.buffer, 0, 8); -// } -// public void Write(byte data) -// { -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (byte):" + data); -// } -//#endif -// outStream.WriteByte(data); -// } -// public void Write(short data) -// { -// this.buffer[0] = (byte)data; -// this.buffer[1] = (byte)(data >> 8); -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (short):" + data); -// } -//#endif -// outStream.Write(this.buffer, 0, 2); -// } -// public void Write(ushort data) -// { -// this.buffer[0] = (byte)data; -// this.buffer[1] = (byte)(data >> 8); - -//#if DEBUG -// if (dbug_EnableBreak) -// { -// dbugCheckBreak(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (ushort):" + data); -// } -//#endif - -// outStream.Write(this.buffer, 0, 2); - -// } - - - -//#if DEBUG - - -// FileStream dbug_fs; -// StreamWriter dbug_fsWriter; -// bool dbug_EnableBreak = false; -// bool dbug_EnableLog = false; - -// void dbugCheckBreak() -// { -// if (dbug_EnableBreak) -// { -// //if (Position == 37) -// //{ - -// //} -// } -// } -// void dbugWriteInfo(string info) -// { -// if (dbug_EnableLog) -// { -// dbug_fsWriter.WriteLine(info); -// dbug_fsWriter.Flush(); -// } -// } - -// public void dbugInit(string dbugOutputFileName) -// { -// if (dbug_EnableLog) -// { -// if (this.outStream.Position > 0) -// { - -// dbug_fs = new FileStream(dbugOutputFileName + ".w_bin_debug", FileMode.Append); -// dbug_fsWriter = new StreamWriter(dbug_fs); -// } -// else -// { -// dbug_fs = new FileStream(dbugOutputFileName + ".w_bin_debug", FileMode.Create); -// dbug_fsWriter = new StreamWriter(dbug_fs); -// } - -// } -// } -// void dbugClose() -// { -// if (dbug_EnableLog) -// { -// dbug_fsWriter.Close(); -// dbug_fs.Close(); -// dbug_fs.Dispose(); -// dbug_fsWriter = null; -// dbug_fs = null; -// } - -// } - -//#endif - -// public long Position -// { -// get -// { -// return outStream.Position; -// } -// set -// { -// outStream.Position = value; -// } -// } -// } - -// public class SimpleBinaryReader -// { - -// Stream stream = null; -// byte[] buffer = new byte[16]; - -// public SimpleBinaryReader(Stream stream) -// { -// this.stream = stream; -//#if DEBUG - -// if (dbug_EnableLog) -// { -// dbugInit(); -// } -//#endif -// } -// public bool IsEndOfStream -// { -// get -// { -// return stream.Position == stream.Length; -// } -// } -// public long Position -// { -// get -// { -// return stream.Position; -// } -// set -// { -// stream.Position = value; -// } -// } -// public void Close() -// { -// this.stream = null; -// buffer = null; -// } - -// public bool EndOfStream -// { -// get -// { -// return stream.Position == stream.Length; -// } -// } -// public byte ReadByte() -// { - -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } -// if (dbug_EnableLog) -// { -// int b = stream.ReadByte(); -// dbugWriteInfo(Position - 1 + " (byte) " + b); -// return (byte)b; -// } -// else -// { -// return (byte)stream.ReadByte(); -// } -//#else -// return (byte)stream.ReadByte(); -//#endif - - -// } - -// public UInt32 ReadUInt32() -// { -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (uint32)"); -// } - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 4); - - -// if (dbug_EnableLog) -// { -// uint u = (uint)(mybuffer[0] | mybuffer[1] << 8 | -// mybuffer[2] << 16 | mybuffer[3] << 24); -// dbugWriteInfo(Position - 4 + " (uint32) " + u); -// return u; -// } -// else -// { -// return (uint)(mybuffer[0] | mybuffer[1] << 8 | -// mybuffer[2] << 16 | mybuffer[3] << 24); -// } - -//#else -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 4); -// return (uint)(mybuffer[0] | mybuffer[1] << 8 | -// mybuffer[2] << 16 | mybuffer[3] << 24); - -//#endif -// } - -// public unsafe double ReadDouble() -// { - -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (double)"); -// } - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 8); - -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); -// uint num2 = (uint)(((mybuffer[4] | (mybuffer[5] << 8)) | (mybuffer[6] << 0x10)) | (mybuffer[7] << 0x18)); -// ulong num3 = (num2 << 0x20) | num; - -// if (dbug_EnableLog) -// { - -// double value = *(((double*)&num3)); - -// dbugWriteInfo(Position - 8 + " (double) " + value); - -// return value; -// } -// else -// { - -// return *(((double*)&num3)); -// } -//#else - - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 8); - -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); -// uint num2 = (uint)(((mybuffer[4] | (mybuffer[5] << 8)) | (mybuffer[6] << 0x10)) | (mybuffer[7] << 0x18)); -// ulong num3 = (num2 << 0x20) | num; -// return *(((double*)&num3)); -//#endif -// } -// public unsafe float ReadFloat() -// { - -//#if DEBUG - - -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position + " (float)"); -// } - - - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 4); -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); - -// if (dbug_EnableLog) -// { -// float value = *(((float*)&num)); -// dbugWriteInfo(Position - 4 + " (float) " + value); -// return value; -// } -// else -// { -// return *(((float*)&num)); -// } - - -//#else -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 4); -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); -// return *(((float*)&num)); -//#endif -// } -// public Int32 ReadInt32() -// { -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } - - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 4); -// if (dbug_EnableLog) -// { -// int i32 = (mybuffer[0] | mybuffer[1] << 8 | -// mybuffer[2] << 16 | mybuffer[3] << 24); -// dbugWriteInfo(Position - 4 + " (int32) " + i32); - -// return i32; -// } -// else -// { -// return (mybuffer[0] | mybuffer[1] << 8 | -// mybuffer[2] << 16 | mybuffer[3] << 24); -// } -//#else -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 4); -// return (mybuffer[0] | mybuffer[1] << 8 | -// mybuffer[2] << 16 | mybuffer[3] << 24); -//#endif - -// } -// public Int16 ReadInt16() -// { -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 2); -// if (dbug_EnableLog) -// { -// Int16 i16 = (Int16)(mybuffer[0] | mybuffer[1] << 8); -// dbugWriteInfo(Position - 2 + " (int16) " + i16); -// return i16; -// } -// else -// { -// return (Int16)(mybuffer[0] | mybuffer[1] << 8); -// } -//#else -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 2); -// return (Int16)(mybuffer[0] | mybuffer[1] << 8); - -//#endif - -// } -// public UInt16 ReadUInt16() -// { -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 2); -// if (dbug_EnableLog) -// { -// UInt16 ui16 = (UInt16)(mybuffer[0] | mybuffer[1] << 8); -// dbugWriteInfo(Position - 2 + " (uint16) " + ui16); -// return ui16; -// } -// else -// { -// return (UInt16)(mybuffer[0] | mybuffer[1] << 8); -// } -//#else -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 2); -// return (UInt16)(mybuffer[0] | mybuffer[1] << 8); - - -//#endif -// } -// public long ReadInt64() -// { -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 8); -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); -// uint num2 = (uint)(((mybuffer[4] | (mybuffer[5] << 8)) | (mybuffer[6] << 0x10)) | (mybuffer[7] << 0x18)); - -// if (dbug_EnableLog) -// { -// long l = ((long)num2 << 0x20) | num; -// dbugWriteInfo(Position - 8 + " (int64) " + l); -// return l; -// } -// else -// { -// return ((long)num2 << 0x20) | num; -// } -//#else -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 8); -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); -// uint num2 = (uint)(((mybuffer[4] | (mybuffer[5] << 8)) | (mybuffer[6] << 0x10)) | (mybuffer[7] << 0x18)); -// return ((long)num2 << 0x20) | num; -//#endif - -// } -// public UInt64 ReadUInt64() -// { -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } - - -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 8); -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); -// uint num2 = (uint)(((mybuffer[4] | (mybuffer[5] << 8)) | (mybuffer[6] << 0x10)) | (mybuffer[7] << 0x18)); -// if (dbug_EnableLog) -// { -// UInt64 ui64 = ((UInt64)num2 << 0x20) | num; -// dbugWriteInfo(Position - 8 + " (uint64) " + ui64); -// return ui64; -// } -// else -// { -// return ((UInt64)num2 << 0x20) | num; -// } -//#else -// byte[] mybuffer = this.buffer; -// stream.Read(mybuffer, 0, 8); - -// uint num = (uint)(((mybuffer[0] | (mybuffer[1] << 8)) | (mybuffer[2] << 0x10)) | (mybuffer[3] << 0x18)); -// uint num2 = (uint)(((mybuffer[4] | (mybuffer[5] << 8)) | (mybuffer[6] << 0x10)) | (mybuffer[7] << 0x18)); -// return ((UInt64)num2 << 0x20) | num; - -//#endif - -// } -// public char[] ReadChars(int num) -// { - -// return Encoding.UTF8.GetChars(ReadBytes(num)); -// } -// public byte[] ReadBytes(int num) -// { -//#if DEBUG -// if (dbug_enableBreak) -// { -// dbugCheckBreakPoint(); -// } - -// byte[] buffer = new byte[num]; -// stream.Read(buffer, 0, num); -// if (dbug_EnableLog) -// { -// dbugWriteInfo(Position - num + " (byte[" + num + "]"); -// return buffer; -// } -// else -// { -// return buffer; -// } - -//#else -// byte[] buffer = new byte[num]; -// stream.Read(buffer, 0, num); -// return buffer; -//#endif - -// } -// public Stream BaseStream -// { -// get -// { -// return stream; -// } -// } -//#if DEBUG - -// void dbugCheckBreakPoint() -// { -// if (dbug_enableBreak) -// { -// //if (Position == 35) -// //{ -// //} -// } -// } - -// bool dbug_EnableLog = false; -// bool dbug_enableBreak = false; -// FileStream dbug_fs; -// StreamWriter dbug_fsWriter; - - -// void dbugWriteInfo(string info) -// { -// if (dbug_EnableLog) -// { -// dbug_fsWriter.WriteLine(info); -// dbug_fsWriter.Flush(); -// } -// } -// void dbugInit() -// { -// if (dbug_EnableLog) -// { -// if (this.stream.Position > 0) -// { - -// dbug_fs = new FileStream(((FileStream)stream).Name + ".r_bin_debug", FileMode.Append); -// dbug_fsWriter = new StreamWriter(dbug_fs); -// } -// else -// { -// dbug_fs = new FileStream(((FileStream)stream).Name + ".r_bin_debug", FileMode.Create); -// dbug_fsWriter = new StreamWriter(dbug_fs); -// } - -// } -// } -// void dbugClose() -// { -// if (dbug_EnableLog) -// { -// dbug_fsWriter.Close(); -// dbug_fs.Close(); -// dbug_fs.Dispose(); -// dbug_fsWriter = null; -// dbug_fs = null; -// } - -// } - -//#endif -// } - -//} \ No newline at end of file diff --git a/src/SharpConnect.Data/Es/EsDocParser.cs b/src/SharpConnect.Data/Es/EsDocParser.cs index e3afa87..4dbac46 100644 --- a/src/SharpConnect.Data/Es/EsDocParser.cs +++ b/src/SharpConnect.Data/Es/EsDocParser.cs @@ -1,29 +1,22 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors - -using System; +//MIT, 2015-present, brezza92, EngineKit and contributors namespace SharpConnect.Data { class EaseDocParser : EsParserBase { - EaseDocument easeDoc; + EaseDocument _easeDoc; public EaseDocParser(EaseDocument blankdoc) { - easeDoc = blankdoc; - } - protected override EsElem CreateElement() - { - return easeDoc.CreateElement(); + _easeDoc = blankdoc; } - protected override EsArr CreateArray() - { - return easeDoc.CreateArray(); - } + protected override EsElem CreateElement() => _easeDoc.CreateElement(); + + protected override EsArr CreateArray() => _easeDoc.CreateArray(); protected override void AddElementAttribute(EsElem targetElem, string key, object value) { - targetElem[key] = value; + targetElem.AppendAttribute(key, value); } protected override void AddArrayElement(EsArr targetArray, object value) diff --git a/src/SharpConnect.Data/Es/EsParserLogger.cs b/src/SharpConnect.Data/Es/EsParserLogger.cs index 7cd7252..d16376b 100644 --- a/src/SharpConnect.Data/Es/EsParserLogger.cs +++ b/src/SharpConnect.Data/Es/EsParserLogger.cs @@ -1,4 +1,4 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors +//MIT, 2015-present, brezza92, EngineKit and contributors using System; using System.IO; namespace SharpConnect.Data @@ -6,29 +6,29 @@ namespace SharpConnect.Data #if DEBUG static class dbugEsParserLogger { - static FileStream dbugFs; - static StreamWriter writer; + static FileStream s_dbugFs; + static StreamWriter s_writer; public static void Init(string outputfile) { - if (writer != null) + if (s_writer != null) { - writer.Close(); - writer.Dispose(); - writer = null; + s_writer.Close(); + s_writer.Dispose(); + s_writer = null; } - if (dbugFs != null) + if (s_dbugFs != null) { - dbugFs.Close(); - dbugFs = null; + s_dbugFs.Close(); + s_dbugFs = null; } //------------------------- - dbugFs = new FileStream(outputfile, FileMode.Create); - writer = new StreamWriter(dbugFs); - writer.AutoFlush = true; + s_dbugFs = new FileStream(outputfile, FileMode.Create); + s_writer = new StreamWriter(s_dbugFs); + s_writer.AutoFlush = true; } public static void WriteLine(string text) { - writer.WriteLine(text); + s_writer.WriteLine(text); } } #endif diff --git a/src/SharpConnect.Data/Melt/MeltingEss.cs b/src/SharpConnect.Data/Melt/MeltingEss.cs deleted file mode 100644 index 7b4fc1a..0000000 --- a/src/SharpConnect.Data/Melt/MeltingEss.cs +++ /dev/null @@ -1,1240 +0,0 @@ -//MIT, 2018, EngineKit -using System; -using System.Text; -using System.Collections; -using System.Collections.Generic; -using System.Globalization; - - -namespace SharpConnect.Data.Internal -{ - - public static class GlobalRegisteredTypes - { - static Dictionary _registeredDic = new Dictionary(); - public static void Register(MyTypeInfo myTypeInfo) - { - if (!_registeredDic.ContainsKey(myTypeInfo.type)) - { - _registeredDic.Add(myTypeInfo.type, myTypeInfo); - } - } - public static bool TryGetMyTypeInfo(Type orgType, out MyTypeInfo found) - { - return _registeredDic.TryGetValue(orgType, out found); - } - } - - public delegate void SerializeDelegate(SerializeWalker walker, object obj); - public delegate object DeserializeDelegate(DeserializerWalker walker, object obj); - public delegate object DeserializeCreateInstanceDelegate(DeserializerWalker walker); - - public class MyTypeMbInfo - { - public readonly Type type; - public readonly string name; - public readonly int mbIndex; - public MyTypeMbInfo(string name, Type type, int mbIndex) - { - this.type = type; - this.name = name; - this.mbIndex = mbIndex; - } - } - public class MyTypeInfo - { - Dictionary _dic = new Dictionary(); - internal readonly Type type; - string fullname; - - public SerializeDelegate _serDel; - public DeserializeDelegate _deserDel; - public DeserializeCreateInstanceDelegate _createInstDel; - - public MyTypeInfo(string fullname, System.Type type) - { - this.fullname = fullname; - this.type = type; - _dic.Add("", null); - - GlobalRegisteredTypes.Register(this); - - - } - public string FullName { get { return this.fullname; } } - // - public void RegisterMember(string memberName, System.Type memberRetType) - { - if (!_dic.ContainsKey(memberName)) - { - _dic.Add(memberName, new MyTypeMbInfo(memberName, memberRetType, _dic.Count)); - } - } - public int TryGetIndex(string memberName) - { - if (_dic.TryGetValue(memberName, out var found)) - { - return found.mbIndex; - } - return 0; - } - } -} -namespace SharpConnect.Data -{ - public class SerializeWalker - { - public StringBuilder _stbuilder; - bool _useEscapedUnicode = false; - public SerializeWalker() - { - - } - public void WriteStringOrNull(string value) - { - //write string or null value - //with escape value - if (value == null) - { - _stbuilder.Append("null"); - } - else - { - WriteStringValueWithEscape(value); - } - } - public void WriteByteBuffer(byte[] buffer) - { - //encode buffer as base64 - - _stbuilder.Append(Convert.ToBase64String(buffer)); - } - public void WriteByte(byte b) - { - _stbuilder.Append(b.ToString()); - } - void WriteStringValueWithEscape(string s) - { - StringBuilder _output = _stbuilder; - _output.Append('\"'); - - int runIndex = -1; - int l = s.Length; - for (var index = 0; index < l; ++index) - { - var c = s[index]; - - if (_useEscapedUnicode) - { - if (c >= ' ' && c < 128 && c != '\"' && c != '\\') - { - if (runIndex == -1) - runIndex = index; - - continue; - } - } - else - { - if (c != '\t' && c != '\n' && c != '\r' && c != '\"' && c != '\\' && c != '\0')// && c != ':' && c!=',') - { - if (runIndex == -1) - runIndex = index; - - continue; - } - } - - if (runIndex != -1) - { - _output.Append(s, runIndex, index - runIndex); - runIndex = -1; - } - - switch (c) - { - case '\t': _output.Append("\\t"); break; - case '\r': _output.Append("\\r"); break; - case '\n': _output.Append("\\n"); break; - case '"': - case '\\': _output.Append('\\'); _output.Append(c); break; - case '\0': _output.Append("\\u0000"); break; - default: - if (_useEscapedUnicode) - { - _output.Append("\\u"); - _output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo)); - } - else - _output.Append(c); - - break; - } - } - - if (runIndex != -1) - _output.Append(s, runIndex, s.Length - runIndex); - - _output.Append('\"'); - - } - - public void WriteInt16(short value) - { - _stbuilder.Append(value.ToString()); - } - public void WriteUInt16(ushort value) - { - _stbuilder.Append(value.ToString()); - } - public void WriteChar(char value) - { - _stbuilder.Append(value.ToString()); - } - // - public void WriteInt32(int value) - { - _stbuilder.Append(value.ToString()); - } - public void WriteUInt32(uint value) - { - _stbuilder.Append(value.ToString()); - } - public void WriteInt64(int value) - { - _stbuilder.Append(value.ToString()); - } - public void WriteUInt64(uint value) - { - _stbuilder.Append(value.ToString()); - } - // - public void WriteSingle(float value) - { - _stbuilder.Append(value.ToString()); - } - public void WriteDouble(double value) - { - _stbuilder.Append(value.ToString()); - } - public void WriteDecimal(decimal value) - { - _stbuilder.Append(value.ToString()); - } - void WriteDictionary(IDictionary dic) - { - _stbuilder.Append("{"); - if (dic is Dictionary) - { - Dictionary d1 = (Dictionary)dic; - foreach (var kp in d1) - { - WriteStringValueWithEscape(kp.Key); - _stbuilder.Append(":"); - WriteValue(kp.Value); - } - } - else - { - //todo ... - } - - _stbuilder.Append("}"); - } - // - public void WriteValueWithTypeHint(object value, Type typeinfo) - { - //write date with specific typeinfo - - //get runtime type of the value - if (value == null || value is DBNull) - { - _stbuilder.Append("null"); - } - else - { - //check exact type of this value - - //if it is basic type /welknown type - //the we write it as basic type - //if not then find proper deserializer - if (value is string) - { - WriteStringValueWithEscape((string)value); - } - else if (value is char) - { - _stbuilder.Append(value.ToString()); - } - else if (value is int || value is long || - value is decimal || - value is byte || value is short || - value is sbyte || value is ushort || - value is uint || value is ulong) - { - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - } - else if (value is double || value is Double) - { - double d = (double)value; - if (double.IsNaN(d)) - _stbuilder.Append("\"NaN\""); - else if (double.IsInfinity(d)) - { - _stbuilder.Append("\""); - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - _stbuilder.Append("\""); - } - else - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - } - else if (value is float || value is Single) - { - float d = (float)value; - if (float.IsNaN(d)) - _stbuilder.Append("\"NaN\""); - else if (float.IsInfinity(d)) - { - _stbuilder.Append("\""); - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - _stbuilder.Append("\""); - } - else - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - } - else if (value is DateTime) - { - _stbuilder.Append(((DateTime)value).ToString("s")); - } - else if (value is byte[]) - { - WriteByteBuffer((byte[])value); - } - else - { - System.Type t = value.GetType(); - //check if we have a registered serializer - if (Internal.GlobalRegisteredTypes.TryGetMyTypeInfo(t, out Internal.MyTypeInfo registerTypeInfo)) - { - registerTypeInfo._serDel(this, value); - return; - } - if (value is IDictionary) - { - WriteDictionary((IDictionary)value); - } - else if (value is IEnumerable) - { - WriteIEnumerableAsArray((IEnumerable)value); - } - else - { - - - //this type is not declare as export type - //.... - //then - //check only interface impl - - //use type hint - if (Internal.GlobalRegisteredTypes.TryGetMyTypeInfo(typeinfo, out registerTypeInfo)) - { - registerTypeInfo._serDel(this, value); - return; - } - else - { - //not found - _stbuilder.Append("null"); - } - - } - } - } - - } - public void WriteValue(object value) - { - //write object value.... - - //get runtime type of the value - if (value == null || value is DBNull) - { - _stbuilder.Append("null"); - } - else - { - //check exact type of this value - - //if it is basic type /welknown type - //the we write it as basic type - //if not then find proper deserializer - if (value is string) - { - WriteStringValueWithEscape((string)value); - } - else if (value is char) - { - _stbuilder.Append(value.ToString()); - } - else if (value is int || value is long || - value is decimal || - value is byte || value is short || - value is sbyte || value is ushort || - value is uint || value is ulong) - { - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - } - else if (value is double || value is Double) - { - double d = (double)value; - if (double.IsNaN(d)) - _stbuilder.Append("\"NaN\""); - else if (double.IsInfinity(d)) - { - _stbuilder.Append("\""); - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - _stbuilder.Append("\""); - } - else - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - } - else if (value is float || value is Single) - { - float d = (float)value; - if (float.IsNaN(d)) - _stbuilder.Append("\"NaN\""); - else if (float.IsInfinity(d)) - { - _stbuilder.Append("\""); - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - _stbuilder.Append("\""); - } - else - _stbuilder.Append(((IConvertible)value).ToString(NumberFormatInfo.InvariantInfo)); - } - else if (value is DateTime) - { - _stbuilder.Append(((DateTime)value).ToString("s")); - } - else if (value is byte[]) - { - WriteByteBuffer((byte[])value); - } - else - { - System.Type t = value.GetType(); - //check if we have a registered serializer - if (Internal.GlobalRegisteredTypes.TryGetMyTypeInfo(t, out Internal.MyTypeInfo registerTypeInfo)) - { - registerTypeInfo._serDel(this, value); - return; - } - if (value is IDictionary) - { - WriteDictionary((IDictionary)value); - } - else if (value is IEnumerable) - { - WriteIEnumerableAsArray((IEnumerable)value); - } - else - { - //this type is not declare as export type - //.... - //then - //check only interface impl - - - throw new NotSupportedException(); - } - } - } - } - public void AppendString(string str) - { - _stbuilder.Append(str); - } - void WriteIEnumerableAsArray(IEnumerable ienum) - { - _stbuilder.Append('['); - bool appendComma = false; - foreach (var o in ienum) - { - if (appendComma) { _stbuilder.Append(','); } - WriteValue(o); - // - appendComma = true; - - } - _stbuilder.Append(']'); - } - - } - sealed class JSONParameters - { - /// - /// Use the optimized fast Dataset Schema format (default = True) - /// - public bool UseOptimizedDatasetSchema = true; - /// - /// Use the fast GUID format (default = True) - /// - public bool UseFastGuid = true; - /// - /// Serialize null values to the output (default = True) - /// - public bool SerializeNullValues = true; - /// - /// Use the UTC date format (default = True) - /// - public bool UseUTCDateTime = true; - /// - /// Show the readonly properties of types in the output (default = False) - /// - public bool ShowReadOnlyProperties = false; - /// - /// Use the $types extension to optimise the output json (default = True) - /// - public bool UsingGlobalTypes = true; - /// - /// Ignore case when processing json and deserializing - /// - [Obsolete("Not needed anymore and will always match")] - public bool IgnoreCaseOnDeserialize = false; - /// - /// Anonymous types have read only properties - /// - public bool EnableAnonymousTypes = false; - /// - /// Enable fastJSON extensions $types, $type, $map (default = True) - /// - public bool UseExtensions = true; - /// - /// Use escaped unicode i.e. \uXXXX format for non ASCII characters (default = True) - /// - public bool UseEscapedUnicode = true; - /// - /// Output string key dictionaries as "k"/"v" format (default = False) - /// - public bool KVStyleStringDictionary = false; - /// - /// Output Enum values instead of names (default = False) - /// - public bool UseValuesOfEnums = false; - /// - /// Ignore attributes to check for (default : XmlIgnoreAttribute, NonSerialized) - /// - public List IgnoreAttributes = new List { /*typeof(System.Xml.Serialization.XmlIgnoreAttribute), */typeof(NonSerializedAttribute) }; - /// - /// If you have parametric and no default constructor for you classes (default = False) - /// - /// IMPORTANT NOTE : If True then all initial values within the class will be ignored and will be not set - /// - public bool ParametricConstructorOverride = false; - /// - /// Serialize DateTime milliseconds i.e. yyyy-MM-dd HH:mm:ss.nnn (default = false) - /// - public bool DateTimeMilliseconds = false; - /// - /// Maximum depth for circular references in inline mode (default = 20) - /// - public byte SerializerMaxDepth = 20; - /// - /// Inline circular or already seen objects instead of replacement with $i (default = False) - /// - public bool InlineCircularReferences = false; - /// - /// Save property/field names as lowercase (default = false) - /// - public bool SerializeToLowerCaseNames = false; - /// - /// Formatter indent spaces (default = 3) - /// - public byte FormatterIndentSpaces = 3; - - public void FixValues() - { - if (UseExtensions == false) // disable conflicting params - { - UsingGlobalTypes = false; - InlineCircularReferences = true; - } - if (EnableAnonymousTypes) - ShowReadOnlyProperties = true; - } - } - - sealed class JSONSerializer - { - private StringBuilder _output = new StringBuilder(); - //private StringBuilder _before = new StringBuilder(); - private int _before; - private int _MAX_DEPTH = 20; - int _current_depth = 0; - private Dictionary _globalTypes = new Dictionary(); - private Dictionary _cirobj = new Dictionary(); - private JSONParameters _params; - private bool _useEscapedUnicode = false; - - internal JSONSerializer(JSONParameters param) - { - _params = param; - _useEscapedUnicode = _params.UseEscapedUnicode; - _MAX_DEPTH = _params.SerializerMaxDepth; - } - - internal string ConvertToJSON(object obj) - { - WriteValue(obj); - - if (_params.UsingGlobalTypes && _globalTypes != null && _globalTypes.Count > 0) - { - var sb = new StringBuilder(); - sb.Append("\"$types\":{"); - var pendingSeparator = false; - foreach (var kv in _globalTypes) - { - if (pendingSeparator) sb.Append(','); - pendingSeparator = true; - sb.Append('\"'); - sb.Append(kv.Key); - sb.Append("\":\""); - sb.Append(kv.Value); - sb.Append('\"'); - } - sb.Append("},"); - _output.Insert(_before, sb.ToString()); - } - return _output.ToString(); - } - - private void WriteValue(object obj) - { - if (obj == null || obj is DBNull) - _output.Append("null"); - - else if (obj is string || obj is char) - WriteString(obj.ToString()); - - else if (obj is Guid) - WriteGuid((Guid)obj); - - else if (obj is bool) - _output.Append(((bool)obj) ? "true" : "false"); // conform to standard - - else if ( - obj is int || obj is long || - obj is decimal || - obj is byte || obj is short || - obj is sbyte || obj is ushort || - obj is uint || obj is ulong - ) - _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo)); - - else if (obj is double || obj is Double) - { - double d = (double)obj; - if (double.IsNaN(d)) - _output.Append("\"NaN\""); - else if (double.IsInfinity(d)) - { - _output.Append("\""); - _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo)); - _output.Append("\""); - } - else - _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo)); - } - else if (obj is float || obj is Single) - { - float d = (float)obj; - if (float.IsNaN(d)) - _output.Append("\"NaN\""); - else if (float.IsInfinity(d)) - { - _output.Append("\""); - _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo)); - _output.Append("\""); - } - else - _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo)); - } - - else if (obj is DateTime) - WriteDateTime((DateTime)obj); - - else if (obj is DateTimeOffset) - WriteDateTimeOffset((DateTimeOffset)obj); - - else if (obj is TimeSpan) - _output.Append(((TimeSpan)obj).Ticks); - -#if net4 - else if (_params.KVStyleStringDictionary == false && - obj is IEnumerable>) - - WriteStringDictionary((IEnumerable>)obj); -#endif - - else if (_params.KVStyleStringDictionary == false && obj is IDictionary && - obj.GetType().IsGenericType && obj.GetType().GetGenericArguments()[0] == typeof(string)) - - WriteStringDictionary((IDictionary)obj); - else if (obj is IDictionary) - WriteDictionary((IDictionary)obj); - - else if (obj is byte[]) - WriteBytes((byte[])obj); - - else if (obj is IEnumerable) - WriteArray((IEnumerable)obj); - - else if (obj is Enum) - WriteEnum((Enum)obj); - - //custom type - //else if (Reflection.Instance.IsTypeRegistered(obj.GetType())) - // WriteCustom(obj); - - else - WriteObject(obj); - } - - private void WriteDateTimeOffset(DateTimeOffset d) - { - DateTime dt = _params.UseUTCDateTime ? d.UtcDateTime : d.DateTime; - - write_date_value(dt); - - var ticks = dt.Ticks % TimeSpan.TicksPerSecond; - _output.Append('.'); - _output.Append(ticks.ToString("0000000", NumberFormatInfo.InvariantInfo)); - - if (_params.UseUTCDateTime) - _output.Append('Z'); - else - { - if (d.Offset.Hours > 0) - _output.Append("+"); - else - _output.Append("-"); - _output.Append(d.Offset.Hours.ToString("00", NumberFormatInfo.InvariantInfo)); - _output.Append(":"); - _output.Append(d.Offset.Minutes.ToString("00", NumberFormatInfo.InvariantInfo)); - } - - _output.Append('\"'); - } - - //private void WriteNV(NameValueCollection nameValueCollection) - //{ - // _output.Append('{'); - - // bool pendingSeparator = false; - - // foreach (string key in nameValueCollection) - // { - // if (_params.SerializeNullValues == false && (nameValueCollection[key] == null)) - // { - // } - // else - // { - // if (pendingSeparator) _output.Append(','); - // if (_params.SerializeToLowerCaseNames) - // WritePair(key.ToLower(), nameValueCollection[key]); - // else - // WritePair(key, nameValueCollection[key]); - // pendingSeparator = true; - // } - // } - // _output.Append('}'); - //} - - //private void WriteSD(StringDictionary stringDictionary) - //{ - // _output.Append('{'); - - // bool pendingSeparator = false; - - // foreach (DictionaryEntry entry in stringDictionary) - // { - // if (_params.SerializeNullValues == false && (entry.Value == null)) - // { - // } - // else - // { - // if (pendingSeparator) _output.Append(','); - - // string k = (string)entry.Key; - // if (_params.SerializeToLowerCaseNames) - // WritePair(k.ToLower(), entry.Value); - // else - // WritePair(k, entry.Value); - // pendingSeparator = true; - // } - // } - // _output.Append('}'); - //} - - //private void WriteCustom(object obj) - //{ - // //must found - // //if not then throw? - // Serialize s; - // Reflection.Instance._customSerializer.TryGetValue(obj.GetType(), out s); - // WriteStringFast(s(obj)); - //} - - private void WriteEnum(Enum e) - { - // FEATURE : optimize enum write - if (_params.UseValuesOfEnums) - WriteValue(Convert.ToInt32(e)); - else - WriteStringFast(e.ToString()); - } - - private void WriteGuid(Guid g) - { - if (_params.UseFastGuid == false) - WriteStringFast(g.ToString()); - else - WriteBytes(g.ToByteArray()); - } - - private void WriteBytes(byte[] bytes) - { -#if !SILVERLIGHT - WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None)); -#else - WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length)); -#endif - } - - private void WriteDateTime(DateTime dateTime) - { - // datetime format standard : yyyy-MM-dd HH:mm:ss - DateTime dt = dateTime; - if (_params.UseUTCDateTime) - dt = dateTime.ToUniversalTime(); - - write_date_value(dt); - - if (_params.DateTimeMilliseconds) - { - _output.Append('.'); - _output.Append(dt.Millisecond.ToString("000", NumberFormatInfo.InvariantInfo)); - } - - if (_params.UseUTCDateTime) - _output.Append('Z'); - - _output.Append('\"'); - } - - private void write_date_value(DateTime dt) - { - _output.Append('\"'); - _output.Append(dt.Year.ToString("0000", NumberFormatInfo.InvariantInfo)); - _output.Append('-'); - _output.Append(dt.Month.ToString("00", NumberFormatInfo.InvariantInfo)); - _output.Append('-'); - _output.Append(dt.Day.ToString("00", NumberFormatInfo.InvariantInfo)); - _output.Append('T'); // strict ISO date compliance - _output.Append(dt.Hour.ToString("00", NumberFormatInfo.InvariantInfo)); - _output.Append(':'); - _output.Append(dt.Minute.ToString("00", NumberFormatInfo.InvariantInfo)); - _output.Append(':'); - _output.Append(dt.Second.ToString("00", NumberFormatInfo.InvariantInfo)); - } - bool _TypesWritten = false; - private void WriteObject(object obj) - { - int i = 0; - if (_cirobj.TryGetValue(obj, out i) == false) - _cirobj.Add(obj, _cirobj.Count + 1); - else - { - if (_current_depth > 0 && _params.InlineCircularReferences == false) - { - //_circular = true; - _output.Append("{\"$i\":"); - _output.Append(i.ToString()); - _output.Append("}"); - return; - } - } - if (_params.UsingGlobalTypes == false) - _output.Append('{'); - else - { - if (_TypesWritten == false) - { - _output.Append('{'); - _before = _output.Length; - //_output = new StringBuilder(); - } - else - _output.Append('{'); - } - _TypesWritten = true; - _current_depth++; - if (_current_depth > _MAX_DEPTH) - throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH); - - - //Dictionary map = new Dictionary(); - //Type t = obj.GetType(); - //bool append = false; - //if (_params.UseExtensions) - //{ - // if (_params.UsingGlobalTypes == false) - // WritePairFast("$type", Reflection.Instance.GetTypeAssemblyName(t)); - // else - // { - // int dt = 0; - // string ct = Reflection.Instance.GetTypeAssemblyName(t); - // if (_globalTypes.TryGetValue(ct, out dt) == false) - // { - // dt = _globalTypes.Count + 1; - // _globalTypes.Add(ct, dt); - // } - // WritePairFast("$type", dt.ToString()); - // } - // append = true; - //} - - //Getters[] g = Reflection.Instance.GetGetters(t, _params.ShowReadOnlyProperties, _params.IgnoreAttributes); - //int c = g.Length; - //for (int ii = 0; ii < c; ii++) - //{ - // var p = g[ii]; - // object o = p.Getter(obj); - // if (_params.SerializeNullValues == false && (o == null || o is DBNull)) - // { - // //append = false; - // } - // else - // { - // if (append) - // _output.Append(','); - // if (p.memberName != null) - // WritePair(p.memberName, o); - // else if (_params.SerializeToLowerCaseNames) - // WritePair(p.lcName, o); - // else - // WritePair(p.Name, o); - // if (o != null && _params.UseExtensions) - // { - // Type tt = o.GetType(); - // if (tt == typeof(System.Object)) - // map.Add(p.Name, tt.ToString()); - // } - // append = true; - // } - //} - //if (map.Count > 0 && _params.UseExtensions) - //{ - // _output.Append(",\"$map\":"); - // WriteStringDictionary(map); - //} - _output.Append('}'); - _current_depth--; - } - - private void WritePairFast(string name, string value) - { - WriteStringFast(name); - - _output.Append(':'); - - WriteStringFast(value); - } - - private void WritePair(string name, object value) - { - WriteString(name); - - _output.Append(':'); - - WriteValue(value); - } - - private void WriteArray(IEnumerable array) - { - _output.Append('['); - - bool pendingSeperator = false; - - foreach (object obj in array) - { - if (pendingSeperator) _output.Append(','); - - WriteValue(obj); - - pendingSeperator = true; - } - _output.Append(']'); - } - - private void WriteStringDictionary(IDictionary dic) - { - _output.Append('{'); - - bool pendingSeparator = false; - - foreach (DictionaryEntry entry in dic) - { - if (_params.SerializeNullValues == false && (entry.Value == null)) - { - } - else - { - if (pendingSeparator) _output.Append(','); - - string k = (string)entry.Key; - if (_params.SerializeToLowerCaseNames) - WritePair(k.ToLower(), entry.Value); - else - WritePair(k, entry.Value); - pendingSeparator = true; - } - } - _output.Append('}'); - } - - private void WriteStringDictionary(IEnumerable> dic) - { - _output.Append('{'); - bool pendingSeparator = false; - foreach (KeyValuePair entry in dic) - { - if (_params.SerializeNullValues == false && (entry.Value == null)) - { - } - else - { - if (pendingSeparator) _output.Append(','); - string k = entry.Key; - - if (_params.SerializeToLowerCaseNames) - WritePair(k.ToLower(), entry.Value); - else - WritePair(k, entry.Value); - pendingSeparator = true; - } - } - _output.Append('}'); - } - - private void WriteDictionary(IDictionary dic) - { - _output.Append('['); - - bool pendingSeparator = false; - - foreach (DictionaryEntry entry in dic) - { - if (pendingSeparator) _output.Append(','); - _output.Append('{'); - WritePair("k", entry.Key); - _output.Append(","); - WritePair("v", entry.Value); - _output.Append('}'); - - pendingSeparator = true; - } - _output.Append(']'); - } - - private void WriteStringFast(string s) - { - _output.Append('\"'); - _output.Append(s); - _output.Append('\"'); - } - - private void WriteString(string s) - { - _output.Append('\"'); - - int runIndex = -1; - int l = s.Length; - for (var index = 0; index < l; ++index) - { - var c = s[index]; - - if (_useEscapedUnicode) - { - if (c >= ' ' && c < 128 && c != '\"' && c != '\\') - { - if (runIndex == -1) - runIndex = index; - - continue; - } - } - else - { - if (c != '\t' && c != '\n' && c != '\r' && c != '\"' && c != '\\' && c != '\0')// && c != ':' && c!=',') - { - if (runIndex == -1) - runIndex = index; - - continue; - } - } - - if (runIndex != -1) - { - _output.Append(s, runIndex, index - runIndex); - runIndex = -1; - } - - switch (c) - { - case '\t': _output.Append("\\t"); break; - case '\r': _output.Append("\\r"); break; - case '\n': _output.Append("\\n"); break; - case '"': - case '\\': _output.Append('\\'); _output.Append(c); break; - case '\0': _output.Append("\\u0000"); break; - default: - if (_useEscapedUnicode) - { - _output.Append("\\u"); - _output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo)); - } - else - _output.Append(c); - - break; - } - } - - if (runIndex != -1) - _output.Append(s, runIndex, s.Length - runIndex); - - _output.Append('\"'); - } - } - - - public class DeserializerWalker - { - //we walk along the data stream - - Dictionary _rootObject; - Dictionary.Enumerator _objEnum; - KeyValuePair _currentValue; - int level = 0; - - - public void SetRootObject(Dictionary rootObject) - { - _rootObject = rootObject; - level = 0; - _objEnum = rootObject.GetEnumerator(); - } - - public bool Read() - { - //read on current level - bool moveNext = _objEnum.MoveNext(); - _currentValue = _objEnum.Current; - return moveNext; - } - public string ReadKey() - { - return _currentValue.Key; - } - public string ReadValueAsString() - { - return Convert.ToString(_currentValue.Value); - } - public object ReadValueAsObject(System.Type type) - { - //read data as specific object type - if (SharpConnect.Data.Internal.GlobalRegisteredTypes.TryGetMyTypeInfo(type, - out SharpConnect.Data.Internal.MyTypeInfo foundMyTypeInfo)) - { - //found mytype info - //1. create that type - var data = _currentValue.Value as Dictionary; - - if (data != null && foundMyTypeInfo._createInstDel != null) - { - object newInst = foundMyTypeInfo._createInstDel(this); - if (newInst != null) - { - DeserializerWalker newWalker = new DeserializerWalker(); - newWalker.SetRootObject(data); - object result = foundMyTypeInfo._deserDel(newWalker, newInst); - return result; - } - } - } - return null; - } - //8 - public byte ReadValueAsByte() - { - return Convert.ToByte(_currentValue.Value); - } - //16 - public short ReadValueAsInt16() - { - return Convert.ToInt16(_currentValue.Value); - } - public ushort ReadValueAsUInt16() - { - return Convert.ToUInt16(_currentValue.Value); - } - public char ReadChar() - { - return Convert.ToChar(_currentValue.Value); - } - //32 - public int ReadValueAsInt32() - { - return Convert.ToInt32(_currentValue.Value); - } - public uint ReadValueAsUInt32() - { - return Convert.ToUInt32(_currentValue.Value); - } - //64 - public long ReadValueAsInt64() - { - return Convert.ToInt64(_currentValue.Value); - } - public ulong ReadValueAsUInt64() - { - return Convert.ToUInt64(_currentValue.Value); - } - // - public double ReadValueAsDouble() - { - return Convert.ToDouble(_currentValue.Value); - } - public float ReadValueAsSingle() - { - return Convert.ToSingle(_currentValue.Value); - } - public decimal ReadValueAsDecimal() - { - return Convert.ToDecimal(_currentValue.Value); - } - - //byte buffer - public byte[] ReadAsByteBuffer() - { - return _currentValue.Value as byte[]; - } - //date-time - - - } - -} \ No newline at end of file diff --git a/src/SharpConnect.Data/SharpConnect.Data.csproj b/src/SharpConnect.Data/SharpConnect.Data.csproj index 6c6a38e..496e9f6 100644 --- a/src/SharpConnect.Data/SharpConnect.Data.csproj +++ b/src/SharpConnect.Data/SharpConnect.Data.csproj @@ -40,6 +40,7 @@ false false true + Off @@ -64,6 +65,7 @@ 4 false true + true pdbonly @@ -77,21 +79,16 @@ AnyCPU - - - - - diff --git a/src/SharpConnect.Data/TableModel/EsColumnBasedTable.cs b/src/SharpConnect.Data/TableModel/EsColumnBasedTable.cs index 50f39cb..7cd72d9 100644 --- a/src/SharpConnect.Data/TableModel/EsColumnBasedTable.cs +++ b/src/SharpConnect.Data/TableModel/EsColumnBasedTable.cs @@ -1,4 +1,4 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors +//MIT, 2015-present, brezza92, EngineKit and contributors using System; using System.Collections.Generic; @@ -20,21 +20,10 @@ enum ColumnNameState OK } + public int RowCount => _dataColumns[0].RowCount; + + public int ColumnCount => _dataColumns.Count; - public int RowCount - { - get - { - return _dataColumns[0].RowCount; - } - } - public int ColumnCount - { - get - { - return _dataColumns.Count; - } - } public void RemoveColumn(int columnIndex) { //when user remove column or change column name @@ -42,18 +31,12 @@ public void RemoveColumn(int columnIndex) _dataColumns.RemoveAt(columnIndex); _columnNameState = ColumnNameState.Dirty; } - public string GetColumnName(int colIndex) - { - return _dataColumns[colIndex].ColumnName; - } - public object GetCellData(int row, int column) - { - return _dataColumns[column].GetCellData(row); - } - public EsTableColumn GetColumn(int index) - { - return _dataColumns[index]; - } + public string GetColumnName(int colIndex) => _dataColumns[colIndex].ColumnName; + + public object GetCellData(int row, int column) => _dataColumns[column].GetCellData(row); + + public EsTableColumn GetColumn(int index) => _dataColumns[index]; + public IEnumerable GetColumnIterForward() { foreach (EsTableColumn col in _dataColumns) @@ -130,30 +113,17 @@ public class EsTableColumn { EsColumnBasedTable _ownerTable; List _cells = new List(); - string _name; + internal EsTableColumn(EsColumnBasedTable ownerTable, string name) { ColumnName = name; _ownerTable = ownerTable; } - public int RowCount - { - get - { - return _cells.Count; - } - } + public int RowCount => _cells.Count; /// /// TODO: review here *** /// - public string ColumnName - { - get { return _name; } - set - { - _name = value; - } - } + public string ColumnName { get; set; } public void NewBlankRows(int rowCount, object initData) { for (int i = rowCount - 1; i >= 0; --i) @@ -161,11 +131,7 @@ public void NewBlankRows(int rowCount, object initData) _cells.Add(initData); } } - public EsColumnTypeHint TypeHint - { - get; - set; - } + public EsColumnTypeHint TypeHint { get; set; } public void AppendData(object data) { @@ -191,7 +157,9 @@ public int FindRow(string data) } return -1; } - +#if DEBUG + public override string ToString() => ColumnName; +#endif public static void CloneAllCells(EsTableColumn origin, EsTableColumn target) { target._cells.AddRange(origin._cells); diff --git a/src/SharpConnect.Data/TableModel/EsColumnBasedTableHelper.cs b/src/SharpConnect.Data/TableModel/EsColumnBasedTableHelper.cs index d43e935..28a25a8 100644 --- a/src/SharpConnect.Data/TableModel/EsColumnBasedTableHelper.cs +++ b/src/SharpConnect.Data/TableModel/EsColumnBasedTableHelper.cs @@ -1,4 +1,4 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors +//MIT, 2015-present, brezza92, EngineKit and contributors using System; using System.Collections.Generic; @@ -10,12 +10,11 @@ namespace SharpConnect.Data public static class EsColumnBasedTableHelper { public static Encoding s_defaultEncoding = Encoding.UTF8; - public static EsColumnBasedTable CreateColumnBaseTableFromCsv(string file, Encoding enc, bool firstRowIsColumns) + public static EsColumnBasedTable CreateColumnBaseTableFromCsv(Stream stream, Encoding enc, bool firstRowIsColumns, char sep = ',') { var table = new EsColumnBasedTable(); - using (var fs = new FileStream(file, FileMode.Open)) + using (var reader = new StreamReader(stream, enc)) { - var reader = new StreamReader(fs, enc); int line_id = 0; int col_count = 0; EsTableColumn[] columns = null; @@ -23,7 +22,7 @@ public static EsColumnBasedTable CreateColumnBaseTableFromCsv(string file, Encod if (!firstRowIsColumns) { //when first line is not column - string[] cells = ParseCsvLine(firstline); + string[] cells = ParseCsvLine(firstline, sep); col_count = cells.Length; columns = new EsTableColumn[col_count]; for (int i = 0; i < col_count; ++i) @@ -38,7 +37,7 @@ public static EsColumnBasedTable CreateColumnBaseTableFromCsv(string file, Encod else { - string[] col_names = ParseCsvLine(firstline); + string[] col_names = ParseCsvLine(firstline, sep); col_count = col_names.Length; columns = new EsTableColumn[col_count]; for (int i = 0; i < col_count; ++i) @@ -50,7 +49,7 @@ public static EsColumnBasedTable CreateColumnBaseTableFromCsv(string file, Encod string line = reader.ReadLine(); while (line != null) { - string[] cells = ParseCsvLine(line); + string[] cells = ParseCsvLine(line, sep); if (cells.Length != col_count) { throw new NotSupportedException("column count not match!"); @@ -64,12 +63,18 @@ public static EsColumnBasedTable CreateColumnBaseTableFromCsv(string file, Encod line = reader.ReadLine(); } reader.Close(); - fs.Close(); } return table; } + public static EsColumnBasedTable CreateColumnBaseTableFromCsv(string file, Encoding enc, bool firstRowIsColumns) + { + using (var fs = new FileStream(file, FileMode.Open)) + { + return CreateColumnBaseTableFromCsv(fs, enc, firstRowIsColumns); + } + } - static string[] ParseCsvLine(string csvline) + public static string[] ParseCsvLine(string csvline, char sep) { char[] buffer = csvline.ToCharArray(); List output = new List(); @@ -88,7 +93,7 @@ static string[] ParseCsvLine(string csvline) { state = 1; } - else if (c == ',') + else if (c == sep) { output.Add(new string(currentBuffer.ToArray())); currentBuffer.Clear(); @@ -114,7 +119,7 @@ static string[] ParseCsvLine(string csvline) break; case 2: { - if (c == ',') + if (c == sep) { output.Add(new string(currentBuffer.ToArray())); currentBuffer.Clear(); @@ -192,9 +197,12 @@ public static void SaveAsCsvFile(this EsColumnBasedTable table, string filename, w.Write(','); } object cell = table.GetCellData(r, c); - w.Write('"'); - w.Write(cell.ToString()); - w.Write('"'); + if (cell != null) + { + w.Write('"'); + w.Write(cell.ToString()); + w.Write('"'); + } } } diff --git a/src/SharpConnect.Data/TreeModel/BasicReflectiveStructs.cs b/src/SharpConnect.Data/TreeModel/BasicReflectiveStructs.cs deleted file mode 100644 index 490b82a..0000000 --- a/src/SharpConnect.Data/TreeModel/BasicReflectiveStructs.cs +++ /dev/null @@ -1,206 +0,0 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors - -namespace SharpConnect.Data -{ - public struct SimpleStruct - { - public T1 m1; - public T2 m2; - public SimpleStruct(T1 m1, T2 m2) - { - this.m1 = m1; - this.m2 = m2; - } - } - public struct SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public SimpleStruct(T1 m1, T2 m2, T3 m3) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - } - } - - public struct SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - } - } - public class SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public T5 m5; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4, T5 m5) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - this.m5 = m5; - } - } - public class SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public T5 m5; - public T6 m6; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4, T5 m5, T6 m6) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - this.m5 = m5; - this.m6 = m6; - } - } - public class SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public T5 m5; - public T6 m6; - public T7 m7; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4, T5 m5, T6 m6, T7 m7) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - this.m5 = m5; - this.m6 = m6; - this.m7 = m7; - } - } - - public class SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public T5 m5; - public T6 m6; - public T7 m7; - public T8 m8; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4, T5 m5, T6 m6, T7 m7, T8 m8) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - this.m5 = m5; - this.m6 = m6; - this.m7 = m7; - this.m8 = m8; - } - } - - - public class SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public T5 m5; - public T6 m6; - public T7 m7; - public T8 m8; - public T9 m9; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4, T5 m5, T6 m6, T7 m7, T8 m8, T9 m9) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - this.m5 = m5; - this.m6 = m6; - this.m7 = m7; - this.m8 = m8; - this.m9 = m9; - } - } - public class SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public T5 m5; - public T6 m6; - public T7 m7; - public T8 m8; - public T9 m9; - public T10 m10; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4, T5 m5, T6 m6, T7 m7, T8 m8, T9 m9, T10 m10) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - this.m5 = m5; - this.m6 = m6; - this.m7 = m7; - this.m8 = m8; - this.m9 = m9; - this.m10 = m10; - } - } - - public class SimpleStruct - { - public T1 m1; - public T2 m2; - public T3 m3; - public T4 m4; - public T5 m5; - public T6 m6; - public T7 m7; - public T8 m8; - public T9 m9; - public T10 m10; - public T11 m11; - public SimpleStruct(T1 m1, T2 m2, T3 m3, T4 m4, T5 m5, T6 m6, T7 m7, T8 m8, T9 m9, T10 m10, T11 m11) - { - this.m1 = m1; - this.m2 = m2; - this.m3 = m3; - this.m4 = m4; - this.m5 = m5; - this.m6 = m6; - this.m7 = m7; - this.m8 = m8; - this.m9 = m9; - this.m10 = m10; - this.m11 = m11; - } - } - public class Table - { - public Table() - { - } - } -} \ No newline at end of file diff --git a/src/SharpConnect.Data/TreeModel/EsDataImpl.cs b/src/SharpConnect.Data/TreeModel/EsDataImpl.cs index 4e709bd..cbb9b8d 100644 --- a/src/SharpConnect.Data/TreeModel/EsDataImpl.cs +++ b/src/SharpConnect.Data/TreeModel/EsDataImpl.cs @@ -1,4 +1,4 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors +//MIT, 2015-present, brezza92, EngineKit and contributors using System; using System.Collections.Generic; @@ -7,33 +7,30 @@ namespace SharpConnect.Data { public class EaseDocument : EsDoc { - Dictionary _stringTable = new Dictionary(); + //Dictionary _stringTable = new Dictionary(); public EaseDocument() { } public EsElem CreateElement(string elementName) { - return new EaseElement(elementName, this); - } - public EsElem CreateElement() - { - return new EaseElement("", this); - } - public EsArr CreateArray() - { - return new EaseArray(); - } - public int GetStringIndex(string str) - { - _stringTable.TryGetValue(str, out int found); - return found; - } - public EsElem DocumentElement - { - get; - set; + var elem = new EaseElement(); + elem.Name = elementName; + return elem; } + + public EsElem CreateElement() => new EaseElement(); + + public EsArr CreateArray() => new EaseArray(); + + //public int GetStringIndex(string str) + //{ + // _stringTable.TryGetValue(str, out int found); + // return found; + //} + + public EsElem DocumentElement { get; set; } + public EsElem Parse(string jsonstr) { return Parse(jsonstr.ToCharArray()); @@ -44,104 +41,76 @@ public EsElem Parse(char[] jsonstr) parser.Parse(jsonstr); return parser.CurrentElement as EsElem; } + public EsAttr CreateAttribute(string key, object value) => new EaseAttribute(key, value); } - class EaseArray : List, EsArr - { - public void AddItem(object item) - { - Add(item); - } - public IEnumerable GetIterForward() - { - foreach (object obj in this) - { - yield return obj; - } - } - } + static class EsElemHelper { public static EsElem CreateXmlElementForDynamicObject(EsDoc doc) { - return new EaseElement("!j", null); + var elem = new EaseElement(); + elem.Name = "!j"; + return elem; } } - - class EaseElement : EsElem + class EaseArray : EsArr { - //xml-like element + List _member = new List(); - string _name; - int _nameIndex; - EsDoc _owner; - List _childNodes; - Dictionary _attributeDic01 = new Dictionary(); - public EaseElement(string elementName, EsDoc ownerdoc) - { - _name = elementName; - _owner = ownerdoc; - } - public string Name + public object this[int index] { - get - { - return _name; - } - set - { - _name = value; - } + get => _member[index]; + set => _member[index] = value; } - public EsDoc OwnerDocument + + public int Count => _member.Count; + + public void AddItem(object item) { - get - { - return _owner; - } + _member.Add(item); } - public bool HasOwnerDocument + + public void Clear() { - get - { - return _owner != null; - } + _member.Clear(); } - public int ChildCount + + public IEnumerable GetIter() { - get + foreach (object obj in _member) { - if (_childNodes == null) - { - return 0; - } - else - { - return _childNodes.Count; - } + yield return obj; } } - public object GetChild(int index) - { - return _childNodes[index]; - } - public int NameIndex + } + + class EaseElement : EsElem + { + List _childNodes; + + Dictionary _attrs = new Dictionary(); + List _attrsValues = new List(); + + public EaseElement() { - get - { - return _nameIndex; - } + Name = ""; } + public string Name { get; set; } + public int AttributeCount => _attrs.Count; + public int ChildCount => (_childNodes == null) ? 0 : _childNodes.Count; + public object GetChild(int index) => _childNodes[index]; public IEnumerable GetAttributeIterForward() { - if (_attributeDic01 != null) + if (_attrsValues != null) { - foreach (EsAttr attr in _attributeDic01.Values) + foreach (EaseAttribute kv in _attrsValues) { - yield return attr; + yield return kv; } } } + public void AppendChild(EsElem element) { if (_childNodes == null) @@ -150,81 +119,63 @@ public void AppendChild(EsElem element) } _childNodes.Add(element); } - public void RemoveAttribute(EsAttr attr) - { - _attributeDic01.Remove(attr.Name); - } - public void AppendAttribute(EsAttr attr) - { - _attributeDic01.Add(attr.Name, attr); - } - public EsAttr AppendAttribute(string key, object value) + public void RemoveAttribute(string key) { - var attr = new EaseAttribute(key, value); - _attributeDic01.Add(key, attr); - return attr; + if (_attrs.TryGetValue(key, out int index)) + { + _attrs.Remove(key); + _attrsValues.RemoveAt(index); + } } - public object GetAttributeValue(string key) + public void AppendAttribute(string key, object value) { - EsAttr found = GetAttribute(key); - if (found != null) + //check unique key + if (!_attrs.TryGetValue(key, out int index)) { - return found.Value; + _attrs.Add(key, _attrsValues.Count); + _attrsValues.Add(new EaseAttribute(key, value)); } else { - return null; + throw new Exception("duplicated key"); } } - public EsAttr GetAttribute(string key) - { - EsAttr existing; - _attributeDic01.TryGetValue(key, out existing); - return existing; - } - /// - /// get attribute value if exist / set=> insert or replace existing value with specific value - /// - /// - /// - public object this[string key] + + + public object GetAttributeValue(string key) { - get + if (_attrs.TryGetValue(key, out int index)) { - EsAttr found = GetAttribute(key); - if (found == null) - { - return null; - } - else - { - return found.Value; - } + return _attrsValues[index].Value; } - set + return null; + } + public EsAttr GetAttribute(int index) + { + return _attrsValues[index]; + } + + public EsAttr GetAttribute(string key) + { + if (_attrs.TryGetValue(key, out int index)) { - //replace value if existing - //we create new attr and replace it - //so it not affect existing attr - _attributeDic01[key] = new EaseAttribute(key, value); + return _attrsValues[index]; } + return null; } + public object UserData { get; set; } } + class EaseAttribute : EsAttr { - int _localNameIndex; - public EaseAttribute() - { - } public EaseAttribute(string name, object value) { Name = name; Value = value; } - public string Name { get; set; } - public object Value { get; set; } - public int AttributeLocalNameIndex => _localNameIndex; + public string Name { get; } + public object Value { get; } public override string ToString() => Name + ":" + Value; } @@ -303,37 +254,39 @@ public static EsElem GetAttributeValueAsElem(this EsElem esElem, string attrName { return esElem.GetAttributeValue(attrName) as EsElem; } + //----------------------------------------------------------------------- - public static void WriteJson(this EsDoc doc, StringBuilder stBuilder) + public static void WriteJson(this EsDoc doc, StringBuilder sb) { //write to var docElem = doc.DocumentElement; if (docElem != null) { - WriteJson(docElem, stBuilder); + WriteJson(docElem, sb); } } - static void WriteJson(EsArr esArr, StringBuilder stBuilder) + static void WriteJson(EsArr esArr, StringBuilder sb) { - stBuilder.Append('['); + sb.Append('['); int j = esArr.Count; for (int i = 0; i < j; ++i) { if (i > 0) { - stBuilder.Append(','); + sb.Append(','); } - WriteJson(esArr[i], stBuilder); + WriteJson(esArr[i], sb); } - stBuilder.Append(']'); + sb.Append(']'); } - public static void WriteJson(this EsElem esElem, StringBuilder stBuilder) + + public static void WriteJson(this EsElem esElem, StringBuilder sb) { - EaseElement leqE = (EaseElement)esElem; - stBuilder.Append('{'); + EaseElement elem = (EaseElement)esElem; + sb.Append('{'); //check docattr= - var nameAttr = leqE.GetAttribute("!n"); + string nameAttr = elem.GetAttributeValueAsString("!n"); int attrCount = 0; if (nameAttr == null) { @@ -346,15 +299,13 @@ public static void WriteJson(this EsElem esElem, StringBuilder stBuilder) else { //use default elementname - stBuilder.Append("\"!n\":\""); + sb.Append("\"!n\":\""); //TODO: review string escape here *** - stBuilder.Append(leqE.Name); - stBuilder.Append('"'); + sb.Append(elem.Name); + sb.Append('"'); attrCount = 1; } - - - foreach (var attr in leqE.GetAttributeIterForward()) + foreach (EsAttr attr in elem.GetAttributeIterForward()) { if (attr.Name == "!n") { @@ -362,40 +313,41 @@ public static void WriteJson(this EsElem esElem, StringBuilder stBuilder) } if (attrCount > 0) { - stBuilder.Append(','); + sb.Append(','); } - stBuilder.Append('"'); - stBuilder.Append(attr.Name); //TODO: review escape string here - stBuilder.Append('"'); - stBuilder.Append(':'); - WriteJson(attr.Value, stBuilder); + sb.Append('"'); + sb.Append(attr.Name); //TODO: review escape string here + sb.Append('"'); + sb.Append(':'); + WriteJson(attr.Value, sb); attrCount++; } //------------------- //for children nodes - int j = leqE.ChildCount; + int j = elem.ChildCount; //create children nodes if (j > 0) { if (attrCount > 0) { - stBuilder.Append(','); + sb.Append(','); } - stBuilder.Append("\"!c\":["); + sb.Append("\"!c\":["); for (int i = 0; i < j; ++i) { if (i > 0) { - stBuilder.Append(','); + sb.Append(','); } - WriteJson(leqE.GetChild(i), stBuilder); + WriteJson(elem.GetChild(i), sb); } - stBuilder.Append(']'); + sb.Append(']'); } //------------------- - stBuilder.Append('}'); + sb.Append('}'); } + public static string ToJsonString(this EsElem esElem) { var stbuilder = new StringBuilder(); @@ -404,7 +356,7 @@ public static string ToJsonString(this EsElem esElem) } - public static void WriteJson(object elem, StringBuilder stBuilder) + public static void WriteJson(object elem, StringBuilder sb) { //recursive #if DEBUG @@ -412,13 +364,15 @@ public static void WriteJson(object elem, StringBuilder stBuilder) #endif if (elem == null) { - stBuilder.Append("null"); + sb.Append("null"); } else if (elem is string) { - stBuilder.Append('"'); - stBuilder.Append((string)elem); - stBuilder.Append('"'); + sb.Append('"'); + //TODO: proper escape json string + //ensure we scape " inside this string + sb.Append((string)elem); + sb.Append('"'); } else if (elem is double || (elem is float) || @@ -426,49 +380,49 @@ public static void WriteJson(object elem, StringBuilder stBuilder) (elem is uint)) { //TODO: review all primitive conversion - stBuilder.Append(elem.ToString()); + sb.Append(elem.ToString()); } - else if (elem is Array) + else if (elem is Array a) { - stBuilder.Append('['); + sb.Append('['); //write element into array - Array a = elem as Array; + int j = a.Length; for (int i = 0; i < j; ++i) { if (i > 0) { - stBuilder.Append(','); + sb.Append(','); } - WriteJson(a.GetValue(i), stBuilder); + WriteJson(a.GetValue(i), sb); } - stBuilder.Append(']'); + sb.Append(']'); } - else if (elem is EaseElement) + else if (elem is EaseElement ease_elem) { - WriteJson((EsElem)elem, stBuilder); + WriteJson(ease_elem, sb); } - else if (elem is EsArr) + else if (elem is EsArr es_arr) { - WriteJson((EsArr)elem, stBuilder); + WriteJson(es_arr, sb); } - else if (elem is DateTime) + else if (elem is DateTime d) { //write datetime as string - stBuilder.Append('"'); - stBuilder.Append(string.Format("{0:u}", (DateTime)elem)); - stBuilder.Append('"'); + sb.Append('"'); + sb.Append(string.Format("{0:u}", d)); + sb.Append('"'); } else { - stBuilder.Append(elem.ToString()); + //get if we + Type elemType = elem.GetType(); + //find codec of this type + + sb.Append(elem.ToString()); //throw new NotSupportedException(); } } - //----------------------------------------------------------------------- - public static void WriteXml(this EsDoc doc, StringBuilder stbuiolder) - { - throw new NotSupportedException(); - } + } } \ No newline at end of file diff --git a/src/SharpConnect.Data/TreeModel/EsDataInterface.cs b/src/SharpConnect.Data/TreeModel/EsDataInterface.cs index 711c817..1a6a2da 100644 --- a/src/SharpConnect.Data/TreeModel/EsDataInterface.cs +++ b/src/SharpConnect.Data/TreeModel/EsDataInterface.cs @@ -1,44 +1,53 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors +//MIT, 2015-present, brezza92, EngineKit and contributors using System.Collections.Generic; namespace SharpConnect.Data { + /// + /// ease element + /// public interface EsElem { string Name { get; set; } - EsDoc OwnerDocument { get; } - bool HasOwnerDocument { get; } - int NameIndex { get; } IEnumerable GetAttributeIterForward(); - void RemoveAttribute(EsAttr attr); + void RemoveAttribute(string key); void AppendChild(EsElem element); - void AppendAttribute(EsAttr attr); - EsAttr AppendAttribute(string key, object value); + void AppendAttribute(string key, object value); object GetAttributeValue(string key); EsAttr GetAttribute(string key); + EsAttr GetAttribute(int index); + int ChildCount { get; } + int AttributeCount { get; } object GetChild(int index); - object this[string attrName] { get; set; } + object UserData { get; set; } } + /// + /// ease attribute + /// public interface EsAttr { - string Name { get; set; } - object Value { get; set; } - int AttributeLocalNameIndex { get; } + string Name { get; } + object Value { get; } } + /// + /// ease array + /// public interface EsArr { void AddItem(object item); - IEnumerable GetIterForward(); + IEnumerable GetIter(); void Clear(); int Count { get; } object this[int index] { get; set; } } + /// + /// ease doc + /// public interface EsDoc { - - EsElem CreateElement(string elementName); EsElem CreateElement(); + EsElem CreateElement(string name); EsArr CreateArray(); EsElem DocumentElement { get; set; } } diff --git a/src/SharpConnect.Data/TreeModel/EsParser.cs b/src/SharpConnect.Data/TreeModel/EsParser.cs index d945fd2..72a5dfc 100644 --- a/src/SharpConnect.Data/TreeModel/EsParser.cs +++ b/src/SharpConnect.Data/TreeModel/EsParser.cs @@ -1,4 +1,4 @@ -//MIT, 2015-2016, brezza92, EngineKit and contributors +//MIT, 2015-present, brezza92, EngineKit and contributors using System; using System.Collections.Generic; using System.Text; @@ -168,6 +168,24 @@ static void ReadBlockComment(char[] sourceBuffer, int startAt, ref int latestInd } + bool _isSuccess; + bool IsSuccess + { + get => _isSuccess; + set + { +#if DEBUG + if (!value) + { + + } +#endif + _isSuccess = value; + } + } + + + public virtual void Parse(char[] sourceBuffer) { OnParseStart(); @@ -175,12 +193,13 @@ public virtual void Parse(char[] sourceBuffer) EsElementKind currentElementKind = EsElementKind.Unknown; Stack elemKindStack = new Stack(); //-------------------------------------------------------------- + IsSuccess = true; StringBuilder myBuffer = new StringBuilder(); //string lastestKey = ""; ParsingState currentState = ParsingState._0_Init; int j = sourceBuffer.Length; - bool isSuccess = true; + bool isInKeyPart = false; NumberPart numberPart = NumberPart.IntegerPart; @@ -195,7 +214,8 @@ public virtual void Parse(char[] sourceBuffer) ValueHint currentValueHint = ValueHint.Unknown; for (i = 0; i < j; i++) { - if (!isSuccess) + + if (!IsSuccess) { OnError(ref i); //handle the error **** @@ -256,7 +276,7 @@ public virtual void Parse(char[] sourceBuffer) } else { - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -272,7 +292,7 @@ public virtual void Parse(char[] sourceBuffer) } else { - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -302,7 +322,7 @@ public virtual void Parse(char[] sourceBuffer) if (currentElementKind != EsElementKind.Object) { NotifyError(); - isSuccess = false; + IsSuccess = false; } else { @@ -353,7 +373,7 @@ public virtual void Parse(char[] sourceBuffer) } else { - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -366,7 +386,7 @@ public virtual void Parse(char[] sourceBuffer) //number or other token will error in keypart*** NotifyError(); - isSuccess = false; + IsSuccess = false; break; } } @@ -472,7 +492,7 @@ public virtual void Parse(char[] sourceBuffer) else { //error - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -480,7 +500,7 @@ public virtual void Parse(char[] sourceBuffer) default: { NotifyError(); - isSuccess = false; + IsSuccess = false; } break; } @@ -523,7 +543,7 @@ public virtual void Parse(char[] sourceBuffer) } else { - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -533,7 +553,7 @@ public virtual void Parse(char[] sourceBuffer) { //TODO: add recovery extension here NotifyError(); - isSuccess = false; + IsSuccess = false; break; } } @@ -582,7 +602,7 @@ public virtual void Parse(char[] sourceBuffer) if (currentElementKind != EsElementKind.Array) { NotifyError(); - isSuccess = false; + IsSuccess = false; } else { @@ -618,7 +638,7 @@ public virtual void Parse(char[] sourceBuffer) } else { - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -711,7 +731,7 @@ public virtual void Parse(char[] sourceBuffer) } else { - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -748,7 +768,7 @@ public virtual void Parse(char[] sourceBuffer) else { NotifyError(); - isSuccess = false; + IsSuccess = false; break; } } @@ -767,7 +787,7 @@ public virtual void Parse(char[] sourceBuffer) break; default: NotifyError(); - isSuccess = false; + IsSuccess = false; break; } } @@ -781,7 +801,7 @@ public virtual void Parse(char[] sourceBuffer) break; default: NotifyError(); - isSuccess = false; + IsSuccess = false; break; } } @@ -829,10 +849,63 @@ public virtual void Parse(char[] sourceBuffer) break; } } + else if (c == '\r') + { + //stop here + if (i < j - 1) + { + if (sourceBuffer[i + 1] == '\n') + { + //\r\n + i++; + + NewValue(myBuffer, currentValueHint); + //clear + myBuffer.Length = 0; + + switch (currentElementKind) + { + default: throw new NotSupportedException(); + case EsElementKind.Array: + isInKeyPart = false; + currentState = ParsingState._5_ExpectObjectValueOrArrayElement; + break; + case EsElementKind.Object: + isInKeyPart = true; + currentState = ParsingState._1_ObjectKey; + break; + } + } + else + { + //only R + } + } + } + else if (c == '\n') + { + //stop + NewValue(myBuffer, currentValueHint); + //clear + myBuffer.Length = 0; + + switch (currentElementKind) + { + default: throw new NotSupportedException(); + case EsElementKind.Array: + isInKeyPart = false; + currentState = ParsingState._5_ExpectObjectValueOrArrayElement; + break; + case EsElementKind.Object: + isInKeyPart = true; + currentState = ParsingState._1_ObjectKey; + break; + } + } else { - isSuccess = false; + IsSuccess = false; NotifyError(); } } @@ -855,14 +928,14 @@ public virtual void Parse(char[] sourceBuffer) else { NotifyError(); - isSuccess = false; + IsSuccess = false; } break; case '}': if (isInKeyPart) { NotifyError(); - isSuccess = false; + IsSuccess = false; } else { @@ -881,7 +954,7 @@ public virtual void Parse(char[] sourceBuffer) if (isInKeyPart) { NotifyError(); - isSuccess = false; + IsSuccess = false; } else { @@ -901,7 +974,7 @@ public virtual void Parse(char[] sourceBuffer) if (isInKeyPart) { NotifyError(); - isSuccess = false; + IsSuccess = false; } else { @@ -990,11 +1063,10 @@ enum CurrentObject Array } - Stack keyStack = new Stack(); - Stack elemStack = new Stack(); - object currentElem = null; - string currentKey = null; - + Stack _keyStack = new Stack(); + Stack _elemStack = new Stack(); + object _currentElem = null; + string _currentKey = null; public EsParserBase() { @@ -1011,39 +1083,39 @@ protected override void OnParseStart() } protected override void BeginObject() { - if (currentKey != null) + if (_currentKey != null) { - keyStack.Push(currentKey); + _keyStack.Push(_currentKey); } - currentKey = null; - if (currentElem != null) + _currentKey = null; + if (_currentElem != null) { - elemStack.Push(currentElem); + _elemStack.Push(_currentElem); } - currentElem = CreateElement(); + _currentElem = CreateElement(); } void InternalPopCurrentObjectAndPushToPrevContext() { //current element should be object - object c_object = currentElem; - if (elemStack.Count > 0) + object c_object = _currentElem; + if (_elemStack.Count > 0) { //pop from stack - currentElem = elemStack.Pop(); - currentKey = null; - if (c_object == currentElem) + _currentElem = _elemStack.Pop(); + _currentKey = null; + if (c_object == _currentElem) { throw new System.Exception(); } E c_elem = null; A c_arr = null; - if ((c_elem = currentElem as E) != null) + if ((c_elem = _currentElem as E) != null) { - currentKey = keyStack.Pop(); - AddElementAttribute(c_elem, currentKey, c_object); + _currentKey = _keyStack.Pop(); + AddElementAttribute(c_elem, _currentKey, c_object); } - else if ((c_arr = currentElem as A) != null) + else if ((c_arr = _currentElem as A) != null) { AddArrayElement(c_arr, c_object); } @@ -1059,16 +1131,16 @@ protected override void EndObject() } protected override void BeginArray() { - if (currentKey != null) + if (_currentKey != null) { - keyStack.Push(currentKey); + _keyStack.Push(_currentKey); } - currentKey = null; - if (currentElem != null) + _currentKey = null; + if (_currentElem != null) { - elemStack.Push(currentElem); + _elemStack.Push(_currentElem); } - currentElem = CreateArray(); + _currentElem = CreateArray(); } protected override void EndArray() { @@ -1080,7 +1152,7 @@ protected override void OnParseEnd() } protected override void NewKey(StringBuilder tmpBuffer, ValueHint valueHint) { - currentKey = tmpBuffer.ToString(); + _currentKey = tmpBuffer.ToString(); } protected override void NewValue(StringBuilder tmpBuffer, ValueHint valueHint) { @@ -1124,11 +1196,11 @@ protected override void NewValue(StringBuilder tmpBuffer, ValueHint valueHint) E c_elem = null; A c_arr = null; - if ((c_elem = currentElem as E) != null) + if ((c_elem = _currentElem as E) != null) { - AddElementAttribute(c_elem, currentKey, c_object); + AddElementAttribute(c_elem, _currentKey, c_object); } - else if ((c_arr = currentElem as A) != null) + else if ((c_arr = _currentElem as A) != null) { AddArrayElement(c_arr, c_object); } @@ -1146,6 +1218,6 @@ protected override void OnError(ref int currentIndex) { base.OnError(ref currentIndex); } - public object CurrentElement { get { return currentElem; } } + public object CurrentElement => _currentElem; } } \ No newline at end of file diff --git a/src/SharpConnect.Data/TreeModel/EsUniqueStringTable.cs b/src/SharpConnect.Data/TreeModel/EsUniqueStringTable.cs index 17eb211..fdd7053 100644 --- a/src/SharpConnect.Data/TreeModel/EsUniqueStringTable.cs +++ b/src/SharpConnect.Data/TreeModel/EsUniqueStringTable.cs @@ -7,14 +7,15 @@ namespace SharpConnect.Data public class EsUniqueStringTable { - Dictionary dic; - List list; + Dictionary _dic; + List _list; + public EsUniqueStringTable() { - dic = new Dictionary(); - list = new List(); - dic.Add(string.Empty, 0); - list.Add(string.Empty); + _dic = new Dictionary(); + _list = new List(); + _dic.Add("", 0); + _list.Add(""); } public int GetStringIndex(string str) @@ -25,7 +26,7 @@ public int GetStringIndex(string str) return 0; } int foundIndex; - if (dic.TryGetValue(str, out foundIndex)) + if (_dic.TryGetValue(str, out foundIndex)) { return foundIndex; } @@ -44,60 +45,49 @@ public int AddStringIfNotExist(string str) } //--------------------------------------- int foundIndex; - if (dic.TryGetValue(str, out foundIndex)) + if (_dic.TryGetValue(str, out foundIndex)) { return foundIndex; } else { - int index = dic.Count; - dic.Add(str, index); - list.Add(str); + int index = _dic.Count; + _dic.Add(str, index); + _list.Add(str); return index; } } - public bool Contains(string str) - { - return dic.ContainsKey(str); - } - public int Count - { - get - { - return dic.Count; - } - } - public string GetString(int index) - { - return list[index]; - } + + public bool Contains(string str) => _dic.ContainsKey(str); + + public int Count => _dic.Count; + + public string GetString(int index) => _list[index]; + public IEnumerable WordIter { get { - foreach (string str in dic.Keys) + foreach (string str in _dic.Keys) { yield return str; } } } - public List GetStringList() - { - return list; - } + public List GetStringList() => _list; public EsUniqueStringTable Clone() { EsUniqueStringTable newClone = new EsUniqueStringTable(); - Dictionary cloneDic = newClone.dic; + Dictionary cloneDic = newClone._dic; cloneDic.Clear(); - foreach (KeyValuePair kp in this.dic) + foreach (KeyValuePair kp in _dic) { cloneDic.Add(kp.Key, kp.Value); } - newClone.list.Clear(); - newClone.list.AddRange(list); + newClone._list.Clear(); + newClone._list.AddRange(_list); return newClone; } diff --git a/src/SharpConnect.Data/Utils/EsCompressionUtils.cs b/src/SharpConnect.Data/Utils/EsCompressionUtils.cs deleted file mode 100644 index cd83f15..0000000 --- a/src/SharpConnect.Data/Utils/EsCompressionUtils.cs +++ /dev/null @@ -1,72 +0,0 @@ -//MIT, 2016-2017 -using System; -using System.IO; -using System.IO.Compression; -namespace SharpConnect.Data -{ - - public static class CompressionUtils - { - - public static byte[] GetCompressData(byte[] orgBuffer) - { - using (MemoryStream ms = new MemoryStream()) - using (GZipStream compressedzipStream = new GZipStream(ms, CompressionMode.Compress, true)) - { - //Console.WriteLine("Compression"); - compressedzipStream.Write(orgBuffer, 0, orgBuffer.Length); - // Close the stream. - compressedzipStream.Close(); - //Console.WriteLine("Original size: {0}, Compressed size: {1}", orgBuffer.Length, ms.Length); - - // Reset the memory stream position to begin decompression. - ms.Position = 0; - byte[] compressedData = ms.ToArray(); - ms.Close(); - return compressedData; - } - } - public static byte[] DecompressData(byte[] compressedBuffer) - { - - using (MemoryStream ms2 = new MemoryStream()) - using (MemoryStream decompressedMs = new MemoryStream()) - using (GZipStream zipStream = new GZipStream(ms2, CompressionMode.Decompress)) - { - ms2.Write(compressedBuffer, 0, compressedBuffer.Length); - ms2.Position = 0; - //Console.WriteLine("Decompression"); - // Use the ReadAllBytesFromStream to read the stream. - int totalCount = ReadAllBytesFromStream(zipStream, decompressedMs); - // Console.WriteLine("Decompressed {0} bytes", totalCount); - byte[] decompressedBuffer = decompressedMs.ToArray(); - - return decompressedBuffer; - } - } - static int ReadAllBytesFromStream(Stream compressStream, MemoryStream outputStream) - { - // Use this method is used to read all bytes from a stream. - int offset = 0; - int totalCount = 0; - byte[] buffer = new byte[256]; - - while (true) - { - //read into buffer - int bytesRead = compressStream.Read(buffer, 0, 100); - if (bytesRead == 0) - { - break; - } - outputStream.Write(buffer, 0, bytesRead); - offset += bytesRead; - totalCount += bytesRead; - } - return totalCount; - } - - - - } -} \ No newline at end of file diff --git a/src/Test01/Program.cs b/src/Test01/Program.cs index 91ce03a..99514da 100644 --- a/src/Test01/Program.cs +++ b/src/Test01/Program.cs @@ -11,9 +11,10 @@ class Program { static void Main(string[] args) { - TestLqDoc(); + TestParseEaseDoc(); + TestParseCommentInJsonText(); } - static void TestLqDoc() + static void TestParseEaseDoc() { EaseDocument doc = new EaseDocument(); var elem = doc.CreateElement("user_info"); @@ -36,5 +37,19 @@ static void TestLqDoc() List memberlist4 = new List() { 1, 2, 3, 4, 5 }; elem.AppendAttribute("memberlist4", memberlist4); } + static void TestParseCommentInJsonText() + { + //test ease doc, json with comment + string teststring = @"/**144*/{ + ""a"":20,/**144*/ + //this is a comment + + //another comment + ""b"":""x""}/**144*/"; + + EaseDocument esdoc = new EaseDocument(); + EsElem esElem = esdoc.Parse(teststring); + + } } }