Merging changes

This commit is contained in:
Taha committed 2023-09-04 16:25:40 -04:00
1 parent c4216d2272
commit 797816be7e
437 files changed
+54228 -28

No files matched your search

@@ -0,0 +1,146 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using BCG.Utilities;
namespace BCG
{
public class CompressionClientDeserializer : IClientDeserializer
{
protected IBlueTableSchema mySchema;
protected IBlueTableSchema myFirstSchema;
protected IClientRowDeserializer myRowDeserializer;
public CompressionClientDeserializer()
{
myFirstSchema = null;
mySchema = null;
}
#region IClientDeserializer Members
public void deserialize(Stream[] streams, out byte[] theOps, out Array theRows)
{
BinaryReader br = new BinaryReader(UtilityMethods.getAggregatedStream(streams));
// BlueTrace.WriteDeserializeStart(streams.Length, br.BaseStream.Length);
// emit # of streams and total length
ArrayList ops = new ArrayList(), rows = new ArrayList();
IBlueRowCollection[] result;
while (true)
{
byte op;
try
{
int value = br.BaseStream.ReadByte();
if (value == -1) break;
op = (byte)value;
// BlueTrace.WriteDeserializeOperation(op);
}
catch (EndOfStreamException)
{
break;
}
if (op == StreamOpCode.create)
{
br.ReadString(); //pubsubDeserializer
br.ReadString(); //clientDeserializer
mySchema = new BlueTableSchema();
mySchema.deserialze(br);
//keep track of the first schema you've ever seen, so you know how to reorder columns
if (myFirstSchema == null)
myFirstSchema = mySchema;
/// decompress here
int compressedMessageSize = br.ReadInt32();
byte[] compressedData = br.ReadBytes(compressedMessageSize);
BinaryReader decompressedBr = new BinaryReader(UtilityMethods.decompress(compressedData));
result = new IBlueRowCollection[] { myGetRows(decompressedBr, op, decompressedBr.ReadInt32()) };
myEncorporateRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else
{
if (mySchema != null)
{
if (op == StreamOpCode.add || op == StreamOpCode.change || op == StreamOpCode.remove)
{
result = new IBlueRowCollection[] { myGetRows(br, op, 1) };
myEncorporateRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleChange)
{
int compressedMessageSize = br.ReadInt32();
byte[] compressedData = br.ReadBytes(compressedMessageSize);
BinaryReader decompressedBr = new BinaryReader(UtilityMethods.decompress(compressedData));
result = new IBlueRowCollection[] { myGetRows(decompressedBr, op, decompressedBr.ReadInt32()) };
myEncorporateRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleRemoveAdd)
{
int compressedMessageSize = br.ReadInt32();
byte[] compressedData = br.ReadBytes(compressedMessageSize);
BinaryReader decompressedBr = new BinaryReader(UtilityMethods.decompress(compressedData));
result =
new IBlueRowCollection[] {
myGetRows (decompressedBr, StreamOpCode.remove, decompressedBr.ReadInt32 ()),
myGetRows (decompressedBr, StreamOpCode.add, decompressedBr.ReadInt32 ())
};
myEncorporateRows(result[0], StreamOpCode.remove);
myEncorporateRows(result[1], StreamOpCode.add);
ops.Add(op);
rows.Add(result);
}
else
{
// BlueEventLog.logEvent("Illegal op-code received", BlueEventLevel.Error);
}
}
else
{
// BlueEventLog.logEvent("Received a non create operation even though the schema" +
// "has never been created", BlueEventLevel.Warning);
}
}
}
theOps = ops.ToArray(typeof(byte)) as byte[];
theRows = rows.ToArray();
// BlueTrace.WriteDeserializeStop(rows.Count);
}
#endregion
private IBlueRowCollection myGetRows(BinaryReader br, byte op, int nRows)
{
BlueTable retVal = new BlueTable(mySchema);
if (myRowDeserializer == null)
myRowDeserializer = new ClientUniversalRowDeserializer(mySchema);
else if (op == StreamOpCode.create)
myRowDeserializer = new ClientReorderingRowDeserializer(myFirstSchema, mySchema);
for (int i = 0; i < nRows; i++)
{
IBlueRow row;
myRowDeserializer.deserializeRow(null, br, op, out row);
retVal.addRow(row);
}
return retVal;
}
private void myEncorporateRows(IBlueRowCollection rows, byte op) { }
}
}
@@ -0,0 +1,192 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Collections;
using BCG.Utilities;
namespace BCG
{
public class CompressionPubsubDeserializer : IPubsubDeserializer
{
protected IDictionary myState = new Hashtable();
protected IBlueTableSchema mySchema;
protected string myClientDeserializerName; //for the getState method
protected IPubsubRowDeserializer myRowDeserializer;
public CompressionPubsubDeserializer() { }
#region IPubSubDeserializer Members
public virtual void deserialize(Stream[] streams, out byte[] theOps, out Array theRows)
{
BinaryReader br = new BinaryReader(UtilityMethods.getAggregatedStream(streams));
ArrayList ops = new ArrayList(), rows = new ArrayList();
while (true)
{
IDictionary[] result;
byte op;
try
{
int value = br.BaseStream.ReadByte();
if (value == -1) break;
op = (byte)value;
}
catch (EndOfStreamException)
{
break;
}
if (op == StreamOpCode.create)
{
myState.Clear();
br.ReadString(); //the pubsub-deserializer name, should be the same as this's name
myClientDeserializerName = br.ReadString(); //the client-deserializer name
(mySchema = new BlueTableSchema()).deserialze(br);
/// deserialize this part
int compressedMessageSize = br.ReadInt32();
BinaryReader decompressedBr = new BinaryReader(UtilityMethods.decompress(br.ReadBytes(compressedMessageSize)));
result = new IDictionary[] { myGetRows(decompressedBr, op, decompressedBr.ReadInt32()) };
myEncorporatRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else
{
if (mySchema != null)
{
if (op == StreamOpCode.add || op == StreamOpCode.change || op == StreamOpCode.remove)
{
result = new IDictionary[] { myGetRows(br, op, 1) };
myEncorporatRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleChange)
{
int compressedMessageSize = br.ReadInt32();
BinaryReader decompressedBr = new BinaryReader(UtilityMethods.decompress(br.ReadBytes(compressedMessageSize)));
result = new IDictionary[] { myGetRows(decompressedBr, op, decompressedBr.ReadInt32()) };
myEncorporatRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleRemoveAdd)
{
ops.Add(op);
int compressedMessageSize = br.ReadInt32();
BinaryReader decompressedBr = new BinaryReader(UtilityMethods.decompress(br.ReadBytes(compressedMessageSize)));
result = new IDictionary[] {
myGetRows (decompressedBr, StreamOpCode.remove, decompressedBr.ReadInt32 ()),
myGetRows (decompressedBr, StreamOpCode.add, decompressedBr.ReadInt32 ())
};
myEncorporatRows(result[0], StreamOpCode.remove);
myEncorporatRows(result[1], StreamOpCode.add);
rows.Add(result);
}
else
{
// BlueEventLog.logEvent("Illegal op-code received", BlueEventLevel.Error);
}
}
else
{
// BlueEventLog.logEvent("Received a non create operation even though the schema" +
// "has never been created", BlueEventLevel.Warning);
}
}
}
theOps = ops.ToArray(typeof(byte)) as byte[];
theRows = rows.ToArray();
}
/// <summary>
/// Sends in a create signal, so that new clients can get a create everytime and start
/// afresh from there
/// </summary>
/// <returns></returns>
public virtual byte[] getState()
{
if (mySchema == null)
return new byte[] { };
else
{
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(StreamOpCode.create);
bw.Write(GetType().AssemblyQualifiedName);
bw.Write(myClientDeserializerName);
mySchema.serialize(bw);
/// compress it here
BinaryWriter decompressedBw = new BinaryWriter(new MemoryStream());
decompressedBw.Write(myState.Count);
foreach (byte[] row in myState.Values)
decompressedBw.Write(row);
decompressedBw.BaseStream.Position = 0;
byte[] compressedData = UtilityMethods.compress(decompressedBw.BaseStream);
bw.Write(compressedData.Length);
bw.Write(compressedData);
return (bw.BaseStream as MemoryStream).ToArray();
}
}
#endregion
/// <summary>
/// Every row that has been deserialized passes through this method, so that it can update the state.
/// </summary>
/// <param name="rows"></param>
/// <param name="op"></param>
protected virtual void myEncorporatRows(IDictionary rows, byte op)
{
if (op == StreamOpCode.add || op == StreamOpCode.create)
foreach (DictionaryEntry de in rows)
{
if (myState.Contains(de.Key))
{
// BlueEventLog2.instance().logEvent(String.Format("Duplicate row creation. t: {0} id:{1}", mySchema.tableName, de.Key), BlueEventLog2Level.Fatal);
StringBuilder b = new StringBuilder();
foreach (string n in mySchema.columnNames)
b.AppendFormat(" {0}", n);
// BlueEventLog2.instance().logEvent(String.Format("Schema:{0}", b.ToString()), BlueEventLog2Level.Fatal);
}
myState.Add(de.Key, de.Value);
}
else if (op == StreamOpCode.remove)
foreach (DictionaryEntry de in rows)
{
if (!myState.Contains(de.Key))
{
// BlueEventLog2.instance().logEvent(String.Format("Unknown row deletion. t: {0} id:{1}", mySchema.tableName, de.Key), BlueEventLog2Level.Fatal);
StringBuilder b = new StringBuilder();
foreach (string n in mySchema.columnNames)
b.AppendFormat(" {0}", n);
// BlueEventLog2.instance().logEvent(String.Format("Schema:{0}", b.ToString()), BlueEventLog2Level.Fatal);
}
myState.Remove(de.Key);
}
else if (op == StreamOpCode.change || op == StreamOpCode.multipleChange)
foreach (DictionaryEntry de in rows)
myState[de.Key] = de.Value;
}
/// <summary>
/// Mass deserialization happens here, also since there is no knowledge of the schema
/// </summary>
/// <param name="br"></param>
/// <param name="op"></param>
/// <param name="noOfRows"></param>
/// <returns></returns>
private IDictionary myGetRows (BinaryReader br, byte op, int noOfRows)
{
myRowDeserializer = myRowDeserializer == null ? new PubsubUniversalRowDeserializer (mySchema) : myRowDeserializer;
Hashtable retVal = new Hashtable ();
for (int i = 0; i < noOfRows; i++)
{
int id; object row;
myRowDeserializer.deserializeRow (myState, br, op, out id, out row);
retVal.Add (id, row);
}
return retVal;
}
}
}
@@ -0,0 +1,90 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace BCG
{
public class CompressionSerializer : IBlueDataSerializer
{
private IBlueRowSerializer myRowSerializer;
private string myPubsubDeserializerName = "BCG.CompressionPubsubDeserializer, DataStreamGateway", myClientDeserializerName = "BCG.CompressionClientDeserializer";
public CompressionSerializer (IBlueTableSchema schema)
{
myRowSerializer = new UniversalRowSerializer (schema);
}
public void serialize(byte op, IBlueRowCollection[] rows, out byte[] serializedData)
{
// BlueTrace.WriteSerializeStart(op, rows.Length);
BinaryWriter bw = new BinaryWriter(new MemoryStream());
if (op == StreamOpCode.add || op == StreamOpCode.remove || op == StreamOpCode.change)
{
bw.Write(op);
/// no need to compress the only row
myRowSerializer.serializeRow(BlueDataUtility.extractRow(rows[0], 0), op, bw);
}
else if (op == StreamOpCode.create)
{
IBlueRowCollection createdRows = rows[0];
bw.Write(op);
bw.Write(myPubsubDeserializerName);
bw.Write(myClientDeserializerName);
int dummyIdCol = 0;
int[] dummyIdList = new int[1];
//the schema doesn't sort anything right now, because the C++ pub sub client depends on things being in a certain order
IBlueTableSchema sortedSchema = BlueDataUtility.getSortedSchema(createdRows.schema, out dummyIdList, out dummyIdCol);
sortedSchema.serialize(bw);
/// compress it here
BinaryWriter decompressedBw = new BinaryWriter(new MemoryStream());
decompressedBw.Write(createdRows.Count);
foreach (IBlueRow r in createdRows)
myRowSerializer.serializeRow(r, StreamOpCode.add, decompressedBw);
decompressedBw.BaseStream.Position = 0;
byte[] compressedData = UtilityMethods.compress(decompressedBw.BaseStream);
bw.Write(compressedData.Length);
bw.Write(compressedData);
}
else if (op == StreamOpCode.multipleRemoveAdd)
{
bw.Write(op);
IBlueRowCollection delRows = rows[0], addRows = rows[1];
/// compress it here
BinaryWriter decompressedBw = new BinaryWriter(new MemoryStream());
decompressedBw.Write(delRows.Count);
foreach (IBlueRow dr in delRows)
myRowSerializer.serializeRow(dr, StreamOpCode.remove, decompressedBw);
decompressedBw.Write(addRows.Count);
foreach (IBlueRow ar in addRows)
myRowSerializer.serializeRow(ar, StreamOpCode.add, decompressedBw);
decompressedBw.BaseStream.Position = 0;
byte[] compressedData = UtilityMethods.compress(decompressedBw.BaseStream);
bw.Write(compressedData.Length);
bw.Write(compressedData);
}
else if (op == StreamOpCode.multipleChange)
{
bw.Write(op);
IBlueRowCollection changedRows = rows[0];
/// compress it here
BinaryWriter decompressedBw = new BinaryWriter(new MemoryStream());
decompressedBw.Write(changedRows.Count);
foreach (IBlueRow cr in changedRows)
myRowSerializer.serializeRow(cr, StreamOpCode.change, decompressedBw);
decompressedBw.BaseStream.Position = 0;
byte[] compressedData = UtilityMethods.compress(decompressedBw.BaseStream);
bw.Write(compressedData.Length);
bw.Write(compressedData);
}
bw.BaseStream.Position = 0;
serializedData = (bw.BaseStream as MemoryStream).ToArray();
// BlueTrace.WriteSerializeStop(serializedData.Length);
}
}
}
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class BBOOptionDeserializer : ClientFixedDeserializer
{
public BBOOptionDeserializer() { }
}
}
@@ -0,0 +1,49 @@
using System;
using BCG.Utilities;
namespace BCG
{
public abstract class ClientFixedDeserializer : ClientDeserializer
{
private BlueTable myCurrentState;
public ClientFixedDeserializer () {}
protected override IBlueRowCollection myGetRows (System.IO.BinaryReader br, byte op, int nRows)
{
BlueTable retVal = new BlueTable (mySchema);
op = op == StreamOpCode.create ? StreamOpCode.add :
op == StreamOpCode.multipleChange ? StreamOpCode.change : op;
if (myRowDeserializer == null)
{
myRowDeserializer = new ClientFixedRowDeserializer (mySchema);
myCurrentState = new BlueTable (mySchema);
}
for (int i = 0; i < nRows; i++)
{
IBlueRow r;
myRowDeserializer.deserializeRow (myCurrentState, br, op, out r);
retVal.addRow (r);
}
return retVal;
}
protected override void myEncorporateRows (IBlueRowCollection rows, byte op)
{
if (op == StreamOpCode.create)
myCurrentState = new BlueTable (rows);
else if (op == StreamOpCode.add)
myCurrentState.addRows (rows);
else if (op == StreamOpCode.remove)
myCurrentState.deleteRows (rows);
else if (op == StreamOpCode.change || op == StreamOpCode.multipleChange)
myCurrentState.changeRows (rows);
else
{
// BlueEventLog.logAssert (false, "Illegal operation for this context");
}
}
}
}
@@ -0,0 +1,38 @@
using System;
using System.IO;
using BCG.Utilities;
namespace BCG
{
public class ClientFixedRowDeserializer : IClientRowDeserializer
{
private PrimitiveDeserializationHelper myHelper;
private IBlueTableSchema mySchema;
public ClientFixedRowDeserializer (IBlueTableSchema schema)
{
myHelper = new PrimitiveDeserializationHelper (mySchema = schema);
}
#region IClientRowDeserializer Members
public void deserializeRow (IBlueRowCollection currentState, BinaryReader br, byte op, out IBlueRow r)
{
if (op == StreamOpCode.add || op == StreamOpCode.change)
{
object[] retVal = new object[mySchema.columnInfo.Length];
foreach (ColumnInfo ci in mySchema.columnInfo)
retVal[ci.colNo] = myHelper.deserializeColumn (ci.colNo, br);
r = new BlueRow (mySchema, retVal);
}
else if (op == StreamOpCode.remove)
r = currentState[br.ReadInt32 ()];
else
{
// BlueEventLog.logAssert (false, op.ToString() + " not valid in this context");
r = null;
}
}
#endregion
}
}
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class MarketOptionTheoClientDeserializer : ClientFixedDeserializer
{
public MarketOptionTheoClientDeserializer() { }
}
}
@@ -0,0 +1,13 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class BBOOptionSerializer : FixedSerializer
{
public BBOOptionSerializer(IBlueTableSchema schema)
: base(schema, "BCG.BBOOptionPubsubDeserializer", "BCG.BBOOptionDeserializer")
{ }
}
}
@@ -0,0 +1,35 @@
using System;
using System.IO;
namespace BCG
{
/// <summary>
/// Optimized to serialize fixed length rows, ie schemas that have only primitive types and non-nulls
/// </summary>
public class FixedRowSerializer : IBlueRowSerializer
{
private PrimitiveSerializationHelper myHelper;
private int myIdColNo;
private IBlueTableSchema mySchema;
public FixedRowSerializer (IBlueTableSchema schema)
{
myIdColNo = schema["id"].colNo;
myHelper = new PrimitiveSerializationHelper (schema);
mySchema = schema;
}
#region IBlueRowSerializer Members
public void serializeRow (IBlueRow r, byte op, BinaryWriter bw)
{
if (op == StreamOpCode.remove)
myHelper.serializeColumn (r, myIdColNo, bw);
else
foreach (ColumnInfo ci in r.schema.columnInfo)
myHelper.serializeColumn (r, ci.colNo, bw);
}
#endregion
}
}
@@ -0,0 +1,20 @@
using System;
using System.IO;
namespace BCG
{
/// <summary>
/// Tailored to serialize tables that haved fixed schema (ie no dynamic length types like strings, arrays etc and no nulls)
/// </summary>
public abstract class FixedSerializer : BlueDataSerializer
{
public FixedSerializer (IBlueTableSchema schema,
string pubsubDeserializer,
string clientDeserializer)
: base (pubsubDeserializer, clientDeserializer)
{
myRowSerializer = new FixedRowSerializer (schema);
}
}
}
@@ -0,0 +1,14 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class MarketOptionTheoSerializer : FixedSerializer
{
public MarketOptionTheoSerializer(IBlueTableSchema schema)
: base(schema, "BCG.MarketOptionTheoPubsubDeserializer",
"BCG.MarketOptionTheoClientDeserializer")
{ }
}
}
@@ -0,0 +1,11 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class BBOOptionPubsubDeserializer : PubsubFixedDeserializer
{
public BBOOptionPubsubDeserializer() { }
}
}
@@ -0,0 +1,12 @@
using System;
using System.Collections.Generic;
using System.Text;
namespace BCG
{
public class MarketOptionTheoPubsubDeserializer : PubsubFixedDeserializer
{
public MarketOptionTheoPubsubDeserializer()
{ }
}
}
@@ -0,0 +1,32 @@
using System;
using System.Collections;
using System.IO;
namespace BCG
{
public abstract class PubsubFixedDeserializer : PubsubDeserializer
{
protected BlueTable myCurrentState;
public PubsubFixedDeserializer () {}
protected override IDictionary myGetRows (BinaryReader br, byte op, int noOfRows)
{
if (myDeserializer == null)
myDeserializer = new PubsubFixedRowDeserializer (mySchema);
IDictionary retVal = new Hashtable ();
op = op == StreamOpCode.create ? StreamOpCode.add :
op == StreamOpCode.multipleChange ? StreamOpCode.change : op;
for (int i = 0; i < noOfRows; i++)
{
int id;
object row;
myDeserializer.deserializeRow (myState, br, op, out id, out row);
retVal.Add (id, row);
}
return retVal;
}
}
}
@@ -0,0 +1,37 @@
using System;
using System.IO;
using System.Collections;
namespace BCG
{
public class PubsubFixedRowDeserializer : IPubsubRowDeserializer
{
private int myRowSize, myIdOffset;
public PubsubFixedRowDeserializer (IBlueTableSchema schema)
{
foreach (ColumnInfo ci in schema.columnInfo)
{
myRowSize += SerializationUtilityMethods.getFixedLengthTypeSize (ci.colType);
myIdOffset += ci.colNo < schema["id"].colNo ? SerializationUtilityMethods.getFixedLengthTypeSize (ci.colType) : 0;
}
}
#region IPubsubRowDeserializer Members
public void deserializeRow (IDictionary currentState, BinaryReader br, byte op, out int id, out object row)
{
if (op == StreamOpCode.add || op == StreamOpCode.change)
{
row = br.ReadBytes (myRowSize);
id = BitConverter.ToInt32 (row as byte[], myIdOffset);
}
else //delete => only the id
{
id = br.ReadInt32 ();
row = currentState[id];
}
}
#endregion
}
}
@@ -0,0 +1,56 @@
using System;
using System.IO;
using System.Collections;
using BCG.Utilities;
namespace BCG
{
public abstract class ClientFixedChangingDeserializer : ClientDeserializer
{
private string [] myChangingCols;
protected BlueTable myCurrentState;
public ClientFixedChangingDeserializer (string[] changingCols)
{
myChangingCols = changingCols;
}
protected override IBlueRowCollection myGetRows (System.IO.BinaryReader br, byte op, int nRows)
{
BlueTable retVal = new BlueTable (mySchema);
op = op == StreamOpCode.create ? StreamOpCode.add :
op == StreamOpCode.multipleChange ? StreamOpCode.change : op;
if (myRowDeserializer == null)
{
myRowDeserializer = new ClientFixedChangingRowDeserializer (mySchema, myChangingCols);
myCurrentState = new BlueTable (mySchema);
}
for (int i = 0; i < nRows; i++)
{
IBlueRow r;
myRowDeserializer.deserializeRow (myCurrentState, br, op, out r);
retVal.addRow (r);
}
return retVal;
}
protected override void myEncorporateRows (IBlueRowCollection rows, byte op)
{
if (op == StreamOpCode.create)
myCurrentState = new BlueTable (rows);
else if (op == StreamOpCode.add)
myCurrentState.addRows (rows);
else if (op == StreamOpCode.remove)
myCurrentState.deleteRows (rows);
else if (op == StreamOpCode.change || op == StreamOpCode.multipleChange)
myCurrentState.changeRows (rows);
else
{
// BlueEventLog.logAssert (false, "Illegal operation for this context");
}
}
}
}
@@ -0,0 +1,67 @@
using System;
using System.Collections;
using System.IO;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Deserializes a fixed length row with no nulls on the client side.
/// </summary>
public class ClientFixedChangingRowDeserializer : IClientRowDeserializer
{
private int[] myChangingColIndices;
protected PrimitiveDeserializationHelper myHelper;
protected IBlueTableSchema mySchema;
public ClientFixedChangingRowDeserializer (IBlueTableSchema schema, string[] changingCols)
{
myHelper = new PrimitiveDeserializationHelper (mySchema = schema);
myChangingColIndices = new int [changingCols.Length];
for (int i = 0; i < changingCols.Length; i++)
myChangingColIndices[i] = schema[changingCols[i]].colNo;
Array.Sort (myChangingColIndices);
}
public void deserializeRow (IBlueRowCollection currentState, BinaryReader br, byte op, out IBlueRow r)
{
if (op == StreamOpCode.add)
myDeserializeAdd (currentState, br, out r);
else if (op == StreamOpCode.remove)
myDeserializeRemove (currentState, br, out r);
else if (op == StreamOpCode.change)
myDeserializeChange (currentState, br, out r);
else
{
r = null;
// BlueEventLog.logAssert (false, "Illegal operation for this function, can only deal with single row " +
// "add, delete and change");
}
}
protected virtual void myDeserializeAdd (IBlueRowCollection currentState, BinaryReader br, out IBlueRow r)
{
object[] retVal = new object[mySchema.columnInfo.Length];
foreach (ColumnInfo ci in mySchema.columnInfo)
retVal[ci.colNo] = myHelper.deserializeColumn (ci.colNo, br);
r = new BlueRow (mySchema, retVal);
}
protected virtual void myDeserializeRemove (IBlueRowCollection currentState, BinaryReader br, out IBlueRow r)
{
r = currentState[br.ReadInt32()];
}
protected virtual void myDeserializeChange (IBlueRowCollection currentState, BinaryReader br, out IBlueRow r)
{
MutableBlueRow rv = new MutableBlueRow (currentState[br.ReadInt32 ()]);
foreach (int colNo in myChangingColIndices)
rv.setValue (colNo, myHelper.deserializeColumn (colNo, br));
r = rv;
}
}
}
@@ -0,0 +1,90 @@
using System;
using System.Collections;
using System.IO;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Specializes in serializing rows that are sent over as a result of a change; only the changed columns are
/// sent together with the id.
/// </summary>
public class FixedChangingRowSerializer : IBlueRowSerializer
{
private int[] myChangingColIndices;
private PrimitiveSerializationHelper myHelper;
private IBlueTableSchema mySchema;
public FixedChangingRowSerializer (IBlueTableSchema schema, params string[] changingColumns)
{
myHelper = new PrimitiveSerializationHelper (schema);
myChangingColIndices = new int[changingColumns.Length];
for (int i = 0; i < changingColumns.Length; i++)
myChangingColIndices[i] = schema[changingColumns[i]].colNo;
Array.Sort (myChangingColIndices);
mySchema = schema;
}
#region IBlueRowSerializer Members
public void serializeRow (IBlueRow r, byte op, BinaryWriter bw)
{
if (op == StreamOpCode.add)
{
mySerializeAdd (r, bw);
}
else if (op == StreamOpCode.remove)
{
mySerializeRemove (r, bw);
}
else if (op == StreamOpCode.change)
{
mySerializeChange (r, bw);
}
else
{
// BlueEventLog.logAssert (false, String.Format ("{0} is not a valid op in this context", op));
}
}
#endregion
/// <summary>
/// The whole row is written, one column after the other with the order defined by the schema. There
/// are no columns headers
/// </summary>
/// <param name="r"></param>
/// <param name="bw"></param>
protected virtual void mySerializeAdd (IBlueRow r, BinaryWriter bw)
{
foreach (ColumnInfo ci in r.schema.columnInfo)
myHelper.serializeColumn (r, ci.colNo, bw);
}
/// <summary>
/// Only the id is written
/// </summary>
/// <param name="r"></param>
/// <param name="bw"></param>
protected virtual void mySerializeRemove (IBlueRow r, BinaryWriter bw)
{
myHelper.serializeColumn (r, r.schema["id"].colNo, bw);
}
/// <summary>
/// Serializes only the changed columns, alongside the id. So the format is
/// {id, changedColumns*}. The order of the changedColumns are sorted according
/// to their index in the schema.
/// </summary>
/// <param name="r"></param>
/// <param name="bw"></param>
protected virtual void mySerializeChange (IBlueRow r, BinaryWriter bw)
{
myHelper.serializeColumn (r, r.schema["id"].colNo, bw);
foreach (int colNo in myChangingColIndices)
myHelper.serializeColumn (r, colNo, bw);
}
}
}
@@ -0,0 +1,110 @@
using System;
using System.Collections;
using System.IO;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Tailored to serialize tables that haved fixed schema (ie no dynamic length types like strings, arrays etc and no nulls)
/// and are constantly changing
/// </summary>
public abstract class FixedChangingSerializer : BlueDataSerializer
{
public FixedChangingSerializer (IBlueTableSchema schema,
string[] changingCols,
string pubsubDeserializer,
string clientDeserializer)
: base (pubsubDeserializer, clientDeserializer)
{
myRowSerializer = new FixedChangingRowSerializer (schema, changingCols);
}
}
#region BidAsk
public class BidAskSerializer : FixedChangingSerializer
{
public BidAskSerializer (IBlueTableSchema schema)
: base (schema,
new string[] {"bidAskZone"},
"BCG.BidAskPubsubDeserializer",
"BCG.BidAskClientDeserializer"
)
{}
}
public class BidAskPubsubDeserializer : PubsubFixedChangingDeserializer
{
public BidAskPubsubDeserializer () : base (new string[] {"bidAskZone"})
{}
}
public class BidAskClientDeserializer : ClientFixedChangingDeserializer
{
public BidAskClientDeserializer () : base (new string[] {"bidAskZone"})
{}
}
#endregion
#region HHMarketPrice
public class HHMarketPriceSerializer : FixedChangingSerializer
{
public HHMarketPriceSerializer(IBlueTableSchema schema)
: base(schema,
new string[] { "MarketPrice" },
"BCG.HHMarketPricePubsubDeserializer",
"BCG.HHMarketPriceClientDeserializer"
)
{ }
}
public class HHMarketPricePubsubDeserializer : PubsubFixedChangingDeserializer
{
public HHMarketPricePubsubDeserializer()
: base(new string[] { "MarketPrice" })
{ }
}
public class HHMarketPriceClientDeserializer : ClientFixedChangingDeserializer
{
public HHMarketPriceClientDeserializer()
: base(new string[] { "MarketPrice" })
{ }
}
#endregion
#region ThrottledMarketPrice
public class ThrottledPriceSerializer : FixedChangingSerializer
{
public ThrottledPriceSerializer(IBlueTableSchema schema)
: base(schema,
new string[] { "PRICE" },
"BCG.ThrottledPricePubsubDeserializer",
"BCG.ThrottledPriceClientDeserializer"
)
{ }
}
public class ThrottledPricePubsubDeserializer : PubsubFixedChangingDeserializer
{
public ThrottledPricePubsubDeserializer()
: base(new string[] { "PRICE" })
{ }
}
public class ThrottledPriceClientDeserializer : ClientFixedChangingDeserializer
{
public ThrottledPriceClientDeserializer()
: base(new string[] { "PRICE" })
{ }
}
#endregion
}
@@ -0,0 +1,41 @@
using System;
using System.IO;
using System.Collections;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Pairs up with FixedSerializer to deserialize messages in the pubsub.
/// </summary>
public abstract class PubsubFixedChangingDeserializer : PubsubDeserializer
{
private string[] myChangingCols;
protected BlueTable myCurrentState;
public PubsubFixedChangingDeserializer (string[] changingColumns)
{
myChangingCols = changingColumns;
}
protected override IDictionary myGetRows (BinaryReader br, byte op, int noOfRows)
{
if (myDeserializer == null)
myDeserializer = new PubsubFixedChangingRowDeserializer (mySchema, myChangingCols);
IDictionary retVal = new Hashtable ();
op = op == StreamOpCode.create ? StreamOpCode.add :
op == StreamOpCode.multipleChange ? StreamOpCode.change : op;
for (int i = 0; i < noOfRows; i++)
{
int id;
object row;
myDeserializer.deserializeRow (myState, br, op, out id, out row);
retVal.Add (id, row);
}
return retVal;
}
}
}
@@ -0,0 +1,84 @@
using System;
using System.IO;
using System.Collections;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Pairs up with FixedSerializer to deserialize messages in the pubsub.
/// </summary>
public class PubsubFixedChangingRowDeserializer : IPubsubRowDeserializer
{
private int myFullRowSize;
private PrimitiveDeserializationHelper myDeserHelper;
private PrimitiveSerializationHelper mySerHelper;
private IBlueTableSchema mySchema;
private int[] myOffsets, myChangedColIndices;
private int myIdIndex;
public PubsubFixedChangingRowDeserializer (IBlueTableSchema schema, params string[] changingColNames)
{
myDeserHelper = new PrimitiveDeserializationHelper (mySchema = schema);
mySerHelper = new PrimitiveSerializationHelper (mySchema);
myIdIndex = mySchema["id"].colNo;
myOffsets = new int[schema.columnInfo.Length];
//size calulcations
foreach (ColumnInfo ci in mySchema.columnInfo)
{
myOffsets[ci.colNo] += myFullRowSize;
myFullRowSize += SerializationUtilityMethods.getFixedLengthTypeSize (ci.colType);
}
myChangedColIndices = new int[changingColNames.Length];
for (int i = 0; i < changingColNames.Length; i++)
myChangedColIndices[i] = mySchema[changingColNames[i]].colNo;
Array.Sort (myChangedColIndices);
}
#region IPubsubRowDeserializer Members
public void deserializeRow (IDictionary currentState, BinaryReader br, byte op, out int id, out object row)
{
if (op == StreamOpCode.add)
myDeserializeAdd (currentState, br, out id, out row);
else if (op == StreamOpCode.remove)
myDeserializeRemove (currentState, br, out id, out row);
else if (op == StreamOpCode.change)
myDeserializeChange (currentState, br, out id, out row);
else
{
id = int.MinValue;
row = null;
// BlueEventLog.logAssert (false, "Illegal operation for this context");
}
}
#endregion
protected virtual void myDeserializeAdd (IDictionary currentState, BinaryReader br, out int id, out object row)
{
row = br.ReadBytes (myFullRowSize);
id = BitConverter.ToInt32 (row as byte[], myOffsets[myIdIndex]);
}
protected virtual void myDeserializeRemove (IDictionary currentState, BinaryReader br, out int id, out object row)
{
id = br.ReadInt32 ();
row = currentState[id];
}
protected virtual void myDeserializeChange (IDictionary currentState, BinaryReader br, out int id, out object row)
{
id = br.ReadInt32 ();
BinaryWriter bw = new BinaryWriter (new MemoryStream (currentState[id] as byte[]));
foreach (int colIndex in myChangedColIndices)
{
object newValue = myDeserHelper.deserializeColumn (colIndex, br);
bw.BaseStream.Position = myOffsets[colIndex];
mySerHelper.serializeColumn (newValue, colIndex, bw);
}
row = (bw.BaseStream as MemoryStream).ToArray ();
}
}
}
@@ -0,0 +1,171 @@
using System;
using System.Collections;
using System.IO;
using System.IO.Compression;
using BCG.Utilities;
//using BCG.Utilities.BlueConfiguration;
namespace BCG
{
public class LookupTableClientDeserializer : IClientDeserializer
{
public LookupTableClientDeserializer() {
mySchema = new LookupTableSchema();
myLookupTables = null;
}
private IClientRowDeserializer myRowDeserializer;
private LookupTableSchema mySchema;
private LookupTable[] myLookupTables;
public BinaryReader myGetReaderForRestOfStream(Stream theStream)
{
//teh rest of the stream is only compressed data
long compressedBytesLength = theStream.Length - theStream.Position;
byte[] compressedBytes = new byte[compressedBytesLength];
theStream.Read(compressedBytes, 0, (int)compressedBytesLength);
//get a stream to read the uncompressed data
SharpZipCompressor deKompressor = new SharpZipCompressor();
MemoryStream decompressed = new MemoryStream();
deKompressor.decompress(new MemoryStream(compressedBytes), decompressed);
decompressed.Position = 0;
return new BinaryReader(decompressed);
}
#region IClientDeserializer methods
public void deserialize(Stream[] streams, out byte[] theOps, out Array theRows)
{
ArrayList ops = new ArrayList();
ArrayList rows = new ArrayList();
IBlueRowCollection[] result;
foreach (Stream theStream in streams)
{
byte op;
BinaryReader br = new BinaryReader(theStream);
op = br.ReadByte();
if (op == StreamOpCode.create)
{
br.ReadString(); //pubsub deserializer
br.ReadString(); //client deserializer
br = myGetReaderForRestOfStream(theStream);
result = new IBlueRowCollection[] { myHandleCreate(br) };
ops.Add(op);
rows.Add(result);
}
else
{
//the schema and lookup tables should already be created. We just need to update everything.
//figure out how long the rest of the compressed data is
br = myGetReaderForRestOfStream(theStream);
if (mySchema != null)
{
if (op == StreamOpCode.add || op == StreamOpCode.change || op == StreamOpCode.remove)
{
myDeserializeLookupTableUpdates(br);
result = new IBlueRowCollection[] { myGetRows(br, op, 1) };
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleChange)
{
myDeserializeLookupTableUpdates(br);
int numRows = br.ReadInt32();
result = new IBlueRowCollection[] { myGetRows(br, op, numRows) };
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleRemoveAdd)
{
myDeserializeLookupTableUpdates(br);
result = new IBlueRowCollection[2];
int numDeletedRows = br.ReadInt32();
result[0] = myGetRows(br, StreamOpCode.remove, numDeletedRows);
int numAddedRows = br.ReadInt32();
result[1] = myGetRows(br, StreamOpCode.add, numAddedRows);
ops.Add(op);
rows.Add(result);
}
else{}
// BlueEventLog.logEvent("Illegal op-code recieved", BlueEventLevel.Error);
}
else
{
// BlueEventLog.logEvent("Received a non create operation even though the schema" +
// "has never been created", BlueEventLevel.Error);
}
}
}
theOps = ops.ToArray(typeof(byte)) as byte[];
theRows = rows.ToArray();
}
#endregion
IBlueRowCollection myHandleCreate(BinaryReader br)
{
mySchema.deserialze(br);
//build the lookup tables now
// There is one less than the length of the lookupTableGroups because the first one
//is always the default group which isn't stored in a lookup table.
myLookupTables = new LookupTable[mySchema.lookupGroups.Length - 1];
//start with 1 because we don't store the 0th lookup table
for (int i = 0; i < myLookupTables.Length; ++i)
myLookupTables[i] = new LookupTable(mySchema, i+1);
myDeserializeLookupTableUpdates(br);
//now read the rows
int numRows = br.ReadInt32();
return myGetRows(br, StreamOpCode.create, numRows);
}
private IBlueRowCollection myGetRows(BinaryReader br, byte op, int nRows)
{
BlueTable retVal = new BlueTable(mySchema);
myRowDeserializer = myRowDeserializer == null ? new LookupTableClientRowDeserializer(mySchema,myLookupTables) : myRowDeserializer;
for (int i = 0; i < nRows; i++)
{
IBlueRow row;
myRowDeserializer.deserializeRow(null, br, op, out row);
retVal.addRow(row);
}
return retVal;
}
private void myDeserializeLookupTableUpdates(BinaryReader br)
{
for (int i = 0; i < myLookupTables.Length; ++i)
myLookupTables[i].deserializeUpdates(br);
}
}
}
@@ -0,0 +1,107 @@
using System;
using System.Collections;
using System.IO;
using BCG.Utilities;
//using BCG.Utilities.BlueConfiguration;
namespace BCG
{
/// <summary>
/// Helps the ClientUniversalDeserializer in deserilizing by dealing with the deserialization process
/// of one row. This leaves the ClientUniversalDeserializer to deserializer headers (indicating operations)
/// </summary>
internal class LookupTableClientRowDeserializer : IClientRowDeserializer
{
private LookupTableSchema mySchema;
private LookupTable[] myTables;
private int myNullMapLength = 0;
private PrimitiveDeserializationHelper myDeserializationHelper;
private BitArray myNullMap;
private int myIdColumn;
public LookupTableClientRowDeserializer (LookupTableSchema schema, LookupTable[] theTables)
{
mySchema = schema;
myTables = theTables;
myDeserializationHelper = new PrimitiveDeserializationHelper (mySchema);
myNullMapLength = Convert.ToInt32((Math.Ceiling(Convert.ToDouble(mySchema.columnNames.Length)/8)));
myIdColumn = schema["id"].colNo;
}
#region IClientRowDeserializer Members
public void deserializeRow (IBlueRowCollection currentState, BinaryReader br, byte op, out IBlueRow r)
{
int rowLength = br.ReadInt32 (); //length information for the row not needed
//rad the null map
myNullMap = new BitArray(br.ReadBytes (myNullMapLength));
object[] values = new object [mySchema.columnNames.Length];
//now read the id
values[myIdColumn] = br.ReadInt32();
//now read the lookup groups
for (int groupNo = 1; groupNo < mySchema.lookupGroups.Length; ++groupNo)
{
BlueRowLookupGroup thisGroup = mySchema.lookupGroups[groupNo];
LookupTable thisTable = myTables[groupNo - 1];
//read the id in, depending upon the size
int idRead = -1;
switch (thisGroup.tableSize)
{
case 8:
idRead = br.ReadByte();
break;
case 16:
idRead = br.ReadInt16();
break;
case 32:
idRead = br.ReadInt32();
break;
default:
throw new BlueDataException("Error: invalid size " + thisGroup.tableSize.ToString() + " specific for lookup group.");
}
object[] thisGroupValues = thisTable.getValuesForIndex(idRead);
if (thisGroupValues == null)
throw new BlueDataException("Error: Couldnt' find values for index " + idRead.ToString());
if (thisGroupValues.Length != thisGroup.groupColNos.Length)
throw new BlueDataException("Error: Values extracted for index " + idRead.ToString() + " had length " + thisGroupValues.Length.ToString() + " but length " + thisGroup.groupColNos.Length.ToString() + " was expected.");
//insert those values into our object array
for (int groupCol = 0; groupCol < thisGroup.groupColNos.Length; ++groupCol)
{
int thisColInOutputRow = thisGroup.groupColNos[groupCol];
values[thisColInOutputRow] = thisGroupValues[groupCol];
}
}
for (int colNo = 0; colNo < values.Length; colNo++)
{
if (myNullMap[colNo])
{
values[colNo] = DBNull.Value;
}
//if it's non null, not the id column, and not part of a lookup group, get it here.
else if (mySchema[colNo].lookupTableGroup == 0 && colNo != myIdColumn)
{
values[colNo] = myDeserializationHelper.deserializeColumn(colNo, br);
}
}
r = new BlueRow(mySchema, values);
}
#endregion
}
}
@@ -0,0 +1,194 @@
using System;
using System.Collections.Generic;
using System.Collections;
using System.IO;
using System.Linq;
using System.Text;
namespace BCG
{
/*
*
* LookupTable
*
* This class represents a lookup table used to store values inside data streams. This allows indexes into the table
* to be passed over the wire, instead of actual values of the rows.
*
* Each table can have multiple lookup table groups. This class represents just one of those groups. This means that all the entries
* contained in the table will have the same schema.
*
*
*
* */
public class LookupTable
{
//each of the entries has the same schema - that is, each of the entries contains the same number of values, with the same
IBlueTableSchema myEntrySchema;
UniversalRowSerializer mySerializer;
ClientUniversalRowDeserializer myDeserializer;
private const int myIdColumn = 0;
//the table is only allowed to reach a maximum size based upon the number of bits you give to it.
//it throws an error if you try to put too much data into it.
private long myMaxSize;
private int mySizeInBits;
public int sizeInBits
{
get { return mySizeInBits; }
}
KeysBasedTable2 myValuesToEntryMap;
//keep track of the last time somebody published you, so you know what values to publish.
int myIdOfLastPublish;
int myIdToUse;
/* builds the local schema, serializer, and desrializer
* initializes to an empty table
*/
public LookupTable(LookupTableSchema theSchema, int lookupGroupNumber)
{
BlueRowLookupGroup group = theSchema.lookupGroups[lookupGroupNumber];
myEntrySchema = group.entrySchema;
//compute how much room you have in the table
mySizeInBits = group.tableSize;
myMaxSize = (long)(Math.Pow(2, group.tableSize) - 1);
myDeserializer = new ClientUniversalRowDeserializer(myEntrySchema);
mySerializer = new UniversalRowSerializer(myEntrySchema);
//create the map
myValuesToEntryMap = new KeysBasedTable2(myEntrySchema, group.groupColNames);
myIdOfLastPublish = 0;
}
/*Checks to see if the given values are in the table. IF they are in there, it returns the index to those values.
If they are not present, it adds them to teh table and returns the new index. */
public int getIndexForValues(params object[] values)
{
int index = 0;
//see if the key is present
IBlueRow thisRowEntry = myValuesToEntryMap.getRow(values);
if (thisRowEntry == null)
{
//check to see if we even have room in the table
if (myIdToUse > myMaxSize)
throw new BlueDataException("Error: LookupTable has reached maximum size. Make a bigger table.");
//we need to entrer this new value into the table. Create a blue row using the next ID
//and the values they supplied to us
object[] thisRowValues = new object[myEntrySchema.columnInfo.Length];
index = myIdToUse;
thisRowValues[myIdColumn] = index;
myIdToUse ++;
//now add in the values they supplied
for (int colNo = myIdColumn+1; colNo < myEntrySchema.columnInfo.Length; ++colNo)
{
thisRowValues[colNo] = values[colNo - 1];
}
IBlueRow newEntryRow = new BlueRow(myEntrySchema, thisRowValues);
myValuesToEntryMap.update(newEntryRow);
}
else
index = (int) thisRowEntry["id"];
return index;
}
//queries the table to get the values that were stored on a given index.
//returns null if the values are not found
public object[] getValuesForIndex(int index)
{
object[] results = null;
//get the row from the table
if (myValuesToEntryMap.containsID(index))
{
IBlueRow thisRow = myValuesToEntryMap[index];
results = new object[myEntrySchema.columnInfo.Length - 1];
//copy the values from the row into the array
for (int colNo = myIdColumn+1; colNo < myEntrySchema.columnInfo.Length; ++ colNo)
{
results[colNo - 1] = thisRow[colNo];
}
}
//if the index isn't in the tablem, can just return the null value
return results;
}
public void deserializeUpdates(BinaryReader br)
{
//get the number of updates that are being published.
int numUpdates = br.ReadInt32();
for (int i = 0; i < numUpdates; ++i)
{
IBlueRow theNewUpdate = null;
myDeserializer.deserializeRow(null, br, StreamOpCode.create, out theNewUpdate);
myValuesToEntryMap.update(theNewUpdate);
int thisID = (int) theNewUpdate[myIdColumn];
if (thisID != myIdToUse)
throw new BlueDataException("Error: bad serialized update given to lookup table. Expected id " + myIdToUse.ToString() + ", found " + thisID.ToString());
++myIdToUse;
}
}
public void serializeUpdates(BinaryWriter bw)
{
int numUpdates = myIdToUse - myIdOfLastPublish;
//serialize the number of updates
bw.Write(numUpdates);
//serialize each update
for (int i = myIdOfLastPublish; i < myIdToUse; ++i)
mySerializer.serializeRow(myValuesToEntryMap[i], StreamOpCode.add, bw);
//store the last id you published so that next time we don't serialize the same updates
myIdOfLastPublish = myIdToUse;
}
/*this function serializes EVERYTHING in the table into the writer. This is
used by the pubsub deserializer, which needs to be able to supply the new state
to any clients connection. */
public void serializeWholeTable(BinaryWriter bw)
{
//serialize the number of updates
bw.Write(myIdToUse);
//serialize each update
for (int i = 0; i < myIdToUse; ++i)
mySerializer.serializeRow(myValuesToEntryMap[i], StreamOpCode.add, bw);
}
}
}
@@ -0,0 +1,226 @@
using System;
using System.Collections;
using System.IO;
using BCG.Utilities;
using System.IO.Compression;
namespace BCG
{
public class LookupTablePubSubDeserializer : IPubsubDeserializer
{
protected IDictionary myState = new Hashtable();
protected LookupTableSchema mySchema;
protected string myClientDeserializerName; //for the getState method
protected IPubsubRowDeserializer myDeserializer;
LookupTable[] myLookupTables;
public LookupTablePubSubDeserializer() {
mySchema = new LookupTableSchema();
}
public BinaryReader myGetReaderForCompressedPortion(Stream theStream)
{
//teh rest of the stream is only compressed data
long compressedBytesLength = theStream.Length - theStream.Position;
byte[] compressedBytes = new byte[compressedBytesLength];
theStream.Read(compressedBytes, 0, (int)compressedBytesLength);
//get a stream to read the uncompressed data
SharpZipCompressor deKompressor = new SharpZipCompressor();
MemoryStream decompressed = new MemoryStream();
deKompressor.decompress(new MemoryStream(compressedBytes), decompressed);
decompressed.Position = 0;
return new BinaryReader(decompressed);
}
#region IPubsubDeserializer Members
public virtual void deserialize(Stream[] streams, out byte[] theOps, out Array theRows)
{
ArrayList ops = new ArrayList(), rows = new ArrayList();
foreach (Stream theStream in streams)
{
BinaryReader br = new BinaryReader(theStream);
IDictionary[] result;
byte op;
op = br.ReadByte();
if (op == StreamOpCode.create)
{
myState.Clear();
br.ReadString(); //the pubsub-deserializer name, should be the same as this's name
myClientDeserializerName = br.ReadString(); //the client-deserializer name
//at this point, the rest of the bytes in the stream are from a GZIP stream
//so we need to read into a GZipStream and decompress
//figure out how long the rest of the compressed data is
br = myGetReaderForCompressedPortion(theStream);
mySchema.deserialze(br);
//now build the lookup tables from the knowledge gleaned at the schema
myLookupTables = new LookupTable[mySchema.lookupGroups.Length - 1];
//start with 1 because we don't store the 0th lookup table
for (int i = 0; i < myLookupTables.Length; ++i)
myLookupTables[i] = new LookupTable(mySchema, i + 1);
myDeserializeLookupTableUpdates(br);
int numRows = br.ReadInt32();
result = new IDictionary[] { myGetRows(br, op, numRows) };
myEncorporatRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else
{
//figure out how long the rest of the compressed data is
br = myGetReaderForCompressedPortion(theStream);
if (mySchema != null)
{
if (op == StreamOpCode.add || op == StreamOpCode.change || op == StreamOpCode.remove)
{
myDeserializeLookupTableUpdates(br);
result = new IDictionary[] { myGetRows(br, op, 1) };
myEncorporatRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleChange)
{
myDeserializeLookupTableUpdates(br);
int numRows = br.ReadInt32();
result = new IDictionary[] { myGetRows(br, op, numRows) };
myEncorporatRows(result[0], op);
ops.Add(op);
rows.Add(result);
}
else if (op == StreamOpCode.multipleRemoveAdd)
{
myDeserializeLookupTableUpdates(br);
int numRemoved = br.ReadInt32();
result = new IDictionary[2];
result[0] = myGetRows(br, StreamOpCode.remove, numRemoved);
int numAdded = br.ReadInt32();
result[1] = myGetRows (br, StreamOpCode.add, numAdded);
myEncorporatRows(result[0], StreamOpCode.remove);
myEncorporatRows(result[1], StreamOpCode.add);
ops.Add(op);
rows.Add(result);
}
else
{
// BlueEventLog.logEvent("Illegal op-code received", BlueEventLevel.Error);
}
}
else
{
// BlueEventLog.logEvent("Received a non create operation even though the schema" +
// "has never been created", BlueEventLevel.Warning);
}
}
}
theOps = ops.ToArray(typeof(byte)) as byte[];
theRows = rows.ToArray();
}
/// <summary>
/// Sends in a create signal, so that new clients can get a create everytime and start
/// afresh from there
/// </summary>
/// <returns></returns>
public virtual byte[] getState()
{
if (mySchema == null)
return new byte[] { };
else
{
BinaryWriter bw = new BinaryWriter(new MemoryStream());
bw.Write(StreamOpCode.create);
bw.Write(GetType().FullName);
bw.Write(myClientDeserializerName);
//the rest of this data has to be serialized.
BinaryWriter compressedBw = new BinaryWriter(new MemoryStream());
mySchema.serialize(compressedBw);
//serialize all the tables
for (int i = 0; i < myLookupTables.Length; ++i)
myLookupTables[i].serializeWholeTable(compressedBw);
compressedBw.Write(myState.Count);
foreach (byte[] row in myState.Values)
compressedBw.Write(row);
//now compress the bytes
MemoryStream compressedStream = new MemoryStream();
SharpZipCompressor Kompressor = new SharpZipCompressor();
compressedBw.BaseStream.Position = 0;
Kompressor.compress(compressedBw.BaseStream, compressedStream);
//append the two streams together
byte[] output = new byte[bw.BaseStream.Length + compressedStream.Length];
bw.BaseStream.Position = 0;
compressedStream.Position = 0;
bw.BaseStream.Read(output, 0, (int) bw.BaseStream.Length);
compressedStream.Read(output, (int) bw.BaseStream.Length, (int) compressedStream.Length);
return output;
}
}
#endregion
private void myDeserializeLookupTableUpdates(BinaryReader br)
{
for (int i = 0; i < myLookupTables.Length; ++i)
myLookupTables[i].deserializeUpdates(br);
}
/// <summary>
/// Every row that has been deserialized passes through this method, so that it can update the state.
/// </summary>
/// <param name="rows"></param>
/// <param name="op"></param>
protected virtual void myEncorporatRows(IDictionary rows, byte op)
{
if (op == StreamOpCode.add || op == StreamOpCode.create)
foreach (DictionaryEntry de in rows)
myState.Add(de.Key, de.Value);
else if (op == StreamOpCode.remove)
foreach (DictionaryEntry de in rows)
myState.Remove(de.Key);
else if (op == StreamOpCode.change || op == StreamOpCode.multipleChange)
foreach (DictionaryEntry de in rows)
myState[de.Key] = de.Value;
}
private IDictionary myGetRows(BinaryReader br, byte op, int noOfRows)
{
//the row deserializer doesn't need to know anything about the lookup tables
myDeserializer = myDeserializer == null ? new PubsubUniversalRowDeserializer(mySchema) : myDeserializer;
Hashtable retVal = new Hashtable();
for (int i = 0; i < noOfRows; i++)
{
int id; object row;
myDeserializer.deserializeRow(myState, br, op, out id, out row);
retVal.Add(id, row);
}
return retVal;
}
}
}
@@ -0,0 +1,211 @@
using System;
using System.Collections;
using System.IO;
using BCG.Utilities;
using System.Collections.Generic;
namespace BCG
{
/// <summary>
/// Helps the LookupTableRowSerializer by serializing one row.
///
/// It does NOT sort the schema, even though the sorted schema doesn't do anything.
/// That is because the schema sorting utility is agnostic of schema type, and so it would destory the grouping information
/// which is VITAL
///
/// It performs a mapping : (row)->byte[]
/// </summary
internal class LookupTableRowSerializer : IBlueRowSerializer
{
private PrimitiveSerializationHelper myPrimitiveSerializationHelper;
private int myFixedSize;
private int[] myNonFixedColIndexes;
private int myIdColumn;
private LookupTableSchema mySchema;
private LookupTable[] myTables;
//this null map is the null map that will be written to the wire
//therefore, its values represent the nulls in row, ordered by the-rearranged schema.
private BitArray myNullMap;
private byte[] myNullMapArray; //just so that a new instance is not created everytime
public LookupTableRowSerializer(LookupTableSchema schema, LookupTable[] theTables)
{
mySchema = schema;
myTables = theTables;
myPrimitiveSerializationHelper = new PrimitiveSerializationHelper(mySchema);
myIdColumn = schema["id"].colNo;
myNullMapArray =
new byte[Convert.ToInt32(Math.Ceiling(Convert.ToDouble(mySchema.columnInfo.Length) / 8))];
myNullMap =
new BitArray(myNullMapArray);
myInitSizeCalculations();
}
//the LookupTableSerializer calls this function on all rows to be serialized,
//before it serializes any of them. It does this to update the lookup tables
//that's becuase it writes the updates to the lookup tables to the byte stream
//before it writes the rows.
public void updateLookupTables(IBlueRow r)
{
for (int groupNo = 1; groupNo < mySchema.lookupGroups.Length; ++groupNo)
{
BlueRowLookupGroup thisGroup = mySchema.lookupGroups[groupNo];
LookupTable thisTable = myTables[groupNo - 1];
thisTable.getIndexForValues(thisGroup.extractGroupFromRow(r));
}
}
#region IBlueRowSerializer methods
/// <summary>
/// Row serialized in the following order
/// row size (nullBitMap size + actual row size)
/// null bit map
/// row id
/// row lookup group ids
/// rest of row values
/// </summary>
/// <param name="r"></param>
/// <param name="bw"></param>
public void serializeRow(IBlueRow r, byte op, BinaryWriter bw)
{
myNullMap.SetAll(false);
int sz = myFixedSize;
//first, build the null map
for (int i = 0; i < mySchema.columnNames.Length; i++)
{
if (r[i] == DBNull.Value || r[i] == null)
{
myNullMap[i] = true;
//if this thing isn't in a lookup group, it's no longer going to be accounted for in the fixed size of the table
//therefore we need to decrement the size of this row by the size of the type
if (mySchema[i].lookupTableGroup == 0)
{
if (SerializationUtilityMethods.isFixedLengthType(mySchema[i].colType))
sz -= SerializationUtilityMethods.getFixedLengthTypeSize(mySchema[i].colType);
}
}
}
//now serialize the null map
myNullMap.CopyTo(myNullMapArray, 0);
int thisRowSize = myGetRowSizeInBytes(sz, r);
bw.Write(thisRowSize);
//tehcnically the size calculatinos are all off by 4 becuase tehy don't account for integer telling how big the row is
long startPos = bw.BaseStream.Position;
bw.Write(myNullMapArray);
//write the ID first, for easy access
bw.Write((int)r[myIdColumn]);
//now write all the value stored in lookup table groups
//we don't do this with the first lookup group becuase it's the default one that isn't stored in lookup tables
for (int groupNo = 1; groupNo < mySchema.lookupGroups.Length; ++groupNo)
{
BlueRowLookupGroup thisGroup = mySchema.lookupGroups[groupNo];
LookupTable thisTable = myTables[groupNo - 1];
int thisLookupID = thisTable.getIndexForValues(thisGroup.extractGroupFromRow(r));
//now, depending on the group size, write this value as either a byte, a short, or an int.
switch (thisGroup.tableSize)
{
case 8:
bw.Write((byte)thisLookupID);
break;
case 16:
bw.Write((short)thisLookupID);
break;
case 32:
bw.Write(thisLookupID);
break;
default:
throw new BlueDataException("Error: invalid size " + thisGroup.tableSize.ToString() + " specified for lookup group.");
}
}
//now write the rest of the individual columns
foreach (ColumnInfo ci in mySchema.columnInfo)
//we have already serialized the id column, as well as all the column groups, and we don't serialize any columns that are null
if ( (!myNullMap[ci.colNo])
&& ci.colNo != myIdColumn
&& ci.lookupTableGroup == 0)
{
myPrimitiveSerializationHelper.serializeColumn(r, ci.colNo, bw);
}
long stopPos = bw.BaseStream.Position;
if (stopPos- startPos != thisRowSize)
throw new BlueDataException("Error: Bad Size Calculation in LookupTableRowSerializer. Expected size was "+thisRowSize.ToString()+", actual size was "+(stopPos-startPos).ToString());
}
public void serializeSchema(BinaryWriter bw)
{
mySchema.serialize(bw);
}
#endregion
#region size calculations
/// <summary>
/// Sets up the fixed length (size in bytes occupied by each of the primitive type)
/// and an index for the non primitive type
/// </summary>
private void myInitSizeCalculations()
{
ArrayList temp = new ArrayList();
myFixedSize = myNullMapArray.Length;
//go through all the columns that aren't in lookup groups, and add up their sizes
foreach (ColumnInfo ci in mySchema.columnInfo)
{
//if you're in a lookup table group, your size is always fixed.
if (ci.lookupTableGroup == 0)
{
if (SerializationUtilityMethods.isFixedLengthType(ci.colType))
myFixedSize += SerializationUtilityMethods.getFixedLengthTypeSize(ci.colType);
else
temp.Add(ci.colNo);
}
}
//now add on the size of the lookup groups
foreach (BlueRowLookupGroup group in mySchema.lookupGroups)
myFixedSize += (group.tableSize / 8);
myNonFixedColIndexes = temp.ToArray(typeof(int)) as int[];
}
/// <summary>
/// Find the size of the serialized row, assumes that nullMap has already
/// been built
/// </summary>
/// <param name="fixedSize"></param>
/// <param name="r"></param>
/// <returns></returns>
private int myGetRowSizeInBytes(int fixedSize, IBlueRow r)
{
foreach (int colNo in myNonFixedColIndexes)
{
if (!myNullMap[colNo])
fixedSize += //myGetStringSizeInBytes (r[colNo] as string);
SerializationUtilityMethods.getObjectSerializedSize(r[colNo]);
}
return fixedSize;
}
#endregion
}
}
@@ -0,0 +1,279 @@
using System;
using System.IO;
using BCG.Utilities;
using System.Collections.Generic;
using System.IO.Compression;
namespace BCG
{
/// <summary>
/// Serializes data stored in all IBlueRowCollections that use a LookupTableSchema.
/// </summary>
public class LookupTableSerializer : IBlueDataSerializer
{
private const string myPubSubDeser = "BCG.LookupTablePubSubDeserializer",
myClientDeser = "BCG.LookupTableClientDeserializer";
private LookupTable[] myLookupTables;
private LookupTableSchema mySchema;
private LookupTableRowSerializer myRowSerializer;
//the header writer writes into a regular stream
private BinaryWriter myHeaderWriter;
//the body writer writes into a compressed binary stream
//that way, we shrink the size of the data that we send over the wire
private BinaryWriter myBodyWriter;
public LookupTableSerializer (IBlueTableSchema inSchema, object[] groups)
{
//get the column infos from the input schema
ColumnInfo[] inputColumns = inSchema.columnInfo;
//build the lookup table groups
//there is one more group than input string because we have the 'default' group, which isn't stored in a table
int numGroups = groups.Length + 1;
BlueRowLookupGroup[] lookupGroups = new BlueRowLookupGroup[numGroups];
//we start the groups with group no 1, becuase groups with 0 are not stored in lookup tables
short groupNo = 1;
Dictionary<string, short> colNameToGroupNo = new Dictionary<string, short>();
foreach (string group in groups)
{
string[] sizeAndColumns = group.Split(';');
if (sizeAndColumns.Length != 2)
throw new ArgumentException("Error, bad Lookup Table Group found: " + group);
short tableSize = short.Parse(sizeAndColumns[0]);
string[] columns = sizeAndColumns[1].Split(',');
BlueRowLookupGroup thisGroup = new BlueRowLookupGroup(groupNo, tableSize, columns);
lookupGroups[groupNo] = thisGroup;
foreach (string column in columns)
colNameToGroupNo[column] = groupNo;
++groupNo;
}
//make the lookup group correpsonding to columns that aren't stored in the lookup table
List<string> nonLookupTableColumns = new List<string>();
foreach (ColumnInfo ci in inputColumns)
{
if (!colNameToGroupNo.ContainsKey(ci.colName))
{
nonLookupTableColumns.Add(ci.colName);
}
}
lookupGroups[0] = new BlueRowLookupGroup(0, 0, nonLookupTableColumns.ToArray());
//now build new column infos to replace the old ones
int numCols = inputColumns.Length;
ColumnInfo[] newColumns = new ColumnInfo[numCols];
for (int col = 0; col < numCols; ++col)
{
ColumnInfo inCol = inputColumns[col];
if (inCol.isConstant)
newColumns[col] = new ColumnInfo(inCol.colName, col, inCol.colType, inCol.colValue);
else
{
string colName = inCol.colName;
if (!colNameToGroupNo.ContainsKey(inCol.colName))
newColumns[col] = new ColumnInfo(colName, col, inCol.colType);
else
newColumns[col] = new ColumnInfo(colName, col, inCol.colType, colNameToGroupNo[colName]);
}
}
//now build the schema
mySchema = new LookupTableSchema(inSchema.tableName, newColumns, lookupGroups);
//build the lookup tables. There is one less than the length of the lookupTableGroups because the first one
//is always the default group which isn't stored in a lookup table.
myLookupTables = new LookupTable[mySchema.lookupGroups.Length - 1];
//start with 1 because we don't store the 0th lookup table
for (int i = 0; i < myLookupTables.Length; ++i)
{
myLookupTables[i] = new LookupTable(mySchema, i+1);
}
//now create the row serializer
myRowSerializer = new LookupTableRowSerializer(mySchema, myLookupTables);
}
#region IBlueDataSerializer Members
/// <summary>
/// Serializes the data related to a single op.
/// Supports All Ops
///
/// First, a LookupTableUpdate, which is contained in each op, looks like this:
///
///
/// -LookupTableUpdate:
/// group 1 values size \
/// group 1 value |- all serialized by a single LookupTableObject
/// group 1 value /
/// ....
/// group 2 values size
/// group 2 value key
/// ....
///
///
/// Next, the stream formats of the different op codes
///
///
/// -create :
/// op
/// clientDeser name
/// pubsubsDeser name
/// schema (which is a LookupTableSchema)
/// LookupTableUpdate
/// num rows
/// row 1
/// row 2
/// ....
///
///
/// - add, remove, change:
/// op
/// LookupTableUpdate
/// the row
///
/// -multipleRemoveAdd :
/// op
/// LookupTableUpdate
/// num deleted rows
/// deleted row 1
/// deleted row 2
/// ....
/// num added rows
/// added row 1
/// added row 2
/// ...
///
/// -multipleChange
/// op
/// LookupTableUpdate
/// num changed rows
/// changd row 1
/// changed row 2
/// ...
/// changd row n
///
/// </summary>
/// <param name="op"></param>
/// <param name="rows"></param>
/// <param name="serializedData"></param>
public void serialize(byte op, BCG.IBlueRowCollection[] rows, out byte[] serializedData)
{
myHeaderWriter = new BinaryWriter(new MemoryStream());
myBodyWriter = new BinaryWriter(new MemoryStream());
//everything start with an op
myHeaderWriter.Write(op);
/*go through each of the rows we're about the serialize, and populate the lookup table
* that way, when we serialize the lookup tables, well have something to report*/
foreach (IBlueRowCollection collection in rows)
foreach (IBlueRow r in collection)
myRowSerializer.updateLookupTables(r);
if (op == StreamOpCode.add || op == StreamOpCode.remove || op == StreamOpCode.change)
mySerializeSingleRow(op, BlueDataUtility.extractRow(rows[0], 0));
else if (op == StreamOpCode.create)
mySerializeCreate(rows[0]);
else if (op == StreamOpCode.multipleChange)
mySerializeMultipleChange(rows[0]);
else if (op == StreamOpCode.multipleRemoveAdd)
mySerializeMultipleRemoveAdd(rows[0], rows[1]);
else
{
serializedData = null;
// BlueEventLog.logAssert(false, String.Format("{0} is not a valid op", op));
}
//copy the data from the header and the body of the message
myHeaderWriter.BaseStream.Position = 0;
myBodyWriter.BaseStream.Position = 0;
int headerLength = (int) myHeaderWriter.BaseStream.Length;
MemoryStream zippedMemStream = new MemoryStream();
SharpZipCompressor Kompressor = new SharpZipCompressor();
Kompressor.compress(myBodyWriter.BaseStream,zippedMemStream);
byte[] compressedBytes = zippedMemStream.ToArray();
serializedData = new byte[headerLength + zippedMemStream.Length];
Console.WriteLine(String.Format("Lookuptable Serializer: Header is {0}. Body compresesd from {1} to {2} bytes.", headerLength , myBodyWriter.BaseStream.Length, zippedMemStream.Length));
myHeaderWriter.BaseStream.Read(serializedData, 0, headerLength);
BinaryWriter sizeWriter = new BinaryWriter(new MemoryStream(serializedData));
zippedMemStream.Position = 0;
zippedMemStream.Read(serializedData, headerLength, (int) zippedMemStream.Length);
}
#endregion
void mySerializeSingleRow(byte op, IBlueRow row)
{
mySerializeLookupTableUpdates(myBodyWriter);
myRowSerializer.serializeRow(row, op, myBodyWriter);
}
private void mySerializeCreate (IBlueRowCollection rows)
{
myHeaderWriter.Write(myPubSubDeser);
myHeaderWriter.Write(myClientDeser);
mySchema.serialize(myBodyWriter);
mySerializeLookupTableUpdates(myBodyWriter);
myBodyWriter.Write(rows.Count);
foreach (IBlueRow r in rows)
myRowSerializer.serializeRow(r, StreamOpCode.create, myBodyWriter);
}
private void mySerializeMultipleChange(IBlueRowCollection rows)
{
mySerializeLookupTableUpdates(myBodyWriter);
myBodyWriter.Write(rows.Count);
foreach (IBlueRow r in rows)
myRowSerializer.serializeRow(r,StreamOpCode.change,myBodyWriter);
}
private void mySerializeMultipleRemoveAdd(IBlueRowCollection deletedRows, IBlueRowCollection addedRows)
{
mySerializeLookupTableUpdates(myBodyWriter);
myBodyWriter.Write(deletedRows.Count);
foreach (IBlueRow r in deletedRows)
myRowSerializer.serializeRow(r, StreamOpCode.change, myBodyWriter);
myBodyWriter.Write(addedRows.Count);
foreach (IBlueRow r in addedRows)
myRowSerializer.serializeRow(r, StreamOpCode.add, myBodyWriter);
}
private void mySerializeLookupTableUpdates(BinaryWriter bw)
{
for (int i = 0; i < myLookupTables.Length; ++i)
myLookupTables[i].serializeUpdates(bw);
}
}
}
@@ -0,0 +1,69 @@
using System;
using System.IO;
namespace BCG
{
public class ClientTheoDeserializer : IClientDeserializer
{
private IBlueTableSchema mySchema = null;
public ClientTheoDeserializer() {}
#region IClientDeserializer Members
/// <summary>
/// Deserialized the streams of bytes, as one operation and the resulting rows. The op
/// is either a create or multipleChange.
/// </summary>
/// <param name="streams"></param>
/// <param name="theOps"></param>
/// <param name="theRows"></param>
public void deserialize (Stream[] streams, out byte[] theOps, out Array theRows)
{
bool isCreate = false;
BinaryReader br = new BinaryReader (UtilityMethods.getAggregatedStream (streams));
byte op = Byte.MaxValue;
IBlueRowCollection rows = null;
while (true)
{
try
{
op = br.ReadByte ();
}
catch (EndOfStreamException)
{
break;
}
if (op == StreamOpCode.create)
{
isCreate = true; //we crush all ops (that may be part of this call) but if theres a create we want that to be the
//only op
//ie, we dont want creates to be crushed, as this might lead to clients
//not detecting creates (not sure if its really worth it)
br.ReadString (); //pubsubDeserializer
br.ReadString (); //clientDeserializer
(mySchema = new BlueTableSchema ()) .deserialze (br);
}
rows = myGetRows (br, br.ReadInt32 ());
}
theOps = new byte[] {isCreate ? StreamOpCode.create : op};
theRows = new IBlueRowCollection[] {rows};
}
private IBlueRowCollection myGetRows (BinaryReader br, int n)
{
IBlueRow[] rows = new IBlueRow[n];
for (int i = 0; i < n; i++)
rows[i] = new BlueRow (mySchema, new object[]{
i,
br.ReadByte (),
br.ReadByte (),
new DateTime (br.ReadInt64 ()),
br.ReadDouble ()
});
return new SequentialIDBlueTable (mySchema, rows);
}
#endregion
}
}
@@ -0,0 +1,69 @@
using System;
using System.IO;
using System.Collections;
namespace BCG
{
public class PubsubTheoDeserializer : IPubsubDeserializer
{
private string myClientDeserializerName;
private int myNRows;
private byte[] myState;
private int mySizeOfRow ;
private IBlueTableSchema mySchema;
public PubsubTheoDeserializer()
{
mySizeOfRow = BlueDataValidTypes.getValueTypeSize (BlueDataValidTypes.LONG) +
BlueDataValidTypes.getValueTypeSize (BlueDataValidTypes.BYTE) +
BlueDataValidTypes.getValueTypeSize (BlueDataValidTypes.DOUBLE) +
BlueDataValidTypes.getValueTypeSize (BlueDataValidTypes.BYTE);
}
#region IPubsubDeserializer Members
public void deserialize (Stream[] streams, out byte[] theOps, out Array theRows)
{
byte op = Byte.MaxValue;
BinaryReader br = new BinaryReader (UtilityMethods.getAggregatedStream (streams));
while (true)
{
try
{
op = br.ReadByte ();
}
catch (EndOfStreamException)
{
break;
}
if (op == StreamOpCode.create)
{
br.ReadString (); //pubsubDeser name
myClientDeserializerName = br.ReadString ();
(mySchema = new BlueTableSchema ()).deserialze (br);
}
myState = br.ReadBytes ((myNRows = br.ReadInt32()) * mySizeOfRow);
}
theOps = new byte[] {op};
theRows = new object[] {myState};
}
public byte[] getState()
{
if (myState == null)
return new byte[] {};
else
{
BinaryWriter bw = new BinaryWriter (new MemoryStream ());
bw.Write (StreamOpCode.create);
bw.Write (GetType().FullName);
bw.Write (myClientDeserializerName);
mySchema.serialize (bw);
bw.Write (myNRows);
bw.Write (myState);
return (bw.BaseStream as MemoryStream).ToArray ();
}
}
#endregion
}
}
@@ -0,0 +1,98 @@
using System;
using System.IO;
using BCG.Utilities;
namespace BCG
{
/// <summary>
/// Serializes the theos, as one table. This is independent of the operation; we transmit
/// the whole state everytime theres a change of any kind. However the operation is also
/// serialized as part of the data; its eaither a create of batchChange
/// </summary>
public class TheoSerializer : IBlueDataSerializer
{
private const string myPubSubDeser = "BCG.PubsubTheoDeserializer",
myClientDeser = "BCG.ClientTheoDeserializer";
public TheoSerializer (IBlueTableSchema schema) {}
public TheoSerializer () {}
#region IBlueDataSerializer Members
/// <summary>
/// Serializes the data related to a single op. The only ops written are either a create
/// or multipleChange
/// -create
/// op
/// clientDeser name
/// pubsubsDeser name
/// schema
/// nRows
/// rows
/// -multipleChange
/// op
/// nRows
/// rows
/// This method extracts the rows accprding to the op, massages the op either to be a create
/// or multipleChange and passes it on to mySerialize
/// </summary>
/// <param name="op"></param>
/// <param name="rows"></param>
/// <param name="serializedData"></param>
public void serialize (byte op, BCG.IBlueRowCollection[] rows, out byte[] serializedData)
{
IBlueRowCollection totalRows = null;
if (op == StreamOpCode.create || op == StreamOpCode.multipleChange)
totalRows = rows[0];
else if (op == StreamOpCode.multipleRemoveAdd)
totalRows = rows[1];
else
// BlueEventLog.logAssert (false, String.Format ("{0} is not a valid op", op));
op = op == StreamOpCode.multipleRemoveAdd ? StreamOpCode.multipleChange : op;
serializedData = mySerialize (op, totalRows);
}
/// <summary>
/// expects a create or multipleChange.
/// </summary>
/// <param name="op"></param>
/// <param name="rows"></param>
/// <returns></returns>
private byte[] mySerialize (byte op, IBlueRowCollection rows)
{
BinaryWriter bw = new BinaryWriter (new MemoryStream ());
bw.Write (op);
if (op == StreamOpCode.create)
{
bw.Write (myPubSubDeser);
bw.Write (myClientDeser);
myReorderSchema (rows.schema).serialize (bw);
}
bw.Write (rows.Count);
foreach (IBlueRow r in rows)
{
bw.Write ((byte)r["arrayIndex"]);
bw.Write ((byte)r["cell"]);
bw.Write ((long)((DateTime)r["expiration"]).Ticks);
bw.Write ((double)r["value"]);
}
bw.BaseStream.Position = 0;
return (bw.BaseStream as MemoryStream).ToArray ();
}
#endregion
public static IBlueTableSchema getSchema()
{return myReorderSchema(new BlueTableSchema("serializedTheos"));}
private static IBlueTableSchema myReorderSchema (IBlueTableSchema schema)
{
return new BlueTableSchema (schema.tableName,
new ColumnInfo ("id", 0, typeof(int)),
new ColumnInfo ("arrayIndex", 1, typeof(byte)),
new ColumnInfo ("cell", 2, typeof(byte)),
new ColumnInfo ("expiration", 3, typeof(DateTime)),
new ColumnInfo ("value", 4, typeof(double)));
}
}
}