From e30a76296900bb44a4043ffc14c5d1259a1ea3f2 Mon Sep 17 00:00:00 2001 From: Taha Date: Fri, 29 Sep 2023 22:15:51 -0400 Subject: [PATCH] Adding tests --- .../BlueData/BlueDataUtility.cs | 835 ++++++++++++------ .../Test/CompressionSerializationTest.cs | 236 +++++ .../Test/FixedChangingRowSerializationTest.cs | 100 +++ .../Test/FixedChangingSerializationTest.cs | 40 + .../Test/MarketOptionTheoSerializationTest.cs | 73 ++ .../Messaging/Test/Performance.cs | 46 + .../Messaging/Test/TableAccumulatorTest.cs | 275 ++++++ .../Test/UniversalRowSerializerTest.cs | 58 ++ .../DataStreamPublisher/Program.cs | 2 +- .../DataStreamQueryAnalyzer/Program.cs | 3 +- src/DataStreamSuite/DataStreamSuite.sln | 18 +- .../DataStreamTests/DataStreamTests.csproj | 19 - .../UniversalSerializationTest.cs | 195 ++++ .../DataStreamTests/UnitTest1.cs | 15 - 14 files changed, 1592 insertions(+), 323 deletions(-) create mode 100644 src/DataStreamSuite/DataStreamCore/Messaging/Test/CompressionSerializationTest.cs create mode 100644 src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingRowSerializationTest.cs create mode 100644 src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingSerializationTest.cs create mode 100644 src/DataStreamSuite/DataStreamCore/Messaging/Test/MarketOptionTheoSerializationTest.cs create mode 100644 src/DataStreamSuite/DataStreamCore/Messaging/Test/Performance.cs create mode 100644 src/DataStreamSuite/DataStreamCore/Messaging/Test/TableAccumulatorTest.cs create mode 100644 src/DataStreamSuite/DataStreamCore/Messaging/Test/UniversalRowSerializerTest.cs create mode 100644 src/DataStreamSuite/DataStreamTests/StreamSerialization/UniversalSerializationTest.cs diff --git a/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs b/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs index 3ae2e9092..86b3b4241 100644 --- a/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs +++ b/src/DataStreamSuite/DataStreamCore/BlueData/BlueDataUtility.cs @@ -13,32 +13,42 @@ using System.Linq.Expressions; //using mbts.spark; using mbts; -namespace BCG { - public static class BlueDataUtility { +namespace BCG +{ + public static class BlueDataUtility + { #region Extensions - public static DateTime get_datetime(this IBlueRow r, string col_name, DateTime err_value = default(DateTime)) { + public static DateTime get_datetime(this IBlueRow r, string col_name, DateTime err_value = default(DateTime)) + { return BlueDataUtility.get_row_datetime_value(r, col_name, err_value); } - public static DateTime get_datetime(this IBlueRow r, int col_no, DateTime err_value = default(DateTime)) { + public static DateTime get_datetime(this IBlueRow r, int col_no, DateTime err_value = default(DateTime)) + { return BlueDataUtility.get_row_datetime_value(r, col_no, err_value); } - public static T get_enum(this IBlueRow r, string col_name, T err_value = default(T)) where T : struct { + public static T get_enum(this IBlueRow r, string col_name, T err_value = default(T)) where T : struct + { return BlueDataUtility.get_row_enum_value(r, col_name, err_value); } - public static T get_enum(this IBlueRow r, int col_no, T err_value = default(T)) where T : struct { + public static T get_enum(this IBlueRow r, int col_no, T err_value = default(T)) where T : struct + { return BlueDataUtility.get_row_enum_value(r, col_no, err_value); } - public static T get(this IBlueRow r, string col_name, T err_value = default(T)) { + public static T get(this IBlueRow r, string col_name, T err_value = default(T)) + { return get_row_value(r, col_name, err_value); } - public static T get(this IBlueRow r, int col_no, T err_value = default(T)) { + public static T get(this IBlueRow r, int col_no, T err_value = default(T)) + { return get_row_value(r, col_no, err_value); } - public static IBlueRowCollection where(this IBlueRowCollection rows, Func where_func) { + public static IBlueRowCollection where(this IBlueRowCollection rows, Func where_func) + { if (rows == null) return null; - else { + else + { BlueTable rv = new BlueTable(rows.schema); foreach (IBlueRow r in rows) if (where_func(r)) @@ -47,24 +57,28 @@ namespace BCG { } } - public static IEnumerable to_ienum(this IBlueRowCollection rows) { + public static IEnumerable to_ienum(this IBlueRowCollection rows) + { List rv = new List(); foreach (IBlueRow r in rows) rv.Add(r); return rv; } - public static IBlueTableSchema add_columns(this IBlueTableSchema input_schema, params Tuple[] cols) { + public static IBlueTableSchema add_columns(this IBlueTableSchema input_schema, params Tuple[] cols) + { List cis = new List(input_schema.columnInfo); foreach (Tuple c in cols) cis.Add(new ColumnInfo(c.Item2, cis.Count, c.Item1)); return new BlueTableSchema(input_schema.tableName, cis.ToArray()); } - public static IBlueRowCollection to_collection(this IBlueRow r) { + public static IBlueRowCollection to_collection(this IBlueRow r) + { if (r == null) return null; - else { + else + { BlueTable rv = new BlueTable(r.schema); rv.addRow(r); return rv; @@ -73,13 +87,17 @@ namespace BCG { public static IBlueRowCollection adapt_for_sql_storage(this IBlueRowCollection rows, bool handle_datetime_min = false, - bool handle_double_nan = false) { - if (rows != null) { + bool handle_double_nan = false) + { + if (rows != null) + { BlueTable rv = new BlueTable(rows.schema); - foreach (IBlueRow r in rows) { + foreach (IBlueRow r in rows) + { MutableBlueRow mr = new MutableBlueRow(r); rv.addRow(mr); - foreach (ColumnInfo ci in rows.schema.columnInfo) { + foreach (ColumnInfo ci in rows.schema.columnInfo) + { if (handle_datetime_min && ci.colType == typeof(DateTime) && DateTime.MinValue.Equals(r[ci.colName])) mr.setValue(ci.colName, DBNull.Value); if (handle_double_nan && ci.colType == typeof(double) && Double.IsNaN(r.get(ci.colName))) @@ -87,16 +105,19 @@ namespace BCG { } } return rv; - } else + } + else return null; } #endregion - public static void print_table(this IBlueRowCollection table, Func get_col_width) { + public static void print_table(this IBlueRowCollection table, Func get_col_width) + { // Print column headers - Console.WriteLine("______________________________________"); - foreach (var col_name in table.schema.columnNames) { + Console.WriteLine($"{table.schema.tableName}______________________________________"); + foreach (var col_name in table.schema.columnNames) + { int col_width = get_col_width(col_name); Console.Write($"{col_name.PadRight(col_width)} "); } @@ -104,12 +125,15 @@ namespace BCG { Console.WriteLine("______________________________________"); // Print table data - foreach (IBlueRow row in table) { - foreach (string col_name in table.schema.columnNames) { + foreach (IBlueRow row in table) + { + foreach (string col_name in table.schema.columnNames) + { int col_width = get_col_width(col_name); object row_val = row[col_name]; string row_val_str = row_val.ToString(); - if (row_val != null) { + if (row_val != null) + { Console.Write($"{row_val_str.PadRight(col_width)} "); } } @@ -138,7 +162,8 @@ namespace BCG { { TypeCode.UInt64, typeof(UInt64) } }; - public static IBlueTableSchema form_schema(string table_name, params Tuple[] cols) { + public static IBlueTableSchema form_schema(string table_name, params Tuple[] cols) + { List cis = new List(); foreach (Tuple c in cols) cis.Add(new ColumnInfo(c.Item1, cis.Count, _typecode_to_type[c.Item2])); @@ -154,14 +179,17 @@ namespace BCG { /// /// /// - public static int getRowHashCode(IBlueRow row, bool isColAlphabetically) { + public static int getRowHashCode(IBlueRow row, bool isColAlphabetically) + { string retVal = ""; - if (isColAlphabetically) { + if (isColAlphabetically) + { string[] colNames = row.schema.columnNames; Array.Sort(colNames); foreach (string col in colNames) retVal += row[col].ToString(); - } else + } + else foreach (object o in row) retVal += o.ToString(); return retVal.GetHashCode(); @@ -173,7 +201,8 @@ namespace BCG { /// /// /// - public static int getRowHashCode(IBlueRow row, params string[] colNames) { + public static int getRowHashCode(IBlueRow row, params string[] colNames) + { string retVal = ""; foreach (string colName in colNames) retVal += row[colName].ToString(); @@ -185,7 +214,8 @@ namespace BCG { /// /// /// - public static DataTable toDataTable(IBlueRowCollection rows) { + public static DataTable toDataTable(IBlueRowCollection rows) + { DataTable retTable = getTableFromSchema(rows.schema); retTable.BeginLoadData(); foreach (IBlueRow row in rows) @@ -200,7 +230,8 @@ namespace BCG { /// /// /// - public static DataRow toDataRow(IBlueRow row, DataTable table) { + public static DataRow toDataRow(IBlueRow row, DataTable table) + { DataRow retRow = table.NewRow(); foreach (string colName in row.schema.columnNames) retRow[colName] = row[colName]; @@ -223,7 +254,8 @@ namespace BCG { /// table whos Schema is desired /// /// - public static IBlueTableSchema getSchema(DataTable table) { + public static IBlueTableSchema getSchema(DataTable table) + { ColumnInfo[] cis = new ColumnInfo[table.Columns.Count]; foreach (DataColumn col in table.Columns) cis[col.Ordinal] = new ColumnInfo(col.ColumnName, col.Ordinal, col.DataType); @@ -236,7 +268,8 @@ namespace BCG { /// /// /// - public static IBlueTableSchema getSchema(object o) { + public static IBlueTableSchema getSchema(object o) + { return getSchema(o.GetType()); } @@ -246,7 +279,8 @@ namespace BCG { /// /// Base schema /// Columns to add - public static IBlueTableSchema addColumnsToSchema(IBlueTableSchema schema, params ColumnInfo[] cis) { + public static IBlueTableSchema addColumnsToSchema(IBlueTableSchema schema, params ColumnInfo[] cis) + { ArrayList rv = new ArrayList(schema.columnInfo); rv.AddRange(cis); return new BlueTableSchema(schema.tableName, rv.ToArray(typeof(ColumnInfo)) as ColumnInfo[]); @@ -258,7 +292,8 @@ namespace BCG { /// /// /// - public static IBlueTableSchema appendSchemas(IBlueTableSchema s1, IBlueTableSchema appendedSchema) { + public static IBlueTableSchema appendSchemas(IBlueTableSchema s1, IBlueTableSchema appendedSchema) + { List cis = new List(s1.columnInfo); foreach (ColumnInfo c in appendedSchema.columnInfo) if (c.colName != "id") @@ -267,15 +302,18 @@ namespace BCG { } - public static IBlueTableSchema getSchema(Type t) { + public static IBlueTableSchema getSchema(Type t) + { return getSchema(t, false); } - public static IBlueTableSchema getSchema(Type t, bool createIdField) { + public static IBlueTableSchema getSchema(Type t, bool createIdField) + { return getSchema(t, t.Name, createIdField); } - public static IBlueTableSchema getSchema(Type t, string tableName, bool createIdField) { + public static IBlueTableSchema getSchema(Type t, string tableName, bool createIdField) + { ArrayList colInfos = new ArrayList(); int i = 0; foreach (PropertyInfo pi in t.GetProperties()) @@ -295,17 +333,20 @@ namespace BCG { tableName); } - public static IBlueTableSchema getSchema(Type t, string tableName) { + public static IBlueTableSchema getSchema(Type t, string tableName) + { return new BlueTableSchema(getSchema(t).columnInfo, tableName); } - public static IBlueRow createRowFromType(IBlueTableSchema schema, object o) { + public static IBlueRow createRowFromType(IBlueTableSchema schema, object o) + { return createRowFromType(schema, o, null); } //creates a row from the given type, and if idVal is not null, using the given id - public static IBlueRow createRowFromType(IBlueTableSchema schema, object o, object idVal) { + public static IBlueRow createRowFromType(IBlueTableSchema schema, object o, object idVal) + { object[] rowArray = new object[schema.columnInfo.Length]; Type t = o.GetType(); foreach (PropertyInfo pi in t.GetProperties()) @@ -324,7 +365,8 @@ namespace BCG { } public static MutableBlueRow create_mutable_row(IBlueTableSchema schema, object o, object idVal, - Func type_converter) { + Func type_converter) + { object[] rowArray = new object[schema.columnInfo.Length]; Type t = o.GetType(); foreach (PropertyInfo pi in t.GetProperties()) @@ -343,7 +385,8 @@ namespace BCG { } - public static IBlueTableSchema get_schema(Type t, string tableName, bool createIdField, Func type_converter) { + public static IBlueTableSchema get_schema(Type t, string tableName, bool createIdField, Func type_converter) + { List colInfos = new List(); int i = 0; if (createIdField) @@ -357,13 +400,16 @@ namespace BCG { } public static MutableBlueRow create_mutable_row_not_slow(IBlueTableSchema schema, FieldInfo[] fields, PropertyInfo[] props, - object o, object idVal, Func data_converter) { + object o, object idVal, Func data_converter) + { object[] rowArray = new object[schema.columnInfo.Length]; - if (props != null) { + if (props != null) + { foreach (PropertyInfo pi in props) rowArray[schema[pi.Name].colNo] = data_converter(pi.PropertyType, pi.GetValue(o, null)); } - if (fields != null) { + if (fields != null) + { foreach (FieldInfo fi in fields) rowArray[schema[fi.Name].colNo] = data_converter(fi.FieldType, fi.GetValue(o)); } @@ -372,16 +418,19 @@ namespace BCG { return new MutableBlueRow(schema, rowArray); } - public static T createTypeFromRow(IBlueRow row) { + public static T createTypeFromRow(IBlueRow row) + { return (T)createTypeFromRow(row, typeof(T)); } - public static object createTypeFromRow(IBlueRow row, Type t) { + public static object createTypeFromRow(IBlueRow row, Type t) + { object outValue = Activator.CreateInstance(t); PropertyInfo[] properties = t.GetProperties(); - foreach (PropertyInfo pi in properties) { + foreach (PropertyInfo pi in properties) + { if (myIsActiveProperty(pi)) if (row.Contains(pi.Name)) if (row[pi.Name].Equals(DBNull.Value) && !pi.PropertyType.Equals(typeof(Object))) @@ -390,7 +439,8 @@ namespace BCG { pi.SetValue(outValue, row[pi.Name], null); } FieldInfo[] fields = t.GetFields(); - foreach (FieldInfo fi in fields) { + foreach (FieldInfo fi in fields) + { if (myIsActiveField(fi)) if (row.Contains(fi.Name)) if (row[fi.Name].Equals(DBNull.Value) && !fi.FieldType.Equals(typeof(Object))) @@ -405,15 +455,18 @@ namespace BCG { //these functions should originally have been made public //but changing that would change a bunch of code - public static bool isActiveProperty(PropertyInfo pi) { + public static bool isActiveProperty(PropertyInfo pi) + { return myIsActiveProperty(pi); } - public static bool isActiveField(FieldInfo fi) { + public static bool isActiveField(FieldInfo fi) + { return myIsActiveField(fi); } - private static bool myIsActiveProperty(PropertyInfo pi) { + private static bool myIsActiveProperty(PropertyInfo pi) + { if (pi.GetGetMethod() == null) return false; foreach (Attribute att in pi.GetCustomAttributes(true)) @@ -422,7 +475,8 @@ namespace BCG { return true; } - private static bool myIsActiveField(FieldInfo fi) { + private static bool myIsActiveField(FieldInfo fi) + { if (!fi.IsPublic) return false; foreach (Attribute att in fi.GetCustomAttributes(true)) @@ -431,7 +485,8 @@ namespace BCG { return true; } - private static bool myIsActiveMember(MemberInfo mi) { + private static bool myIsActiveMember(MemberInfo mi) + { if (!(mi is FieldInfo) || !(mi is PropertyInfo) || (mi is PropertyInfo && (mi as PropertyInfo).GetGetMethod() == null) || @@ -443,17 +498,21 @@ namespace BCG { return true; } - private static bool myDoesRowExistsInTable(IBlueRowCollection brc2, string[] columns, object[] oarray) { + private static bool myDoesRowExistsInTable(IBlueRowCollection brc2, string[] columns, object[] oarray) + { bool rowExists = false; - foreach (IBlueRow br in brc2) { + foreach (IBlueRow br in brc2) + { bool allElementsSame = true; - for (int i = 0; i < columns.Length; i++) { + for (int i = 0; i < columns.Length; i++) + { string col = columns[i]; object o1 = br[col]; object o2 = oarray[i]; allElementsSame = (o1.Equals(o2) == false) ? false : allElementsSame; } - if (allElementsSame == true) { + if (allElementsSame == true) + { rowExists = true; break; } @@ -468,7 +527,8 @@ namespace BCG { /// Schema whose table needs to be created /// /// - public static DataTable getTableFromSchema(IBlueTableSchema schema) { + public static DataTable getTableFromSchema(IBlueTableSchema schema) + { DataTable retTable = new DataTable(schema.tableName); foreach (ColumnInfo ci in schema.columnInfo) retTable.Columns.Add(ci.colName, ci.colType); @@ -480,20 +540,24 @@ namespace BCG { /// /// source row /// - public static IBlueRow toBlueRow(DataRow row) { + public static IBlueRow toBlueRow(DataRow row) + { return new BlueRow(getSchema(row), row); } - public static IBlueRowCollection toIBlueRowCollection(DataTable dt) { + public static IBlueRowCollection toIBlueRowCollection(DataTable dt) + { BlueTable retVal = new BlueTable(getSchema(dt)); foreach (DataRow dr in dt.Rows) retVal.addRow(dr); return retVal; } - public static IBlueRowCollection toIBlueRowCollection(DataRow[] rows) { + public static IBlueRowCollection toIBlueRowCollection(DataRow[] rows) + { BlueTable retVal = null; - foreach (DataRow dr in rows) { + foreach (DataRow dr in rows) + { IBlueRow r = toBlueRow(dr); if (retVal == null) retVal = new BlueTable(r.schema); @@ -510,7 +574,8 @@ namespace BCG { /// /// /// - public static IBlueRow extractRow(IBlueRowCollection rows, int index) { + public static IBlueRow extractRow(IBlueRowCollection rows, int index) + { int i = 0; foreach (IBlueRow row in rows) if (i++ == index) @@ -524,13 +589,15 @@ namespace BCG { /// /// /// - public static bool computeRowEquality(IBlueRow r1, IBlueRow r2) { + public static bool computeRowEquality(IBlueRow r1, IBlueRow r2) + { return computeRowEquality(r1, r2, r1.schema.columnNames); } public static bool computeRowEquality(IBlueRow r1, IBlueRow r2, - params string[] colNames) { + params string[] colNames) + { return compareRows(r1, r2, colNames) == 0 ? true : false; } @@ -541,7 +608,8 @@ namespace BCG { /// /// /// - public static string rowToString(IBlueRow row, params string[] colNames) { + public static string rowToString(IBlueRow row, params string[] colNames) + { string retVal = ""; foreach (string colName in colNames) retVal += (row[colName] != null ? row[colName].ToString().Trim() : "NULL") + "\n"; @@ -550,10 +618,12 @@ namespace BCG { public static string rowToString(IBlueRow row) { return rowToString(row, row.schema.columnNames); } - public static string rowCollectionToString(IBlueRowCollection rowColl) { + public static string rowCollectionToString(IBlueRowCollection rowColl) + { if (rowColl == null) return "Null IBlueRowCollection"; - else { + else + { string retVal = ""; foreach (IBlueRow r in rowColl) retVal += retVal == "" ? rowToString(r) : "\n" + rowToString(r); @@ -572,9 +642,11 @@ namespace BCG { /// public static int compareRows(IBlueRow r1, IBlueRow r2, - params string[] colNames) { + params string[] colNames) + { int retVal = 0; - foreach (string colName in colNames) { + foreach (string colName in colNames) + { object val1 = r1[colName]; object val2 = r2[colName]; retVal = _compare_row_cols(val1, val2); @@ -584,13 +656,16 @@ namespace BCG { return retVal; } - private static int _compare_row_cols(object v1, object v2) { + private static int _compare_row_cols(object v1, object v2) + { if (_is_null(v1)) return _is_null(v2) ? 0 : -1; - else { + else + { if (_is_null(v2)) return 1; - else { + else + { if (v1 is IComparable && v2 is IComparable) return (v1 as IComparable).CompareTo(v2); else if (v1 is byte[] && v2 is byte[]) @@ -601,7 +676,8 @@ namespace BCG { } } - private static bool _compare_bytes(byte[] v1, byte[] v2) { + private static bool _compare_bytes(byte[] v1, byte[] v2) + { if (v1.Length != v2.Length) return false; else @@ -618,7 +694,8 @@ namespace BCG { /// a row with the values to be converted /// the desired schema for the output row /// - public static IBlueRow changeSchema(IBlueRow inRow, IBlueTableSchema newSchema) { + public static IBlueRow changeSchema(IBlueRow inRow, IBlueTableSchema newSchema) + { object[] outputValues = new object[newSchema.columnInfo.Length]; for (int i = 0; i < outputValues.Length; ++i) @@ -633,7 +710,8 @@ namespace BCG { /// /// /// - public static IBlueRowCollection combineTables(params IBlueRowCollection[] tables) { + public static IBlueRowCollection combineTables(params IBlueRowCollection[] tables) + { //get some base cases out of the way if (tables.Length == 0) return null; @@ -645,12 +723,14 @@ namespace BCG { int numCols = tables[0].schema.columnInfo.Length; int idCol = tables[0].schema["id"].colNo; IBlueRowCollection previousTable = null; - foreach (IBlueRowCollection table in tables) { + foreach (IBlueRowCollection table in tables) + { if (previousTable != null) if (!compareSchemas(previousTable.schema, table.schema)) throw new ArgumentException("Error, tables must have the same schema to be combined"); - foreach (IBlueRow r in table) { + foreach (IBlueRow r in table) + { object[] values = new object[numCols]; r.CopyTo(values, 0); values[idCol] = idToUseNext++; @@ -670,7 +750,8 @@ namespace BCG { /// /// /// - public static string[] compareRows(IBlueRow r1, IBlueRow r2) { + public static string[] compareRows(IBlueRow r1, IBlueRow r2) + { ArrayList retVal = new ArrayList(); foreach (string col in r1.schema.columnNames) if (!r1[col].Equals(r2[col])) @@ -678,7 +759,8 @@ namespace BCG { return retVal.ToArray(typeof(string)) as string[]; } - public static BlueTable cloneRowCollection(IBlueRowCollection rows) { + public static BlueTable cloneRowCollection(IBlueRowCollection rows) + { BlueTable retVal = new BlueTable(rows.schema); foreach (IBlueRow r in rows) retVal.addRow(new BlueRow(r)); @@ -693,7 +775,8 @@ namespace BCG { /// /// /// - public static IBlueRow getNewReplacedRow(IBlueRow r, object[] newValues, int[] indexes) { + public static IBlueRow getNewReplacedRow(IBlueRow r, object[] newValues, int[] indexes) + { if (!newValues.Length.Equals(indexes.Length)) throw new Exception("Debug Assert"); @@ -704,11 +787,13 @@ namespace BCG { return new BlueRow(r.schema, rowArray); } - public static IBlueRow getNewReplacedRow(IBlueRow r, object newValue, int index) { + public static IBlueRow getNewReplacedRow(IBlueRow r, object newValue, int index) + { return getNewReplacedRow(r, new object[] { newValue }, new int[] { index }); } - public static IBlueRow getNewReplacedRow(IBlueRow r, object newValue, string colName) { + public static IBlueRow getNewReplacedRow(IBlueRow r, object newValue, string colName) + { return getNewReplacedRow(r, newValue, r.schema[colName].colNo); } @@ -718,7 +803,8 @@ namespace BCG { /// /// /// - public static IBlueRow computeMaxRow(IBlueRowCollection rows, params string[] cols) { + public static IBlueRow computeMaxRow(IBlueRowCollection rows, params string[] cols) + { IBlueRow retVal = rows.Count != 0 ? BlueDataUtility.extractRow(rows, 0) : null; foreach (IBlueRow r in rows) retVal = compareRows(r, retVal, cols) > 0 ? r : retVal; @@ -731,7 +817,8 @@ namespace BCG { /// /// /// - public static IBlueRow computeMinRow(IBlueRowCollection rows, params string[] cols) { + public static IBlueRow computeMinRow(IBlueRowCollection rows, params string[] cols) + { IBlueRow retVal = rows.Count != 0 ? BlueDataUtility.extractRow(rows, 0) : null; foreach (IBlueRow r in rows) retVal = compareRows(r, retVal, cols) < 0 ? r : retVal; @@ -744,20 +831,24 @@ namespace BCG { /// /// /// - public static IBlueRow computeSum(IBlueRowCollection rows, params string[] cols) { + public static IBlueRow computeSum(IBlueRowCollection rows, params string[] cols) + { if (rows.Count == 0) return null; IBlueRow retVal = BlueDataUtility.extractRow(rows, 0); object[] sums = new object[cols.Length]; int[] idxs = new int[cols.Length]; - for (int i = 0; i < cols.Length; i++) { + for (int i = 0; i < cols.Length; i++) + { sums[i] = 0.0; idxs[i] = rows.schema[cols[i]].colNo; } - foreach (IBlueRow r in rows) { - for (int i = 0; i < cols.Length; i++) { + foreach (IBlueRow r in rows) + { + for (int i = 0; i < cols.Length; i++) + { double dval = BlueDataUtility.get_row_value(r, cols[i], 0.0); //r[cols[i]] == null || r[cols[i]] is DBNull ? 0.0 : (double)r[cols[i]]; sums[i] = (double)sums[i] + dval; @@ -768,7 +859,8 @@ namespace BCG { } - public static IBlueRow computeSum(IBlueRowCollection rows, params string[] cols) { + public static IBlueRow computeSum(IBlueRowCollection rows, params string[] cols) + { if (rows.Count == 0) return null; IBlueRow retVal = BlueDataUtility.extractRow(rows, 0); if (rows.Count == 1) return retVal; @@ -776,13 +868,16 @@ namespace BCG { object[] sums = new object[cols.Length]; int[] idxs = new int[cols.Length]; - for (int i = 0; i < cols.Length; i++) { + for (int i = 0; i < cols.Length; i++) + { sums[i] = default(T); idxs[i] = rows.schema[cols[i]].colNo; } - foreach (IBlueRow r in rows) { - for (int i = 0; i < cols.Length; i++) { + foreach (IBlueRow r in rows) + { + for (int i = 0; i < cols.Length; i++) + { T tval = r[cols[i]] == null || r[cols[i]] is DBNull ? default(T) : (T)r[cols[i]]; sums[i] = MagicAdder.Add((T)sums[i], tval); } @@ -797,14 +892,16 @@ namespace BCG { /// /// /// - public static bool rowPresent(IBlueRowCollection table, IBlueRow row) { + public static bool rowPresent(IBlueRowCollection table, IBlueRow row) + { return table.containsID((int)row["id"]); } public static void computeDifferences(IBlueRowCollection newRows, IBlueRowCollection oldRows, out IBlueRowCollection dRows, - out IBlueRowCollection aRows) { + out IBlueRowCollection aRows) + { computeDifferences( newRows, oldRows, @@ -814,7 +911,8 @@ namespace BCG { } public static void compute_differences_fast(IBlueRowCollection new_rows, IBlueRowCollection old_rows, - out IBlueRowCollection out_d_rows, out IBlueRowCollection out_a_rows) { + out IBlueRowCollection out_d_rows, out IBlueRowCollection out_a_rows) + { int[] col_indices = new int[new_rows.schema.columnNames.Length]; for (int i = 0; i < col_indices.Length; i++) col_indices[i] = i; @@ -822,8 +920,10 @@ namespace BCG { } public static void compute_differences_fast(IBlueRowCollection new_rows, IBlueRowCollection old_rows, int[] col_indices, - out IBlueRowCollection out_d_rows, out IBlueRowCollection out_a_rows) { - Func rows_equal = (r1, r2) => { + out IBlueRowCollection out_d_rows, out IBlueRowCollection out_a_rows) + { + Func rows_equal = (r1, r2) => + { foreach (int col_no in col_indices) if (!(r1[col_no] ?? DBNull.Value).Equals(r2[col_no] ?? DBNull.Value)) return false; @@ -835,7 +935,8 @@ namespace BCG { foreach (IBlueRow r in new_rows) if (!BlueDataUtility.rowPresent(old_rows, r)) add_rows.addRow(r); - else if (!rows_equal(r, old_rows[(int)r["id"]])) { + else if (!rows_equal(r, old_rows[(int)r["id"]])) + { add_rows.addRow(r); del_rows.addRow(old_rows[(int)r["id"]]); } @@ -852,7 +953,8 @@ namespace BCG { IBlueRowCollection c2, string[] columns, out IBlueRowCollection dRows, - out IBlueRowCollection aRows) { + out IBlueRowCollection aRows) + { dRows = new BlueTable(c1.schema); aRows = new BlueTable(c1.schema); @@ -861,7 +963,8 @@ namespace BCG { if (!BlueDataUtility.rowPresent(c2, nr)) (aRows as BlueTable).addRow(nr); else if (BlueDataUtility.compareRows(nr, c2[(int) - nr["id"]], columns) != 0) { + nr["id"]], columns) != 0) + { (aRows as BlueTable).addRow(nr); (dRows as BlueTable).addRow(c2[(int)nr["id"]]); @@ -874,11 +977,14 @@ namespace BCG { } //brcDiff = brc1 - brc2 - public static void diff(IBlueRowCollection brc1, IBlueRowCollection brc2, string[] columns, out IBlueRowCollection brcDiff) { + public static void diff(IBlueRowCollection brc1, IBlueRowCollection brc2, string[] columns, out IBlueRowCollection brcDiff) + { brcDiff = new BlueTable(brc1.schema); - foreach (IBlueRow br in brc1) { + foreach (IBlueRow br in brc1) + { object[] oarray = new object[columns.Length]; - for (int i = 0; i < columns.Length; i++) { + for (int i = 0; i < columns.Length; i++) + { string col = columns[i]; oarray[i] = br[col]; } @@ -893,7 +999,8 @@ namespace BCG { /// /// /// - public static void absorbChanges(BlueTable t, IBlueRowCollection dels, IBlueRowCollection adds) { + public static void absorbChanges(BlueTable t, IBlueRowCollection dels, IBlueRowCollection adds) + { foreach (IBlueRow r in dels) if (!t.deleteRow(r)) throw new Exception(String.Format("{0} does not have row with id {1} to delete", t.schema.tableName, r["id"])); @@ -902,7 +1009,8 @@ namespace BCG { t.addRow(r); } - public static IBlueRowCollection toBlueRowCollection(IBlueRow r) { + public static IBlueRowCollection toBlueRowCollection(IBlueRow r) + { BlueTable rv = new BlueTable(r.schema); rv.addRow(r); return rv; @@ -914,9 +1022,11 @@ namespace BCG { /// /// /// - public static IBlueRowCollection toBlueRowCollection(ICollection col) { + public static IBlueRowCollection toBlueRowCollection(ICollection col) + { BlueTable retVal = null; - foreach (IBlueRow r in col) { + foreach (IBlueRow r in col) + { retVal = retVal ?? new BlueTable(r.schema); retVal.addRow(r); } @@ -935,19 +1045,23 @@ namespace BCG { IBlueRowCollection adds, out IBlueRowCollection truelyDels, out IBlueRowCollection truelyAdds, - string[] cols) { + string[] cols) + { truelyDels = new BlueTable(dels); truelyAdds = new BlueTable(adds); - foreach (IBlueRow r in dels) { + foreach (IBlueRow r in dels) + { if (adds.containsID((int)r["id"]) && - BlueDataUtility.computeRowEquality(adds[(int)r["id"]], r, cols)) { + BlueDataUtility.computeRowEquality(adds[(int)r["id"]], r, cols)) + { (truelyDels as BlueTable).deleteRow((int)r["id"]); (truelyAdds as BlueTable).deleteRow((int)r["id"]); } } } - public static IBlueRowCollection getSerializableCollection(IBlueRowCollection coll) { + public static IBlueRowCollection getSerializableCollection(IBlueRowCollection coll) + { BlueTable retVal = new OrderedBlueTable(coll.schema); foreach (IBlueRow r in coll) retVal.addRow(new BlueRow(r)); @@ -960,7 +1074,8 @@ namespace BCG { /// /// /// - public static ArrayList extractColumn(IBlueRowCollection rows, string colName) { + public static ArrayList extractColumn(IBlueRowCollection rows, string colName) + { ArrayList rv = new ArrayList(); foreach (IBlueRow r in rows) rv.Add(r[colName]); @@ -979,16 +1094,19 @@ namespace BCG { public static void checkConsistency(IBlueRowCollection oldState, IBlueRowCollection newRows, IBlueRowCollection delRows, - IBlueRowCollection addedRows) { + IBlueRowCollection addedRows) + { BlueTable calc = new BlueTable(oldState); Debug.Assert(oldState != null && newRows != null && delRows != null && addedRows != null); - foreach (IBlueRow r in delRows) { + foreach (IBlueRow r in delRows) + { Debug.Assert(calc.containsID((int)r["id"]), "deleted row's id = " + r["id"] + " does not exist"); calc.deleteRow(r); } - foreach (IBlueRow r in addedRows) { + foreach (IBlueRow r in addedRows) + { Debug.Assert(!calc.containsID((int)r["id"]), "added rows's id = " + r["id"].ToString() + " already exists"); calc.addRow(r); } @@ -1005,7 +1123,8 @@ namespace BCG { /// /// /// - public static object[] getSelectedValues(IBlueRow r, params string[] colNames) { + public static object[] getSelectedValues(IBlueRow r, params string[] colNames) + { object[] retVal = new object[colNames.Length]; for (int i = 0; i < colNames.Length; i++) retVal[i] = r[colNames[i]]; @@ -1021,8 +1140,10 @@ namespace BCG { /// /// /// - public static IBlueRow getRowWithKey(IBlueRowCollection rows, string[] keyColumns, object[] colValues) { - foreach (IBlueRow r in rows) { + public static IBlueRow getRowWithKey(IBlueRowCollection rows, string[] keyColumns, object[] colValues) + { + foreach (IBlueRow r in rows) + { object[] vals = getSelectedValues(r, keyColumns); if (CollectionHelpers.equal(vals, colValues)) return r; @@ -1030,7 +1151,8 @@ namespace BCG { return null; } - public static IBlueRowCollection deepCopy(IBlueRowCollection rows) { + public static IBlueRowCollection deepCopy(IBlueRowCollection rows) + { BlueTable retVal = new BlueTable(rows.schema); foreach (IBlueRow r in rows) retVal.addRow(new BlueRow(r)); @@ -1044,7 +1166,8 @@ namespace BCG { /// /// /// - public static int[] getColumnsInSortedOrder(IBlueTableSchema schema, bool includeId) { + public static int[] getColumnsInSortedOrder(IBlueTableSchema schema, bool includeId) + { ArrayList names = new ArrayList(schema.columnNames), retVal = new ArrayList(); names.Sort(); @@ -1057,33 +1180,40 @@ namespace BCG { //this class is used so that we can sort a schema by column name //that way, prepublished tables will allways get published with schemas in the same order //regardless of how the underlying streams end up working - private class ColumnInfoComparisonWrapper : IComparable { + private class ColumnInfoComparisonWrapper : IComparable + { ColumnInfo myColumn; - public string ColumnName { + public string ColumnName + { get { return myColumn.colName; } //can't set it, these are only for reading columns } - public ColumnInfo Column { + public ColumnInfo Column + { get { return myColumn; } } - public ColumnInfoComparisonWrapper(ColumnInfo theColumn) { + public ColumnInfoComparisonWrapper(ColumnInfo theColumn) + { myColumn = theColumn; } - public int CompareTo(ColumnInfoComparisonWrapper otherGuy) { + public int CompareTo(ColumnInfoComparisonWrapper otherGuy) + { return ColumnName.CompareTo(otherGuy.ColumnName); } } - public static IBlueTableSchema getSortedSchema(IBlueTableSchema inSchema) { + public static IBlueTableSchema getSortedSchema(IBlueTableSchema inSchema) + { List sortedColNames = new List(inSchema.columnNames); sortedColNames.Sort(); List sortedColInfos = new List(); int colNo = 0; - foreach (string c in sortedColNames) { + foreach (string c in sortedColNames) + { ColumnInfo ci = inSchema[c]; sortedColInfos.Add(new ColumnInfo(c, colNo++, ci.colType)); @@ -1091,13 +1221,15 @@ namespace BCG { return new BlueTableSchema(inSchema.tableName, sortedColInfos.ToArray()); } - public static IBlueTableSchema getSortedSchema(IBlueTableSchema theSchema, out int[] sortedSchemaToOriginalSchemaMapping, out int idColumnInSortedSchema) { + public static IBlueTableSchema getSortedSchema(IBlueTableSchema theSchema, out int[] sortedSchemaToOriginalSchemaMapping, out int idColumnInSortedSchema) + { //for now this function will not do anything //that is because we don't want to break the C++ deserialization code int numCols = theSchema.columnNames.Length; sortedSchemaToOriginalSchemaMapping = new int[numCols]; - for (int col = 0; col < theSchema.columnNames.Length; ++col) { + for (int col = 0; col < theSchema.columnNames.Length; ++col) + { //the mapping is just the identity mapping sortedSchemaToOriginalSchemaMapping[col] = col; @@ -1151,34 +1283,43 @@ namespace BCG { /// /// /// true if equal - public static bool compareSchemas(IBlueTableSchema s1, IBlueTableSchema s2) { + public static bool compareSchemas(IBlueTableSchema s1, IBlueTableSchema s2) + { bool result = true; - try { + try + { if (s1.columnInfo.Length != s2.columnInfo.Length) result = false; else - foreach (ColumnInfo ci1 in s1.columnInfo) { + foreach (ColumnInfo ci1 in s1.columnInfo) + { ColumnInfo ci2 = s2[ci1.colNo]; - if (ci1.colName != ci2.colName || ci1.colType != ci2.colType) { + if (ci1.colName != ci2.colName || ci1.colType != ci2.colType) + { result = false; break; } } - } catch { + } + catch + { result = false; // the col# wasn't found in s2 } return result; } - public static IBlueRowCollection removeRows(BlueTable table, string[] cols, object[] vals) { + public static IBlueRowCollection removeRows(BlueTable table, string[] cols, object[] vals) + { IBlueRowCollection dels = findMatchingRows(table, cols, vals); table.deleteRows(dels); return dels; } - public static IBlueRowCollection findMatchingRows(IBlueRowCollection rows, string[] cols, object[] vals) { + public static IBlueRowCollection findMatchingRows(IBlueRowCollection rows, string[] cols, object[] vals) + { BlueTable rv = new BlueTable(rows.schema); - foreach (IBlueRow r in rows) { + foreach (IBlueRow r in rows) + { bool match = true; for (int i = 0; i < cols.Length; i++) match &= vals[i].Equals(r[cols[i]]); @@ -1188,7 +1329,8 @@ namespace BCG { return rv; } - public static void checkRowTypes(IBlueRowCollection rows) { + public static void checkRowTypes(IBlueRowCollection rows) + { foreach (IBlueRow r in rows) foreach (string col in r.schema.columnNames) if (r[col] != null && r[col] != DBNull.Value) @@ -1196,12 +1338,14 @@ namespace BCG { String.Format("col {0} in table {1} is of type {2} in schema but is a {3} in the row", col, rows.schema.tableName, r.schema[col].colType.ToString(), r[col].GetType().ToString())); } - public static void addRows(ref BlueTable table, ICollection rows) { + public static void addRows(ref BlueTable table, ICollection rows) + { foreach (IBlueRow r in rows) table.addRow(r); } - public static void removeRows(ref BlueTable table, ICollection rows) { + public static void removeRows(ref BlueTable table, ICollection rows) + { foreach (IBlueRow r in rows) table.deleteRow(r); } @@ -1209,7 +1353,8 @@ namespace BCG { public static void sortOutPacket(IBlueRowCollection dels, IBlueRowCollection adds, string[] keyCols, out IBlueRowCollection addedRows, out IBlueRowCollection deletedRows, - out IBlueRowCollection changedRows) { + out IBlueRowCollection changedRows) + { addedRows = new BlueTable(dels.schema); deletedRows = new BlueTable(dels.schema); changedRows = new BlueTable(dels.schema); @@ -1222,39 +1367,49 @@ namespace BCG { foreach (IBlueRow r in adds) keyedAdds.update(r); - foreach (IBlueRow r in keyedDels) { + foreach (IBlueRow r in keyedDels) + { object[] key = BlueDataUtility.getSelectedValues(r, keyCols); - if (keyedAdds.getRow(key) != null) { + if (keyedAdds.getRow(key) != null) + { ///change (changedRows as BlueTable).addRow(r); - } else { + } + else + { ///delete (deletedRows as BlueTable).addRow(r); } } - foreach (IBlueRow r in keyedAdds) { + foreach (IBlueRow r in keyedAdds) + { object[] key = BlueDataUtility.getSelectedValues(r, keyCols); - if (keyedDels.getRow(key) == null) { + if (keyedDels.getRow(key) == null) + { (addedRows as BlueTable).addRow(r); } } } - public static int HashExpStrike(DateTime exp, double strike) { + public static int HashExpStrike(DateTime exp, double strike) + { return ((DateTime)exp).ToShortDateString().GetHashCode() ^ strike.GetHashCode(); } - public static IEnumerable collection_to_ienum(IBlueRowCollection rows) { + public static IEnumerable collection_to_ienum(IBlueRowCollection rows) + { List rv = new List(); foreach (IBlueRow r in rows) rv.Add(r); return rv; } - public static IBlueRowCollection ienum_to_collection(IEnumerable rows) { + public static IBlueRowCollection ienum_to_collection(IEnumerable rows) + { BlueTable rv = null; - if (rows.Count() > 0) { + if (rows.Count() > 0) + { rv = new BlueTable(rows.ElementAt(0).schema); foreach (IBlueRow r in rows) rv.addRow(r); @@ -1262,13 +1417,15 @@ namespace BCG { return rv; } - public static IBlueTableSchema add_column(IBlueTableSchema input_schema, string new_col_name, Type new_col_type) { + public static IBlueTableSchema add_column(IBlueTableSchema input_schema, string new_col_name, Type new_col_type) + { List cis = new List(input_schema.columnInfo); cis.Add(new ColumnInfo(new_col_name, cis.Count, new_col_type)); return new BlueTableSchema(input_schema.tableName, cis.ToArray()); } - public static IBlueTableSchema remove_columns(IBlueTableSchema input_schema, params string[] col_names) { + public static IBlueTableSchema remove_columns(IBlueTableSchema input_schema, params string[] col_names) + { Dictionary removed_col_names = new Dictionary(); foreach (string c in col_names) removed_col_names[c] = true; @@ -1279,14 +1436,16 @@ namespace BCG { return new BlueTableSchema(cis.ToArray(), input_schema.tableName); } - public static int[] get_column_indices(IBlueTableSchema schema, string[] col_names) { + public static int[] get_column_indices(IBlueTableSchema schema, string[] col_names) + { List rv = new List(); foreach (string c in col_names) rv.Add(schema[c].colNo); return rv.ToArray(); } - public static string get_appended_string_val(IBlueRow r, int[] col_indices) { + public static string get_appended_string_val(IBlueRow r, int[] col_indices) + { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < col_indices.Length; i++) sb.Append(r[col_indices[i]]); @@ -1294,29 +1453,35 @@ namespace BCG { } public delegate string RowValueToString(IBlueRow r, int col_index); - public static string get_appended_string_val(IBlueRow r, int[] col_indices, RowValueToString to_string_conv) { + public static string get_appended_string_val(IBlueRow r, int[] col_indices, RowValueToString to_string_conv) + { System.Text.StringBuilder sb = new System.Text.StringBuilder(); for (int i = 0; i < col_indices.Length; i++) sb.Append(to_string_conv(r, i)); return sb.ToString(); } - public static IDictionary> group_together(IBlueRowCollection rows, string[] group_by_col_names) { + public static IDictionary> group_together(IBlueRowCollection rows, string[] group_by_col_names) + { BlueRowHasher hasher = new BlueRowHasher(group_by_col_names.Length); return group_together(rows, BlueDataUtility.get_column_indices(rows.schema, group_by_col_names), ref hasher); } - public static IDictionary> group_together(IBlueRowCollection rows, string[] group_by_col_names, ref BlueRowHasher hasher) { + public static IDictionary> group_together(IBlueRowCollection rows, string[] group_by_col_names, ref BlueRowHasher hasher) + { return group_together(rows, BlueDataUtility.get_column_indices(rows.schema, group_by_col_names), ref hasher); } - public static IDictionary> group_together(IBlueRowCollection rows, int[] group_by_col_nos, ref BlueRowHasher hasher) { + public static IDictionary> group_together(IBlueRowCollection rows, int[] group_by_col_nos, ref BlueRowHasher hasher) + { Dictionary> rv = new Dictionary>(); hasher = hasher ?? new BlueRowHasher(group_by_col_nos.Length); - foreach (IBlueRow r in rows) { + foreach (IBlueRow r in rows) + { int row_hash = hasher.get_hash(r, group_by_col_nos); List this_group_rows = null; - if (!rv.TryGetValue(row_hash, out this_group_rows)) { + if (!rv.TryGetValue(row_hash, out this_group_rows)) + { this_group_rows = new List(); rv.Add(row_hash, this_group_rows); } @@ -1325,7 +1490,8 @@ namespace BCG { return rv; } - public static void copy_to_row(IBlueRow row, string[] data_col_names, MutableBlueRow output_row) { + public static void copy_to_row(IBlueRow row, string[] data_col_names, MutableBlueRow output_row) + { foreach (string cn in data_col_names) output_row.setValue(cn, row[cn]); } @@ -1334,52 +1500,64 @@ namespace BCG { /// Copies the column nos specified in data_cols from row, to output_row /// starting from index start_col_index /// - public static void copy_to_row(IBlueRow row, int[] data_col_nos, object[] output_row, int start_col_index) { + public static void copy_to_row(IBlueRow row, int[] data_col_nos, object[] output_row, int start_col_index) + { foreach (int col_no in data_col_nos) output_row[start_col_index++] = row[col_no]; } - public static object compute_min_max(object v1, object v2, bool is_max) { - if (!TypeHelper.is_dbnull(v1) && !TypeHelper.is_dbnull(v2)) { - if (TypeHelper.is_numeric_type(v1) && TypeHelper.is_numeric_type(v2)) { + public static object compute_min_max(object v1, object v2, bool is_max) + { + if (!TypeHelper.is_dbnull(v1) && !TypeHelper.is_dbnull(v2)) + { + if (TypeHelper.is_numeric_type(v1) && TypeHelper.is_numeric_type(v2)) + { double v1_num = (double)Convert.ChangeType(v1, TypeCode.Double), v2_num = (double)Convert.ChangeType(v2, TypeCode.Double); v1_num = Double.IsNaN(v1_num) ? (is_max ? Double.MinValue : Double.MaxValue) : v1_num; v2_num = Double.IsNaN(v2_num) ? (is_max ? Double.MinValue : Double.MaxValue) : v2_num; double rv = is_max ? Math.Max(v1_num, v2_num) : Math.Min(v1_num, v2_num); return Convert.ChangeType(rv, v1.GetType()); - } else + } + else return v1; - } else + } + else return TypeHelper.is_dbnull(v1) ? v2 : v1; } #region Sorting - public static class ParallelSort { - public class TreeRowEffComparer : IComparer { + public static class ParallelSort + { + public class TreeRowEffComparer : IComparer + { private int _depth_in_tree_col_no; private int[] _aggregation_tree_col_nos; private Pair[] _sort_map; - public TreeRowEffComparer(int depth_in_tree_col_no, int[] aggregation_tree_col_nos, Pair[] sort_map) { + public TreeRowEffComparer(int depth_in_tree_col_no, int[] aggregation_tree_col_nos, Pair[] sort_map) + { _depth_in_tree_col_no = depth_in_tree_col_no; _aggregation_tree_col_nos = aggregation_tree_col_nos; _sort_map = sort_map; } - public int Compare(IBlueRow x, IBlueRow y) { + public int Compare(IBlueRow x, IBlueRow y) + { return BlueDataUtility.sort_in_a_tree(x, y, _depth_in_tree_col_no, _aggregation_tree_col_nos, _sort_map); } } - public class TabularRowComparer : IComparer { + public class TabularRowComparer : IComparer + { private IEnumerable> _sort_map; public TabularRowComparer(IEnumerable> sort_map) { _sort_map = sort_map; } public int Compare(IBlueRow x, IBlueRow y) { return BlueDataUtility.compare_rows(x, y, _sort_map); } } - public class TabularRowHashPairComparer : IComparer> { + public class TabularRowHashPairComparer : IComparer> + { private Pair[] _sort_map; public TabularRowHashPairComparer(Pair[] sort_map) { _sort_map = sort_map; } @@ -1388,11 +1566,13 @@ namespace BCG { #region Public Static Methods - public static void QuicksortSequential(IList arr, IComparer comparer) { + public static void QuicksortSequential(IList arr, IComparer comparer) + { QuicksortSequential(arr, comparer, 0, arr.Count - 1); } - public static void QuicksortParallel(IList arr, IComparer comparer) { + public static void QuicksortParallel(IList arr, IComparer comparer) + { QuicksortParallel(arr, comparer, 0, arr.Count - 1); } @@ -1400,20 +1580,27 @@ namespace BCG { #region Private Static Methods - private static void QuicksortSequential(IList arr, IComparer comparer, int left, int right) { - if (right > left) { + private static void QuicksortSequential(IList arr, IComparer comparer, int left, int right) + { + if (right > left) + { int pivot = Partition(arr, comparer, left, right); QuicksortSequential(arr, comparer, left, pivot - 1); QuicksortSequential(arr, comparer, pivot + 1, right); } } - private static void QuicksortParallel(IList arr, IComparer comparer, int left, int right) { + private static void QuicksortParallel(IList arr, IComparer comparer, int left, int right) + { const int SEQUENTIAL_THRESHOLD = 64; - if (right > left) { - if (right - left < SEQUENTIAL_THRESHOLD) { + if (right > left) + { + if (right - left < SEQUENTIAL_THRESHOLD) + { QuicksortSequential(arr, comparer, left, right); - } else { + } + else + { int pivot = Partition(arr, comparer, left, right); System.Threading.Tasks.Parallel.Invoke(new Action[] { delegate {QuicksortParallel(arr, comparer, left, pivot - 1);}, delegate {QuicksortParallel(arr, comparer, pivot + 1, right); } @@ -1422,21 +1609,25 @@ namespace BCG { } } - private static void Swap(IList arr, int i, int j) { + private static void Swap(IList arr, int i, int j) + { T tmp = arr[i]; arr[i] = arr[j]; arr[j] = tmp; } - private static int Partition(IList arr, IComparer comparer, int low, int high) { + private static int Partition(IList arr, IComparer comparer, int low, int high) + { // Simple partitioning implementation int pivotPos = (high + low) / 2; T pivot = arr[pivotPos]; Swap(arr, low, pivotPos); int left = low; - for (int i = low + 1; i <= high; i++) { - if (comparer.Compare(arr[i], pivot) < 0) { + for (int i = low + 1; i <= high; i++) + { + if (comparer.Compare(arr[i], pivot) < 0) + { left++; Swap(arr, i, left); } @@ -1449,8 +1640,10 @@ namespace BCG { #endregion } - public static int compare_rows(IBlueRow r1, IBlueRow r2, Dictionary sort_map) { - foreach (KeyValuePair p in sort_map) { + public static int compare_rows(IBlueRow r1, IBlueRow r2, Dictionary sort_map) + { + foreach (KeyValuePair p in sort_map) + { int comp = compare_send_dontcare_to_last(r1, p.Key, r2, p.Key, p.Value); if (comp != 0) return comp; @@ -1458,8 +1651,10 @@ namespace BCG { return 0; } - public static int compare_rows(IBlueRow r1, IBlueRow r2, IEnumerable> sort_map) { - foreach (Pair p in sort_map) { + public static int compare_rows(IBlueRow r1, IBlueRow r2, IEnumerable> sort_map) + { + foreach (Pair p in sort_map) + { int comp = compare_send_dontcare_to_last(r1, p.first, r2, p.first, p.second); if (comp != 0) return comp; @@ -1469,13 +1664,15 @@ namespace BCG { public static int compare_send_dontcare_to_last(IBlueRow r1, int r1_col_no, IBlueRow r2, int r2_col_no, - bool low_to_high) { + bool low_to_high) + { object o1 = BlueDataUtility.get_row_value(r1, r1_col_no, DBNull.Value), o2 = BlueDataUtility.get_row_value(r2, r2_col_no, DBNull.Value); return compare_send_dontcare_to_last(o1, o2, low_to_high); } - public static List> get_indexed_sort_map(List> sort_map, IBlueTableSchema schema) { + public static List> get_indexed_sort_map(List> sort_map, IBlueTableSchema schema) + { List> rv = new List>(); foreach (Pair p in sort_map) rv.Add(new Pair(schema[p.first].colNo, p.second)); @@ -1486,13 +1683,15 @@ namespace BCG { /// empty strings etc are sent to the last public static int compare_send_dontcare_to_last(IBlueRow r1, string r1_col_name, IBlueRow r2, string r2_col_name, - bool low_to_high) { + bool low_to_high) + { object o1 = BlueDataUtility.get_row_value(r1, r1_col_name, DBNull.Value), o2 = BlueDataUtility.get_row_value(r2, r2_col_name, DBNull.Value); return compare_send_dontcare_to_last(o1, o2, low_to_high); } - public static int compare_send_dontcare_to_last(object o1, object o2, bool low_to_high) { + public static int compare_send_dontcare_to_last(object o1, object o2, bool low_to_high) + { if (is_dont_care_val(o1)) return is_dont_care_val(o2) ? 0 : 1; else @@ -1500,7 +1699,8 @@ namespace BCG { : ((IComparable)o2).CompareTo(o1)); } - public static bool is_dont_care_val(object o) { + public static bool is_dont_care_val(object o) + { return o == null || o == DBNull.Value || o is string && String.IsNullOrEmpty((string)o) || o is double && (Double.IsInfinity((double)o) || Double.IsNaN((double)o)) || @@ -1512,22 +1712,26 @@ namespace BCG { #region Tree Aggregation - public static int[] convert_aggregation_tree(string[] aggregation_tree_col_names, IBlueTableSchema schema) { + public static int[] convert_aggregation_tree(string[] aggregation_tree_col_names, IBlueTableSchema schema) + { List rv = new List(); foreach (string col_name in aggregation_tree_col_names) rv.Add(schema[col_name].colNo); return rv.ToArray(); } - public static bool is_leaf_node(IBlueRow r, int depth_in_tree_col_no, int[] aggregation_tree) { + public static bool is_leaf_node(IBlueRow r, int depth_in_tree_col_no, int[] aggregation_tree) + { return BlueDataUtility.get_row_value(r, depth_in_tree_col_no, -1) == (aggregation_tree.Count() - 1); } - public static bool is_leaf_node(IBlueRow r, string depth_in_tree_col_name, string[] aggregation_tree) { + public static bool is_leaf_node(IBlueRow r, string depth_in_tree_col_name, string[] aggregation_tree) + { return BlueDataUtility.get_row_value(r, depth_in_tree_col_name, -1) == (aggregation_tree.Count() - 1); } - public static string generate_aggregation_based_id(IBlueRow r, int depth_in_tree_col_no, int[] aggregation_tree) { + public static string generate_aggregation_based_id(IBlueRow r, int depth_in_tree_col_no, int[] aggregation_tree) + { int aggregation_priority = BlueDataUtility.get_row_value(r, depth_in_tree_col_no, -1); string rv = String.Empty; for (int p = 0; p <= aggregation_priority; p++) @@ -1537,7 +1741,8 @@ namespace BCG { /// Generates a string based id for a row in a tree /// by appending the values of the nodes above it - public static string generate_aggregation_based_id(IBlueRow r, string depth_in_tree_col_name, string[] aggregation_tree) { + public static string generate_aggregation_based_id(IBlueRow r, string depth_in_tree_col_name, string[] aggregation_tree) + { int aggregation_priority = BlueDataUtility.get_row_value(r, depth_in_tree_col_name, -1); string rv = String.Empty; for (int p = 0; p <= aggregation_priority; p++) @@ -1549,12 +1754,15 @@ namespace BCG { /// Given an aggregation hierarchy tree, figures if the first /// arg is a parent of the second arg. /// - public static bool is_parent(IBlueRow parent_row, IBlueRow child_row, string depth_in_tree_col_name, string[] aggregation_tree) { + public static bool is_parent(IBlueRow parent_row, IBlueRow child_row, string depth_in_tree_col_name, string[] aggregation_tree) + { System.Diagnostics.Debug.Assert(parent_row.Contains(depth_in_tree_col_name) && child_row.Contains(depth_in_tree_col_name)); int parent_depth = BlueDataUtility.get_row_value(parent_row, depth_in_tree_col_name, Int32.MaxValue), child_depth = BlueDataUtility.get_row_value(child_row, depth_in_tree_col_name, Int32.MaxValue); - if (parent_depth < child_depth) { - for (int p = 0; p <= parent_depth; p++) { + if (parent_depth < child_depth) + { + for (int p = 0; p <= parent_depth; p++) + { string col_name = aggregation_tree.ElementAt(p); object parent_val = BlueDataUtility.get_row_value(parent_row, col_name, DBNull.Value), child_val = BlueDataUtility.get_row_value(child_row, col_name, DBNull.Value); @@ -1562,15 +1770,19 @@ namespace BCG { return false; } return true; - } else + } + else return false; } - public static bool is_parent(IBlueRow parent_row, IBlueRow child_row, int depth_in_tree_col_no, int[] aggregation_tree) { + public static bool is_parent(IBlueRow parent_row, IBlueRow child_row, int depth_in_tree_col_no, int[] aggregation_tree) + { int parent_depth = BlueDataUtility.get_row_value(parent_row, depth_in_tree_col_no, Int32.MaxValue), child_depth = BlueDataUtility.get_row_value(child_row, depth_in_tree_col_no, Int32.MaxValue); - if (parent_depth < child_depth) { - for (int p = 0; p <= parent_depth; p++) { + if (parent_depth < child_depth) + { + for (int p = 0; p <= parent_depth; p++) + { int col_no = aggregation_tree[p]; object parent_val = BlueDataUtility.get_row_value(parent_row, col_no, DBNull.Value), child_val = BlueDataUtility.get_row_value(child_row, col_no, DBNull.Value); @@ -1578,21 +1790,26 @@ namespace BCG { return false; } return true; - } else + } + else return false; } - public static int sort_in_a_tree(IBlueRow r1, IBlueRow r2, string depth_in_tree_col_name, string[] aggregation_tree, Dictionary sort_map) { + public static int sort_in_a_tree(IBlueRow r1, IBlueRow r2, string depth_in_tree_col_name, string[] aggregation_tree, Dictionary sort_map) + { if (BlueDataUtility.is_parent(r1, r2, depth_in_tree_col_name, aggregation_tree)) return -1; else if (BlueDataUtility.is_parent(r2, r1, depth_in_tree_col_name, aggregation_tree)) return 1; else if (get_row_value(r1, "id", Int32.MaxValue).Equals(get_row_value(r2, "id", Int32.MaxValue))) return 0; - else { - for (int p = 0; p < aggregation_tree.Count(); p++) { + else + { + for (int p = 0; p < aggregation_tree.Count(); p++) + { /// sort_map is used to leaf nodes - if (p == aggregation_tree.Count() - 1) { + if (p == aggregation_tree.Count() - 1) + { /// sorting for leaf nodes is special, since they can be /// sorted by data columns System.Diagnostics.Debug.Assert(BlueDataUtility.is_leaf_node(r1, depth_in_tree_col_name, aggregation_tree) && BlueDataUtility.is_leaf_node(r2, depth_in_tree_col_name, aggregation_tree)); @@ -1612,17 +1829,21 @@ namespace BCG { } } - public static int sort_in_a_tree(IBlueRow r1, IBlueRow r2, int depth_in_tree_col_no, int[] aggregation_tree, Pair[] sort_map) { + public static int sort_in_a_tree(IBlueRow r1, IBlueRow r2, int depth_in_tree_col_no, int[] aggregation_tree, Pair[] sort_map) + { if (BlueDataUtility.is_parent(r1, r2, depth_in_tree_col_no, aggregation_tree)) return -1; else if (BlueDataUtility.is_parent(r2, r1, depth_in_tree_col_no, aggregation_tree)) return 1; else if (get_row_value(r1, "id", Int32.MaxValue).Equals(get_row_value(r2, "id", Int32.MaxValue))) return 0; - else { - for (int p = 0; p < aggregation_tree.Count(); p++) { + else + { + for (int p = 0; p < aggregation_tree.Count(); p++) + { /// sort_map is used to leaf nodes - if (p == aggregation_tree.Count() - 1) { + if (p == aggregation_tree.Count() - 1) + { /// sorting for leaf nodes is special, since they can be /// sorted by data columns //System.Diagnostics.Debug.Assert(BlueDataUtility.is_leaf_node(r1, depth_in_tree_col_name, aggregation_tree) && BlueDataUtility.is_leaf_node(r2, depth_in_tree_col_name, aggregation_tree)); @@ -1646,123 +1867,169 @@ namespace BCG { #region Column accessors - public static T get_array_value(Array r, int col_no, T error_val) { - try { + public static T get_array_value(Array r, int col_no, T error_val) + { + try + { object rv = (r != null && col_no > -1 && col_no < r.Length) ? r.GetValue(col_no) : DBNull.Value; if (rv == null || rv == DBNull.Value) return error_val; else return (T)Convert.ChangeType(rv, typeof(T)); - } catch { + } + catch + { return error_val; } } - public static DateTime get_array_datetime_value(Array r, int col_no, DateTime error_val) { - try { + public static DateTime get_array_datetime_value(Array r, int col_no, DateTime error_val) + { + try + { object rv = (r != null && col_no > -1 && col_no < r.Length) ? r.GetValue(col_no) : error_val; return _get_datetime_value(rv, error_val); - } catch { + } + catch + { return error_val; } } - public static T get_row_value(IBlueRow r, int col_no, T error_val) { - try { + public static T get_row_value(IBlueRow r, int col_no, T error_val) + { + try + { object rv = (r != null && col_no > -1 && col_no < r.schema.columnInfo.Length) ? r[col_no] : DBNull.Value; if (rv == null || rv == DBNull.Value) return error_val; else return (T)Convert.ChangeType(rv, typeof(T)); - } catch { + } + catch + { return error_val; } } - public static T get_row_value(IBlueRow r, string col_name, T error_val) { - try { + public static T get_row_value(IBlueRow r, string col_name, T error_val) + { + try + { object rv = (r != null && r.Contains(col_name)) ? r[col_name] : DBNull.Value; if (rv == null || rv == DBNull.Value) return error_val; else return (T)Convert.ChangeType(rv, typeof(T)); - } catch { + } + catch + { return error_val; } } - public static T get_row_enum_value(IBlueRow r, string col_name, T error_val) where T : struct { - try { + public static T get_row_enum_value(IBlueRow r, string col_name, T error_val) where T : struct + { + try + { object rv = r.Contains(col_name) ? r[col_name] : DBNull.Value; return _get_row_enum_value(rv, error_val); - } catch { + } + catch + { return error_val; } } - public static T get_row_enum_value(IBlueRow r, int col_no, T error_val) where T : struct { - try { + public static T get_row_enum_value(IBlueRow r, int col_no, T error_val) where T : struct + { + try + { object rv = (r != null && col_no > -1 && col_no < r.schema.columnInfo.Length) ? r[col_no] : DBNull.Value; return _get_row_enum_value(rv, error_val); - } catch { + } + catch + { return error_val; } } - private static T _get_row_enum_value(object o, T error_val) where T : struct { - try { + private static T _get_row_enum_value(object o, T error_val) where T : struct + { + try + { if (o == null || o == DBNull.Value) return error_val; - else if (o is string) { + else if (o is string) + { T result = error_val; if (Enum.TryParse((string)o, true, out result)) return result; return error_val; - } else if (o is Int32 || o is Int16 || o is UInt16 || o is UInt32) + } + else if (o is Int32 || o is Int16 || o is UInt16 || o is UInt32) return (T)o; else if (o is T) return (T)o; else return error_val; - } catch { + } + catch + { return error_val; } } - public static DateTime get_row_datetime_value(IBlueRow r, string col_name, DateTime error_val) { - try { + public static DateTime get_row_datetime_value(IBlueRow r, string col_name, DateTime error_val) + { + try + { object rv = (r != null && r.Contains(col_name)) ? r[col_name] : error_val; return _get_datetime_value(rv, error_val); - } catch { + } + catch + { return error_val; } } - public static DateTime get_row_datetime_value(IBlueRow r, int col_no, DateTime error_val) { - try { + public static DateTime get_row_datetime_value(IBlueRow r, int col_no, DateTime error_val) + { + try + { object rv = (r != null && col_no > -1 && col_no < r.schema.columnInfo.Length) ? r[col_no] : error_val; return _get_datetime_value(rv, error_val); - } catch { + } + catch + { return error_val; } } - private static DateTime _get_datetime_value(object v, DateTime error_val) { - try { + private static DateTime _get_datetime_value(object v, DateTime error_val) + { + try + { if (v == null || v == DBNull.Value) return error_val; - else { + else + { if (v is DateTime) return (DateTime)v; - else if (v is string) { + else if (v is string) + { DateTime rv_dt = error_val; DateTime.TryParse((string)v, out rv_dt); return rv_dt; - } else { + } + else + { double oa_date = (double)Convert.ChangeType(v, typeof(Double)); return DateTime.FromOADate(oa_date); } } - } catch { + } + catch + { return error_val; } } @@ -1773,7 +2040,8 @@ namespace BCG { /// /// Reads a schema file name, and return the constructed schema /// - public static IBlueTableSchema createSchemaFromCSVSchemaFile(string schemaFileName) { + public static IBlueTableSchema createSchemaFromCSVSchemaFile(string schemaFileName) + { StreamReader sr = new StreamReader(schemaFileName); IBlueTableSchema retVal = createSchemaFromCSVSchemaFile(sr); sr.Close(); @@ -1784,7 +2052,8 @@ namespace BCG { /// Builds a schema from a schema file. Note that the stream is not closed, so /// the calling code should do so /// - public static IBlueTableSchema createSchemaFromCSVSchemaFile(TextReader sr) { + public static IBlueTableSchema createSchemaFromCSVSchemaFile(TextReader sr) + { string tableName = sr.ReadLine(); ArrayList t = new ArrayList(); string l = ""; @@ -1792,12 +2061,14 @@ namespace BCG { t.Add(l.Trim()); string[] cols = t.ToArray(typeof(string)) as String[]; ColumnInfo[] cis = new ColumnInfo[cols.Length]; - for (int i = 0; i < cols.Length; i++) { + for (int i = 0; i < cols.Length; i++) + { string[] colTags = cols[i].Split('/'); cis[i] = new ColumnInfo(colTags[0], i, TypeInstanceLoader.loadType(colTags[1])); } IBlueTableSchema retVal = new BlueTableSchema(cis, tableName); - if (retVal["id"] == null) { + if (retVal["id"] == null) + { ArrayList temp = new ArrayList(retVal.columnInfo); temp.Add(new ColumnInfo("id", temp.Count, typeof(System.Int32))); retVal = new BlueTableSchema(retVal.tableName, @@ -1810,13 +2081,17 @@ namespace BCG { /// Creates an IBlueRow from a CSV data file row; if the string already contains an id, /// the id argument is ignored /// - public static IBlueRow createRowFromCSVFileRow(string fileRow, IBlueTableSchema schema, int id) { + public static IBlueRow createRowFromCSVFileRow(string fileRow, IBlueTableSchema schema, int id) + { string[] toks = CSVParser.parse(fileRow); ArrayList rowList = new ArrayList(); - if (toks.Length == schema.columnNames.Length) { + if (toks.Length == schema.columnNames.Length) + { for (int i = 0; i < toks.Length; i++) rowList.Add(myConvertTo(schema[i].colType, toks[i])); - } else { + } + else + { int idIndex = schema["id"].colNo; for (int i = 0; i < toks.Length; i++) rowList.Add(myConvertTo(schema[i < idIndex ? i : i + 1].colType, toks[i])); @@ -1828,7 +2103,8 @@ namespace BCG { /// /// Returns the CSV data string corresponding to the row /// - public static string toCSVDataString(IBlueRow r) { + public static string toCSVDataString(IBlueRow r) + { string retVal = ""; for (int i = 0; i < r.schema.columnNames.Length; i++) retVal += @@ -1838,7 +2114,8 @@ namespace BCG { return retVal.Remove(retVal.Length - 1, 1); } - public static string[] toCSVSchemaFileStrings(IBlueTableSchema schema) { + public static string[] toCSVSchemaFileStrings(IBlueTableSchema schema) + { string[] retVal = new string[2]; retVal[0] = schema.tableName; foreach (ColumnInfo ci in schema.columnInfo) @@ -1850,11 +2127,13 @@ namespace BCG { /// /// Converts a CSV data value to its original type. /// - private static object myConvertTo(Type t, string val) { + private static object myConvertTo(Type t, string val) + { val = val.Trim(); if (t.Equals(typeof(System.String))) return val; - else if (val != "") { + else if (val != "") + { if (t.Equals(typeof(System.Char))) return Convert.ToChar(val); if (t.Equals(typeof(System.Int16))) @@ -1873,17 +2152,21 @@ namespace BCG { return DBNull.Value; } - private static object myToDateTime(string val) { - try { + private static object myToDateTime(string val) + { + try + { return Convert.ToDateTime(val); - } catch (FormatException) //datetime is not stored in one of the string formats - { + } + catch (FormatException) //datetime is not stored in one of the string formats + { return val.IndexOf('.') > -1 ? DateTime.FromOADate(Convert.ToDouble(val)) : new DateTime(Convert.ToInt64(val)); } } - public static IBlueRowCollection createRowsFromCSVFileWithoutTypes(string fileAddress) { + public static IBlueRowCollection createRowsFromCSVFileWithoutTypes(string fileAddress) + { StreamReader sr = new StreamReader(fileAddress); string cols = sr.ReadLine(); string[] columns = cols.Split(','); @@ -1906,15 +2189,18 @@ namespace BCG { /// /// Uses a cached compiled expression to implement a truly generic add function. Will throw if given types that cannot be added. /// - internal class MagicAdder { + internal class MagicAdder + { static Func add; - static MagicAdder() { + static MagicAdder() + { ParameterExpression left = Expression.Parameter(typeof(T), "a"); ParameterExpression right = Expression.Parameter(typeof(T), "b"); add = (Func)Expression.Lambda(Expression.Add(left, right), left, right).Compile(); } - public static T Add(T a, T b) { + public static T Add(T a, T b) + { return add(a, b); } } @@ -1922,7 +2208,8 @@ namespace BCG { #region Misc - public static void swap(ref T t1, ref T t2) { + public static void swap(ref T t1, ref T t2) + { T temp = t1; t1 = t2; t2 = temp; diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Test/CompressionSerializationTest.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Test/CompressionSerializationTest.cs new file mode 100644 index 000000000..0196ec0ad --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Test/CompressionSerializationTest.cs @@ -0,0 +1,236 @@ +// using System; +// using System.IO; +// using NUnit.Framework; + +// namespace BCG +// { + +// /// +// /// Tests the deserialization happening within the pubsub. +// /// +// [TestGroup] +// public class CompressionSerializationTest +// { +// protected IBlueTableSchema mySchema; +// protected BlueTable myTable; +// protected IBlueDataSerializer mySer; +// protected IPubsubDeserializer myPubsubDeser; +// protected IClientDeserializer myClientDeser; + + +// [Test] +// public static void test_compression() +// { +// int n_len = 10000000; +// for (int t = 0; t < 10; t++) +// { +// Random rnd = new Random(DateTime.Now.Millisecond); +// byte[] data = new byte[n_len]; +// rnd.NextBytes(data); + +// BCG.Utilities.General.HighPerformanceTimer timer = new Utilities.General.HighPerformanceTimer(); +// timer.start(); +// byte[] compr = UtilityMethods.compress(new MemoryStream(data)); +// timer.stop(); +// Console.WriteLine("Time to compress {0} bytes {1} msecs ratio {2}", n_len, timer.lastIntervalTime, (1.0 * data.Length)/(1.0 * compr.Length)); + +// timer.start(); +// Stream decompr_str = UtilityMethods.decompress(compr); +// timer.stop(); +// Console.WriteLine("Time to de-compress {0} bytes {1} msecs", n_len, timer.lastIntervalTime); + +// decompr_str.Position = 0; +// Assert.AreEqual(data.Length, (int)decompr_str.Length); +// for (int i = 0; i < data.Length; i++) +// Assert.AreEqual(data[i], decompr_str.ReadByte()); +// } +// } + +// public CompressionSerializationTest() +// { +// mySchema = new BlueTableSchema(myGetTableName(), +// new ColumnInfo("id", 0, typeof(int)), +// new ColumnInfo("i1", 1, typeof(int)), +// new ColumnInfo("d1", 2, typeof(double)), +// new ColumnInfo("dt", 3, typeof(DateTime)), +// new ColumnInfo("x", 4, typeof(byte)) +// ); +// mySer = new CompressionSerializer(mySchema); +// myClientDeser = new ClientDeserializationController(); +// myPubsubDeser = new PubsubDeserializationController(); +// } + +// protected virtual string myGetTableName() +// { +// return "testUniversal"; +// } + +// /// +// /// Tests the entire cycle. This is done by 'publishing' data to the serializationController (ie a series of +// /// adds, deletions, changes etc) and getting the bytes and feeding it into a pubsubDeseriazlier and a clientDeserializer. +// /// At every step the data is tested for consistency. At the end the getState is used to get all the data, and its passed +// /// through the clientDeserializer to get all the rows. +// /// +// [Test] +// public void testEntireProcess() +// { +// myTable = new BlueTable(mySchema); +// byte[] data; +// int id; +// //create +// for (id = 0; id < 100; id++) +// myTable.addRow(myGetRow(id)); + +// byte[] ops; +// Array rows; +// IBlueRowCollection del, add; +// IBlueRowCollection[] receivedData; +// IBlueRow r; + +// //create +// mySer.serialize(StreamOpCode.create, new IBlueRowCollection[] { myTable }, out data); +// myWrite(StreamOpCode.create, data); +// myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// Assert.AreEqual(1, ops.Length); +// Assert.AreEqual(StreamOpCode.create, ops[0]); +// Assert.AreEqual(1, rows.Length); +// receivedData = rows.GetValue(0) as IBlueRowCollection[]; +// Assert.AreEqual(1, receivedData.Length); + +// BlueDataUtility.computeDifferences(receivedData[0], myTable, out del, out add); +// Assert.AreEqual(0, del.Count); +// Assert.AreEqual(0, add.Count); + +// //single add +// r = myGetRow(id); +// BlueTable temp = new BlueTable(mySchema); +// myTable.addRow(r); +// temp.addRow(r); +// mySer.serialize(StreamOpCode.add, new IBlueRowCollection[] { temp }, out data); +// myWrite(StreamOpCode.add, data); +// myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// Assert.AreEqual(1, ops.Length); +// Assert.AreEqual(StreamOpCode.add, ops[0]); +// Assert.AreEqual(1, rows.Length); +// receivedData = rows.GetValue(0) as IBlueRowCollection[]; +// Assert.AreEqual(1, receivedData.Length); +// BlueDataUtility.computeDifferences(receivedData[0], temp, out del, out add); +// Assert.AreEqual(0, del.Count); +// Assert.AreEqual(0, add.Count); + +// //single delete +// r = myTable[0]; //delete row with id 0 +// temp = new BlueTable(mySchema); +// myTable.deleteRow(0); +// temp.addRow(r); +// mySer.serialize(StreamOpCode.remove, new IBlueRowCollection[] { temp }, out data); +// myWrite(StreamOpCode.remove, data); +// myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// Assert.AreEqual(1, ops.Length); +// Assert.AreEqual(StreamOpCode.remove, ops[0]); +// Assert.AreEqual(1, rows.Length); +// receivedData = rows.GetValue(0) as IBlueRowCollection[]; +// Assert.AreEqual(1, receivedData.Length); +// BlueDataUtility.computeDifferences(receivedData[0], temp, out del, out add); +// Assert.AreEqual(0, del.Count); +// Assert.AreEqual(0, add.Count); + +// //batch deletes and adds +// //0 was removed earlier, so lets delete from 1 to 24 first, and then add 101 to 124 +// BlueTable delRows = new BlueTable(mySchema), addRows = new BlueTable(mySchema); +// for (int i = 1; i < 25; i++) +// { +// delRows.addRow(myTable[i]); +// myTable.deleteRow(i); +// } +// for (id = 101; id < 125; id++) +// { +// r = myGetRow(id); +// addRows.addRow(r); +// myTable.addRow(r); +// } +// for (int i = 25; i < 125; i++) +// Assert.AreEqual(true, myTable.containsID(i)); +// Assert.AreEqual(100, myTable.Count); + +// mySer.serialize(StreamOpCode.multipleRemoveAdd, new IBlueRowCollection[] { delRows, addRows }, out data); +// myWrite(StreamOpCode.multipleRemoveAdd, data); +// myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// Assert.AreEqual(1, ops.Length); +// Assert.AreEqual(StreamOpCode.multipleRemoveAdd, ops[0]); +// Assert.AreEqual(1, rows.Length); +// receivedData = rows.GetValue(0) as IBlueRowCollection[]; +// Assert.AreEqual(2, receivedData.Length); +// BlueDataUtility.computeDifferences(receivedData[0], delRows, out del, out add); +// Assert.AreEqual(0, del.Count); +// Assert.AreEqual(0, add.Count); +// BlueDataUtility.computeDifferences(receivedData[1], addRows, out del, out add); +// Assert.AreEqual(0, del.Count); +// Assert.AreEqual(0, add.Count); + +// //pure changes only +// //change the first 25, 25-49 +// BlueTable changedRows = new BlueTable(mySchema); +// for (int i = 25; i < 50; i++) +// { +// MutableBlueRow mr = new MutableBlueRow(myTable[i]); +// mr.setValue(4, Byte.MaxValue); +// myTable.changeRow(mr); +// changedRows.addRow(mr); +// } +// mySer.serialize(StreamOpCode.multipleChange, new IBlueRowCollection[] { changedRows }, out data); +// myWrite(StreamOpCode.multipleChange, data); +// myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// Assert.AreEqual(1, ops.Length); +// Assert.AreEqual(StreamOpCode.multipleChange, ops[0]); +// Assert.AreEqual(1, rows.Length); +// receivedData = rows.GetValue(0) as IBlueRowCollection[]; +// Assert.AreEqual(1, receivedData.Length); +// BlueDataUtility.computeDifferences(receivedData[0], changedRows, out del, out add); +// Assert.AreEqual(0, del.Count); +// Assert.AreEqual(0, add.Count); + +// //final test +// data = myPubsubDeser.getState(); +// new ClientDeserializationController().deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); +// Assert.AreEqual(1, ops.Length); +// Assert.AreEqual(StreamOpCode.create, ops[0]); +// Assert.AreEqual(1, rows.Length); +// receivedData = rows.GetValue(0) as IBlueRowCollection[]; +// Assert.AreEqual(1, receivedData.Length); +// BlueDataUtility.computeDifferences(receivedData[0], myTable, out del, out add); +// Assert.AreEqual(0, del.Count); +// Assert.AreEqual(0, add.Count); + +// } + +// private IBlueRow myGetRow(int id) +// { +// return new BlueRow(mySchema, // the day pp fixed this test. +// id, id + 10, id * 3.0, new DateTime(2008, 6, 4, 0, 0, 0, DateTimeKind.Unspecified), Convert.ToByte(id)); +// } + +// private void myWrite(byte op, byte[] data) +// { +// string s = ""; +// if (op == StreamOpCode.add) +// s = "add one row"; +// else if (op == StreamOpCode.change) +// s = "change one row"; +// else if (op == StreamOpCode.create) +// s = "create"; +// else if (op == StreamOpCode.multipleChange) +// s = "multiple change"; +// else if (op == StreamOpCode.multipleRemoveAdd) +// s = "multiple add remove"; +// else if (op == StreamOpCode.remove) +// s = "remove one row"; +// Console.WriteLine("op = {0}, size = {1}", s, data.Length); +// } +// } +// } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingRowSerializationTest.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingRowSerializationTest.cs new file mode 100644 index 000000000..7426db6b5 --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingRowSerializationTest.cs @@ -0,0 +1,100 @@ +// using System; +// using System.IO; +// using System.Collections; +// using NUnit.Framework; + +// namespace BCG +// { +// [TestGroup] +// public class FixedChangingRowSerializationTest +// { +// private IBlueTableSchema mySchema = new BlueTableSchema ("Test", +// new ColumnInfo ("i", 0, typeof(int)), +// new ColumnInfo ("b", 1, typeof(bool)), +// new ColumnInfo ("d", 2, typeof(double)), +// new ColumnInfo ("id", 3, typeof(int)), +// new ColumnInfo ("dt", 4, typeof(DateTime)), +// new ColumnInfo ("bt", 5, typeof(byte))); +// private BlueTable myState; +// private Random myRnd = new Random (DateTime.Now.Millisecond); +// private IBlueRowSerializer mySerializer; +// private IClientRowDeserializer myRowDeserializer; + +// public FixedChangingRowSerializationTest () +// { +// myState = new BlueTable (mySchema); +// mySerializer = new FixedChangingRowSerializer (mySchema, "bt"); +// myRowDeserializer = new ClientFixedChangingRowDeserializer (mySchema, new string[] {"bt"}); +// } + +// [Test] +// public void addTest () +// { +// for (int i = 0; i < 1000; i++) +// { +// BinaryWriter bw = new BinaryWriter (new MemoryStream ()); +// IBlueRow r = myCreateRow (i); +// mySerializer.serializeRow (r, StreamOpCode.add, bw); + +// BinaryReader br = new BinaryReader (new MemoryStream ((bw.BaseStream as MemoryStream).ToArray ())); +// Assert.AreEqual (r["i"], br.ReadInt32()); +// Assert.AreEqual (r["b"], br.ReadBoolean ()); +// Assert.AreEqual (r["d"], br.ReadDouble ()); +// Assert.AreEqual (r["id"], br.ReadInt32 ()); +// Assert.AreEqual (((DateTime)r["dt"]).Ticks, br.ReadInt64()); +// Assert.AreEqual (r["bt"], br.ReadByte ()); +// } +// } + +// [Test] +// public void removeTest () +// { +// for (int i = 0; i < 1000; i++) +// { +// BinaryWriter bw = new BinaryWriter (new MemoryStream ()); +// IBlueRow r = myCreateRow (i); +// mySerializer.serializeRow (r, StreamOpCode.remove, bw); + +// BinaryReader br = new BinaryReader (new MemoryStream ((bw.BaseStream as MemoryStream).ToArray ())); +// Assert.AreEqual (r["id"], br.ReadInt32()); +// } +// } + +// [Test] +// public void changeTest () +// { +// for (int i = 0; i < 1000; i++) +// { +// BinaryWriter bw = new BinaryWriter (new MemoryStream ()); +// IBlueRow r = myCreateRow (i); +// mySerializer.serializeRow (r, StreamOpCode.change, bw); + +// BinaryReader br = new BinaryReader (new MemoryStream ((bw.BaseStream as MemoryStream).ToArray ())); +// Assert.AreEqual (r["id"], br.ReadInt32()); +// Assert.AreEqual (r["bt"], br.ReadByte()); +// bool isEnd = false; +// try +// { +// br.ReadByte (); +// } +// catch (EndOfStreamException) +// { +// isEnd = true; +// } +// Assert.That (isEnd); +// } +// } + +// private IBlueRow myCreateRow (int id) +// { +// return new BlueRow (mySchema, +// myRnd.Next (1000), +// myRnd.Next (1000) % 2 == 0, +// myRnd.NextDouble (), +// id, +// DateTime.Now, +// Convert.ToByte (10)); +// } + +// } +// } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingSerializationTest.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingSerializationTest.cs new file mode 100644 index 000000000..d11c70996 --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Test/FixedChangingSerializationTest.cs @@ -0,0 +1,40 @@ +// using System; + +// namespace BCG +// { + +// public class TestFixedChangingSerializer : FixedChangingSerializer +// { +// public TestFixedChangingSerializer (IBlueTableSchema schema) +// : base (schema, +// new string[] {"x"}, +// "BCG.PubsubTestFixedChangingDeserializer", +// "BCG.ClientTestFixedChangingDeserializer" +// ) +// {} +// } + +// public class PubsubTestFixedChangingDeserializer : PubsubFixedChangingDeserializer +// { +// public PubsubTestFixedChangingDeserializer () : base (new string[] {"x"}) +// {} +// } + +// public class ClientTestFixedChangingDeserializer : ClientFixedChangingDeserializer +// { +// public ClientTestFixedChangingDeserializer () : base (new string[] {"x"}) +// {} +// } + + +// public class FixedChangingSerializationTest : UniversalSerializationTest +// { +// public FixedChangingSerializationTest () {} + +// protected override string myGetTableName() +// { +// return "testFixedChanging"; +// } + +// } +// } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Test/MarketOptionTheoSerializationTest.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Test/MarketOptionTheoSerializationTest.cs new file mode 100644 index 000000000..5b5a0dae2 --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Test/MarketOptionTheoSerializationTest.cs @@ -0,0 +1,73 @@ +// using System; +// using System.Collections; +// using System.IO; +// using NUnit.Framework; +// using BCG.Utilities.General; + +// namespace BCG +// { +// [TestFixture] +// public class MarketOptionTheoSerializationTest +// { +// private IBlueTableSchema mySchema = new BlueTableSchema ("marketOptionTheo", +// new ColumnInfo ("arrayIndex", 0, typeof(byte)), +// new ColumnInfo ("cell", 1, typeof(byte)), +// new ColumnInfo ("expiration", 2, typeof(DateTime)), +// new ColumnInfo ("id", 3, typeof(int)), +// new ColumnInfo ("value", 4, typeof(double)) +// ); + +// public MarketOptionTheoSerializationTest () {} + +// [Test] +// public void serializationPerformanceTest () +// { +// MarketOptionTheoSerializer ser = new MarketOptionTheoSerializer (mySchema); +// IClientDeserializer deser = new MarketOptionTheoClientDeserializer (); +// BlueTable bt = new BlueTable (mySchema); +// int count = 3000; +// byte[] ops; +// Array rows; +// HighPerformanceTimer timer = new HighPerformanceTimer (); +// byte[] serData = null; + +// for (int i = 0; i < count; i++) +// bt.addRow (myGetRow (i)); + + +// ///serialization +// //create +// ser.serialize (StreamOpCode.create, new IBlueRowCollection[] {bt}, out serData); +// deser.deserialize (new Stream [] {new MemoryStream (serData)}, out ops, out rows); +// ArrayList times = new ArrayList (); +// for (int i = 0; i < 25; i++) +// { +// timer.start (); +// ser.serialize (StreamOpCode.multipleRemoveAdd, new IBlueRowCollection[] {bt, bt}, out serData); +// timer.stop (); +// times.Add (timer.lastIntervalTime); +// Console.WriteLine (String.Format ("serialization of {0} rows, time = {1}, size = {2}", count, timer.lastIntervalTime, serData.Length)); +// } +// times.Sort (); +// Console.WriteLine ("Median time = {0}", times[times.Count/2]); +// //deserialization +// times.Clear (); +// for (int i = 0; i < 25; i++) +// { +// timer.start (); +// deser.deserialize (new Stream [] {new MemoryStream (serData)}, out ops, out rows); +// timer.stop(); +// times.Add (timer.lastIntervalTime); +// Console.WriteLine (String.Format ("deserialization of {0} rows, time = {1}", count, timer.lastIntervalTime)); +// } +// times.Sort (); +// Console.WriteLine ("Median time = {0}", times[times.Count/2]); +// } + +// private IBlueRow myGetRow (int id) +// { +// return new BlueRow (mySchema, +// Convert.ToByte (2), Convert.ToByte (4), DateTime.Now, id, 10.324555); +// } +// } +// } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Test/Performance.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Test/Performance.cs new file mode 100644 index 000000000..b1803fa04 --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Test/Performance.cs @@ -0,0 +1,46 @@ +// using System; +// using NUnit.Framework; +// using BCG.Utilities.General; + +// namespace BCG +// { +// [TestFixture] +// public class Performance +// { +// public Performance() +// { +// } + +// [Test] +// public void testContructionTime () +// { +// double totalTime; +// string deserName = "BCG.ClientUniversalDeserializer"; +// HighPerformanceTimer timer = new HighPerformanceTimer (); +// IClientDeserializer cd; +// for (int i = 0; i < 100; i++) +// { +// timer.start (); +// cd = Activator.CreateInstance (Type.GetType (deserName)) as IClientDeserializer; +// timer.stop (); +// //Console.Write (timer.lastIntervalTime.ToString() + " "); +// } +// Console.WriteLine ("average time = " + timer.totalMilliseconds / 100); +// totalTime = timer.totalMilliseconds; + +// timer = new HighPerformanceTimer (); +// for (int i = 0; i < 100; i++) +// { +// timer.start (); +// cd = new ClientUniversalDeserializer (); +// timer.stop (); +// //Console.Write (timer.lastIntervalTime.ToString () + " "); +// } +// Console.WriteLine ("average time = " + timer.totalMilliseconds / 100); +// Console.WriteLine ("Ratio = " + totalTime/timer.totalMilliseconds); +// } + + + +// } +// } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Test/TableAccumulatorTest.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Test/TableAccumulatorTest.cs new file mode 100644 index 000000000..c2d7d79b3 --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Test/TableAccumulatorTest.cs @@ -0,0 +1,275 @@ +// using System; +// using System.IO; +// using NUnit.Framework; + +// namespace BCG +// { +// [TestFixture] +// public class TableAccumulatorTest +// { +// private IBlueTableSchema mySchema = new BlueTableSchema ("test", +// new ColumnInfo ("id", 0, typeof(int)), +// new ColumnInfo ("x", 1, typeof(int))); +// private SubscriberCore mySubCore = new SubscriberCore (); +// private IBlueRowCollection myNr, myAr, myDr; + +// public TableAccumulatorTest() {} + +// [SetUp] +// public void tearDown () +// { +// myNr = myAr = myDr = null; +// } + +// #region create +// [Test] +// public void testCreate () +// { +// TableAccumulator ta = new TableAccumulator ("test", mySubCore); +// IBlueDataSerializer ser = new BlueDataSerializationController (); +// byte[] data; +// BlueTable bt = new BlueTable (mySchema); +// for (int i = 0; i < 100; i++) +// bt.addRow (new BlueRow (mySchema, i, 2*i)); +// ser.serialize (StreamOpCode.create, new IBlueRowCollection[] {bt}, out data); +// ta.onUpdate += new TableUpdateDelegate (myHandleUpdate); +// ta.update (new Stream[] {new MemoryStream (data)}); + +// //testing the data +// IBlueRowCollection dr, ar; +// //new rows +// BlueDataUtility.computeDifferences (bt, myNr, out dr, out ar); +// Assert.AreEqual (0, dr.Count); +// Assert.AreEqual (0, ar.Count); +// //added rows +// BlueDataUtility.computeDifferences (bt, myAr, out dr, out ar); +// Assert.AreEqual (0, dr.Count); +// Assert.AreEqual (0, ar.Count); +// //deleted rows; +// Assert.AreEqual (0, myDr.Count); +// ta.onUpdate -= new TableUpdateDelegate (myHandleUpdate); +// } +// #endregion + +// #region single add, delete and change +// [Test] +// public void testAddRemoveChange () +// { +// TableAccumulator ta = new TableAccumulator ("test", mySubCore); +// IBlueDataSerializer ser = new BlueDataSerializationController (); +// byte[] data; +// BlueTable bt = new BlueTable (mySchema); +// for (int i = 0; i < 100; i++) +// bt.addRow (new BlueRow (mySchema, i, 2*i)); +// ser.serialize (StreamOpCode.create, new IBlueRowCollection[] {bt}, out data); +// ta.onUpdate += new TableUpdateDelegate (myHandleUpdate); +// ta.update (new Stream[] {new MemoryStream (data)}); + +// //add +// //add a row with id 100 +// bt.clear (); +// bt.addRow (new BlueRow (mySchema, 100, 200)); +// ser.serialize (StreamOpCode.add, new IBlueRowCollection[] {bt}, out data); +// ta.update (new Stream[] {new MemoryStream (data)}); +// //testing the add data +// Assert.AreEqual (101, myNr.Count); +// for (int i = 0; i < 101; i++) +// myNr.containsID (i); +// Assert.AreEqual (0, myDr.Count); +// Assert.AreEqual (1, myAr.Count); +// Assert.That (myAr.containsID (100)); + +// //remove +// //remove the row with id 0 +// bt.clear (); +// bt.addRow (new BlueRow (mySchema, 0, 0)); +// ser.serialize (StreamOpCode.remove, new IBlueRowCollection[] {bt}, out data); +// ta.update (new Stream[] {new MemoryStream (data)}); +// //testing remove data +// Assert.AreEqual (100, myNr.Count); +// for (int i = 0; i < 101; i++) +// { +// Assert.That ((i == 0 && !myNr.containsID (i)) || (i != 0 && myNr.containsID (i))); +// } +// Assert.AreEqual (0, myAr.Count); +// Assert.AreEqual (1, myDr.Count); +// Assert.That (myDr.containsID (0)); + +// //change +// bt.clear (); +// bt.addRow (new BlueRow (mySchema, 100, -100)); +// ser.serialize (StreamOpCode.change, new IBlueRowCollection[] {bt}, out data); +// ta.update (new Stream[] {new MemoryStream (data)}); +// //testing changed data +// Assert.AreEqual (100, myNr.Count); +// Assert.AreEqual (1, myAr.Count); +// Assert.AreEqual (100, BlueDataUtility.extractRow (myAr, 0)["id"]); +// Assert.AreEqual (-100, BlueDataUtility.extractRow (myAr, 0)["x"]); +// Assert.AreEqual (1, myDr.Count); +// Assert.AreEqual (100, BlueDataUtility.extractRow (myDr, 0)["id"]); +// Assert.AreEqual (200, BlueDataUtility.extractRow (myDr, 0)["x"]); +// ta.onUpdate -= new TableUpdateDelegate (myHandleUpdate); +// } +// #endregion + +// #region multiple change +// public void testMultipleChange () +// { +// TableAccumulator ta = new TableAccumulator ("test", mySubCore); +// IBlueDataSerializer ser = new BlueDataSerializationController (); +// byte[] data; +// BlueTable bt = new BlueTable (mySchema); +// for (int i = 0; i < 100; i++) +// bt.addRow (new BlueRow (mySchema, i, 2*i)); +// ser.serialize (StreamOpCode.create, new IBlueRowCollection[] {bt}, out data); +// ta.onUpdate += new TableUpdateDelegate (myHandleUpdate); +// ta.update (new Stream[] {new MemoryStream (data)}); + +// //partial rows changed +// bt.clear (); +// for (int i = 0; i < 50; i++) +// bt.addRow (new BlueRow (mySchema, i, -2*i)); +// ser.serialize (StreamOpCode.multipleChange, new IBlueRowCollection[] {bt}, out data); +// ta.update (new Stream[] {new MemoryStream (data)}); +// //checking received data +// Assert.AreEqual (100, myNr.Count); +// foreach (IBlueRow r in myNr) +// { +// if ((int)r["id"] < 50) +// Assert.AreEqual ((int)r["id"] * -2, r["x"]); +// else +// Assert.AreEqual ((int)r["id"] * 2, r["x"]); +// } +// Assert.AreEqual (50, myAr.Count); +// foreach (IBlueRow r in myAr) +// Assert.AreEqual ((int)r["id"] * -2, r["x"]); +// Assert.AreEqual (50, myDr.Count); +// foreach (IBlueRow r in myDr) +// Assert.AreEqual ((int)r["id"] * 2, r["x"]); + +// //full rows changed +// bt.clear (); +// for (int i = 0; i < 100; i++) +// bt.addRow (new BlueRow (mySchema, i, -2*i)); +// ser.serialize (StreamOpCode.multipleChange, new IBlueRowCollection[] {bt}, out data); +// ta.update (new Stream[] {new MemoryStream (data)}); +// //checking received data +// Assert.AreEqual (100, myNr.Count); +// foreach (IBlueRow r in myNr) +// { +// Assert.AreEqual ((int)r["id"] * -2, r["x"]); +// } +// Assert.AreEqual (100, myAr.Count); +// foreach (IBlueRow r in myAr) +// Assert.AreEqual ((int)r["id"] * -2, r["x"]); +// Assert.AreEqual (100, myDr.Count); +// foreach (IBlueRow r in myDr) +// { +// if ((int)r["id"] < 50) +// Assert.AreEqual ((int)r["id"] * -2, r["x"]); +// else +// Assert.AreEqual ((int)r["id"] * 2, r["x"]); +// } +// ta.onUpdate -= new TableUpdateDelegate (myHandleUpdate); +// } +// #endregion + +// #region multiple deletes/adds +// public void testMultipleDeletesAdds () +// { + +// TableAccumulator ta = new TableAccumulator ("test", mySubCore); +// IBlueDataSerializer ser = new BlueDataSerializationController (); +// byte[] data; +// BlueTable bt = new BlueTable (mySchema); +// for (int i = 0; i < 100; i++) +// bt.addRow (new BlueRow (mySchema, i, 2*i)); +// ser.serialize (StreamOpCode.create, new IBlueRowCollection[] {bt}, out data); +// ta.onUpdate += new TableUpdateDelegate (myHandleUpdate); +// ta.update (new Stream[] {new MemoryStream (data)}); + +// BlueTable at = new BlueTable (mySchema), +// dt = new BlueTable (mySchema); +// for (int i = 0; i < 50; i++) +// dt.addRow (new BlueRow (mySchema, i, 2*i)); +// for (int i = 100; i < 150; i++) +// at.addRow (new BlueRow (mySchema, i, 2*i)); +// ser.serialize (StreamOpCode.multipleRemoveAdd, new IBlueRowCollection[] {dt, at}, out data); +// ta.update (new Stream[] {new MemoryStream (data)}); + +// //checking state +// Assert.AreEqual (100, myNr.Count); +// for (int i = 50; i < 150; i++) +// Assert.That (myNr.containsID (i)); +// Assert.AreEqual (50, myDr.Count); +// for (int i = 0; i < 50; i++) +// Assert.That (myDr.containsID (i)); +// Assert.AreEqual (50, myAr.Count); +// for (int i = 100; i < 150; i++) +// Assert.That (myAr.containsID (i)); +// ta.onUpdate -= new TableUpdateDelegate (myHandleUpdate); +// } +// #endregion + +// #region multiple ops in one stream +// [Test] +// public void testMultipleOps () +// { +// TableAccumulator ta = new TableAccumulator ("test", mySubCore); +// ta.onUpdate += new TableUpdateDelegate (myHandleUpdate); +// IBlueDataSerializer ser = new BlueDataSerializationController (); +// byte[] data; +// MemoryStream ms = new MemoryStream (); +// BlueTable bt = new BlueTable (mySchema); +// for (int i = 0; i < 100; i++) +// bt.addRow (new BlueRow (mySchema, i, 2*i)); +// ser.serialize (StreamOpCode.create, new IBlueRowCollection[] {bt}, out data); +// ta.update (new Stream[] {new MemoryStream (data)}); +// //ms.Write (data, 0, data.Length); +// //changing the first 5 rows +// bt.clear (); +// for (int i = 0; i < 5; i++) +// bt.addRow (new BlueRow (mySchema, i, 1000)); +// ser.serialize (StreamOpCode.multipleChange, new IBlueRowCollection[] {bt}, out data); +// ms.Write (data, 0, data.Length); +// //delete id 5 +// bt.clear (); +// bt.addRow (new BlueRow (mySchema, 5, 10)); +// ser.serialize (StreamOpCode.remove, new IBlueRowCollection[] {bt}, out data); +// ms.Write (data, 0, data.Length); +// //add id 100 +// bt.clear (); +// bt.addRow (new BlueRow (mySchema, 100, 200)); +// ser.serialize (StreamOpCode.add, new IBlueRowCollection[] {bt}, out data); +// ms.Write (data, 0, data.Length); +// //delete 4 and add 5 +// bt.clear (); +// BlueTable dels = new BlueTable (bt.schema); +// for (int i = 90; i < 94; i++) +// dels.addRow (new BlueRow (mySchema, i, i*2)); + +// for (int i = 101; i < 106; i++) +// bt.addRow (new BlueRow (mySchema, i, 2*i)); +// ser.serialize (StreamOpCode.multipleRemoveAdd, new IBlueRowCollection[] {dels, bt}, out data); +// ms.Write (data, 0, data.Length); +// ms.Position = 0; +// ta.update (new Stream[] {ms}); + +// Assert.AreEqual (101, myNr.Count); +// Assert.AreEqual (10, myDr.Count); +// Assert.AreEqual (11, myAr.Count); +// ta.onUpdate -= new TableUpdateDelegate (myHandleUpdate); + +// } +// #endregion + +// private void myHandleUpdate (IBlueRowCollection nr, IBlueRowCollection ar, IBlueRowCollection dr) +// { +// myNr = nr; +// myAr = ar; +// myDr = dr; +// } + + +// } +// } diff --git a/src/DataStreamSuite/DataStreamCore/Messaging/Test/UniversalRowSerializerTest.cs b/src/DataStreamSuite/DataStreamCore/Messaging/Test/UniversalRowSerializerTest.cs new file mode 100644 index 000000000..e7882a50a --- /dev/null +++ b/src/DataStreamSuite/DataStreamCore/Messaging/Test/UniversalRowSerializerTest.cs @@ -0,0 +1,58 @@ +// using System; +// using System.IO; +// using NUnit.Framework; + +// namespace BCG +// { +// [TestFixture] +// public class UniversalRowSerializerTest +// { +// private IBlueRowSerializer myRowSerializer; +// private IClientRowDeserializer myRowDeserializer; +// private Random myRnd = new Random (DateTime.Now.Millisecond); +// private IBlueTableSchema mySchema = new BlueTableSchema ("Test", +// new ColumnInfo ("id", 0, typeof(int)), +// new ColumnInfo ("int1", 1, typeof(int)), +// new ColumnInfo ("int2", 2, typeof(int)), +// new ColumnInfo ("double1", 3, typeof(double)), +// new ColumnInfo ("double2", 4, typeof(double)), +// new ColumnInfo ("byte1", 5, typeof(byte)), +// new ColumnInfo ("string1", 6, typeof(string)), +// new ColumnInfo ("string2", 7, typeof(string))); +// public UniversalRowSerializerTest () {} + +// [Test] +// public void testSerialiazationCycle () +// { +// myRowSerializer = new UniversalRowSerializer (mySchema); +// myRowDeserializer = new ClientUniversalRowDeserializer (mySchema); +// for (int i = 0; i < 10000; i++) +// { +// BinaryWriter bw = new BinaryWriter (new MemoryStream ()); +// IBlueRow ir = myGetRandomRow (); +// myRowSerializer.serializeRow (ir, StreamOpCode.add, bw); + +// IBlueRow or; +// (bw.BaseStream as MemoryStream).Position = 0; +// BinaryReader br = new BinaryReader (bw.BaseStream); +// myRowDeserializer.deserializeRow (null, br, StreamOpCode.add, out or); +// Assert.That (BlueDataUtility.computeRowEquality (ir, or)); +// } +// } + +// private IBlueRow myGetRandomRow () +// { +// return new BlueRow (mySchema, +// myRnd.Next (1000), +// myRnd.Next (5)% 3 == 0 ? DBNull.Value as object : myRnd.Next (1000) as object, +// myRnd.Next (5)% 3 == 0 ? DBNull.Value as object: myRnd.Next (1000) as object, +// myRnd.Next (5)% 3 == 0 ? DBNull.Value as object : myRnd.NextDouble () as object, +// myRnd.Next (5)% 3 == 0 ? DBNull.Value as object : myRnd.NextDouble () as object, +// myRnd.Next (5)% 3 == 0 ? DBNull.Value as object : Convert.ToByte (76) as object, +// myRnd.Next (5)% 3 == 0 ? DBNull.Value as object : "abcdefgh" as object, +// myRnd.Next (5)% 3 == 0 ? DBNull.Value as object : "1234567890" as object +// ); + +// } +// } +// } diff --git a/src/DataStreamSuite/DataStreamPublisher/Program.cs b/src/DataStreamSuite/DataStreamPublisher/Program.cs index b5c21e183..d9bd77bf5 100644 --- a/src/DataStreamSuite/DataStreamPublisher/Program.cs +++ b/src/DataStreamSuite/DataStreamPublisher/Program.cs @@ -19,7 +19,7 @@ Console.WriteLine("Starting DSPublisher..."); _subscribe_to_stream(); void _subscribe_to_stream() { - BCG.ViewStream vs = new TableStream("time"); + BCG.ViewStream vs = new TableStream("literal"); vs.onChange += on_change; } diff --git a/src/DataStreamSuite/DataStreamQueryAnalyzer/Program.cs b/src/DataStreamSuite/DataStreamQueryAnalyzer/Program.cs index d4c91a80e..4b298e2bd 100644 --- a/src/DataStreamSuite/DataStreamQueryAnalyzer/Program.cs +++ b/src/DataStreamSuite/DataStreamQueryAnalyzer/Program.cs @@ -29,7 +29,8 @@ ts.keep_polling(TimeSpan.FromSeconds(1)); void _subscribe_to_stream() { - BCG.ViewStream vs = new BCG.SecondStream(10); + BCG.ViewStream vs = //new BCG.SecondStream(10); + new LiteralStream("n", "2.0"); ViewPublisher vp = new ViewPublisher("phoenix", new PubTableBroker(), vs); vs.onChange += on_change; } diff --git a/src/DataStreamSuite/DataStreamSuite.sln b/src/DataStreamSuite/DataStreamSuite.sln index d2f25aa2c..cc02853e7 100644 --- a/src/DataStreamSuite/DataStreamSuite.sln +++ b/src/DataStreamSuite/DataStreamSuite.sln @@ -21,19 +21,7 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "spark_core", "..\client\spa EndProject Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "spark_api", "..\client\spark_api\spark_api.csproj", "{52DD33DB-00F5-44BF-AE0F-5FC58FB2277E}" EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BlueRegistry", "BlueRegistry\BlueRegistry.csproj", "{0FD1BE7A-AEC8-4575-BA58-20E0F45E5214}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "BaseUtilities", "BaseUtilities\BaseUtilities.csproj", "{A9EDEEBD-A03A-4281-8FAF-2419D3E7009C}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GuiUtilities", "GuiUtilities\GuiUtilities.csproj", "{CADBA1B3-0837-44DD-85BB-70351AD3A028}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArithmeticExpressions", "ArithmeticExpressions\ArithmeticExpressions.csproj", "{EFE6AD17-2564-43A1-B0E5-A2A8DA173002}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataStreamExpressions", "DataStreamExpressions\DataStreamExpressions.csproj", "{D46A152D-AD29-4BEF-980B-5896694E312F}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ColumnMapExpressions", "ColumnMapExpressions\ColumnMapExpressions.csproj", "{A844AB94-195B-4A7F-89CD-9A335985328E}" -EndProject -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ExpressionCore", "ExpressionCore\ExpressionCore.csproj", "{B94AB04B-76D0-4D37-8F2E-7A57A70D289F}" +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "DataStreamTests", "DataStreamTests\DataStreamTests.csproj", "{66AB10D3-155F-4663-B1BC-D0818E17B87B}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -80,6 +68,10 @@ Global {52DD33DB-00F5-44BF-AE0F-5FC58FB2277E}.Debug|Any CPU.Build.0 = Debug|x64 {52DD33DB-00F5-44BF-AE0F-5FC58FB2277E}.Release|Any CPU.ActiveCfg = Release|x64 {52DD33DB-00F5-44BF-AE0F-5FC58FB2277E}.Release|Any CPU.Build.0 = Release|x64 + {66AB10D3-155F-4663-B1BC-D0818E17B87B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {66AB10D3-155F-4663-B1BC-D0818E17B87B}.Debug|Any CPU.Build.0 = Debug|Any CPU + {66AB10D3-155F-4663-B1BC-D0818E17B87B}.Release|Any CPU.ActiveCfg = Release|Any CPU + {66AB10D3-155F-4663-B1BC-D0818E17B87B}.Release|Any CPU.Build.0 = Release|Any CPU {0FD1BE7A-AEC8-4575-BA58-20E0F45E5214}.Debug|Any CPU.ActiveCfg = Debug|Any CPU {0FD1BE7A-AEC8-4575-BA58-20E0F45E5214}.Debug|Any CPU.Build.0 = Debug|Any CPU {0FD1BE7A-AEC8-4575-BA58-20E0F45E5214}.Release|Any CPU.ActiveCfg = Release|Any CPU diff --git a/src/DataStreamSuite/DataStreamTests/DataStreamTests.csproj b/src/DataStreamSuite/DataStreamTests/DataStreamTests.csproj index f892af124..e69de29bb 100644 --- a/src/DataStreamSuite/DataStreamTests/DataStreamTests.csproj +++ b/src/DataStreamSuite/DataStreamTests/DataStreamTests.csproj @@ -1,19 +0,0 @@ - - - - net7.0 - enable - enable - - false - - - - - - - - - - - diff --git a/src/DataStreamSuite/DataStreamTests/StreamSerialization/UniversalSerializationTest.cs b/src/DataStreamSuite/DataStreamTests/StreamSerialization/UniversalSerializationTest.cs new file mode 100644 index 000000000..9d1da91f5 --- /dev/null +++ b/src/DataStreamSuite/DataStreamTests/StreamSerialization/UniversalSerializationTest.cs @@ -0,0 +1,195 @@ +using System; +using System.IO; + +using NUnit.Framework; + +namespace BCG { + + /// + /// Tests the deserialization happening within the pubsub. + /// + public class UniversalSerializationTest { + protected IBlueTableSchema mySchema; + protected BlueTable myTable; + protected IBlueDataSerializer mySer = new BlueDataSerializationController(); + protected IPubsubDeserializer myPubsubDeser = new PubsubDeserializationController(); + protected IClientDeserializer myClientDeser = new ClientDeserializationController(); + + public UniversalSerializationTest() { + mySchema = new BlueTableSchema(myGetTableName(), + new ColumnInfo("id", 0, typeof(int)), + new ColumnInfo("i1", 1, typeof(int)), + new ColumnInfo("d1", 2, typeof(double)), + new ColumnInfo("dt", 3, typeof(DateTime)), + new ColumnInfo("x", 4, typeof(byte)) + ); + } + + protected virtual string myGetTableName() { + return "testUniversal"; + } + + /// + /// Tests the entire cycle. This is done by 'publishing' data to the serializationController (ie a series of + /// adds, deletions, changes etc) and getting the bytes and feeding it into a pubsubDeseriazlier and a clientDeserializer. + /// At every step the data is tested for consistency. At the end the getState is used to get all the data, and its passed + /// through the clientDeserializer to get all the rows. + /// + /// + [Test] + public void testEntireProcess() { + myTable = new BlueTable(mySchema); + byte[] data; + int id; + //create + for (id = 0; id < 100; id++) + myTable.addRow(myGetRow(id)); + + byte[] ops; + Array rows; + IBlueRowCollection del, add; + IBlueRowCollection[] receivedData; + IBlueRow r; + + //create + mySer.serialize(StreamOpCode.create, new IBlueRowCollection[] { myTable }, out data); + myWrite(StreamOpCode.create, data); + myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + Assert.AreEqual(1, ops.Length); + Assert.AreEqual(StreamOpCode.create, ops[0]); + Assert.AreEqual(1, rows.Length); + receivedData = rows.GetValue(0) as IBlueRowCollection[]; + Assert.AreEqual(1, receivedData.Length); + + BlueDataUtility.computeDifferences(receivedData[0], myTable, out del, out add); + Assert.AreEqual(0, del.Count); + Assert.AreEqual(0, add.Count); + + //single add + r = myGetRow(id); + BlueTable temp = new BlueTable(mySchema); + myTable.addRow(r); + temp.addRow(r); + mySer.serialize(StreamOpCode.add, new IBlueRowCollection[] { temp }, out data); + myWrite(StreamOpCode.add, data); + myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + Assert.AreEqual(1, ops.Length); + Assert.AreEqual(StreamOpCode.add, ops[0]); + Assert.AreEqual(1, rows.Length); + receivedData = rows.GetValue(0) as IBlueRowCollection[]; + Assert.AreEqual(1, receivedData.Length); + BlueDataUtility.computeDifferences(receivedData[0], temp, out del, out add); + Assert.AreEqual(0, del.Count); + Assert.AreEqual(0, add.Count); + + //single delete + r = myTable[0]; //delete row with id 0 + temp = new BlueTable(mySchema); + myTable.deleteRow(0); + temp.addRow(r); + mySer.serialize(StreamOpCode.remove, new IBlueRowCollection[] { temp }, out data); + myWrite(StreamOpCode.remove, data); + myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + Assert.AreEqual(1, ops.Length); + Assert.AreEqual(StreamOpCode.remove, ops[0]); + Assert.AreEqual(1, rows.Length); + receivedData = rows.GetValue(0) as IBlueRowCollection[]; + Assert.AreEqual(1, receivedData.Length); + BlueDataUtility.computeDifferences(receivedData[0], temp, out del, out add); + Assert.AreEqual(0, del.Count); + Assert.AreEqual(0, add.Count); + + //batch deletes and adds + //0 was removed earlier, so lets delete from 1 to 24 first, and then add 101 to 124 + BlueTable delRows = new BlueTable(mySchema), addRows = new BlueTable(mySchema); + for (int i = 1; i < 25; i++) { + delRows.addRow(myTable[i]); + myTable.deleteRow(i); + } + for (id = 101; id < 125; id++) { + r = myGetRow(id); + addRows.addRow(r); + myTable.addRow(r); + } + for (int i = 25; i < 125; i++) + Assert.AreEqual(true, myTable.containsID(i)); + Assert.AreEqual(100, myTable.Count); + + mySer.serialize(StreamOpCode.multipleRemoveAdd, new IBlueRowCollection[] { delRows, addRows }, out data); + myWrite(StreamOpCode.multipleRemoveAdd, data); + myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + Assert.AreEqual(1, ops.Length); + Assert.AreEqual(StreamOpCode.multipleRemoveAdd, ops[0]); + Assert.AreEqual(1, rows.Length); + receivedData = rows.GetValue(0) as IBlueRowCollection[]; + Assert.AreEqual(2, receivedData.Length); + BlueDataUtility.computeDifferences(receivedData[0], delRows, out del, out add); + Assert.AreEqual(0, del.Count); + Assert.AreEqual(0, add.Count); + BlueDataUtility.computeDifferences(receivedData[1], addRows, out del, out add); + Assert.AreEqual(0, del.Count); + Assert.AreEqual(0, add.Count); + + //pure changes only + //change the first 25, 25-49 + BlueTable changedRows = new BlueTable(mySchema); + for (int i = 25; i < 50; i++) { + MutableBlueRow mr = new MutableBlueRow(myTable[i]); + mr.setValue(4, Byte.MaxValue); + myTable.changeRow(mr); + changedRows.addRow(mr); + } + mySer.serialize(StreamOpCode.multipleChange, new IBlueRowCollection[] { changedRows }, out data); + myWrite(StreamOpCode.multipleChange, data); + myPubsubDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + myClientDeser.deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + Assert.AreEqual(1, ops.Length); + Assert.AreEqual(StreamOpCode.multipleChange, ops[0]); + Assert.AreEqual(1, rows.Length); + receivedData = rows.GetValue(0) as IBlueRowCollection[]; + Assert.AreEqual(1, receivedData.Length); + BlueDataUtility.computeDifferences(receivedData[0], changedRows, out del, out add); + Assert.AreEqual(0, del.Count); + Assert.AreEqual(0, add.Count); + + //final test + data = myPubsubDeser.getState(); + new ClientDeserializationController().deserialize(new Stream[] { new MemoryStream(data) }, out ops, out rows); + Assert.AreEqual(1, ops.Length); + Assert.AreEqual(StreamOpCode.create, ops[0]); + Assert.AreEqual(1, rows.Length); + receivedData = rows.GetValue(0) as IBlueRowCollection[]; + Assert.AreEqual(1, receivedData.Length); + BlueDataUtility.computeDifferences(receivedData[0], myTable, out del, out add); + Assert.AreEqual(0, del.Count); + Assert.AreEqual(0, add.Count); + + } + + private IBlueRow myGetRow(int id) { + return new BlueRow(mySchema, // the day pp fixed this test. + id, id + 10, id * 3.0, new DateTime(2008, 6, 4, 0, 0, 0, DateTimeKind.Unspecified), Convert.ToByte(id)); + } + + private void myWrite(byte op, byte[] data) { + string s = ""; + if (op == StreamOpCode.add) + s = "add one row"; + else if (op == StreamOpCode.change) + s = "change one row"; + else if (op == StreamOpCode.create) + s = "create"; + else if (op == StreamOpCode.multipleChange) + s = "multiple change"; + else if (op == StreamOpCode.multipleRemoveAdd) + s = "multiple add remove"; + else if (op == StreamOpCode.remove) + s = "remove one row"; + Console.WriteLine("yes, here , op = {0}, size = {1}", s, data.Length); + } + } +} diff --git a/src/DataStreamSuite/DataStreamTests/UnitTest1.cs b/src/DataStreamSuite/DataStreamTests/UnitTest1.cs index bc5cb5f9f..e69de29bb 100644 --- a/src/DataStreamSuite/DataStreamTests/UnitTest1.cs +++ b/src/DataStreamSuite/DataStreamTests/UnitTest1.cs @@ -1,15 +0,0 @@ -namespace DataStreamTests; - -public class Tests -{ - [SetUp] - public void Setup() - { - } - - [Test] - public void Test1() - { - Assert.Pass(); - } -} \ No newline at end of file