From 6946050ada5fd1fb1daff58233ad4dad7bec875a Mon Sep 17 00:00:00 2001 From: lbsa71 Date: Sun, 13 Jan 2008 19:31:56 +0000 Subject: * Added ThirdParty node for external library sources that are shipped with the solution. * Added conceptual TribalMedia.Framework.Data library; this is meant as a generic database layer abstraction library, that should be specialized into OpenSim.Framework.Data * OpenSim.Framework.Data should subclass FieldMappers to extend LLVector3 and LLQuaternions --- .../TribalMedia.Framework.Data/DataReader.cs | 150 +++++++++++++ .../TribalMedia.Framework.Data/DatabaseMapper.cs | 135 +++++++++++ .../TribalMedia.Framework.Data/FieldMapper.cs | 249 +++++++++++++++++++++ .../ObjectTableMapper.cs | 162 ++++++++++++++ .../Properties/AssemblyInfo.cs | 40 ++++ .../TribalMedia.Framework.Data/RowMapper.cs | 85 +++++++ .../TribalMedia.Framework.Data/Schema.cs | 89 ++++++++ .../TribalMedia.Framework.Data/TableMapper.cs | 108 +++++++++ 8 files changed, 1018 insertions(+) create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs new file mode 100644 index 0000000..f0b3e88 --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs @@ -0,0 +1,150 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Data; +using System.IO; + +namespace TribalMedia.Framework.Data +{ + public class DataReader + { + private readonly IDataReader m_source; + + public DataReader(IDataReader source) + { + m_source = source; + } + + public object Get(string name) + { + return m_source[name]; + } + + public ushort GetUShort(string name) + { + return (ushort) m_source.GetInt32(m_source.GetOrdinal(name)); + } + + public byte GetByte(string name) + { + int ordinal = m_source.GetOrdinal(name); + byte value = (byte) m_source.GetInt16(ordinal); + return value; + } + + public sbyte GetSByte(string name) + { + return (sbyte) m_source.GetInt16(m_source.GetOrdinal(name)); + } + + //public Vector3 GetVector(string s) + //{ + // float x = GetFloat(s + "X"); + // float y = GetFloat(s + "Y"); + // float z = GetFloat(s + "Z"); + + // Vector3 vector = new Vector3(x, y, z); + + // return vector; + //} + + //public Quaternion GetQuaternion(string s) + //{ + // float x = GetFloat(s + "X"); + // float y = GetFloat(s + "Y"); + // float z = GetFloat(s + "Z"); + // float w = GetFloat(s + "W"); + + // Quaternion quaternion = new Quaternion(x, y, z, w); + + // return quaternion; + //} + + public float GetFloat(string name) + { + return m_source.GetFloat(m_source.GetOrdinal(name)); + } + + public byte[] GetBytes(string name) + { + int ordinal = m_source.GetOrdinal(name); + + if (m_source.GetValue(ordinal) == DBNull.Value) + { + return null; + } + + byte[] buffer = new byte[16384]; + + MemoryStream memStream = new MemoryStream(); + + long totalRead = 0; + + int bytesRead; + do + { + bytesRead = (int) m_source.GetBytes(ordinal, totalRead, buffer, 0, buffer.Length); + totalRead += bytesRead; + + memStream.Write(buffer, 0, bytesRead); + } while (bytesRead == buffer.Length); + + return memStream.ToArray(); + } + + public string GetString(string name) + { + int ordinal = m_source.GetOrdinal(name); + object value = m_source.GetValue(ordinal); + + if (value is DBNull) + { + return null; + } + + return (string) value; + } + + public bool Read() + { + return m_source.Read(); + } + + internal Guid GetGuid(string name) + { + string guidString = GetString(name); + if (String.IsNullOrEmpty(guidString)) + { + return Guid.Empty; + } + else + { + return new Guid(guidString); + } + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs new file mode 100644 index 0000000..fe31177 --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs @@ -0,0 +1,135 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; + +namespace TribalMedia.Framework.Data +{ + public abstract class DatabaseMapper + { + protected string m_connectionString; + + public DatabaseMapper(string connectionString) + { + m_connectionString = connectionString; + } + + public abstract DbConnection GetNewConnection(); + + public abstract string CreateParamName(string fieldName); + + public DbCommand CreateSelectCommand(TableMapper mapper, DbConnection connection, string fieldName, object key) + { + string table = mapper.TableName; + + DbCommand command = connection.CreateCommand(); + + string conditionString = CreateCondition(mapper, command, fieldName, key); + + string query = + String.Format("select * from {0} where {1}", table, conditionString); + + command.CommandText = query; + command.CommandType = CommandType.Text; + + return command; + } + + public string CreateCondition(TableMapper mapper, DbCommand command, string fieldName, object key) + { + string keyFieldParamName = mapper.CreateParamName(fieldName); + + DbParameter param = command.CreateParameter(); + param.ParameterName = keyFieldParamName; + param.Value = FieldMapper.ConvertToDbType(key); + command.Parameters.Add(param); + + return String.Format("{0}={1}", fieldName, keyFieldParamName); + } + + public DbCommand CreateUpdateCommand(TableMapper mapper, DbConnection connection, object rowMapper, object primaryKey) + { + string table = mapper.TableName; + + List fieldNames = new List(); + + DbCommand command = connection.CreateCommand(); + + foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) + { + if (fieldMapper != mapper.KeyFieldMapper) + { + fieldMapper.ExpandField(rowMapper, command, fieldNames); + } + } + + List assignments = new List(); + + foreach (string field in fieldNames) + { + assignments.Add(String.Format("{0}={1}", field, mapper.CreateParamName(field))); + } + + string conditionString = mapper.CreateCondition(command, mapper.KeyFieldMapper.FieldName, primaryKey); + + command.CommandText = + String.Format("update {0} set {1} where {2}", table, String.Join(", ", assignments.ToArray()), + conditionString); + + return command; + } + + public DbCommand CreateInsertCommand(TableMapper mapper, DbConnection connection, object obj) + { + string table = mapper.TableName; + + List fieldNames = new List(); + + DbCommand command = connection.CreateCommand(); + + foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) + { + fieldMapper.ExpandField(obj, command, fieldNames); + } + + List paramNames = new List(); + + foreach (string field in fieldNames) + { + paramNames.Add(mapper.CreateParamName(field)); + } + + command.CommandText = + String.Format("insert into {0} ({1}) values ({2})", table, String.Join(", ", fieldNames.ToArray()), + String.Join(", ", paramNames.ToArray())); + + return command; + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs new file mode 100644 index 0000000..28a603a --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs @@ -0,0 +1,249 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data.Common; + +namespace TribalMedia.Framework.Data +{ + public delegate TField RowMapperGetAccessor(TRowMapper rowMapper); + + public delegate void RowMapperSetAccessor(TRowMapper rowMapper, TField value); + + public delegate TField ObjectGetAccessor(TObj obj); + + public delegate void ObjectSetAccessor(TObj obj, TField value); + + public abstract class FieldMapper + { + private readonly TableMapper m_tableMapper; + private readonly string m_fieldName; + + public string FieldName + { + get { return m_fieldName; } + } + + protected Type m_valueType; + + public Type ValueType + { + get { return m_valueType; } + } + + public abstract object GetParamValue(object obj); + + public FieldMapper( TableMapper tableMapper, string fieldName, Type valueType) + { + m_fieldName = fieldName; + m_valueType = valueType; + m_tableMapper = tableMapper; + } + + public abstract void SetPropertyFromReader(object mapper, DataReader reader); + + public void RawAddParam(DbCommand command, List fieldNames, string fieldName, object value) + { + string paramName = m_tableMapper.CreateParamName(fieldName); + fieldNames.Add(fieldName); + + DbParameter param = command.CreateParameter(); + param.ParameterName = paramName; + param.Value = value; + + command.Parameters.Add(param); + } + + public void ExpandField(TObj obj, DbCommand command, List fieldNames) + { + string fieldName = FieldName; + object value = GetParamValue(obj); + + //if (ValueType == typeof (Vector3)) + //{ + // Vector3 vector = (Vector3) value; + + // RawAddParam(command, fieldNames, fieldName + "X", vector.X); + // RawAddParam(command, fieldNames, fieldName + "Y", vector.Y); + // RawAddParam(command, fieldNames, fieldName + "Z", vector.Z); + //} + //else if (ValueType == typeof (Quaternion)) + //{ + // Quaternion quaternion = (Quaternion) value; + + // RawAddParam(command, fieldNames, fieldName + "X", quaternion.X); + // RawAddParam(command, fieldNames, fieldName + "Y", quaternion.Y); + // RawAddParam(command, fieldNames, fieldName + "Z", quaternion.Z); + // RawAddParam(command, fieldNames, fieldName + "W", quaternion.W); + //} + //else + //{ + RawAddParam(command, fieldNames, fieldName, ConvertToDbType(value)); + //} + } + + protected object GetValue(DataReader reader) + { + object value; + //if (ValueType == typeof (Vector3)) + //{ + // value = reader.GetVector(m_fieldName); + //} + //else if (ValueType == typeof (Quaternion)) + //{ + // value = reader.GetQuaternion(m_fieldName); + //} + //else + //if (ValueType == typeof(UID)) + //{ + // Guid guid = reader.GetGuid(m_fieldName); + // value = new UID(guid); + //} + //else + if (ValueType == typeof(Guid)) + { + value = reader.GetGuid(m_fieldName); + } + else if (ValueType == typeof (bool)) + { + uint boolVal = reader.GetUShort(m_fieldName); + value = (boolVal == 1); + } + else + if (ValueType == typeof (byte)) + { + value = reader.GetByte(m_fieldName); + } + else if (ValueType == typeof (sbyte)) + { + value = reader.GetSByte(m_fieldName); + } + else if (ValueType == typeof (ushort)) + { + value = reader.GetUShort(m_fieldName); + } + else if (ValueType == typeof (byte[])) + { + value = reader.GetBytes(m_fieldName); + } + else + { + value = reader.Get(m_fieldName); + } + + if (value is DBNull) + { + value = default(ValueType); + } + + return value; + } + + public static object ConvertToDbType(object value) + { + //if (value is UID) + //{ + // return (value as UID).UUID.ToString(); + //} + + return value; + } + } + + public class RowMapperField : FieldMapper + where TRowMapper : RowMapper + { + private readonly RowMapperGetAccessor m_fieldGetAccessor; + private readonly RowMapperSetAccessor m_fieldSetAccessor; + + public override object GetParamValue(object obj) + { + return m_fieldGetAccessor((TRowMapper) obj); + } + + public override void SetPropertyFromReader(object mapper, DataReader reader) + { + object value; + + value = GetValue(reader); + + if (value == null) + { + m_fieldSetAccessor((TRowMapper) mapper, default(TField)); + } + else + { + m_fieldSetAccessor((TRowMapper) mapper, (TField) value); + } + } + + + public RowMapperField(TableMapper tableMapper, string fieldName, RowMapperGetAccessor rowMapperGetAccessor, + RowMapperSetAccessor rowMapperSetAccessor) + : base(tableMapper, fieldName, typeof(TField)) + { + m_fieldGetAccessor = rowMapperGetAccessor; + m_fieldSetAccessor = rowMapperSetAccessor; + } + } + + public class ObjectField : FieldMapper + { + private readonly ObjectGetAccessor m_fieldGetAccessor; + private readonly ObjectSetAccessor m_fieldSetAccessor; + + public override object GetParamValue(object obj) + { + return m_fieldGetAccessor((TObject) obj); + } + + public override void SetPropertyFromReader(object obj, DataReader reader) + { + object value; + + value = GetValue(reader); + + if (value == null) + { + m_fieldSetAccessor((TObject) obj, default(TField)); + } + else + { + m_fieldSetAccessor((TObject) obj, (TField) value); + } + } + + + public ObjectField(TableMapper tableMapper, string fieldName, ObjectGetAccessor rowMapperGetAccessor, + ObjectSetAccessor rowMapperSetAccessor) + : base(tableMapper, fieldName, typeof (TField)) + { + m_fieldGetAccessor = rowMapperGetAccessor; + m_fieldSetAccessor = rowMapperSetAccessor; + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs new file mode 100644 index 0000000..631a2ca --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs @@ -0,0 +1,162 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class ObjectTableMapper : TableMapper + { + public ObjectTableMapper(DatabaseMapper connectionPool, string tableName) + : base(connectionPool, tableName) + { + } + + public bool TryGetValue(TPrimaryKey primaryKey, out TRowMapper value) + { + TRowMapper result = default(TRowMapper); + bool success = false; + + WithConnection(delegate(DbConnection connection) + { + using ( + DbCommand command = + CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) + { + using (IDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + result = FromReader(new DataReader(reader)); + success = true; + } + else + { + success = false; + } + } + } + }); + + value = result; + + return success; + } + + + public virtual bool Remove(TPrimaryKey id) + { + int deleted = 0; + + WithConnection(delegate(DbConnection connection) + { + using ( + DbCommand command = + CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) + { + deleted = command.ExecuteNonQuery(); + } + }); + + if (deleted == 1) + { + return true; + } + else + { + return false; + } + } + + + public DbCommand CreateDeleteCommand(DbConnection connection, string fieldName, TPrimaryKey primaryKey) + { + string table = TableName; + + DbCommand command = connection.CreateCommand(); + + string conditionString = CreateCondition(command, fieldName, primaryKey); + + string query = + String.Format("delete from {0} where {1}", table, conditionString); + + command.CommandText = query; + command.CommandType = CommandType.Text; + + return command; + } + + public virtual bool Update(TPrimaryKey primaryKey, TRowMapper value) + { + int updated = 0; + + WithConnection(delegate(DbConnection connection) + { + using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) + { + updated = command.ExecuteNonQuery(); + } + }); + + if (updated == 1) + { + return true; + } + else + { + return false; + } + } + + public virtual bool Add(TRowMapper value) + { + int added = 0; + + WithConnection(delegate(DbConnection connection) + { + using (DbCommand command = CreateInsertCommand(connection, value)) + { + added = command.ExecuteNonQuery(); + } + }); + + if (added == 1) + { + return true; + } + else + { + return false; + } + } + + public abstract TRowMapper FromReader(DataReader reader); + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs new file mode 100644 index 0000000..4a073e9 --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs @@ -0,0 +1,40 @@ +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly : AssemblyTitle("TribalMedia.Framework.Data")] +[assembly : AssemblyDescription("Generic Database Abstraction Layer")] +[assembly : AssemblyConfiguration("")] +[assembly : AssemblyCompany("TribalMedia")] +[assembly : AssemblyProduct("TribalMedia.Framework.Data")] +[assembly: AssemblyCopyright("Copyright © 2007 Tribal Media")] +[assembly : AssemblyTrademark("")] +[assembly : AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly : ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly : Guid("9269f421-19d9-4eea-bfe3-c0ffe426fada")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly : AssemblyVersion("1.0.0.0")] +[assembly : AssemblyFileVersion("1.0.0.0")] +[assembly : AllowPartiallyTrustedCallers] \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs new file mode 100644 index 0000000..aa22c8b --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs @@ -0,0 +1,85 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class RowMapper + { + public abstract void FillObject(DataReader reader); + } + + public class ObjectMapper : RowMapper + { + private readonly Schema m_schema; + private readonly TObj m_obj; + + public TObj Object + { + get { return m_obj; } + } + + public ObjectMapper(Schema schema, TObj obj) + { + m_schema = schema; + m_obj = obj; + } + + public override void FillObject(DataReader reader) + { + foreach (FieldMapper fieldMapper in m_schema.Fields.Values) + { + fieldMapper.SetPropertyFromReader(m_obj, reader); + } + } + } + + public class RowMapper : RowMapper + { + private readonly Schema m_schema; + private readonly TObj m_obj; + + public TObj Object + { + get { return m_obj; } + } + + public RowMapper(Schema schema, TObj obj) + { + m_schema = schema; + m_obj = obj; + } + + public override void FillObject(DataReader reader) + { + foreach (FieldMapper fieldMapper in m_schema.Fields.Values) + { + fieldMapper.SetPropertyFromReader(this, reader); + } + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs new file mode 100644 index 0000000..b7b8939 --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs @@ -0,0 +1,89 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System.Collections.Generic; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public class Schema + { + protected TableMapper m_tableMapper; + protected Dictionary m_mappings; + + public Dictionary Fields + { + get { return m_mappings; } + } + + public Schema(TableMapper tableMapper) + { + m_mappings = new Dictionary(); + m_tableMapper = tableMapper; + } + } + + public class ObjectSchema : Schema + { + public ObjectSchema(TableMapper tableMapper) : base(tableMapper) + { + } + + public ObjectField AddMapping(string fieldName, + ObjectGetAccessor rowMapperGetAccessor, + ObjectSetAccessor rowMapperSetAccessor) + { + ObjectField rowMapperField = + new ObjectField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); + + m_mappings.Add(fieldName, rowMapperField); + + return rowMapperField; + } + } + + public class RowMapperSchema : Schema + where TRowMapper : RowMapper + { + public RowMapperSchema(TableMapper tableMapper) : base(tableMapper) + { + } + + public RowMapperField AddMapping(string fieldName, + RowMapperGetAccessor + rowMapperGetAccessor, + RowMapperSetAccessor + rowMapperSetAccessor) + { + RowMapperField rowMapperField = + new RowMapperField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); + + m_mappings.Add(fieldName, rowMapperField); + + return rowMapperField; + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs new file mode 100644 index 0000000..f041e79 --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs @@ -0,0 +1,108 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Data; +using System.Data.Common; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class TableMapper + { + private readonly DatabaseMapper m_connectionPool; + private readonly object m_syncRoot = new object(); + + protected void WithConnection(Action action) + { + lock (m_syncRoot) + { + DbConnection m_connection = m_connectionPool.GetNewConnection(); + + if (m_connection.State != ConnectionState.Open) + { + m_connection.Open(); + } + + action(m_connection); + + if (m_connection.State == ConnectionState.Open) + { + m_connection.Close(); + } + } + } + + private readonly string m_tableName; + public string TableName + { + get { return m_tableName; } + } + + private Schema m_schema; + public Schema Schema + { + get { return m_schema; } + } + + private FieldMapper m_keyFieldMapper; + public FieldMapper KeyFieldMapper + { + get { return m_keyFieldMapper; } + } + + public TableMapper(DatabaseMapper connectionPool, string tableName) + { + m_connectionPool = connectionPool; + m_tableName = tableName.ToLower(); // Stupid MySQL hack. + } + + public string CreateParamName(string fieldName) + { + return m_connectionPool.CreateParamName(fieldName); + } + + protected DbCommand CreateSelectCommand(DbConnection connection, string fieldName, object primaryKey) + { + return m_connectionPool.CreateSelectCommand(this, connection, fieldName, primaryKey); + } + + public string CreateCondition(DbCommand command, string fieldName, object key) + { + return m_connectionPool.CreateCondition(this, command, fieldName, key); + } + + public DbCommand CreateInsertCommand(DbConnection connection, object obj) + { + return m_connectionPool.CreateInsertCommand(this, connection, obj); + } + + public DbCommand CreateUpdateCommand(DbConnection connection, object rowMapper, object primaryKey) + { + return m_connectionPool.CreateUpdateCommand(this, connection, rowMapper, primaryKey); + } + } +} \ No newline at end of file -- cgit v1.1 From 6716668187675d5950d2b3a7a925da7327440ca1 Mon Sep 17 00:00:00 2001 From: Jeff Ames Date: Mon, 14 Jan 2008 16:47:36 +0000 Subject: Set svn:eol-style. --- .../TribalMedia.Framework.Data/DataReader.cs | 298 ++++++------- .../TribalMedia.Framework.Data/DatabaseMapper.cs | 268 +++++------ .../TribalMedia.Framework.Data/FieldMapper.cs | 496 ++++++++++----------- .../ObjectTableMapper.cs | 322 ++++++------- .../Properties/AssemblyInfo.cs | 78 ++-- .../TribalMedia.Framework.Data/RowMapper.cs | 168 +++---- .../TribalMedia.Framework.Data/Schema.cs | 176 ++++---- .../TribalMedia.Framework.Data/TableMapper.cs | 214 ++++----- 8 files changed, 1010 insertions(+), 1010 deletions(-) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs index f0b3e88..6f84d43 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs @@ -1,150 +1,150 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Data; -using System.IO; - -namespace TribalMedia.Framework.Data -{ - public class DataReader - { - private readonly IDataReader m_source; - - public DataReader(IDataReader source) - { - m_source = source; - } - - public object Get(string name) - { - return m_source[name]; - } - - public ushort GetUShort(string name) - { - return (ushort) m_source.GetInt32(m_source.GetOrdinal(name)); - } - - public byte GetByte(string name) - { - int ordinal = m_source.GetOrdinal(name); - byte value = (byte) m_source.GetInt16(ordinal); - return value; - } - - public sbyte GetSByte(string name) - { - return (sbyte) m_source.GetInt16(m_source.GetOrdinal(name)); - } - - //public Vector3 GetVector(string s) - //{ - // float x = GetFloat(s + "X"); - // float y = GetFloat(s + "Y"); - // float z = GetFloat(s + "Z"); - - // Vector3 vector = new Vector3(x, y, z); - - // return vector; - //} - - //public Quaternion GetQuaternion(string s) - //{ - // float x = GetFloat(s + "X"); - // float y = GetFloat(s + "Y"); - // float z = GetFloat(s + "Z"); - // float w = GetFloat(s + "W"); - - // Quaternion quaternion = new Quaternion(x, y, z, w); - - // return quaternion; - //} - - public float GetFloat(string name) - { - return m_source.GetFloat(m_source.GetOrdinal(name)); - } - - public byte[] GetBytes(string name) - { - int ordinal = m_source.GetOrdinal(name); - - if (m_source.GetValue(ordinal) == DBNull.Value) - { - return null; - } - - byte[] buffer = new byte[16384]; - - MemoryStream memStream = new MemoryStream(); - - long totalRead = 0; - - int bytesRead; - do - { - bytesRead = (int) m_source.GetBytes(ordinal, totalRead, buffer, 0, buffer.Length); - totalRead += bytesRead; - - memStream.Write(buffer, 0, bytesRead); - } while (bytesRead == buffer.Length); - - return memStream.ToArray(); - } - - public string GetString(string name) - { - int ordinal = m_source.GetOrdinal(name); - object value = m_source.GetValue(ordinal); - - if (value is DBNull) - { - return null; - } - - return (string) value; - } - - public bool Read() - { - return m_source.Read(); - } - - internal Guid GetGuid(string name) - { - string guidString = GetString(name); - if (String.IsNullOrEmpty(guidString)) - { - return Guid.Empty; - } - else - { - return new Guid(guidString); - } - } - } +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Data; +using System.IO; + +namespace TribalMedia.Framework.Data +{ + public class DataReader + { + private readonly IDataReader m_source; + + public DataReader(IDataReader source) + { + m_source = source; + } + + public object Get(string name) + { + return m_source[name]; + } + + public ushort GetUShort(string name) + { + return (ushort) m_source.GetInt32(m_source.GetOrdinal(name)); + } + + public byte GetByte(string name) + { + int ordinal = m_source.GetOrdinal(name); + byte value = (byte) m_source.GetInt16(ordinal); + return value; + } + + public sbyte GetSByte(string name) + { + return (sbyte) m_source.GetInt16(m_source.GetOrdinal(name)); + } + + //public Vector3 GetVector(string s) + //{ + // float x = GetFloat(s + "X"); + // float y = GetFloat(s + "Y"); + // float z = GetFloat(s + "Z"); + + // Vector3 vector = new Vector3(x, y, z); + + // return vector; + //} + + //public Quaternion GetQuaternion(string s) + //{ + // float x = GetFloat(s + "X"); + // float y = GetFloat(s + "Y"); + // float z = GetFloat(s + "Z"); + // float w = GetFloat(s + "W"); + + // Quaternion quaternion = new Quaternion(x, y, z, w); + + // return quaternion; + //} + + public float GetFloat(string name) + { + return m_source.GetFloat(m_source.GetOrdinal(name)); + } + + public byte[] GetBytes(string name) + { + int ordinal = m_source.GetOrdinal(name); + + if (m_source.GetValue(ordinal) == DBNull.Value) + { + return null; + } + + byte[] buffer = new byte[16384]; + + MemoryStream memStream = new MemoryStream(); + + long totalRead = 0; + + int bytesRead; + do + { + bytesRead = (int) m_source.GetBytes(ordinal, totalRead, buffer, 0, buffer.Length); + totalRead += bytesRead; + + memStream.Write(buffer, 0, bytesRead); + } while (bytesRead == buffer.Length); + + return memStream.ToArray(); + } + + public string GetString(string name) + { + int ordinal = m_source.GetOrdinal(name); + object value = m_source.GetValue(ordinal); + + if (value is DBNull) + { + return null; + } + + return (string) value; + } + + public bool Read() + { + return m_source.Read(); + } + + internal Guid GetGuid(string name) + { + string guidString = GetString(name); + if (String.IsNullOrEmpty(guidString)) + { + return Guid.Empty; + } + else + { + return new Guid(guidString); + } + } + } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs index fe31177..0b9d16d 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs @@ -1,135 +1,135 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; - -namespace TribalMedia.Framework.Data -{ - public abstract class DatabaseMapper - { - protected string m_connectionString; - - public DatabaseMapper(string connectionString) - { - m_connectionString = connectionString; - } - - public abstract DbConnection GetNewConnection(); - - public abstract string CreateParamName(string fieldName); - - public DbCommand CreateSelectCommand(TableMapper mapper, DbConnection connection, string fieldName, object key) - { - string table = mapper.TableName; - - DbCommand command = connection.CreateCommand(); - - string conditionString = CreateCondition(mapper, command, fieldName, key); - - string query = - String.Format("select * from {0} where {1}", table, conditionString); - - command.CommandText = query; - command.CommandType = CommandType.Text; - - return command; - } - - public string CreateCondition(TableMapper mapper, DbCommand command, string fieldName, object key) - { - string keyFieldParamName = mapper.CreateParamName(fieldName); - - DbParameter param = command.CreateParameter(); - param.ParameterName = keyFieldParamName; - param.Value = FieldMapper.ConvertToDbType(key); - command.Parameters.Add(param); - - return String.Format("{0}={1}", fieldName, keyFieldParamName); - } - - public DbCommand CreateUpdateCommand(TableMapper mapper, DbConnection connection, object rowMapper, object primaryKey) - { - string table = mapper.TableName; - - List fieldNames = new List(); - - DbCommand command = connection.CreateCommand(); - - foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) - { - if (fieldMapper != mapper.KeyFieldMapper) - { - fieldMapper.ExpandField(rowMapper, command, fieldNames); - } - } - - List assignments = new List(); - - foreach (string field in fieldNames) - { - assignments.Add(String.Format("{0}={1}", field, mapper.CreateParamName(field))); - } - - string conditionString = mapper.CreateCondition(command, mapper.KeyFieldMapper.FieldName, primaryKey); - - command.CommandText = - String.Format("update {0} set {1} where {2}", table, String.Join(", ", assignments.ToArray()), - conditionString); - - return command; - } - - public DbCommand CreateInsertCommand(TableMapper mapper, DbConnection connection, object obj) - { - string table = mapper.TableName; - - List fieldNames = new List(); - - DbCommand command = connection.CreateCommand(); - - foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) - { - fieldMapper.ExpandField(obj, command, fieldNames); - } - - List paramNames = new List(); - - foreach (string field in fieldNames) - { - paramNames.Add(mapper.CreateParamName(field)); - } - - command.CommandText = - String.Format("insert into {0} ({1}) values ({2})", table, String.Join(", ", fieldNames.ToArray()), - String.Join(", ", paramNames.ToArray())); - - return command; - } - } +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; + +namespace TribalMedia.Framework.Data +{ + public abstract class DatabaseMapper + { + protected string m_connectionString; + + public DatabaseMapper(string connectionString) + { + m_connectionString = connectionString; + } + + public abstract DbConnection GetNewConnection(); + + public abstract string CreateParamName(string fieldName); + + public DbCommand CreateSelectCommand(TableMapper mapper, DbConnection connection, string fieldName, object key) + { + string table = mapper.TableName; + + DbCommand command = connection.CreateCommand(); + + string conditionString = CreateCondition(mapper, command, fieldName, key); + + string query = + String.Format("select * from {0} where {1}", table, conditionString); + + command.CommandText = query; + command.CommandType = CommandType.Text; + + return command; + } + + public string CreateCondition(TableMapper mapper, DbCommand command, string fieldName, object key) + { + string keyFieldParamName = mapper.CreateParamName(fieldName); + + DbParameter param = command.CreateParameter(); + param.ParameterName = keyFieldParamName; + param.Value = FieldMapper.ConvertToDbType(key); + command.Parameters.Add(param); + + return String.Format("{0}={1}", fieldName, keyFieldParamName); + } + + public DbCommand CreateUpdateCommand(TableMapper mapper, DbConnection connection, object rowMapper, object primaryKey) + { + string table = mapper.TableName; + + List fieldNames = new List(); + + DbCommand command = connection.CreateCommand(); + + foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) + { + if (fieldMapper != mapper.KeyFieldMapper) + { + fieldMapper.ExpandField(rowMapper, command, fieldNames); + } + } + + List assignments = new List(); + + foreach (string field in fieldNames) + { + assignments.Add(String.Format("{0}={1}", field, mapper.CreateParamName(field))); + } + + string conditionString = mapper.CreateCondition(command, mapper.KeyFieldMapper.FieldName, primaryKey); + + command.CommandText = + String.Format("update {0} set {1} where {2}", table, String.Join(", ", assignments.ToArray()), + conditionString); + + return command; + } + + public DbCommand CreateInsertCommand(TableMapper mapper, DbConnection connection, object obj) + { + string table = mapper.TableName; + + List fieldNames = new List(); + + DbCommand command = connection.CreateCommand(); + + foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) + { + fieldMapper.ExpandField(obj, command, fieldNames); + } + + List paramNames = new List(); + + foreach (string field in fieldNames) + { + paramNames.Add(mapper.CreateParamName(field)); + } + + command.CommandText = + String.Format("insert into {0} ({1}) values ({2})", table, String.Join(", ", fieldNames.ToArray()), + String.Join(", ", paramNames.ToArray())); + + return command; + } + } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs index 28a603a..a1fafbe 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs @@ -1,249 +1,249 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Collections.Generic; -using System.Data.Common; - -namespace TribalMedia.Framework.Data -{ - public delegate TField RowMapperGetAccessor(TRowMapper rowMapper); - - public delegate void RowMapperSetAccessor(TRowMapper rowMapper, TField value); - - public delegate TField ObjectGetAccessor(TObj obj); - - public delegate void ObjectSetAccessor(TObj obj, TField value); - - public abstract class FieldMapper - { - private readonly TableMapper m_tableMapper; - private readonly string m_fieldName; - - public string FieldName - { - get { return m_fieldName; } - } - - protected Type m_valueType; - - public Type ValueType - { - get { return m_valueType; } - } - - public abstract object GetParamValue(object obj); - - public FieldMapper( TableMapper tableMapper, string fieldName, Type valueType) - { - m_fieldName = fieldName; - m_valueType = valueType; - m_tableMapper = tableMapper; - } - - public abstract void SetPropertyFromReader(object mapper, DataReader reader); - - public void RawAddParam(DbCommand command, List fieldNames, string fieldName, object value) - { - string paramName = m_tableMapper.CreateParamName(fieldName); - fieldNames.Add(fieldName); - - DbParameter param = command.CreateParameter(); - param.ParameterName = paramName; - param.Value = value; - - command.Parameters.Add(param); - } - - public void ExpandField(TObj obj, DbCommand command, List fieldNames) - { - string fieldName = FieldName; - object value = GetParamValue(obj); - - //if (ValueType == typeof (Vector3)) - //{ - // Vector3 vector = (Vector3) value; - - // RawAddParam(command, fieldNames, fieldName + "X", vector.X); - // RawAddParam(command, fieldNames, fieldName + "Y", vector.Y); - // RawAddParam(command, fieldNames, fieldName + "Z", vector.Z); - //} - //else if (ValueType == typeof (Quaternion)) - //{ - // Quaternion quaternion = (Quaternion) value; - - // RawAddParam(command, fieldNames, fieldName + "X", quaternion.X); - // RawAddParam(command, fieldNames, fieldName + "Y", quaternion.Y); - // RawAddParam(command, fieldNames, fieldName + "Z", quaternion.Z); - // RawAddParam(command, fieldNames, fieldName + "W", quaternion.W); - //} - //else - //{ - RawAddParam(command, fieldNames, fieldName, ConvertToDbType(value)); - //} - } - - protected object GetValue(DataReader reader) - { - object value; - //if (ValueType == typeof (Vector3)) - //{ - // value = reader.GetVector(m_fieldName); - //} - //else if (ValueType == typeof (Quaternion)) - //{ - // value = reader.GetQuaternion(m_fieldName); - //} - //else - //if (ValueType == typeof(UID)) - //{ - // Guid guid = reader.GetGuid(m_fieldName); - // value = new UID(guid); - //} - //else - if (ValueType == typeof(Guid)) - { - value = reader.GetGuid(m_fieldName); - } - else if (ValueType == typeof (bool)) - { - uint boolVal = reader.GetUShort(m_fieldName); - value = (boolVal == 1); - } - else - if (ValueType == typeof (byte)) - { - value = reader.GetByte(m_fieldName); - } - else if (ValueType == typeof (sbyte)) - { - value = reader.GetSByte(m_fieldName); - } - else if (ValueType == typeof (ushort)) - { - value = reader.GetUShort(m_fieldName); - } - else if (ValueType == typeof (byte[])) - { - value = reader.GetBytes(m_fieldName); - } - else - { - value = reader.Get(m_fieldName); - } - - if (value is DBNull) - { - value = default(ValueType); - } - - return value; - } - - public static object ConvertToDbType(object value) - { - //if (value is UID) - //{ - // return (value as UID).UUID.ToString(); - //} - - return value; - } - } - - public class RowMapperField : FieldMapper - where TRowMapper : RowMapper - { - private readonly RowMapperGetAccessor m_fieldGetAccessor; - private readonly RowMapperSetAccessor m_fieldSetAccessor; - - public override object GetParamValue(object obj) - { - return m_fieldGetAccessor((TRowMapper) obj); - } - - public override void SetPropertyFromReader(object mapper, DataReader reader) - { - object value; - - value = GetValue(reader); - - if (value == null) - { - m_fieldSetAccessor((TRowMapper) mapper, default(TField)); - } - else - { - m_fieldSetAccessor((TRowMapper) mapper, (TField) value); - } - } - - - public RowMapperField(TableMapper tableMapper, string fieldName, RowMapperGetAccessor rowMapperGetAccessor, - RowMapperSetAccessor rowMapperSetAccessor) - : base(tableMapper, fieldName, typeof(TField)) - { - m_fieldGetAccessor = rowMapperGetAccessor; - m_fieldSetAccessor = rowMapperSetAccessor; - } - } - - public class ObjectField : FieldMapper - { - private readonly ObjectGetAccessor m_fieldGetAccessor; - private readonly ObjectSetAccessor m_fieldSetAccessor; - - public override object GetParamValue(object obj) - { - return m_fieldGetAccessor((TObject) obj); - } - - public override void SetPropertyFromReader(object obj, DataReader reader) - { - object value; - - value = GetValue(reader); - - if (value == null) - { - m_fieldSetAccessor((TObject) obj, default(TField)); - } - else - { - m_fieldSetAccessor((TObject) obj, (TField) value); - } - } - - - public ObjectField(TableMapper tableMapper, string fieldName, ObjectGetAccessor rowMapperGetAccessor, - ObjectSetAccessor rowMapperSetAccessor) - : base(tableMapper, fieldName, typeof (TField)) - { - m_fieldGetAccessor = rowMapperGetAccessor; - m_fieldSetAccessor = rowMapperSetAccessor; - } - } +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data.Common; + +namespace TribalMedia.Framework.Data +{ + public delegate TField RowMapperGetAccessor(TRowMapper rowMapper); + + public delegate void RowMapperSetAccessor(TRowMapper rowMapper, TField value); + + public delegate TField ObjectGetAccessor(TObj obj); + + public delegate void ObjectSetAccessor(TObj obj, TField value); + + public abstract class FieldMapper + { + private readonly TableMapper m_tableMapper; + private readonly string m_fieldName; + + public string FieldName + { + get { return m_fieldName; } + } + + protected Type m_valueType; + + public Type ValueType + { + get { return m_valueType; } + } + + public abstract object GetParamValue(object obj); + + public FieldMapper( TableMapper tableMapper, string fieldName, Type valueType) + { + m_fieldName = fieldName; + m_valueType = valueType; + m_tableMapper = tableMapper; + } + + public abstract void SetPropertyFromReader(object mapper, DataReader reader); + + public void RawAddParam(DbCommand command, List fieldNames, string fieldName, object value) + { + string paramName = m_tableMapper.CreateParamName(fieldName); + fieldNames.Add(fieldName); + + DbParameter param = command.CreateParameter(); + param.ParameterName = paramName; + param.Value = value; + + command.Parameters.Add(param); + } + + public void ExpandField(TObj obj, DbCommand command, List fieldNames) + { + string fieldName = FieldName; + object value = GetParamValue(obj); + + //if (ValueType == typeof (Vector3)) + //{ + // Vector3 vector = (Vector3) value; + + // RawAddParam(command, fieldNames, fieldName + "X", vector.X); + // RawAddParam(command, fieldNames, fieldName + "Y", vector.Y); + // RawAddParam(command, fieldNames, fieldName + "Z", vector.Z); + //} + //else if (ValueType == typeof (Quaternion)) + //{ + // Quaternion quaternion = (Quaternion) value; + + // RawAddParam(command, fieldNames, fieldName + "X", quaternion.X); + // RawAddParam(command, fieldNames, fieldName + "Y", quaternion.Y); + // RawAddParam(command, fieldNames, fieldName + "Z", quaternion.Z); + // RawAddParam(command, fieldNames, fieldName + "W", quaternion.W); + //} + //else + //{ + RawAddParam(command, fieldNames, fieldName, ConvertToDbType(value)); + //} + } + + protected object GetValue(DataReader reader) + { + object value; + //if (ValueType == typeof (Vector3)) + //{ + // value = reader.GetVector(m_fieldName); + //} + //else if (ValueType == typeof (Quaternion)) + //{ + // value = reader.GetQuaternion(m_fieldName); + //} + //else + //if (ValueType == typeof(UID)) + //{ + // Guid guid = reader.GetGuid(m_fieldName); + // value = new UID(guid); + //} + //else + if (ValueType == typeof(Guid)) + { + value = reader.GetGuid(m_fieldName); + } + else if (ValueType == typeof (bool)) + { + uint boolVal = reader.GetUShort(m_fieldName); + value = (boolVal == 1); + } + else + if (ValueType == typeof (byte)) + { + value = reader.GetByte(m_fieldName); + } + else if (ValueType == typeof (sbyte)) + { + value = reader.GetSByte(m_fieldName); + } + else if (ValueType == typeof (ushort)) + { + value = reader.GetUShort(m_fieldName); + } + else if (ValueType == typeof (byte[])) + { + value = reader.GetBytes(m_fieldName); + } + else + { + value = reader.Get(m_fieldName); + } + + if (value is DBNull) + { + value = default(ValueType); + } + + return value; + } + + public static object ConvertToDbType(object value) + { + //if (value is UID) + //{ + // return (value as UID).UUID.ToString(); + //} + + return value; + } + } + + public class RowMapperField : FieldMapper + where TRowMapper : RowMapper + { + private readonly RowMapperGetAccessor m_fieldGetAccessor; + private readonly RowMapperSetAccessor m_fieldSetAccessor; + + public override object GetParamValue(object obj) + { + return m_fieldGetAccessor((TRowMapper) obj); + } + + public override void SetPropertyFromReader(object mapper, DataReader reader) + { + object value; + + value = GetValue(reader); + + if (value == null) + { + m_fieldSetAccessor((TRowMapper) mapper, default(TField)); + } + else + { + m_fieldSetAccessor((TRowMapper) mapper, (TField) value); + } + } + + + public RowMapperField(TableMapper tableMapper, string fieldName, RowMapperGetAccessor rowMapperGetAccessor, + RowMapperSetAccessor rowMapperSetAccessor) + : base(tableMapper, fieldName, typeof(TField)) + { + m_fieldGetAccessor = rowMapperGetAccessor; + m_fieldSetAccessor = rowMapperSetAccessor; + } + } + + public class ObjectField : FieldMapper + { + private readonly ObjectGetAccessor m_fieldGetAccessor; + private readonly ObjectSetAccessor m_fieldSetAccessor; + + public override object GetParamValue(object obj) + { + return m_fieldGetAccessor((TObject) obj); + } + + public override void SetPropertyFromReader(object obj, DataReader reader) + { + object value; + + value = GetValue(reader); + + if (value == null) + { + m_fieldSetAccessor((TObject) obj, default(TField)); + } + else + { + m_fieldSetAccessor((TObject) obj, (TField) value); + } + } + + + public ObjectField(TableMapper tableMapper, string fieldName, ObjectGetAccessor rowMapperGetAccessor, + ObjectSetAccessor rowMapperSetAccessor) + : base(tableMapper, fieldName, typeof (TField)) + { + m_fieldGetAccessor = rowMapperGetAccessor; + m_fieldSetAccessor = rowMapperSetAccessor; + } + } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs index 631a2ca..44a6542 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs @@ -1,162 +1,162 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public abstract class ObjectTableMapper : TableMapper - { - public ObjectTableMapper(DatabaseMapper connectionPool, string tableName) - : base(connectionPool, tableName) - { - } - - public bool TryGetValue(TPrimaryKey primaryKey, out TRowMapper value) - { - TRowMapper result = default(TRowMapper); - bool success = false; - - WithConnection(delegate(DbConnection connection) - { - using ( - DbCommand command = - CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) - { - using (IDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - result = FromReader(new DataReader(reader)); - success = true; - } - else - { - success = false; - } - } - } - }); - - value = result; - - return success; - } - - - public virtual bool Remove(TPrimaryKey id) - { - int deleted = 0; - - WithConnection(delegate(DbConnection connection) - { - using ( - DbCommand command = - CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) - { - deleted = command.ExecuteNonQuery(); - } - }); - - if (deleted == 1) - { - return true; - } - else - { - return false; - } - } - - - public DbCommand CreateDeleteCommand(DbConnection connection, string fieldName, TPrimaryKey primaryKey) - { - string table = TableName; - - DbCommand command = connection.CreateCommand(); - - string conditionString = CreateCondition(command, fieldName, primaryKey); - - string query = - String.Format("delete from {0} where {1}", table, conditionString); - - command.CommandText = query; - command.CommandType = CommandType.Text; - - return command; - } - - public virtual bool Update(TPrimaryKey primaryKey, TRowMapper value) - { - int updated = 0; - - WithConnection(delegate(DbConnection connection) - { - using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) - { - updated = command.ExecuteNonQuery(); - } - }); - - if (updated == 1) - { - return true; - } - else - { - return false; - } - } - - public virtual bool Add(TRowMapper value) - { - int added = 0; - - WithConnection(delegate(DbConnection connection) - { - using (DbCommand command = CreateInsertCommand(connection, value)) - { - added = command.ExecuteNonQuery(); - } - }); - - if (added == 1) - { - return true; - } - else - { - return false; - } - } - - public abstract TRowMapper FromReader(DataReader reader); - } +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class ObjectTableMapper : TableMapper + { + public ObjectTableMapper(DatabaseMapper connectionPool, string tableName) + : base(connectionPool, tableName) + { + } + + public bool TryGetValue(TPrimaryKey primaryKey, out TRowMapper value) + { + TRowMapper result = default(TRowMapper); + bool success = false; + + WithConnection(delegate(DbConnection connection) + { + using ( + DbCommand command = + CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) + { + using (IDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + result = FromReader(new DataReader(reader)); + success = true; + } + else + { + success = false; + } + } + } + }); + + value = result; + + return success; + } + + + public virtual bool Remove(TPrimaryKey id) + { + int deleted = 0; + + WithConnection(delegate(DbConnection connection) + { + using ( + DbCommand command = + CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) + { + deleted = command.ExecuteNonQuery(); + } + }); + + if (deleted == 1) + { + return true; + } + else + { + return false; + } + } + + + public DbCommand CreateDeleteCommand(DbConnection connection, string fieldName, TPrimaryKey primaryKey) + { + string table = TableName; + + DbCommand command = connection.CreateCommand(); + + string conditionString = CreateCondition(command, fieldName, primaryKey); + + string query = + String.Format("delete from {0} where {1}", table, conditionString); + + command.CommandText = query; + command.CommandType = CommandType.Text; + + return command; + } + + public virtual bool Update(TPrimaryKey primaryKey, TRowMapper value) + { + int updated = 0; + + WithConnection(delegate(DbConnection connection) + { + using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) + { + updated = command.ExecuteNonQuery(); + } + }); + + if (updated == 1) + { + return true; + } + else + { + return false; + } + } + + public virtual bool Add(TRowMapper value) + { + int added = 0; + + WithConnection(delegate(DbConnection connection) + { + using (DbCommand command = CreateInsertCommand(connection, value)) + { + added = command.ExecuteNonQuery(); + } + }); + + if (added == 1) + { + return true; + } + else + { + return false; + } + } + + public abstract TRowMapper FromReader(DataReader reader); + } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs index 4a073e9..583c310 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs @@ -1,40 +1,40 @@ -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -[assembly : AssemblyTitle("TribalMedia.Framework.Data")] -[assembly : AssemblyDescription("Generic Database Abstraction Layer")] -[assembly : AssemblyConfiguration("")] -[assembly : AssemblyCompany("TribalMedia")] -[assembly : AssemblyProduct("TribalMedia.Framework.Data")] -[assembly: AssemblyCopyright("Copyright © 2007 Tribal Media")] -[assembly : AssemblyTrademark("")] -[assembly : AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. - -[assembly : ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM - -[assembly : Guid("9269f421-19d9-4eea-bfe3-c0ffe426fada")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly : AssemblyVersion("1.0.0.0")] -[assembly : AssemblyFileVersion("1.0.0.0")] +using System.Reflection; +using System.Runtime.InteropServices; +using System.Security; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. + +[assembly : AssemblyTitle("TribalMedia.Framework.Data")] +[assembly : AssemblyDescription("Generic Database Abstraction Layer")] +[assembly : AssemblyConfiguration("")] +[assembly : AssemblyCompany("TribalMedia")] +[assembly : AssemblyProduct("TribalMedia.Framework.Data")] +[assembly: AssemblyCopyright("Copyright © 2007 Tribal Media")] +[assembly : AssemblyTrademark("")] +[assembly : AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. + +[assembly : ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM + +[assembly : Guid("9269f421-19d9-4eea-bfe3-c0ffe426fada")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Revision and Build Numbers +// by using the '*' as shown below: + +[assembly : AssemblyVersion("1.0.0.0")] +[assembly : AssemblyFileVersion("1.0.0.0")] [assembly : AllowPartiallyTrustedCallers] \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs index aa22c8b..2771ec9 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs @@ -1,85 +1,85 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public abstract class RowMapper - { - public abstract void FillObject(DataReader reader); - } - - public class ObjectMapper : RowMapper - { - private readonly Schema m_schema; - private readonly TObj m_obj; - - public TObj Object - { - get { return m_obj; } - } - - public ObjectMapper(Schema schema, TObj obj) - { - m_schema = schema; - m_obj = obj; - } - - public override void FillObject(DataReader reader) - { - foreach (FieldMapper fieldMapper in m_schema.Fields.Values) - { - fieldMapper.SetPropertyFromReader(m_obj, reader); - } - } - } - - public class RowMapper : RowMapper - { - private readonly Schema m_schema; - private readonly TObj m_obj; - - public TObj Object - { - get { return m_obj; } - } - - public RowMapper(Schema schema, TObj obj) - { - m_schema = schema; - m_obj = obj; - } - - public override void FillObject(DataReader reader) - { - foreach (FieldMapper fieldMapper in m_schema.Fields.Values) - { - fieldMapper.SetPropertyFromReader(this, reader); - } - } - } +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class RowMapper + { + public abstract void FillObject(DataReader reader); + } + + public class ObjectMapper : RowMapper + { + private readonly Schema m_schema; + private readonly TObj m_obj; + + public TObj Object + { + get { return m_obj; } + } + + public ObjectMapper(Schema schema, TObj obj) + { + m_schema = schema; + m_obj = obj; + } + + public override void FillObject(DataReader reader) + { + foreach (FieldMapper fieldMapper in m_schema.Fields.Values) + { + fieldMapper.SetPropertyFromReader(m_obj, reader); + } + } + } + + public class RowMapper : RowMapper + { + private readonly Schema m_schema; + private readonly TObj m_obj; + + public TObj Object + { + get { return m_obj; } + } + + public RowMapper(Schema schema, TObj obj) + { + m_schema = schema; + m_obj = obj; + } + + public override void FillObject(DataReader reader) + { + foreach (FieldMapper fieldMapper in m_schema.Fields.Values) + { + fieldMapper.SetPropertyFromReader(this, reader); + } + } + } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs index b7b8939..c6bf5d0 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs @@ -1,89 +1,89 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System.Collections.Generic; -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public class Schema - { - protected TableMapper m_tableMapper; - protected Dictionary m_mappings; - - public Dictionary Fields - { - get { return m_mappings; } - } - - public Schema(TableMapper tableMapper) - { - m_mappings = new Dictionary(); - m_tableMapper = tableMapper; - } - } - - public class ObjectSchema : Schema - { - public ObjectSchema(TableMapper tableMapper) : base(tableMapper) - { - } - - public ObjectField AddMapping(string fieldName, - ObjectGetAccessor rowMapperGetAccessor, - ObjectSetAccessor rowMapperSetAccessor) - { - ObjectField rowMapperField = - new ObjectField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); - - m_mappings.Add(fieldName, rowMapperField); - - return rowMapperField; - } - } - - public class RowMapperSchema : Schema - where TRowMapper : RowMapper - { - public RowMapperSchema(TableMapper tableMapper) : base(tableMapper) - { - } - - public RowMapperField AddMapping(string fieldName, - RowMapperGetAccessor - rowMapperGetAccessor, - RowMapperSetAccessor - rowMapperSetAccessor) - { - RowMapperField rowMapperField = - new RowMapperField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); - - m_mappings.Add(fieldName, rowMapperField); - - return rowMapperField; - } - } +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System.Collections.Generic; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public class Schema + { + protected TableMapper m_tableMapper; + protected Dictionary m_mappings; + + public Dictionary Fields + { + get { return m_mappings; } + } + + public Schema(TableMapper tableMapper) + { + m_mappings = new Dictionary(); + m_tableMapper = tableMapper; + } + } + + public class ObjectSchema : Schema + { + public ObjectSchema(TableMapper tableMapper) : base(tableMapper) + { + } + + public ObjectField AddMapping(string fieldName, + ObjectGetAccessor rowMapperGetAccessor, + ObjectSetAccessor rowMapperSetAccessor) + { + ObjectField rowMapperField = + new ObjectField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); + + m_mappings.Add(fieldName, rowMapperField); + + return rowMapperField; + } + } + + public class RowMapperSchema : Schema + where TRowMapper : RowMapper + { + public RowMapperSchema(TableMapper tableMapper) : base(tableMapper) + { + } + + public RowMapperField AddMapping(string fieldName, + RowMapperGetAccessor + rowMapperGetAccessor, + RowMapperSetAccessor + rowMapperSetAccessor) + { + RowMapperField rowMapperField = + new RowMapperField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); + + m_mappings.Add(fieldName, rowMapperField); + + return rowMapperField; + } + } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs index f041e79..15005f8 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs @@ -1,108 +1,108 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Data; -using System.Data.Common; -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public abstract class TableMapper - { - private readonly DatabaseMapper m_connectionPool; - private readonly object m_syncRoot = new object(); - - protected void WithConnection(Action action) - { - lock (m_syncRoot) - { - DbConnection m_connection = m_connectionPool.GetNewConnection(); - - if (m_connection.State != ConnectionState.Open) - { - m_connection.Open(); - } - - action(m_connection); - - if (m_connection.State == ConnectionState.Open) - { - m_connection.Close(); - } - } - } - - private readonly string m_tableName; - public string TableName - { - get { return m_tableName; } - } - - private Schema m_schema; - public Schema Schema - { - get { return m_schema; } - } - - private FieldMapper m_keyFieldMapper; - public FieldMapper KeyFieldMapper - { - get { return m_keyFieldMapper; } - } - - public TableMapper(DatabaseMapper connectionPool, string tableName) - { - m_connectionPool = connectionPool; - m_tableName = tableName.ToLower(); // Stupid MySQL hack. - } - - public string CreateParamName(string fieldName) - { - return m_connectionPool.CreateParamName(fieldName); - } - - protected DbCommand CreateSelectCommand(DbConnection connection, string fieldName, object primaryKey) - { - return m_connectionPool.CreateSelectCommand(this, connection, fieldName, primaryKey); - } - - public string CreateCondition(DbCommand command, string fieldName, object key) - { - return m_connectionPool.CreateCondition(this, command, fieldName, key); - } - - public DbCommand CreateInsertCommand(DbConnection connection, object obj) - { - return m_connectionPool.CreateInsertCommand(this, connection, obj); - } - - public DbCommand CreateUpdateCommand(DbConnection connection, object rowMapper, object primaryKey) - { - return m_connectionPool.CreateUpdateCommand(this, connection, rowMapper, primaryKey); - } - } +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Data; +using System.Data.Common; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class TableMapper + { + private readonly DatabaseMapper m_connectionPool; + private readonly object m_syncRoot = new object(); + + protected void WithConnection(Action action) + { + lock (m_syncRoot) + { + DbConnection m_connection = m_connectionPool.GetNewConnection(); + + if (m_connection.State != ConnectionState.Open) + { + m_connection.Open(); + } + + action(m_connection); + + if (m_connection.State == ConnectionState.Open) + { + m_connection.Close(); + } + } + } + + private readonly string m_tableName; + public string TableName + { + get { return m_tableName; } + } + + private Schema m_schema; + public Schema Schema + { + get { return m_schema; } + } + + private FieldMapper m_keyFieldMapper; + public FieldMapper KeyFieldMapper + { + get { return m_keyFieldMapper; } + } + + public TableMapper(DatabaseMapper connectionPool, string tableName) + { + m_connectionPool = connectionPool; + m_tableName = tableName.ToLower(); // Stupid MySQL hack. + } + + public string CreateParamName(string fieldName) + { + return m_connectionPool.CreateParamName(fieldName); + } + + protected DbCommand CreateSelectCommand(DbConnection connection, string fieldName, object primaryKey) + { + return m_connectionPool.CreateSelectCommand(this, connection, fieldName, primaryKey); + } + + public string CreateCondition(DbCommand command, string fieldName, object key) + { + return m_connectionPool.CreateCondition(this, command, fieldName, key); + } + + public DbCommand CreateInsertCommand(DbConnection connection, object obj) + { + return m_connectionPool.CreateInsertCommand(this, connection, obj); + } + + public DbCommand CreateUpdateCommand(DbConnection connection, object rowMapper, object primaryKey) + { + return m_connectionPool.CreateUpdateCommand(this, connection, rowMapper, primaryKey); + } + } } \ No newline at end of file -- cgit v1.1 From 6d751411b7f996c486052c8cbbdbe1e186cebd9f Mon Sep 17 00:00:00 2001 From: lbsa71 Date: Mon, 14 Jan 2008 22:34:19 +0000 Subject: * Added specialization of DatabaseMapper, DataReader and ObjectFieldMapper to support LLVector3, LLQuaternion and LLUUID * Added PrimitiveBaseShapeTableMapper to show how it's done NOTE: Nothing actually works yet - this code should be considered more of educational value until it's all wired together --- .../TribalMedia.Framework.Data/DataReader.cs | 25 +---------- .../TribalMedia.Framework.Data/DatabaseMapper.cs | 8 +++- .../TribalMedia.Framework.Data/FieldMapper.cs | 52 ++-------------------- .../ObjectTableMapper.cs | 2 - .../TribalMedia.Framework.Data/TableMapper.cs | 9 +++- 5 files changed, 18 insertions(+), 78 deletions(-) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs index 6f84d43..4792e9e 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs @@ -61,29 +61,6 @@ namespace TribalMedia.Framework.Data return (sbyte) m_source.GetInt16(m_source.GetOrdinal(name)); } - //public Vector3 GetVector(string s) - //{ - // float x = GetFloat(s + "X"); - // float y = GetFloat(s + "Y"); - // float z = GetFloat(s + "Z"); - - // Vector3 vector = new Vector3(x, y, z); - - // return vector; - //} - - //public Quaternion GetQuaternion(string s) - //{ - // float x = GetFloat(s + "X"); - // float y = GetFloat(s + "Y"); - // float z = GetFloat(s + "Z"); - // float w = GetFloat(s + "W"); - - // Quaternion quaternion = new Quaternion(x, y, z, w); - - // return quaternion; - //} - public float GetFloat(string name) { return m_source.GetFloat(m_source.GetOrdinal(name)); @@ -134,7 +111,7 @@ namespace TribalMedia.Framework.Data return m_source.Read(); } - internal Guid GetGuid(string name) + public Guid GetGuid(string name) { string guidString = GetString(name); if (String.IsNullOrEmpty(guidString)) diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs index 0b9d16d..63e59aa 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs @@ -41,7 +41,6 @@ namespace TribalMedia.Framework.Data } public abstract DbConnection GetNewConnection(); - public abstract string CreateParamName(string fieldName); public DbCommand CreateSelectCommand(TableMapper mapper, DbConnection connection, string fieldName, object key) @@ -67,7 +66,7 @@ namespace TribalMedia.Framework.Data DbParameter param = command.CreateParameter(); param.ParameterName = keyFieldParamName; - param.Value = FieldMapper.ConvertToDbType(key); + param.Value = ConvertToDbType(key); command.Parameters.Add(param); return String.Format("{0}={1}", fieldName, keyFieldParamName); @@ -131,5 +130,10 @@ namespace TribalMedia.Framework.Data return command; } + + public virtual object ConvertToDbType(object value) + { + return value; + } } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs index a1fafbe..89bc0f0 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs @@ -78,52 +78,18 @@ namespace TribalMedia.Framework.Data command.Parameters.Add(param); } - public void ExpandField(TObj obj, DbCommand command, List fieldNames) + public virtual void ExpandField(TObj obj, DbCommand command, List fieldNames) { string fieldName = FieldName; object value = GetParamValue(obj); - //if (ValueType == typeof (Vector3)) - //{ - // Vector3 vector = (Vector3) value; - - // RawAddParam(command, fieldNames, fieldName + "X", vector.X); - // RawAddParam(command, fieldNames, fieldName + "Y", vector.Y); - // RawAddParam(command, fieldNames, fieldName + "Z", vector.Z); - //} - //else if (ValueType == typeof (Quaternion)) - //{ - // Quaternion quaternion = (Quaternion) value; - - // RawAddParam(command, fieldNames, fieldName + "X", quaternion.X); - // RawAddParam(command, fieldNames, fieldName + "Y", quaternion.Y); - // RawAddParam(command, fieldNames, fieldName + "Z", quaternion.Z); - // RawAddParam(command, fieldNames, fieldName + "W", quaternion.W); - //} - //else - //{ - RawAddParam(command, fieldNames, fieldName, ConvertToDbType(value)); - //} + RawAddParam(command, fieldNames, fieldName, m_tableMapper.ConvertToDbType(value)); } - protected object GetValue(DataReader reader) + protected virtual object GetValue(DataReader reader) { object value; - //if (ValueType == typeof (Vector3)) - //{ - // value = reader.GetVector(m_fieldName); - //} - //else if (ValueType == typeof (Quaternion)) - //{ - // value = reader.GetQuaternion(m_fieldName); - //} - //else - //if (ValueType == typeof(UID)) - //{ - // Guid guid = reader.GetGuid(m_fieldName); - // value = new UID(guid); - //} - //else + if (ValueType == typeof(Guid)) { value = reader.GetGuid(m_fieldName); @@ -162,16 +128,6 @@ namespace TribalMedia.Framework.Data return value; } - - public static object ConvertToDbType(object value) - { - //if (value is UID) - //{ - // return (value as UID).UUID.ToString(); - //} - - return value; - } } public class RowMapperField : FieldMapper diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs index 44a6542..818c530 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs @@ -25,10 +25,8 @@ */ using System; -using System.Collections.Generic; using System.Data; using System.Data.Common; -using TribalMedia.Framework.Data; namespace TribalMedia.Framework.Data { diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs index 15005f8..480a015 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs @@ -62,13 +62,13 @@ namespace TribalMedia.Framework.Data get { return m_tableName; } } - private Schema m_schema; + protected Schema m_schema; public Schema Schema { get { return m_schema; } } - private FieldMapper m_keyFieldMapper; + protected FieldMapper m_keyFieldMapper; public FieldMapper KeyFieldMapper { get { return m_keyFieldMapper; } @@ -104,5 +104,10 @@ namespace TribalMedia.Framework.Data { return m_connectionPool.CreateUpdateCommand(this, connection, rowMapper, primaryKey); } + + public object ConvertToDbType(object value) + { + return m_connectionPool.ConvertToDbType(value); + } } } \ No newline at end of file -- cgit v1.1 From b25f9f322cdbcde7fd8c043137bf07992e5ef318 Mon Sep 17 00:00:00 2001 From: Adam Frisby Date: Tue, 15 Jan 2008 02:09:55 +0000 Subject: * Mother of all commits: * Cleaned up copyright notices in AssemblyInfo.cs's * Added Copyright headers to a bunch of files missing them * Replaced several common string instances with a static constant to prevent reallocation of the same strings thousands of times. "" -> String.Empty is the first such candidate. --- .../Properties/AssemblyInfo.cs | 28 ++++++++++++++++++++++ 1 file changed, 28 insertions(+) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs index 583c310..3a69f89 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs @@ -1,3 +1,31 @@ +/* +* Copyright (c) Contributors, http://opensimulator.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + using System.Reflection; using System.Runtime.InteropServices; using System.Security; -- cgit v1.1 From 47c65295236560b0c58c1797ce2ad19418fa2b94 Mon Sep 17 00:00:00 2001 From: lbsa71 Date: Tue, 15 Jan 2008 10:15:39 +0000 Subject: * Some morw work on specializing the database framework for OpenSim --- .../ObjectTableMapper.cs | 9 ++++---- .../TribalMedia.Framework.Data/TableMapper.cs | 25 +++++++++++++--------- 2 files changed, 19 insertions(+), 15 deletions(-) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs index 818c530..f2ee4f8 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs @@ -32,8 +32,8 @@ namespace TribalMedia.Framework.Data { public abstract class ObjectTableMapper : TableMapper { - public ObjectTableMapper(DatabaseMapper connectionPool, string tableName) - : base(connectionPool, tableName) + public ObjectTableMapper(DatabaseMapper database, string tableName) + : base(database, tableName) { } @@ -52,7 +52,7 @@ namespace TribalMedia.Framework.Data { if (reader.Read()) { - result = FromReader(new DataReader(reader)); + result = FromReader( CreateReader(reader)); success = true; } else @@ -67,8 +67,7 @@ namespace TribalMedia.Framework.Data return success; } - - + public virtual bool Remove(TPrimaryKey id) { int deleted = 0; diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs index 480a015..a2b0aa1 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs @@ -33,14 +33,14 @@ namespace TribalMedia.Framework.Data { public abstract class TableMapper { - private readonly DatabaseMapper m_connectionPool; + private readonly DatabaseMapper m_database; private readonly object m_syncRoot = new object(); protected void WithConnection(Action action) { lock (m_syncRoot) { - DbConnection m_connection = m_connectionPool.GetNewConnection(); + DbConnection m_connection = m_database.GetNewConnection(); if (m_connection.State != ConnectionState.Open) { @@ -74,40 +74,45 @@ namespace TribalMedia.Framework.Data get { return m_keyFieldMapper; } } - public TableMapper(DatabaseMapper connectionPool, string tableName) + public TableMapper(DatabaseMapper database, string tableName) { - m_connectionPool = connectionPool; + m_database = database; m_tableName = tableName.ToLower(); // Stupid MySQL hack. } public string CreateParamName(string fieldName) { - return m_connectionPool.CreateParamName(fieldName); + return m_database.CreateParamName(fieldName); } protected DbCommand CreateSelectCommand(DbConnection connection, string fieldName, object primaryKey) { - return m_connectionPool.CreateSelectCommand(this, connection, fieldName, primaryKey); + return m_database.CreateSelectCommand(this, connection, fieldName, primaryKey); } public string CreateCondition(DbCommand command, string fieldName, object key) { - return m_connectionPool.CreateCondition(this, command, fieldName, key); + return m_database.CreateCondition(this, command, fieldName, key); } public DbCommand CreateInsertCommand(DbConnection connection, object obj) { - return m_connectionPool.CreateInsertCommand(this, connection, obj); + return m_database.CreateInsertCommand(this, connection, obj); } public DbCommand CreateUpdateCommand(DbConnection connection, object rowMapper, object primaryKey) { - return m_connectionPool.CreateUpdateCommand(this, connection, rowMapper, primaryKey); + return m_database.CreateUpdateCommand(this, connection, rowMapper, primaryKey); } public object ConvertToDbType(object value) { - return m_connectionPool.ConvertToDbType(value); + return m_database.ConvertToDbType(value); + } + + protected virtual DataReader CreateReader(IDataReader reader) + { + return new DataReader(reader); } } } \ No newline at end of file -- cgit v1.1 From f5103b98be60cc8b1a69288328cdc20f78857835 Mon Sep 17 00:00:00 2001 From: lbsa71 Date: Tue, 15 Jan 2008 20:07:02 +0000 Subject: * Renamed a bunch of Data baseclasses for clarity and readability (Slowly getting there) --- .../TribalMedia.Framework.Data/BaseDataReader.cs | 127 +++++++++++ .../BaseDatabaseConnector.cs | 139 ++++++++++++ .../TribalMedia.Framework.Data/BaseFieldMapper.cs | 203 +++++++++++++++++ .../TribalMedia.Framework.Data/BaseRowMapper.cs | 85 +++++++ .../TribalMedia.Framework.Data/BaseSchema.cs | 90 ++++++++ .../TribalMedia.Framework.Data/BaseTableMapper.cs | 245 +++++++++++++++++++++ .../TribalMedia.Framework.Data/DataReader.cs | 127 ----------- .../TribalMedia.Framework.Data/DatabaseMapper.cs | 139 ------------ .../TribalMedia.Framework.Data/FieldMapper.cs | 205 ----------------- .../ObjectTableMapper.cs | 159 ------------- .../TribalMedia.Framework.Data/RowMapper.cs | 85 ------- .../TribalMedia.Framework.Data/Schema.cs | 89 -------- .../TribalMedia.Framework.Data/TableMapper.cs | 118 ---------- .../TribalMedia.Framework.Data.snk | Bin 0 -> 596 bytes 14 files changed, 889 insertions(+), 922 deletions(-) create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs create mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs new file mode 100644 index 0000000..34f894c --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs @@ -0,0 +1,127 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Data; +using System.IO; + +namespace TribalMedia.Framework.Data +{ + public class DataReader + { + private readonly IDataReader m_source; + + public DataReader(IDataReader source) + { + m_source = source; + } + + public object Get(string name) + { + return m_source[name]; + } + + public ushort GetUShort(string name) + { + return (ushort)m_source.GetInt32(m_source.GetOrdinal(name)); + } + + public byte GetByte(string name) + { + int ordinal = m_source.GetOrdinal(name); + byte value = (byte)m_source.GetInt16(ordinal); + return value; + } + + public sbyte GetSByte(string name) + { + return (sbyte)m_source.GetInt16(m_source.GetOrdinal(name)); + } + + public float GetFloat(string name) + { + return m_source.GetFloat(m_source.GetOrdinal(name)); + } + + public byte[] GetBytes(string name) + { + int ordinal = m_source.GetOrdinal(name); + + if (m_source.GetValue(ordinal) == DBNull.Value) + { + return null; + } + + byte[] buffer = new byte[16384]; + + MemoryStream memStream = new MemoryStream(); + + long totalRead = 0; + + int bytesRead; + do + { + bytesRead = (int)m_source.GetBytes(ordinal, totalRead, buffer, 0, buffer.Length); + totalRead += bytesRead; + + memStream.Write(buffer, 0, bytesRead); + } while (bytesRead == buffer.Length); + + return memStream.ToArray(); + } + + public string GetString(string name) + { + int ordinal = m_source.GetOrdinal(name); + object value = m_source.GetValue(ordinal); + + if (value is DBNull) + { + return null; + } + + return (string)value; + } + + public bool Read() + { + return m_source.Read(); + } + + public Guid GetGuid(string name) + { + string guidString = GetString(name); + if (String.IsNullOrEmpty(guidString)) + { + return Guid.Empty; + } + else + { + return new Guid(guidString); + } + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs new file mode 100644 index 0000000..ae70fc1 --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs @@ -0,0 +1,139 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; + +namespace TribalMedia.Framework.Data +{ + public abstract class BaseDatabaseConnector + { + protected string m_connectionString; + + public BaseDatabaseConnector(string connectionString) + { + m_connectionString = connectionString; + } + + public abstract DbConnection GetNewConnection(); + public abstract string CreateParamName(string fieldName); + + public DbCommand CreateSelectCommand(BaseTableMapper mapper, DbConnection connection, string fieldName, object key) + { + string table = mapper.TableName; + + DbCommand command = connection.CreateCommand(); + + string conditionString = CreateCondition(mapper, command, fieldName, key); + + string query = + String.Format("select * from {0} where {1}", table, conditionString); + + command.CommandText = query; + command.CommandType = CommandType.Text; + + return command; + } + + public string CreateCondition(BaseTableMapper mapper, DbCommand command, string fieldName, object key) + { + string keyFieldParamName = mapper.CreateParamName(fieldName); + + DbParameter param = command.CreateParameter(); + param.ParameterName = keyFieldParamName; + param.Value = ConvertToDbType(key); + command.Parameters.Add(param); + + return String.Format("{0}={1}", fieldName, keyFieldParamName); + } + + public DbCommand CreateUpdateCommand(BaseTableMapper mapper, DbConnection connection, object rowMapper, object primaryKey) + { + string table = mapper.TableName; + + List fieldNames = new List(); + + DbCommand command = connection.CreateCommand(); + + foreach (BaseFieldMapper fieldMapper in mapper.Schema.Fields.Values) + { + if (fieldMapper != mapper.KeyFieldMapper) + { + fieldMapper.ExpandField(rowMapper, command, fieldNames); + } + } + + List assignments = new List(); + + foreach (string field in fieldNames) + { + assignments.Add(String.Format("{0}={1}", field, mapper.CreateParamName(field))); + } + + string conditionString = mapper.CreateCondition(command, mapper.KeyFieldMapper.FieldName, primaryKey); + + command.CommandText = + String.Format("update {0} set {1} where {2}", table, String.Join(", ", assignments.ToArray()), + conditionString); + + return command; + } + + public DbCommand CreateInsertCommand(BaseTableMapper mapper, DbConnection connection, object obj) + { + string table = mapper.TableName; + + List fieldNames = new List(); + + DbCommand command = connection.CreateCommand(); + + foreach (BaseFieldMapper fieldMapper in mapper.Schema.Fields.Values) + { + fieldMapper.ExpandField(obj, command, fieldNames); + } + + List paramNames = new List(); + + foreach (string field in fieldNames) + { + paramNames.Add(mapper.CreateParamName(field)); + } + + command.CommandText = + String.Format("insert into {0} ({1}) values ({2})", table, String.Join(", ", fieldNames.ToArray()), + String.Join(", ", paramNames.ToArray())); + + return command; + } + + public virtual object ConvertToDbType(object value) + { + return value; + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs new file mode 100644 index 0000000..20d8cf1 --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs @@ -0,0 +1,203 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Collections.Generic; +using System.Data.Common; + +namespace TribalMedia.Framework.Data +{ + //public delegate TField RowMapperGetAccessor(TRowMapper rowMapper); + //public delegate void RowMapperSetAccessor(TRowMapper rowMapper, TField value); + + public delegate TField ObjectGetAccessor(TObj obj); + public delegate void ObjectSetAccessor(TObj obj, TField value); + + public abstract class BaseFieldMapper + { + private readonly BaseTableMapper m_tableMapper; + private readonly string m_fieldName; + + public string FieldName + { + get { return m_fieldName; } + } + + protected Type m_valueType; + + public Type ValueType + { + get { return m_valueType; } + } + + public abstract object GetParamValue(object obj); + + public BaseFieldMapper(BaseTableMapper tableMapper, string fieldName, Type valueType) + { + m_fieldName = fieldName; + m_valueType = valueType; + m_tableMapper = tableMapper; + } + + public abstract void SetPropertyFromReader(object mapper, DataReader reader); + + public void RawAddParam(DbCommand command, List fieldNames, string fieldName, object value) + { + string paramName = m_tableMapper.CreateParamName(fieldName); + fieldNames.Add(fieldName); + + DbParameter param = command.CreateParameter(); + param.ParameterName = paramName; + param.Value = value; + + command.Parameters.Add(param); + } + + public virtual void ExpandField(TObj obj, DbCommand command, List fieldNames) + { + string fieldName = FieldName; + object value = GetParamValue(obj); + + RawAddParam(command, fieldNames, fieldName, m_tableMapper.ConvertToDbType(value)); + } + + protected virtual object GetValue(DataReader reader) + { + object value; + + if (ValueType == typeof(Guid)) + { + value = reader.GetGuid(m_fieldName); + } + else if (ValueType == typeof(bool)) + { + uint boolVal = reader.GetUShort(m_fieldName); + value = (boolVal == 1); + } + else + if (ValueType == typeof(byte)) + { + value = reader.GetByte(m_fieldName); + } + else if (ValueType == typeof(sbyte)) + { + value = reader.GetSByte(m_fieldName); + } + else if (ValueType == typeof(ushort)) + { + value = reader.GetUShort(m_fieldName); + } + else if (ValueType == typeof(byte[])) + { + value = reader.GetBytes(m_fieldName); + } + else + { + value = reader.Get(m_fieldName); + } + + if (value is DBNull) + { + value = default(ValueType); + } + + return value; + } + } + + //public class RowMapperField : FieldMapper + // where TRowMapper : RowMapper + //{ + // private readonly RowMapperGetAccessor m_fieldGetAccessor; + // private readonly RowMapperSetAccessor m_fieldSetAccessor; + + // public override object GetParamValue(object obj) + // { + // return m_fieldGetAccessor((TRowMapper) obj); + // } + + // public override void SetPropertyFromReader(object mapper, DataReader reader) + // { + // object value; + + // value = GetValue(reader); + + // if (value == null) + // { + // m_fieldSetAccessor((TRowMapper) mapper, default(TField)); + // } + // else + // { + // m_fieldSetAccessor((TRowMapper) mapper, (TField) value); + // } + // } + + + // public RowMapperField(TableMapper tableMapper, string fieldName, RowMapperGetAccessor rowMapperGetAccessor, + // RowMapperSetAccessor rowMapperSetAccessor) + // : base(tableMapper, fieldName, typeof(TField)) + // { + // m_fieldGetAccessor = rowMapperGetAccessor; + // m_fieldSetAccessor = rowMapperSetAccessor; + // } + //} + + public class ObjectField : BaseFieldMapper + { + private readonly ObjectGetAccessor m_fieldGetAccessor; + private readonly ObjectSetAccessor m_fieldSetAccessor; + + public override object GetParamValue(object obj) + { + return m_fieldGetAccessor((TObject)obj); + } + + public override void SetPropertyFromReader(object obj, DataReader reader) + { + object value; + + value = GetValue(reader); + + if (value == null) + { + m_fieldSetAccessor((TObject)obj, default(TField)); + } + else + { + m_fieldSetAccessor((TObject)obj, (TField)value); + } + } + + + public ObjectField(BaseTableMapper tableMapper, string fieldName, ObjectGetAccessor rowMapperGetAccessor, + ObjectSetAccessor rowMapperSetAccessor) + : base(tableMapper, fieldName, typeof(TField)) + { + m_fieldGetAccessor = rowMapperGetAccessor; + m_fieldSetAccessor = rowMapperSetAccessor; + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs new file mode 100644 index 0000000..2ab8daf --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs @@ -0,0 +1,85 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class RowMapper + { + public abstract void FillObject(DataReader reader); + } + + public class ObjectMapper : RowMapper + { + private readonly Schema m_schema; + private readonly TObj m_obj; + + public TObj Object + { + get { return m_obj; } + } + + public ObjectMapper(Schema schema, TObj obj) + { + m_schema = schema; + m_obj = obj; + } + + public override void FillObject(DataReader reader) + { + foreach (BaseFieldMapper fieldMapper in m_schema.Fields.Values) + { + fieldMapper.SetPropertyFromReader(m_obj, reader); + } + } + } + + public class RowMapper : RowMapper + { + private readonly Schema m_schema; + private readonly TObj m_obj; + + public TObj Object + { + get { return m_obj; } + } + + public RowMapper(Schema schema, TObj obj) + { + m_schema = schema; + m_obj = obj; + } + + public override void FillObject(DataReader reader) + { + foreach (BaseFieldMapper fieldMapper in m_schema.Fields.Values) + { + fieldMapper.SetPropertyFromReader(this, reader); + } + } + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs new file mode 100644 index 0000000..fc59f3b --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs @@ -0,0 +1,90 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System.Collections.Generic; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public class Schema + { + protected BaseTableMapper m_tableMapper; + protected Dictionary m_mappings; + + public Dictionary Fields + { + get { return m_mappings; } + } + + public Schema(BaseTableMapper tableMapper) + { + m_mappings = new Dictionary(); + m_tableMapper = tableMapper; + } + } + + public class ObjectSchema : Schema + { + public ObjectSchema(BaseTableMapper tableMapper) + : base(tableMapper) + { + } + + public ObjectField AddMapping(string fieldName, + ObjectGetAccessor rowMapperGetAccessor, + ObjectSetAccessor rowMapperSetAccessor) + { + ObjectField rowMapperField = + new ObjectField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); + + m_mappings.Add(fieldName, rowMapperField); + + return rowMapperField; + } + } + + //public class RowMapperSchema : Schema + // where TRowMapper : RowMapper + //{ + // public RowMapperSchema(TableMapper tableMapper) : base(tableMapper) + // { + // } + + // public RowMapperField AddMapping(string fieldName, + // RowMapperGetAccessor + // rowMapperGetAccessor, + // RowMapperSetAccessor + // rowMapperSetAccessor) + // { + // RowMapperField rowMapperField = + // new RowMapperField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); + + // m_mappings.Add(fieldName, rowMapperField); + + // return rowMapperField; + // } + //} +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs new file mode 100644 index 0000000..e4fe0fd --- /dev/null +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs @@ -0,0 +1,245 @@ +/* +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * The name of Tribal Media AB may not be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.Data; +using System.Data.Common; +using TribalMedia.Framework.Data; + +namespace TribalMedia.Framework.Data +{ + public abstract class BaseTableMapper + { + private readonly BaseDatabaseConnector m_database; + private readonly object m_syncRoot = new object(); + + protected void WithConnection(Action action) + { + lock (m_syncRoot) + { + DbConnection m_connection = m_database.GetNewConnection(); + + if (m_connection.State != ConnectionState.Open) + { + m_connection.Open(); + } + + action(m_connection); + + if (m_connection.State == ConnectionState.Open) + { + m_connection.Close(); + } + } + } + + private readonly string m_tableName; + public string TableName + { + get { return m_tableName; } + } + + protected Schema m_schema; + public Schema Schema + { + get { return m_schema; } + } + + protected BaseFieldMapper m_keyFieldMapper; + public BaseFieldMapper KeyFieldMapper + { + get { return m_keyFieldMapper; } + } + + public BaseTableMapper(BaseDatabaseConnector database, string tableName) + { + m_database = database; + m_tableName = tableName.ToLower(); // Stupid MySQL hack. + } + + public string CreateParamName(string fieldName) + { + return m_database.CreateParamName(fieldName); + } + + protected DbCommand CreateSelectCommand(DbConnection connection, string fieldName, object primaryKey) + { + return m_database.CreateSelectCommand(this, connection, fieldName, primaryKey); + } + + public string CreateCondition(DbCommand command, string fieldName, object key) + { + return m_database.CreateCondition(this, command, fieldName, key); + } + + public DbCommand CreateInsertCommand(DbConnection connection, object obj) + { + return m_database.CreateInsertCommand(this, connection, obj); + } + + public DbCommand CreateUpdateCommand(DbConnection connection, object rowMapper, object primaryKey) + { + return m_database.CreateUpdateCommand(this, connection, rowMapper, primaryKey); + } + + public object ConvertToDbType(object value) + { + return m_database.ConvertToDbType(value); + } + + protected virtual DataReader CreateReader(IDataReader reader) + { + return new DataReader(reader); + } + } + + public abstract class BaseTableMapper : BaseTableMapper + { + public BaseTableMapper(BaseDatabaseConnector database, string tableName) + : base(database, tableName) + { + } + + public bool TryGetValue(TPrimaryKey primaryKey, out TRowMapper value) + { + TRowMapper result = default(TRowMapper); + bool success = false; + + WithConnection(delegate(DbConnection connection) + { + using ( + DbCommand command = + CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) + { + using (IDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + result = FromReader(CreateReader(reader)); + success = true; + } + else + { + success = false; + } + } + } + }); + + value = result; + + return success; + } + + public virtual bool Remove(TPrimaryKey id) + { + int deleted = 0; + + WithConnection(delegate(DbConnection connection) + { + using ( + DbCommand command = + CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) + { + deleted = command.ExecuteNonQuery(); + } + }); + + if (deleted == 1) + { + return true; + } + else + { + return false; + } + } + + + public DbCommand CreateDeleteCommand(DbConnection connection, string fieldName, TPrimaryKey primaryKey) + { + string table = TableName; + + DbCommand command = connection.CreateCommand(); + + string conditionString = CreateCondition(command, fieldName, primaryKey); + + string query = + String.Format("delete from {0} where {1}", table, conditionString); + + command.CommandText = query; + command.CommandType = CommandType.Text; + + return command; + } + + public virtual bool Update(TPrimaryKey primaryKey, TRowMapper value) + { + int updated = 0; + + WithConnection(delegate(DbConnection connection) + { + using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) + { + updated = command.ExecuteNonQuery(); + } + }); + + if (updated == 1) + { + return true; + } + else + { + return false; + } + } + + public virtual bool Add(TRowMapper value) + { + int added = 0; + + WithConnection(delegate(DbConnection connection) + { + using (DbCommand command = CreateInsertCommand(connection, value)) + { + added = command.ExecuteNonQuery(); + } + }); + + if (added == 1) + { + return true; + } + else + { + return false; + } + } + + public abstract TRowMapper FromReader(DataReader reader); + } +} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs deleted file mode 100644 index 4792e9e..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DataReader.cs +++ /dev/null @@ -1,127 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Data; -using System.IO; - -namespace TribalMedia.Framework.Data -{ - public class DataReader - { - private readonly IDataReader m_source; - - public DataReader(IDataReader source) - { - m_source = source; - } - - public object Get(string name) - { - return m_source[name]; - } - - public ushort GetUShort(string name) - { - return (ushort) m_source.GetInt32(m_source.GetOrdinal(name)); - } - - public byte GetByte(string name) - { - int ordinal = m_source.GetOrdinal(name); - byte value = (byte) m_source.GetInt16(ordinal); - return value; - } - - public sbyte GetSByte(string name) - { - return (sbyte) m_source.GetInt16(m_source.GetOrdinal(name)); - } - - public float GetFloat(string name) - { - return m_source.GetFloat(m_source.GetOrdinal(name)); - } - - public byte[] GetBytes(string name) - { - int ordinal = m_source.GetOrdinal(name); - - if (m_source.GetValue(ordinal) == DBNull.Value) - { - return null; - } - - byte[] buffer = new byte[16384]; - - MemoryStream memStream = new MemoryStream(); - - long totalRead = 0; - - int bytesRead; - do - { - bytesRead = (int) m_source.GetBytes(ordinal, totalRead, buffer, 0, buffer.Length); - totalRead += bytesRead; - - memStream.Write(buffer, 0, bytesRead); - } while (bytesRead == buffer.Length); - - return memStream.ToArray(); - } - - public string GetString(string name) - { - int ordinal = m_source.GetOrdinal(name); - object value = m_source.GetValue(ordinal); - - if (value is DBNull) - { - return null; - } - - return (string) value; - } - - public bool Read() - { - return m_source.Read(); - } - - public Guid GetGuid(string name) - { - string guidString = GetString(name); - if (String.IsNullOrEmpty(guidString)) - { - return Guid.Empty; - } - else - { - return new Guid(guidString); - } - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs deleted file mode 100644 index 63e59aa..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/DatabaseMapper.cs +++ /dev/null @@ -1,139 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; - -namespace TribalMedia.Framework.Data -{ - public abstract class DatabaseMapper - { - protected string m_connectionString; - - public DatabaseMapper(string connectionString) - { - m_connectionString = connectionString; - } - - public abstract DbConnection GetNewConnection(); - public abstract string CreateParamName(string fieldName); - - public DbCommand CreateSelectCommand(TableMapper mapper, DbConnection connection, string fieldName, object key) - { - string table = mapper.TableName; - - DbCommand command = connection.CreateCommand(); - - string conditionString = CreateCondition(mapper, command, fieldName, key); - - string query = - String.Format("select * from {0} where {1}", table, conditionString); - - command.CommandText = query; - command.CommandType = CommandType.Text; - - return command; - } - - public string CreateCondition(TableMapper mapper, DbCommand command, string fieldName, object key) - { - string keyFieldParamName = mapper.CreateParamName(fieldName); - - DbParameter param = command.CreateParameter(); - param.ParameterName = keyFieldParamName; - param.Value = ConvertToDbType(key); - command.Parameters.Add(param); - - return String.Format("{0}={1}", fieldName, keyFieldParamName); - } - - public DbCommand CreateUpdateCommand(TableMapper mapper, DbConnection connection, object rowMapper, object primaryKey) - { - string table = mapper.TableName; - - List fieldNames = new List(); - - DbCommand command = connection.CreateCommand(); - - foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) - { - if (fieldMapper != mapper.KeyFieldMapper) - { - fieldMapper.ExpandField(rowMapper, command, fieldNames); - } - } - - List assignments = new List(); - - foreach (string field in fieldNames) - { - assignments.Add(String.Format("{0}={1}", field, mapper.CreateParamName(field))); - } - - string conditionString = mapper.CreateCondition(command, mapper.KeyFieldMapper.FieldName, primaryKey); - - command.CommandText = - String.Format("update {0} set {1} where {2}", table, String.Join(", ", assignments.ToArray()), - conditionString); - - return command; - } - - public DbCommand CreateInsertCommand(TableMapper mapper, DbConnection connection, object obj) - { - string table = mapper.TableName; - - List fieldNames = new List(); - - DbCommand command = connection.CreateCommand(); - - foreach (FieldMapper fieldMapper in mapper.Schema.Fields.Values) - { - fieldMapper.ExpandField(obj, command, fieldNames); - } - - List paramNames = new List(); - - foreach (string field in fieldNames) - { - paramNames.Add(mapper.CreateParamName(field)); - } - - command.CommandText = - String.Format("insert into {0} ({1}) values ({2})", table, String.Join(", ", fieldNames.ToArray()), - String.Join(", ", paramNames.ToArray())); - - return command; - } - - public virtual object ConvertToDbType(object value) - { - return value; - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs deleted file mode 100644 index 89bc0f0..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/FieldMapper.cs +++ /dev/null @@ -1,205 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Collections.Generic; -using System.Data.Common; - -namespace TribalMedia.Framework.Data -{ - public delegate TField RowMapperGetAccessor(TRowMapper rowMapper); - - public delegate void RowMapperSetAccessor(TRowMapper rowMapper, TField value); - - public delegate TField ObjectGetAccessor(TObj obj); - - public delegate void ObjectSetAccessor(TObj obj, TField value); - - public abstract class FieldMapper - { - private readonly TableMapper m_tableMapper; - private readonly string m_fieldName; - - public string FieldName - { - get { return m_fieldName; } - } - - protected Type m_valueType; - - public Type ValueType - { - get { return m_valueType; } - } - - public abstract object GetParamValue(object obj); - - public FieldMapper( TableMapper tableMapper, string fieldName, Type valueType) - { - m_fieldName = fieldName; - m_valueType = valueType; - m_tableMapper = tableMapper; - } - - public abstract void SetPropertyFromReader(object mapper, DataReader reader); - - public void RawAddParam(DbCommand command, List fieldNames, string fieldName, object value) - { - string paramName = m_tableMapper.CreateParamName(fieldName); - fieldNames.Add(fieldName); - - DbParameter param = command.CreateParameter(); - param.ParameterName = paramName; - param.Value = value; - - command.Parameters.Add(param); - } - - public virtual void ExpandField(TObj obj, DbCommand command, List fieldNames) - { - string fieldName = FieldName; - object value = GetParamValue(obj); - - RawAddParam(command, fieldNames, fieldName, m_tableMapper.ConvertToDbType(value)); - } - - protected virtual object GetValue(DataReader reader) - { - object value; - - if (ValueType == typeof(Guid)) - { - value = reader.GetGuid(m_fieldName); - } - else if (ValueType == typeof (bool)) - { - uint boolVal = reader.GetUShort(m_fieldName); - value = (boolVal == 1); - } - else - if (ValueType == typeof (byte)) - { - value = reader.GetByte(m_fieldName); - } - else if (ValueType == typeof (sbyte)) - { - value = reader.GetSByte(m_fieldName); - } - else if (ValueType == typeof (ushort)) - { - value = reader.GetUShort(m_fieldName); - } - else if (ValueType == typeof (byte[])) - { - value = reader.GetBytes(m_fieldName); - } - else - { - value = reader.Get(m_fieldName); - } - - if (value is DBNull) - { - value = default(ValueType); - } - - return value; - } - } - - public class RowMapperField : FieldMapper - where TRowMapper : RowMapper - { - private readonly RowMapperGetAccessor m_fieldGetAccessor; - private readonly RowMapperSetAccessor m_fieldSetAccessor; - - public override object GetParamValue(object obj) - { - return m_fieldGetAccessor((TRowMapper) obj); - } - - public override void SetPropertyFromReader(object mapper, DataReader reader) - { - object value; - - value = GetValue(reader); - - if (value == null) - { - m_fieldSetAccessor((TRowMapper) mapper, default(TField)); - } - else - { - m_fieldSetAccessor((TRowMapper) mapper, (TField) value); - } - } - - - public RowMapperField(TableMapper tableMapper, string fieldName, RowMapperGetAccessor rowMapperGetAccessor, - RowMapperSetAccessor rowMapperSetAccessor) - : base(tableMapper, fieldName, typeof(TField)) - { - m_fieldGetAccessor = rowMapperGetAccessor; - m_fieldSetAccessor = rowMapperSetAccessor; - } - } - - public class ObjectField : FieldMapper - { - private readonly ObjectGetAccessor m_fieldGetAccessor; - private readonly ObjectSetAccessor m_fieldSetAccessor; - - public override object GetParamValue(object obj) - { - return m_fieldGetAccessor((TObject) obj); - } - - public override void SetPropertyFromReader(object obj, DataReader reader) - { - object value; - - value = GetValue(reader); - - if (value == null) - { - m_fieldSetAccessor((TObject) obj, default(TField)); - } - else - { - m_fieldSetAccessor((TObject) obj, (TField) value); - } - } - - - public ObjectField(TableMapper tableMapper, string fieldName, ObjectGetAccessor rowMapperGetAccessor, - ObjectSetAccessor rowMapperSetAccessor) - : base(tableMapper, fieldName, typeof (TField)) - { - m_fieldGetAccessor = rowMapperGetAccessor; - m_fieldSetAccessor = rowMapperSetAccessor; - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs deleted file mode 100644 index f2ee4f8..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/ObjectTableMapper.cs +++ /dev/null @@ -1,159 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Data; -using System.Data.Common; - -namespace TribalMedia.Framework.Data -{ - public abstract class ObjectTableMapper : TableMapper - { - public ObjectTableMapper(DatabaseMapper database, string tableName) - : base(database, tableName) - { - } - - public bool TryGetValue(TPrimaryKey primaryKey, out TRowMapper value) - { - TRowMapper result = default(TRowMapper); - bool success = false; - - WithConnection(delegate(DbConnection connection) - { - using ( - DbCommand command = - CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) - { - using (IDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - result = FromReader( CreateReader(reader)); - success = true; - } - else - { - success = false; - } - } - } - }); - - value = result; - - return success; - } - - public virtual bool Remove(TPrimaryKey id) - { - int deleted = 0; - - WithConnection(delegate(DbConnection connection) - { - using ( - DbCommand command = - CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) - { - deleted = command.ExecuteNonQuery(); - } - }); - - if (deleted == 1) - { - return true; - } - else - { - return false; - } - } - - - public DbCommand CreateDeleteCommand(DbConnection connection, string fieldName, TPrimaryKey primaryKey) - { - string table = TableName; - - DbCommand command = connection.CreateCommand(); - - string conditionString = CreateCondition(command, fieldName, primaryKey); - - string query = - String.Format("delete from {0} where {1}", table, conditionString); - - command.CommandText = query; - command.CommandType = CommandType.Text; - - return command; - } - - public virtual bool Update(TPrimaryKey primaryKey, TRowMapper value) - { - int updated = 0; - - WithConnection(delegate(DbConnection connection) - { - using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) - { - updated = command.ExecuteNonQuery(); - } - }); - - if (updated == 1) - { - return true; - } - else - { - return false; - } - } - - public virtual bool Add(TRowMapper value) - { - int added = 0; - - WithConnection(delegate(DbConnection connection) - { - using (DbCommand command = CreateInsertCommand(connection, value)) - { - added = command.ExecuteNonQuery(); - } - }); - - if (added == 1) - { - return true; - } - else - { - return false; - } - } - - public abstract TRowMapper FromReader(DataReader reader); - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs deleted file mode 100644 index 2771ec9..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/RowMapper.cs +++ /dev/null @@ -1,85 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public abstract class RowMapper - { - public abstract void FillObject(DataReader reader); - } - - public class ObjectMapper : RowMapper - { - private readonly Schema m_schema; - private readonly TObj m_obj; - - public TObj Object - { - get { return m_obj; } - } - - public ObjectMapper(Schema schema, TObj obj) - { - m_schema = schema; - m_obj = obj; - } - - public override void FillObject(DataReader reader) - { - foreach (FieldMapper fieldMapper in m_schema.Fields.Values) - { - fieldMapper.SetPropertyFromReader(m_obj, reader); - } - } - } - - public class RowMapper : RowMapper - { - private readonly Schema m_schema; - private readonly TObj m_obj; - - public TObj Object - { - get { return m_obj; } - } - - public RowMapper(Schema schema, TObj obj) - { - m_schema = schema; - m_obj = obj; - } - - public override void FillObject(DataReader reader) - { - foreach (FieldMapper fieldMapper in m_schema.Fields.Values) - { - fieldMapper.SetPropertyFromReader(this, reader); - } - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs deleted file mode 100644 index c6bf5d0..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Schema.cs +++ /dev/null @@ -1,89 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System.Collections.Generic; -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public class Schema - { - protected TableMapper m_tableMapper; - protected Dictionary m_mappings; - - public Dictionary Fields - { - get { return m_mappings; } - } - - public Schema(TableMapper tableMapper) - { - m_mappings = new Dictionary(); - m_tableMapper = tableMapper; - } - } - - public class ObjectSchema : Schema - { - public ObjectSchema(TableMapper tableMapper) : base(tableMapper) - { - } - - public ObjectField AddMapping(string fieldName, - ObjectGetAccessor rowMapperGetAccessor, - ObjectSetAccessor rowMapperSetAccessor) - { - ObjectField rowMapperField = - new ObjectField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); - - m_mappings.Add(fieldName, rowMapperField); - - return rowMapperField; - } - } - - public class RowMapperSchema : Schema - where TRowMapper : RowMapper - { - public RowMapperSchema(TableMapper tableMapper) : base(tableMapper) - { - } - - public RowMapperField AddMapping(string fieldName, - RowMapperGetAccessor - rowMapperGetAccessor, - RowMapperSetAccessor - rowMapperSetAccessor) - { - RowMapperField rowMapperField = - new RowMapperField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); - - m_mappings.Add(fieldName, rowMapperField); - - return rowMapperField; - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs deleted file mode 100644 index a2b0aa1..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TableMapper.cs +++ /dev/null @@ -1,118 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Data; -using System.Data.Common; -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public abstract class TableMapper - { - private readonly DatabaseMapper m_database; - private readonly object m_syncRoot = new object(); - - protected void WithConnection(Action action) - { - lock (m_syncRoot) - { - DbConnection m_connection = m_database.GetNewConnection(); - - if (m_connection.State != ConnectionState.Open) - { - m_connection.Open(); - } - - action(m_connection); - - if (m_connection.State == ConnectionState.Open) - { - m_connection.Close(); - } - } - } - - private readonly string m_tableName; - public string TableName - { - get { return m_tableName; } - } - - protected Schema m_schema; - public Schema Schema - { - get { return m_schema; } - } - - protected FieldMapper m_keyFieldMapper; - public FieldMapper KeyFieldMapper - { - get { return m_keyFieldMapper; } - } - - public TableMapper(DatabaseMapper database, string tableName) - { - m_database = database; - m_tableName = tableName.ToLower(); // Stupid MySQL hack. - } - - public string CreateParamName(string fieldName) - { - return m_database.CreateParamName(fieldName); - } - - protected DbCommand CreateSelectCommand(DbConnection connection, string fieldName, object primaryKey) - { - return m_database.CreateSelectCommand(this, connection, fieldName, primaryKey); - } - - public string CreateCondition(DbCommand command, string fieldName, object key) - { - return m_database.CreateCondition(this, command, fieldName, key); - } - - public DbCommand CreateInsertCommand(DbConnection connection, object obj) - { - return m_database.CreateInsertCommand(this, connection, obj); - } - - public DbCommand CreateUpdateCommand(DbConnection connection, object rowMapper, object primaryKey) - { - return m_database.CreateUpdateCommand(this, connection, rowMapper, primaryKey); - } - - public object ConvertToDbType(object value) - { - return m_database.ConvertToDbType(value); - } - - protected virtual DataReader CreateReader(IDataReader reader) - { - return new DataReader(reader); - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk new file mode 100644 index 0000000..fc71027 Binary files /dev/null and b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk differ -- cgit v1.1 From 3af939d9939e777dd0de17e931f92b1c56fc0a4d Mon Sep 17 00:00:00 2001 From: lbsa71 Date: Tue, 15 Jan 2008 20:18:59 +0000 Subject: * vs croaked on strong name key * updated disclaimer --- .../TribalMedia.Framework.Data/Properties/AssemblyInfo.cs | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs index 3a69f89..457624e 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs @@ -1,6 +1,5 @@ /* -* Copyright (c) Contributors, http://opensimulator.org/ -* See CONTRIBUTORS.TXT for a full list of copyright holders. +* Copyright (c) Tribal Media AB, http://tribalmedia.se/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: @@ -9,8 +8,7 @@ * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. -* * Neither the name of the OpenSim Project nor the -* names of its contributors may be used to endorse or promote products +* * The name of Tribal Media AB may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -- cgit v1.1 From 5e757d2ad1ae3ad158a9b5f6077abcfaf9fac616 Mon Sep 17 00:00:00 2001 From: lbsa71 Date: Wed, 16 Jan 2008 12:25:13 +0000 Subject: * More work on getting the database framework to actually work --- .../TribalMedia.Framework.Data/BaseDataReader.cs | 4 +- .../BaseDatabaseConnector.cs | 2 + .../TribalMedia.Framework.Data/BaseFieldMapper.cs | 48 ++-------------------- .../TribalMedia.Framework.Data/BaseRowMapper.cs | 37 +++-------------- .../TribalMedia.Framework.Data/BaseSchema.cs | 30 ++------------ .../TribalMedia.Framework.Data/BaseTableMapper.cs | 12 +++--- 6 files changed, 24 insertions(+), 109 deletions(-) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs index 34f894c..67fb7c1 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs @@ -30,11 +30,11 @@ using System.IO; namespace TribalMedia.Framework.Data { - public class DataReader + public class BaseDataReader { private readonly IDataReader m_source; - public DataReader(IDataReader source) + public BaseDataReader(IDataReader source) { m_source = source; } diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs index ae70fc1..e5d4d62 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs @@ -135,5 +135,7 @@ namespace TribalMedia.Framework.Data { return value; } + + public abstract BaseDataReader CreateReader(IDataReader reader); } } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs index 20d8cf1..20f919a 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs @@ -29,10 +29,7 @@ using System.Collections.Generic; using System.Data.Common; namespace TribalMedia.Framework.Data -{ - //public delegate TField RowMapperGetAccessor(TRowMapper rowMapper); - //public delegate void RowMapperSetAccessor(TRowMapper rowMapper, TField value); - +{ public delegate TField ObjectGetAccessor(TObj obj); public delegate void ObjectSetAccessor(TObj obj, TField value); @@ -62,7 +59,7 @@ namespace TribalMedia.Framework.Data m_tableMapper = tableMapper; } - public abstract void SetPropertyFromReader(object mapper, DataReader reader); + public abstract void SetPropertyFromReader(object mapper, BaseDataReader reader); public void RawAddParam(DbCommand command, List fieldNames, string fieldName, object value) { @@ -84,7 +81,7 @@ namespace TribalMedia.Framework.Data RawAddParam(command, fieldNames, fieldName, m_tableMapper.ConvertToDbType(value)); } - protected virtual object GetValue(DataReader reader) + protected virtual object GetValue(BaseDataReader reader) { object value; @@ -128,43 +125,6 @@ namespace TribalMedia.Framework.Data } } - //public class RowMapperField : FieldMapper - // where TRowMapper : RowMapper - //{ - // private readonly RowMapperGetAccessor m_fieldGetAccessor; - // private readonly RowMapperSetAccessor m_fieldSetAccessor; - - // public override object GetParamValue(object obj) - // { - // return m_fieldGetAccessor((TRowMapper) obj); - // } - - // public override void SetPropertyFromReader(object mapper, DataReader reader) - // { - // object value; - - // value = GetValue(reader); - - // if (value == null) - // { - // m_fieldSetAccessor((TRowMapper) mapper, default(TField)); - // } - // else - // { - // m_fieldSetAccessor((TRowMapper) mapper, (TField) value); - // } - // } - - - // public RowMapperField(TableMapper tableMapper, string fieldName, RowMapperGetAccessor rowMapperGetAccessor, - // RowMapperSetAccessor rowMapperSetAccessor) - // : base(tableMapper, fieldName, typeof(TField)) - // { - // m_fieldGetAccessor = rowMapperGetAccessor; - // m_fieldSetAccessor = rowMapperSetAccessor; - // } - //} - public class ObjectField : BaseFieldMapper { private readonly ObjectGetAccessor m_fieldGetAccessor; @@ -175,7 +135,7 @@ namespace TribalMedia.Framework.Data return m_fieldGetAccessor((TObject)obj); } - public override void SetPropertyFromReader(object obj, DataReader reader) + public override void SetPropertyFromReader(object obj, BaseDataReader reader) { object value; diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs index 2ab8daf..e8292fd 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs @@ -28,14 +28,14 @@ using TribalMedia.Framework.Data; namespace TribalMedia.Framework.Data { - public abstract class RowMapper + public abstract class BaseRowMapper { - public abstract void FillObject(DataReader reader); + public abstract void FillObject(BaseDataReader reader); } - public class ObjectMapper : RowMapper + public class BaseRowMapper : BaseRowMapper { - private readonly Schema m_schema; + private readonly BaseSchema m_schema; private readonly TObj m_obj; public TObj Object @@ -43,38 +43,13 @@ namespace TribalMedia.Framework.Data get { return m_obj; } } - public ObjectMapper(Schema schema, TObj obj) + public BaseRowMapper(BaseSchema schema, TObj obj) { m_schema = schema; m_obj = obj; } - public override void FillObject(DataReader reader) - { - foreach (BaseFieldMapper fieldMapper in m_schema.Fields.Values) - { - fieldMapper.SetPropertyFromReader(m_obj, reader); - } - } - } - - public class RowMapper : RowMapper - { - private readonly Schema m_schema; - private readonly TObj m_obj; - - public TObj Object - { - get { return m_obj; } - } - - public RowMapper(Schema schema, TObj obj) - { - m_schema = schema; - m_obj = obj; - } - - public override void FillObject(DataReader reader) + public override void FillObject(BaseDataReader reader) { foreach (BaseFieldMapper fieldMapper in m_schema.Fields.Values) { diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs index fc59f3b..a6740c2 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs @@ -29,7 +29,7 @@ using TribalMedia.Framework.Data; namespace TribalMedia.Framework.Data { - public class Schema + public class BaseSchema { protected BaseTableMapper m_tableMapper; protected Dictionary m_mappings; @@ -39,16 +39,16 @@ namespace TribalMedia.Framework.Data get { return m_mappings; } } - public Schema(BaseTableMapper tableMapper) + public BaseSchema(BaseTableMapper tableMapper) { m_mappings = new Dictionary(); m_tableMapper = tableMapper; } } - public class ObjectSchema : Schema + public class BaseSchema : BaseSchema { - public ObjectSchema(BaseTableMapper tableMapper) + public BaseSchema(BaseTableMapper tableMapper) : base(tableMapper) { } @@ -65,26 +65,4 @@ namespace TribalMedia.Framework.Data return rowMapperField; } } - - //public class RowMapperSchema : Schema - // where TRowMapper : RowMapper - //{ - // public RowMapperSchema(TableMapper tableMapper) : base(tableMapper) - // { - // } - - // public RowMapperField AddMapping(string fieldName, - // RowMapperGetAccessor - // rowMapperGetAccessor, - // RowMapperSetAccessor - // rowMapperSetAccessor) - // { - // RowMapperField rowMapperField = - // new RowMapperField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); - - // m_mappings.Add(fieldName, rowMapperField); - - // return rowMapperField; - // } - //} } \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs index e4fe0fd..e4ea055 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs @@ -62,8 +62,8 @@ namespace TribalMedia.Framework.Data get { return m_tableName; } } - protected Schema m_schema; - public Schema Schema + protected BaseSchema m_schema; + public BaseSchema Schema { get { return m_schema; } } @@ -110,9 +110,9 @@ namespace TribalMedia.Framework.Data return m_database.ConvertToDbType(value); } - protected virtual DataReader CreateReader(IDataReader reader) + protected virtual BaseDataReader CreateReader(IDataReader reader) { - return new DataReader(reader); + return m_database.CreateReader(reader); } } @@ -138,7 +138,7 @@ namespace TribalMedia.Framework.Data { if (reader.Read()) { - result = FromReader(CreateReader(reader)); + result = FromReader( CreateReader(reader)); success = true; } else @@ -240,6 +240,6 @@ namespace TribalMedia.Framework.Data } } - public abstract TRowMapper FromReader(DataReader reader); + public abstract TRowMapper FromReader(BaseDataReader reader); } } \ No newline at end of file -- cgit v1.1 From b8820a75ef3bf27d3128cf3787915033aad0a463 Mon Sep 17 00:00:00 2001 From: Jeff Ames Date: Sat, 26 Jan 2008 05:06:19 +0000 Subject: Ugly workaround for mono-1.2.6 compile failure in TribalMedia code. Future versions of mono should not need this. Please revert if this makes you cry. --- .../TribalMedia.Framework.Data/BaseTableMapper.cs | 115 ++++++++++++++------- 1 file changed, 75 insertions(+), 40 deletions(-) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs index e4ea055..d69fcbb 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs @@ -123,50 +123,68 @@ namespace TribalMedia.Framework.Data { } + // HACK: This is a temporary function used by TryGetValue(). + // Due to a bug in mono 1.2.6, delegate blocks cannot contain + // a using() block. This has been fixed in SVN, so the next + // mono release should work. + private void TryGetConnectionValue(DbConnection connection, TPrimaryKey primaryKey, ref TRowMapper result, ref bool success) + { + using ( + DbCommand command = + CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) + { + using (IDataReader reader = command.ExecuteReader()) + { + if (reader.Read()) + { + result = FromReader( CreateReader(reader)); + success = true; + } + else + { + success = false; + } + } + } + } + public bool TryGetValue(TPrimaryKey primaryKey, out TRowMapper value) { TRowMapper result = default(TRowMapper); bool success = false; WithConnection(delegate(DbConnection connection) - { - using ( - DbCommand command = - CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) - { - using (IDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - result = FromReader( CreateReader(reader)); - success = true; - } - else - { - success = false; - } - } - } - }); + { + TryGetConnectionValue(connection, primaryKey, ref result, ref success); + }); value = result; return success; } + // HACK: This is a temporary function used by Remove(). + // Due to a bug in mono 1.2.6, delegate blocks cannot contain + // a using() block. This has been fixed in SVN, so the next + // mono release should work. + protected virtual void TryDelete(DbConnection connection, TPrimaryKey id, ref int deleted) + { + using ( + DbCommand command = + CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) + { + deleted = command.ExecuteNonQuery(); + } + } + public virtual bool Remove(TPrimaryKey id) { int deleted = 0; WithConnection(delegate(DbConnection connection) - { - using ( - DbCommand command = - CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) - { - deleted = command.ExecuteNonQuery(); - } - }); + { + TryDelete(connection, id, ref deleted); + }); if (deleted == 1) { @@ -178,7 +196,6 @@ namespace TribalMedia.Framework.Data } } - public DbCommand CreateDeleteCommand(DbConnection connection, string fieldName, TPrimaryKey primaryKey) { string table = TableName; @@ -196,17 +213,26 @@ namespace TribalMedia.Framework.Data return command; } + // HACK: This is a temporary function used by Update(). + // Due to a bug in mono 1.2.6, delegate blocks cannot contain + // a using() block. This has been fixed in SVN, so the next + // mono release should work. + protected void TryUpdate(DbConnection connection, TPrimaryKey primaryKey, TRowMapper value, ref int updated) + { + using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) + { + updated = command.ExecuteNonQuery(); + } + } + public virtual bool Update(TPrimaryKey primaryKey, TRowMapper value) { int updated = 0; WithConnection(delegate(DbConnection connection) - { - using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) - { - updated = command.ExecuteNonQuery(); - } - }); + { + TryUpdate(connection, primaryKey, value, ref updated); + }); if (updated == 1) { @@ -218,17 +244,26 @@ namespace TribalMedia.Framework.Data } } + // HACK: This is a temporary function used by Add(). + // Due to a bug in mono 1.2.6, delegate blocks cannot contain + // a using() block. This has been fixed in SVN, so the next + // mono release should work. + protected void TryAdd(DbConnection connection, TRowMapper value, ref int added) + { + using (DbCommand command = CreateInsertCommand(connection, value)) + { + added = command.ExecuteNonQuery(); + } + } + public virtual bool Add(TRowMapper value) { int added = 0; WithConnection(delegate(DbConnection connection) - { - using (DbCommand command = CreateInsertCommand(connection, value)) - { - added = command.ExecuteNonQuery(); - } - }); + { + TryAdd(connection, value, ref added); + }); if (added == 1) { -- cgit v1.1 From 755ad9e3e0447b60299b08a18624064d1d64141b Mon Sep 17 00:00:00 2001 From: MW Date: Mon, 4 Feb 2008 12:04:02 +0000 Subject: First part of avatar persistence, currently only really works in standalone mode (with accounts_authenticate set to true), it also only currently has a mysql database connector. (sqlite one will follow soon). It also uses the tribalmedia database system, so this needs checking to see if the old problems with mono have been fixed. To use, see the appearance section in opensim.ini.example, set "persist = true", then add the correct connection string for your database.(see mysql-AvatarAppearance.sql in share folder for a example of the table mysql table structure). This could possible be used in a very small grid, but would mean each region server would need to connect to the same mysql database. But the work to move the code to one of the grid servers shouldn't be too much. --- .../TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs | 1 + 1 file changed, 1 insertion(+) (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs index e5d4d62..45ca650 100644 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs +++ b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs @@ -138,4 +138,5 @@ namespace TribalMedia.Framework.Data public abstract BaseDataReader CreateReader(IDataReader reader); } + } \ No newline at end of file -- cgit v1.1 From b3b1f74485882c14478a6e74de0f7c9da13ff7d2 Mon Sep 17 00:00:00 2001 From: lbsa71 Date: Mon, 3 Mar 2008 07:48:35 +0000 Subject: * Started the ardous task to rename the TribalMedia.Framework.Data to OpenSim.Framework.Data.Base It's you !! How are you gentlemen !! --- .../TribalMedia.Framework.Data/BaseDataReader.cs | 127 ---------- .../BaseDatabaseConnector.cs | 142 ----------- .../TribalMedia.Framework.Data/BaseFieldMapper.cs | 163 ------------ .../TribalMedia.Framework.Data/BaseRowMapper.cs | 60 ----- .../TribalMedia.Framework.Data/BaseSchema.cs | 68 ----- .../TribalMedia.Framework.Data/BaseTableMapper.cs | 280 --------------------- .../Properties/AssemblyInfo.cs | 66 ----- .../TribalMedia.Framework.Data.snk | Bin 596 -> 0 bytes 8 files changed, 906 deletions(-) delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs delete mode 100644 ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk (limited to 'ThirdParty') diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs deleted file mode 100644 index 67fb7c1..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDataReader.cs +++ /dev/null @@ -1,127 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Data; -using System.IO; - -namespace TribalMedia.Framework.Data -{ - public class BaseDataReader - { - private readonly IDataReader m_source; - - public BaseDataReader(IDataReader source) - { - m_source = source; - } - - public object Get(string name) - { - return m_source[name]; - } - - public ushort GetUShort(string name) - { - return (ushort)m_source.GetInt32(m_source.GetOrdinal(name)); - } - - public byte GetByte(string name) - { - int ordinal = m_source.GetOrdinal(name); - byte value = (byte)m_source.GetInt16(ordinal); - return value; - } - - public sbyte GetSByte(string name) - { - return (sbyte)m_source.GetInt16(m_source.GetOrdinal(name)); - } - - public float GetFloat(string name) - { - return m_source.GetFloat(m_source.GetOrdinal(name)); - } - - public byte[] GetBytes(string name) - { - int ordinal = m_source.GetOrdinal(name); - - if (m_source.GetValue(ordinal) == DBNull.Value) - { - return null; - } - - byte[] buffer = new byte[16384]; - - MemoryStream memStream = new MemoryStream(); - - long totalRead = 0; - - int bytesRead; - do - { - bytesRead = (int)m_source.GetBytes(ordinal, totalRead, buffer, 0, buffer.Length); - totalRead += bytesRead; - - memStream.Write(buffer, 0, bytesRead); - } while (bytesRead == buffer.Length); - - return memStream.ToArray(); - } - - public string GetString(string name) - { - int ordinal = m_source.GetOrdinal(name); - object value = m_source.GetValue(ordinal); - - if (value is DBNull) - { - return null; - } - - return (string)value; - } - - public bool Read() - { - return m_source.Read(); - } - - public Guid GetGuid(string name) - { - string guidString = GetString(name); - if (String.IsNullOrEmpty(guidString)) - { - return Guid.Empty; - } - else - { - return new Guid(guidString); - } - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs deleted file mode 100644 index 45ca650..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseDatabaseConnector.cs +++ /dev/null @@ -1,142 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Collections.Generic; -using System.Data; -using System.Data.Common; - -namespace TribalMedia.Framework.Data -{ - public abstract class BaseDatabaseConnector - { - protected string m_connectionString; - - public BaseDatabaseConnector(string connectionString) - { - m_connectionString = connectionString; - } - - public abstract DbConnection GetNewConnection(); - public abstract string CreateParamName(string fieldName); - - public DbCommand CreateSelectCommand(BaseTableMapper mapper, DbConnection connection, string fieldName, object key) - { - string table = mapper.TableName; - - DbCommand command = connection.CreateCommand(); - - string conditionString = CreateCondition(mapper, command, fieldName, key); - - string query = - String.Format("select * from {0} where {1}", table, conditionString); - - command.CommandText = query; - command.CommandType = CommandType.Text; - - return command; - } - - public string CreateCondition(BaseTableMapper mapper, DbCommand command, string fieldName, object key) - { - string keyFieldParamName = mapper.CreateParamName(fieldName); - - DbParameter param = command.CreateParameter(); - param.ParameterName = keyFieldParamName; - param.Value = ConvertToDbType(key); - command.Parameters.Add(param); - - return String.Format("{0}={1}", fieldName, keyFieldParamName); - } - - public DbCommand CreateUpdateCommand(BaseTableMapper mapper, DbConnection connection, object rowMapper, object primaryKey) - { - string table = mapper.TableName; - - List fieldNames = new List(); - - DbCommand command = connection.CreateCommand(); - - foreach (BaseFieldMapper fieldMapper in mapper.Schema.Fields.Values) - { - if (fieldMapper != mapper.KeyFieldMapper) - { - fieldMapper.ExpandField(rowMapper, command, fieldNames); - } - } - - List assignments = new List(); - - foreach (string field in fieldNames) - { - assignments.Add(String.Format("{0}={1}", field, mapper.CreateParamName(field))); - } - - string conditionString = mapper.CreateCondition(command, mapper.KeyFieldMapper.FieldName, primaryKey); - - command.CommandText = - String.Format("update {0} set {1} where {2}", table, String.Join(", ", assignments.ToArray()), - conditionString); - - return command; - } - - public DbCommand CreateInsertCommand(BaseTableMapper mapper, DbConnection connection, object obj) - { - string table = mapper.TableName; - - List fieldNames = new List(); - - DbCommand command = connection.CreateCommand(); - - foreach (BaseFieldMapper fieldMapper in mapper.Schema.Fields.Values) - { - fieldMapper.ExpandField(obj, command, fieldNames); - } - - List paramNames = new List(); - - foreach (string field in fieldNames) - { - paramNames.Add(mapper.CreateParamName(field)); - } - - command.CommandText = - String.Format("insert into {0} ({1}) values ({2})", table, String.Join(", ", fieldNames.ToArray()), - String.Join(", ", paramNames.ToArray())); - - return command; - } - - public virtual object ConvertToDbType(object value) - { - return value; - } - - public abstract BaseDataReader CreateReader(IDataReader reader); - } - -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs deleted file mode 100644 index 20f919a..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseFieldMapper.cs +++ /dev/null @@ -1,163 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Collections.Generic; -using System.Data.Common; - -namespace TribalMedia.Framework.Data -{ - public delegate TField ObjectGetAccessor(TObj obj); - public delegate void ObjectSetAccessor(TObj obj, TField value); - - public abstract class BaseFieldMapper - { - private readonly BaseTableMapper m_tableMapper; - private readonly string m_fieldName; - - public string FieldName - { - get { return m_fieldName; } - } - - protected Type m_valueType; - - public Type ValueType - { - get { return m_valueType; } - } - - public abstract object GetParamValue(object obj); - - public BaseFieldMapper(BaseTableMapper tableMapper, string fieldName, Type valueType) - { - m_fieldName = fieldName; - m_valueType = valueType; - m_tableMapper = tableMapper; - } - - public abstract void SetPropertyFromReader(object mapper, BaseDataReader reader); - - public void RawAddParam(DbCommand command, List fieldNames, string fieldName, object value) - { - string paramName = m_tableMapper.CreateParamName(fieldName); - fieldNames.Add(fieldName); - - DbParameter param = command.CreateParameter(); - param.ParameterName = paramName; - param.Value = value; - - command.Parameters.Add(param); - } - - public virtual void ExpandField(TObj obj, DbCommand command, List fieldNames) - { - string fieldName = FieldName; - object value = GetParamValue(obj); - - RawAddParam(command, fieldNames, fieldName, m_tableMapper.ConvertToDbType(value)); - } - - protected virtual object GetValue(BaseDataReader reader) - { - object value; - - if (ValueType == typeof(Guid)) - { - value = reader.GetGuid(m_fieldName); - } - else if (ValueType == typeof(bool)) - { - uint boolVal = reader.GetUShort(m_fieldName); - value = (boolVal == 1); - } - else - if (ValueType == typeof(byte)) - { - value = reader.GetByte(m_fieldName); - } - else if (ValueType == typeof(sbyte)) - { - value = reader.GetSByte(m_fieldName); - } - else if (ValueType == typeof(ushort)) - { - value = reader.GetUShort(m_fieldName); - } - else if (ValueType == typeof(byte[])) - { - value = reader.GetBytes(m_fieldName); - } - else - { - value = reader.Get(m_fieldName); - } - - if (value is DBNull) - { - value = default(ValueType); - } - - return value; - } - } - - public class ObjectField : BaseFieldMapper - { - private readonly ObjectGetAccessor m_fieldGetAccessor; - private readonly ObjectSetAccessor m_fieldSetAccessor; - - public override object GetParamValue(object obj) - { - return m_fieldGetAccessor((TObject)obj); - } - - public override void SetPropertyFromReader(object obj, BaseDataReader reader) - { - object value; - - value = GetValue(reader); - - if (value == null) - { - m_fieldSetAccessor((TObject)obj, default(TField)); - } - else - { - m_fieldSetAccessor((TObject)obj, (TField)value); - } - } - - - public ObjectField(BaseTableMapper tableMapper, string fieldName, ObjectGetAccessor rowMapperGetAccessor, - ObjectSetAccessor rowMapperSetAccessor) - : base(tableMapper, fieldName, typeof(TField)) - { - m_fieldGetAccessor = rowMapperGetAccessor; - m_fieldSetAccessor = rowMapperSetAccessor; - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs deleted file mode 100644 index e8292fd..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseRowMapper.cs +++ /dev/null @@ -1,60 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public abstract class BaseRowMapper - { - public abstract void FillObject(BaseDataReader reader); - } - - public class BaseRowMapper : BaseRowMapper - { - private readonly BaseSchema m_schema; - private readonly TObj m_obj; - - public TObj Object - { - get { return m_obj; } - } - - public BaseRowMapper(BaseSchema schema, TObj obj) - { - m_schema = schema; - m_obj = obj; - } - - public override void FillObject(BaseDataReader reader) - { - foreach (BaseFieldMapper fieldMapper in m_schema.Fields.Values) - { - fieldMapper.SetPropertyFromReader(this, reader); - } - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs deleted file mode 100644 index a6740c2..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseSchema.cs +++ /dev/null @@ -1,68 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System.Collections.Generic; -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public class BaseSchema - { - protected BaseTableMapper m_tableMapper; - protected Dictionary m_mappings; - - public Dictionary Fields - { - get { return m_mappings; } - } - - public BaseSchema(BaseTableMapper tableMapper) - { - m_mappings = new Dictionary(); - m_tableMapper = tableMapper; - } - } - - public class BaseSchema : BaseSchema - { - public BaseSchema(BaseTableMapper tableMapper) - : base(tableMapper) - { - } - - public ObjectField AddMapping(string fieldName, - ObjectGetAccessor rowMapperGetAccessor, - ObjectSetAccessor rowMapperSetAccessor) - { - ObjectField rowMapperField = - new ObjectField(m_tableMapper, fieldName, rowMapperGetAccessor, rowMapperSetAccessor); - - m_mappings.Add(fieldName, rowMapperField); - - return rowMapperField; - } - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs deleted file mode 100644 index d69fcbb..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/BaseTableMapper.cs +++ /dev/null @@ -1,280 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System; -using System.Data; -using System.Data.Common; -using TribalMedia.Framework.Data; - -namespace TribalMedia.Framework.Data -{ - public abstract class BaseTableMapper - { - private readonly BaseDatabaseConnector m_database; - private readonly object m_syncRoot = new object(); - - protected void WithConnection(Action action) - { - lock (m_syncRoot) - { - DbConnection m_connection = m_database.GetNewConnection(); - - if (m_connection.State != ConnectionState.Open) - { - m_connection.Open(); - } - - action(m_connection); - - if (m_connection.State == ConnectionState.Open) - { - m_connection.Close(); - } - } - } - - private readonly string m_tableName; - public string TableName - { - get { return m_tableName; } - } - - protected BaseSchema m_schema; - public BaseSchema Schema - { - get { return m_schema; } - } - - protected BaseFieldMapper m_keyFieldMapper; - public BaseFieldMapper KeyFieldMapper - { - get { return m_keyFieldMapper; } - } - - public BaseTableMapper(BaseDatabaseConnector database, string tableName) - { - m_database = database; - m_tableName = tableName.ToLower(); // Stupid MySQL hack. - } - - public string CreateParamName(string fieldName) - { - return m_database.CreateParamName(fieldName); - } - - protected DbCommand CreateSelectCommand(DbConnection connection, string fieldName, object primaryKey) - { - return m_database.CreateSelectCommand(this, connection, fieldName, primaryKey); - } - - public string CreateCondition(DbCommand command, string fieldName, object key) - { - return m_database.CreateCondition(this, command, fieldName, key); - } - - public DbCommand CreateInsertCommand(DbConnection connection, object obj) - { - return m_database.CreateInsertCommand(this, connection, obj); - } - - public DbCommand CreateUpdateCommand(DbConnection connection, object rowMapper, object primaryKey) - { - return m_database.CreateUpdateCommand(this, connection, rowMapper, primaryKey); - } - - public object ConvertToDbType(object value) - { - return m_database.ConvertToDbType(value); - } - - protected virtual BaseDataReader CreateReader(IDataReader reader) - { - return m_database.CreateReader(reader); - } - } - - public abstract class BaseTableMapper : BaseTableMapper - { - public BaseTableMapper(BaseDatabaseConnector database, string tableName) - : base(database, tableName) - { - } - - // HACK: This is a temporary function used by TryGetValue(). - // Due to a bug in mono 1.2.6, delegate blocks cannot contain - // a using() block. This has been fixed in SVN, so the next - // mono release should work. - private void TryGetConnectionValue(DbConnection connection, TPrimaryKey primaryKey, ref TRowMapper result, ref bool success) - { - using ( - DbCommand command = - CreateSelectCommand(connection, KeyFieldMapper.FieldName, primaryKey)) - { - using (IDataReader reader = command.ExecuteReader()) - { - if (reader.Read()) - { - result = FromReader( CreateReader(reader)); - success = true; - } - else - { - success = false; - } - } - } - } - - public bool TryGetValue(TPrimaryKey primaryKey, out TRowMapper value) - { - TRowMapper result = default(TRowMapper); - bool success = false; - - WithConnection(delegate(DbConnection connection) - { - TryGetConnectionValue(connection, primaryKey, ref result, ref success); - }); - - value = result; - - return success; - } - - // HACK: This is a temporary function used by Remove(). - // Due to a bug in mono 1.2.6, delegate blocks cannot contain - // a using() block. This has been fixed in SVN, so the next - // mono release should work. - protected virtual void TryDelete(DbConnection connection, TPrimaryKey id, ref int deleted) - { - using ( - DbCommand command = - CreateDeleteCommand(connection, KeyFieldMapper.FieldName, id)) - { - deleted = command.ExecuteNonQuery(); - } - } - - public virtual bool Remove(TPrimaryKey id) - { - int deleted = 0; - - WithConnection(delegate(DbConnection connection) - { - TryDelete(connection, id, ref deleted); - }); - - if (deleted == 1) - { - return true; - } - else - { - return false; - } - } - - public DbCommand CreateDeleteCommand(DbConnection connection, string fieldName, TPrimaryKey primaryKey) - { - string table = TableName; - - DbCommand command = connection.CreateCommand(); - - string conditionString = CreateCondition(command, fieldName, primaryKey); - - string query = - String.Format("delete from {0} where {1}", table, conditionString); - - command.CommandText = query; - command.CommandType = CommandType.Text; - - return command; - } - - // HACK: This is a temporary function used by Update(). - // Due to a bug in mono 1.2.6, delegate blocks cannot contain - // a using() block. This has been fixed in SVN, so the next - // mono release should work. - protected void TryUpdate(DbConnection connection, TPrimaryKey primaryKey, TRowMapper value, ref int updated) - { - using (DbCommand command = CreateUpdateCommand(connection, value, primaryKey)) - { - updated = command.ExecuteNonQuery(); - } - } - - public virtual bool Update(TPrimaryKey primaryKey, TRowMapper value) - { - int updated = 0; - - WithConnection(delegate(DbConnection connection) - { - TryUpdate(connection, primaryKey, value, ref updated); - }); - - if (updated == 1) - { - return true; - } - else - { - return false; - } - } - - // HACK: This is a temporary function used by Add(). - // Due to a bug in mono 1.2.6, delegate blocks cannot contain - // a using() block. This has been fixed in SVN, so the next - // mono release should work. - protected void TryAdd(DbConnection connection, TRowMapper value, ref int added) - { - using (DbCommand command = CreateInsertCommand(connection, value)) - { - added = command.ExecuteNonQuery(); - } - } - - public virtual bool Add(TRowMapper value) - { - int added = 0; - - WithConnection(delegate(DbConnection connection) - { - TryAdd(connection, value, ref added); - }); - - if (added == 1) - { - return true; - } - else - { - return false; - } - } - - public abstract TRowMapper FromReader(BaseDataReader reader); - } -} \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs deleted file mode 100644 index 457624e..0000000 --- a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/Properties/AssemblyInfo.cs +++ /dev/null @@ -1,66 +0,0 @@ -/* -* Copyright (c) Tribal Media AB, http://tribalmedia.se/ -* -* Redistribution and use in source and binary forms, with or without -* modification, are permitted provided that the following conditions are met: -* * Redistributions of source code must retain the above copyright -* notice, this list of conditions and the following disclaimer. -* * Redistributions in binary form must reproduce the above copyright -* notice, this list of conditions and the following disclaimer in the -* documentation and/or other materials provided with the distribution. -* * The name of Tribal Media AB may not be used to endorse or promote products -* derived from this software without specific prior written permission. -* -* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY -* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED -* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE -* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY -* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES -* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; -* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND -* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT -* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS -* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. -* -*/ - -using System.Reflection; -using System.Runtime.InteropServices; -using System.Security; - -// General Information about an assembly is controlled through the following -// set of attributes. Change these attribute values to modify the information -// associated with an assembly. - -[assembly : AssemblyTitle("TribalMedia.Framework.Data")] -[assembly : AssemblyDescription("Generic Database Abstraction Layer")] -[assembly : AssemblyConfiguration("")] -[assembly : AssemblyCompany("TribalMedia")] -[assembly : AssemblyProduct("TribalMedia.Framework.Data")] -[assembly: AssemblyCopyright("Copyright © 2007 Tribal Media")] -[assembly : AssemblyTrademark("")] -[assembly : AssemblyCulture("")] - -// Setting ComVisible to false makes the types in this assembly not visible -// to COM components. If you need to access a type in this assembly from -// COM, set the ComVisible attribute to true on that type. - -[assembly : ComVisible(false)] - -// The following GUID is for the ID of the typelib if this project is exposed to COM - -[assembly : Guid("9269f421-19d9-4eea-bfe3-c0ffe426fada")] - -// Version information for an assembly consists of the following four values: -// -// Major Version -// Minor Version -// Build Number -// Revision -// -// You can specify all the values or you can default the Revision and Build Numbers -// by using the '*' as shown below: - -[assembly : AssemblyVersion("1.0.0.0")] -[assembly : AssemblyFileVersion("1.0.0.0")] -[assembly : AllowPartiallyTrustedCallers] \ No newline at end of file diff --git a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk b/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk deleted file mode 100644 index fc71027..0000000 Binary files a/ThirdParty/TribalMedia/TribalMedia.Framework.Data/TribalMedia.Framework.Data.snk and /dev/null differ -- cgit v1.1 From 279e0061c515ee0a03036bef68eea9738273d785 Mon Sep 17 00:00:00 2001 From: Johan Berntsson Date: Tue, 4 Mar 2008 05:31:54 +0000 Subject: Merged 3Di code that provides scene and avatar serialization, and plugin support for region move/split/merge. See ThirdParty/3Di/README.txt. Unless the new modules are used there should be no noticeable changes when running OpenSim. --- ThirdParty/3Di/LoadBalancer/LoadBalancerPlugin.cs | 1101 ++++++++++++++++++++ ThirdParty/3Di/LoadBalancer/TcpClient.cs | 240 +++++ ThirdParty/3Di/LoadBalancer/TcpServer.cs | 219 ++++ ThirdParty/3Di/README.txt | 82 ++ .../MonitorGUI/htdocs/MonitorGUI/View.pm | 214 ++++ .../3Di/RegionMonitor/MonitorGUI/htdocs/MyCGI.pm | 91 ++ .../RegionMonitor/MonitorGUI/htdocs/monitor.cgi | 202 ++++ .../ServerPlugin/RegionMonitorPlugin.cs | 129 +++ ThirdParty/3Di/RegionProxy/RegionProxyPlugin.cs | 513 +++++++++ 9 files changed, 2791 insertions(+) create mode 100644 ThirdParty/3Di/LoadBalancer/LoadBalancerPlugin.cs create mode 100644 ThirdParty/3Di/LoadBalancer/TcpClient.cs create mode 100644 ThirdParty/3Di/LoadBalancer/TcpServer.cs create mode 100644 ThirdParty/3Di/README.txt create mode 100644 ThirdParty/3Di/RegionMonitor/MonitorGUI/htdocs/MonitorGUI/View.pm create mode 100644 ThirdParty/3Di/RegionMonitor/MonitorGUI/htdocs/MyCGI.pm create mode 100644 ThirdParty/3Di/RegionMonitor/MonitorGUI/htdocs/monitor.cgi create mode 100644 ThirdParty/3Di/RegionMonitor/ServerPlugin/RegionMonitorPlugin.cs create mode 100644 ThirdParty/3Di/RegionProxy/RegionProxyPlugin.cs (limited to 'ThirdParty') diff --git a/ThirdParty/3Di/LoadBalancer/LoadBalancerPlugin.cs b/ThirdParty/3Di/LoadBalancer/LoadBalancerPlugin.cs new file mode 100644 index 0000000..6812777 --- /dev/null +++ b/ThirdParty/3Di/LoadBalancer/LoadBalancerPlugin.cs @@ -0,0 +1,1101 @@ +/* +* Copyright (c) Contributors, http://opensimulator.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.IO; +using System.Net; +using System.Xml; +using System.Text; +using System.Xml.Serialization; +using System.Net.Sockets; +using System.Collections; +using System.Collections.Generic; +using System.Diagnostics; +using System.Threading; + +using OpenSim.Framework; +using OpenSim.Framework.Console; +using OpenSim.Framework.Servers; +using OpenSim.Region.Environment; +using OpenSim.Region.Environment.Scenes; +using OpenSim.Region.ClientStack; + +using Nwc.XmlRpc; +using Nini.Config; + +using Mono.Addins; + +using libsecondlife; +using libsecondlife.Packets; + +[assembly:Addin] +[assembly:AddinDependency ("OpenSim", "0.5")] + +namespace OpenSim.ApplicationPlugins.LoadBalancer +{ + [Extension("/OpenSim/Startup")] + public class LoadBalancerPlugin : IApplicationPlugin + { + private static readonly log4net.ILog m_log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType); + + private OpenSimMain simMain; + private BaseHttpServer commandServer; + + private List udpServers; + private List regionData; + + private int proxyOffset; + private string proxyURL; + private SceneManager sceneManager; + private string serializeDir; + + private TcpServer mTcpServer; + private TcpClient mTcpClient; + + public void Initialise(OpenSimMain openSim) + { + m_log.Info("[BALANCER] "+"Entering Initialize()"); + + StartTcpServer(); + ClientView.SynchronizeClient = new ClientView.SynchronizeClientHandler(SynchronizePackets); + AsynchronousSocketListener.PacketHandler = new AsynchronousSocketListener.PacketRecieveHandler(SynchronizePacketRecieve); + + this.sceneManager = openSim.SceneManager; + this.udpServers = openSim.UdpServers; + this.regionData = openSim.RegionData; + this.simMain = openSim; + this.commandServer = openSim.HttpServer; + + proxyOffset = Int32.Parse(openSim.ConfigSource.Configs["Network"].GetString("proxy_offset", "0")); + proxyURL = openSim.ConfigSource.Configs["Network"].GetString("proxy_url", ""); + if(proxyURL.Length==0) return; + + serializeDir = openSim.ConfigSource.Configs["Network"].GetString("serialize_dir", "/tmp/"); + + commandServer.AddXmlRPCHandler("SerializeRegion", SerializeRegion); + commandServer.AddXmlRPCHandler("DeserializeRegion_Move", DeserializeRegion_Move); + commandServer.AddXmlRPCHandler("DeserializeRegion_Clone", DeserializeRegion_Clone); + commandServer.AddXmlRPCHandler("TerminateRegion", TerminateRegion); + + commandServer.AddXmlRPCHandler("SplitRegion", SplitRegion); + commandServer.AddXmlRPCHandler("MergeRegions", MergeRegions); + commandServer.AddXmlRPCHandler("UpdatePhysics", UpdatePhysics); + commandServer.AddXmlRPCHandler("GetStatus", GetStatus); + + m_log.Info("[BALANCER] "+"Exiting Initialize()"); + } + + private void StartTcpServer() + { + Thread server_thread = new Thread(new ThreadStart( + delegate { + mTcpServer = new TcpServer(10001); + mTcpServer.start(); + })); + server_thread.Start(); + } + + public void Close() + { + } + + private XmlRpcResponse GetStatus(XmlRpcRequest request) + { + XmlRpcResponse response = new XmlRpcResponse(); + try + { + m_log.Info("[BALANCER] "+"Entering RegionStatus()"); + + int src_port = (int)request.Params[0]; + Scene scene = null; + // try to get the scene object + RegionInfo src_region = SearchRegionFromPortNum(src_port); + if (sceneManager.TryGetScene(src_region.RegionID, out scene) == false) + { + m_log.Error("[BALANCER] "+"The Scene is not found"); + return response; + } + // serialization of client's informations + List presences = scene.GetScenePresences(); + int get_scene_presence = presences.Count; + int get_scene_presence_filter = 0; + foreach (ScenePresence pre in presences) + { + ClientView client = (ClientView) pre.ControllingClient; + //if(pre.MovementFlag!=0 && client.PacketProcessingEnabled==true) { + if(client.PacketProcessingEnabled==true) { + get_scene_presence_filter++; + } + } + List avatars = scene.GetAvatars(); + int get_avatar = avatars.Count; + int get_avatar_filter = 0; + string avatar_names = ""; + foreach (ScenePresence pre in avatars) + { + ClientView client = (ClientView) pre.ControllingClient; + //if(pre.MovementFlag!=0 && client.PacketProcessingEnabled==true) { + if(client.PacketProcessingEnabled==true) { + get_avatar_filter++; + avatar_names += pre.Firstname + " " + pre.Lastname + "; "; + } + } + + Hashtable responseData = new Hashtable(); + responseData["get_scene_presence_filter"] = get_scene_presence_filter; + responseData["get_scene_presence"] = get_scene_presence; + responseData["get_avatar_filter"] = get_avatar_filter; + responseData["get_avatar"] = get_avatar; + responseData["avatar_names"] = avatar_names; + response.Value = responseData; + + m_log.Info("[BALANCER] "+"Exiting RegionStatus()"); + } + catch (Exception e) + { + m_log.Error("[BALANCER] "+e.ToString()); + m_log.Error("[BALANCER] "+e.StackTrace); + } + return response; + } + + private XmlRpcResponse SerializeRegion(XmlRpcRequest request) + { + try + { + m_log.Info("[BALANCER] "+"Entering SerializeRegion()"); + + string src_url = (string)request.Params[0]; + int src_port = (int)request.Params[1]; + + SerializeRegion(src_url, src_port); + + m_log.Info("[BALANCER] "+"Exiting SerializeRegion()"); + } + catch (Exception e) + { + m_log.Error("[BALANCER] "+e.ToString()); + m_log.Error("[BALANCER] "+e.StackTrace); + } + + return new XmlRpcResponse(); + } + + private XmlRpcResponse DeserializeRegion_Move(XmlRpcRequest request) + { + try + { + m_log.Info("[BALANCER] "+"Entering DeserializeRegion_Move()"); + + string src_url = (string)request.Params[0]; + int src_port = (int)request.Params[1]; + string dst_url = (string)request.Params[2]; + int dst_port = (int)request.Params[3]; + + DeserializeRegion_Move(src_port, dst_port, src_url, dst_url); + + m_log.Info("[BALANCER] "+"Exiting DeserializeRegion_Move()"); + } + catch (Exception e) + { + m_log.Error("[BALANCER] "+e.ToString()); + m_log.Error("[BALANCER] "+e.StackTrace); + } + + return new XmlRpcResponse(); + } + + private XmlRpcResponse DeserializeRegion_Clone(XmlRpcRequest request) + { + try + { + m_log.Info("[BALANCER] "+"Entering DeserializeRegion_Clone()"); + + string src_url = (string)request.Params[0]; + int src_port = (int)request.Params[1]; + string dst_url = (string)request.Params[2]; + int dst_port = (int)request.Params[3]; + + DeserializeRegion_Clone(src_port, dst_port, src_url, dst_url); + + m_log.Info("[BALANCER] "+"Exiting DeserializeRegion_Clone()"); + } + catch (Exception e) + { + m_log.Error("[BALANCER] "+e.ToString()); + m_log.Error("[BALANCER] "+e.StackTrace); + throw e; + } + + return new XmlRpcResponse(); + } + + private XmlRpcResponse TerminateRegion(XmlRpcRequest request) + { + try + { + m_log.Info("[BALANCER] "+"Entering TerminateRegion()"); + + int src_port = (int)request.Params[0]; + + // backgroud + WaitCallback callback = new WaitCallback(TerminateRegion); + ThreadPool.QueueUserWorkItem(callback, src_port); + + m_log.Info("[BALANCER] "+"Exiting TerminateRegion()"); + } + catch (Exception e) + { + m_log.Error("[BALANCER] "+e.ToString()); + m_log.Error("[BALANCER] "+e.StackTrace); + } + + return new XmlRpcResponse(); + } + + // internal functions + + private void SerializeRegion(string src_url, int src_port) + { + RegionInfo src_region = null; + + //------------------------------------------ + // Processing of origin region + //------------------------------------------ + + // search origin region + src_region = SearchRegionFromPortNum(src_port); + + if (src_region == null) + { + m_log.Error("[BALANCER] "+"Region not found"); + return; + } + + simMain.ProxyCommand(src_region.proxyUrl, "BlockClientMessages", src_url, src_port + proxyOffset); + + // serialization of origin region's data + SerializeRegion(src_region, serializeDir); + } + + private void DeserializeRegion_Move(int src_port, int dst_port, string src_url, string dst_url) + { + RegionInfo dst_region = null; + + //------------------------------------------ + // Processing of destination region + //------------------------------------------ + + // import the source region's data + dst_region = DeserializeRegion(dst_port, true, serializeDir); + + simMain.ProxyCommand(dst_region.proxyUrl, "ChangeRegion", src_port + proxyOffset, src_url, dst_port + proxyOffset, dst_url); + simMain.ProxyCommand(dst_region.proxyUrl, "UnblockClientMessages", dst_url, dst_port + proxyOffset); + } + + private void DeserializeRegion_Clone(int src_port, int dst_port, string src_url, string dst_url) + { + RegionInfo dst_region = null; + + //------------------------------------------ + // Processing of destination region + //------------------------------------------ + + // import the source region's data + dst_region = DeserializeRegion(dst_port, false, serializeDir); + + // Decide who is in charge for each section + int[] port = new int[] { src_port, dst_port }; + string[] url = new string[] { "http://" + src_url + ":" + commandServer.Port, "http://" + dst_url + ":" + commandServer.Port }; + for(int i=0; i<2; i++) simMain.XmlRpcCommand(url[i], "SplitRegion", i, 2, port[0], port[1], url[0], url[1]); + + // Enable the proxy + simMain.ProxyCommand(dst_region.proxyUrl, "AddRegion", src_port + proxyOffset, src_url, dst_port + proxyOffset, dst_url); + simMain.ProxyCommand(dst_region.proxyUrl, "UnblockClientMessages", dst_url, dst_port + proxyOffset); + } + + private void TerminateRegion(object param) + { + RegionInfo src_region = null; + int src_port = (int)param; + + //------------------------------------------ + // Processing of remove region + //------------------------------------------ + + // search origin region + src_region = SearchRegionFromPortNum(src_port); + + if (src_region == null) + { + m_log.Error("[BALANCER] "+"Region not found"); + return; + } + + isSplit = false; + + // remove client resources + RemoveAllClientResource(src_region); + // remove old region + RemoveRegion(src_region.RegionID, src_region.InternalEndPoint.Port); + + m_log.Info("[BALANCER] "+"Region terminated"); + } + + private RegionInfo SearchRegionFromPortNum(int portnum) + { + RegionInfo result = null; + + foreach (RegionInfo rinfo in regionData) + { + if (rinfo.InternalEndPoint.Port == portnum) + { +// m_log.Info("BALANCER", +// "Region found. Internal Port = {0}, Handle={1}", +// rinfo.InternalEndPoint.Port, rinfo.RegionHandle); + result = rinfo; + break; + } + } + + return result; + } + + private UDPServer SearchUDPServerFromPortNum(int portnum) + { + return udpServers.Find( delegate(UDPServer server) { return (portnum + proxyOffset == ((IPEndPoint) server.Server.LocalEndPoint).Port); }); + } + + private void SerializeRegion(RegionInfo src_region, string export_dir) + { + Scene scene = null; + List presences; + string filename; + int i = 0; + + // try to get the scene object + if (sceneManager.TryGetScene(src_region.RegionID, out scene) == false) + { + m_log.Error("[BALANCER] "+"The Scene is not found"); + return; + } + + // create export directory + DirectoryInfo dirinfo = new DirectoryInfo(export_dir); + if (!dirinfo.Exists) + { + dirinfo.Create(); + } + + // serialization of client's informations + presences = scene.GetScenePresences(); + + foreach (ScenePresence pre in presences) + { + SerializeClient(i, scene, pre, export_dir); + i++; + } + + // serialization of region data + SearializableRegionInfo dst_region = new SearializableRegionInfo(src_region); + + filename = export_dir + "RegionInfo_" + src_region.RegionID.ToString() + ".bin"; + Util.SerializeToFile(filename, dst_region); + + // backup current scene's entities + //scene.Backup(); + + m_log.InfoFormat("[BALANCER] "+"region serialization completed [{0}]", + src_region.RegionID.ToString()); + } + + private void SerializeClient(int idx, Scene scene, ScenePresence pre, string export_dir) + { + string filename; + IClientAPI controller = null; + + m_log.InfoFormat("[BALANCER] "+"agent id : {0}", pre.m_uuid); + + uint[] circuits = scene.ClientManager.GetAllCircuits(pre.m_uuid); + + foreach (uint code in circuits) + { + m_log.InfoFormat("[BALANCER] "+"circuit code : {0}", code); + + if (scene.ClientManager.TryGetClient(code, out controller)) + { + ClientInfo info = controller.GetClientInfo(); + + filename = export_dir + "ClientInfo-" + String.Format("{0:0000}", idx) + "_" + controller.CircuitCode.ToString() + ".bin"; + + Util.SerializeToFile(filename, info); + + m_log.InfoFormat("[BALANCER] "+"client info serialized [filename={0}]", filename); + } + } + + //filename = export_dir + "Presence_" + controller.AgentId.ToString() + ".bin"; + filename = export_dir + "Presence_" + String.Format("{0:0000}", idx) + ".bin"; + + Util.SerializeToFile(filename, pre); + + m_log.InfoFormat("[BALANCER] "+"scene presence serialized [filename={0}]", filename); + } + + private RegionInfo DeserializeRegion(int dst_port, bool move_flag, string import_dir) + { + string[] files = null; + RegionInfo dst_region = null; + + try + { + // deserialization of region data + files = Directory.GetFiles(import_dir, "RegionInfo_*.bin"); + + foreach (string filename in files) + { + m_log.InfoFormat("[BALANCER] RegionInfo filename = [{0}]", filename); + + dst_region = new RegionInfo((SearializableRegionInfo)Util.DeserializeFromFile(filename)); + + m_log.InfoFormat("[BALANCER] "+"RegionID = [{0}]", dst_region.RegionID.ToString()); + m_log.InfoFormat("[BALANCER] "+"RegionHandle = [{0}]", dst_region.RegionHandle); + m_log.InfoFormat("[BALANCER] "+"ProxyUrl = [{0}]", dst_region.proxyUrl); + m_log.InfoFormat("[BALANCER] "+"OriginRegionID = [{0}]", dst_region.originRegionID.ToString()); + + CreateCloneRegion(dst_region, dst_port, true); + + File.Delete(filename); + + m_log.InfoFormat("[BALANCER] "+"region deserialized [{0}]", dst_region.RegionID); + } + + // deserialization of client data + DeserializeClient(dst_region, import_dir); + + m_log.InfoFormat("[BALANCER] "+"region deserialization completed [{0}]", + dst_region.ToString()); + } + catch (Exception e) + { + m_log.Error("[BALANCER] "+e.ToString()); + m_log.Error("[BALANCER] "+e.StackTrace); + throw e; + } + + return dst_region; + } + + private void DeserializeClient(RegionInfo dst_region, string import_dir) + { + ScenePresence sp = null; + ClientInfo data = null; + Scene scene = null; + string[] files = null; + IClientAPI controller = null; + UDPServer udpserv = null; + + if (sceneManager.TryGetScene(dst_region.RegionID, out scene)) + { + // search udpserver + udpserv = SearchUDPServerFromPortNum(scene.RegionInfo.InternalEndPoint.Port); + + // restore the scene presence +/* + files = Directory.GetFiles(import_dir, "Presence_*.bin"); + Array.Sort(files); + + foreach (string filename in files) + { + sp = (ScenePresence)Util.DeserializeFromFile(filename); + Console.WriteLine("agent id = {0}", sp.m_uuid); + + scene.m_restorePresences.Add(sp.m_uuid, sp); + File.Delete(filename); + + m_log.InfoFormat("[BALANCER] "+"scene presence deserialized [{0}]", sp.m_uuid); + } +*/ + for (int i = 0; ; i++) + { + string filename = import_dir + "Presence_" + String.Format("{0:0000}", i) + ".bin"; + + if (!File.Exists(filename)) + { + break; + } + + sp = (ScenePresence)Util.DeserializeFromFile(filename); + Console.WriteLine("agent id = {0}", sp.m_uuid); + + scene.m_restorePresences.Add(sp.m_uuid, sp); + File.Delete(filename); + + m_log.InfoFormat("[BALANCER] " + "scene presence deserialized [{0}]", sp.m_uuid); + + // restore the ClientView + + files = Directory.GetFiles(import_dir, "ClientInfo-" + String.Format("{0:0000}", i) + "_*.bin"); + + foreach (string fname in files) + { + int start = fname.IndexOf('_'); + int end = fname.LastIndexOf('.'); + uint circuit_code = uint.Parse(fname.Substring(start + 1, end - start - 1)); + m_log.InfoFormat("[BALANCER] " + "client circuit code = {0}", circuit_code); + + data = (ClientInfo)Util.DeserializeFromFile(fname); + + AgentCircuitData agentdata = new AgentCircuitData(data.agentcircuit); + scene.AuthenticateHandler.AddNewCircuit(circuit_code, agentdata); + + udpserv.RestoreClient(agentdata, data.userEP, data.proxyEP); + + // waiting for the scene-presense restored + lock (scene.m_restorePresences) + { + Monitor.Wait(scene.m_restorePresences, 3000); + } + + if (scene.ClientManager.TryGetClient(circuit_code, out controller)) + { + m_log.InfoFormat("[BALANCER] " + "get client [{0}]", circuit_code); + controller.SetClientInfo(data); + } + + File.Delete(fname); + + m_log.InfoFormat("[BALANCER] " + "client info deserialized [{0}]", circuit_code); + } + + // backup new scene's entities + //scene.Backup(); + } + } + } + + private void CreateCloneRegion(RegionInfo dst_region, int dst_port, bool createID_flag) + { + if (createID_flag) + { + dst_region.RegionID = LLUUID.Random(); + } + + // change RegionInfo (memory only) + dst_region.InternalEndPoint.Port = dst_port; + dst_region.ExternalHostName = proxyURL.Split(new char[] { '/', ':' })[3]; + + // Create new region + simMain.CreateRegion(dst_region, false); + } + + private void RemoveRegion(LLUUID regionID, int port) + { + Scene killScene; + if (sceneManager.TryGetScene(regionID, out killScene)) + { + Console.WriteLine("scene found."); + + if ((sceneManager.CurrentScene != null) + && (sceneManager.CurrentScene.RegionInfo.RegionID == killScene.RegionInfo.RegionID)) + { + sceneManager.TrySetCurrentScene(".."); + } + + m_log.Info("Removing region : " + killScene.RegionInfo.RegionName); + regionData.Remove(killScene.RegionInfo); + sceneManager.CloseScene(killScene); + } + + // Shutting down the UDP server + UDPServer udpsvr = SearchUDPServerFromPortNum(port); + + if (udpsvr != null) + { + udpsvr.Server.Close(); + udpServers.Remove(udpsvr); + } + } + + private void RemoveAllClientResource(RegionInfo src_region) + { + Scene scene = null; + List presences; + IClientAPI controller = null; + + // try to get the scene object + if (sceneManager.TryGetScene(src_region.RegionID, out scene) == false) + { + m_log.Error("[BALANCER] "+"The Scene is not found"); + return; + } + + // serialization of client's informations + presences = scene.GetScenePresences(); + + // remove all scene presences + foreach (ScenePresence pre in presences) + { + uint[] circuits = scene.ClientManager.GetAllCircuits(pre.m_uuid); + + foreach (uint code in circuits) + { + m_log.InfoFormat("[BALANCER] "+"circuit code : {0}", code); + + if (scene.ClientManager.TryGetClient(code, out controller)) + { + // stopping clientview thread + if (((ClientView)controller).PacketProcessingEnabled) + { + controller.Stop(); + ((ClientView)controller).PacketProcessingEnabled = false; + } + // teminateing clientview thread + controller.Terminate(); + m_log.Info("[BALANCER] "+"client thread stopped"); + } + } + + // remove scene presence + scene.RemoveClient(pre.m_uuid); + } + } + + /* + * This section implements scene splitting and synchronization + */ + + private bool[] isLocalNeighbour; + private string[] sceneURL; + private int[] regionPortList; + private TcpClient[] tcpClientList; + private bool isSplit = false; + + private XmlRpcResponse SplitRegion(XmlRpcRequest request) + { + try + { + int myID = (int) request.Params[0]; + int numRegions = (int) request.Params[1]; + regionPortList = new int[numRegions]; + sceneURL = new string[numRegions]; + tcpClientList = new TcpClient[numRegions]; + + for(int i=0; i presences = scene.GetScenePresences(); +presences.Sort(); + foreach (ScenePresence pre in presences) + { + // Divide the presences evenly over the set of subscenes + ClientView client = (ClientView) pre.ControllingClient; + client.PacketProcessingEnabled = (( (i + myID) % sceneURL.Length) == 0); + + m_log.InfoFormat("[SPLITSCENE] === SplitRegion {0}: SP.PacketEnabled {1}", region.RegionID, client.PacketProcessingEnabled); + + if (!client.PacketProcessingEnabled) + { + // stopping clientview thread + client.Stop(); + } + + ++i; + } + + scene.splitID = myID; + scene.SynchronizeScene = new Scene.SynchronizeSceneHandler(SynchronizeScenes); + isSplit = true; + } + else + { + m_log.Error("[SPLITSCENE] "+String.Format("Scene not found {0}", region.RegionID)); + } + } + catch (Exception e) + { + m_log.Error("[SPLITSCENE] "+e.ToString()); + m_log.Error("[SPLITSCENE] "+e.StackTrace); + } + + return new XmlRpcResponse(); + } + + private XmlRpcResponse MergeRegions(XmlRpcRequest request) + { + // This should only be called for the master scene + try + { + m_log.Info("[BALANCER] "+"Entering MergeRegions()"); + + string src_url = (string) request.Params[0]; + int src_port = (int) request.Params[1]; + + RegionInfo region = SearchRegionFromPortNum(src_port); + + simMain.ProxyCommand(region.proxyUrl, "BlockClientMessages", src_url, src_port + proxyOffset); + + Scene scene; + if (sceneManager.TryGetScene(region.RegionID, out scene)) + { + isSplit = false; + + scene.SynchronizeScene = null; + scene.Region_Status = RegionStatus.Up; + + List presences = scene.GetScenePresences(); + foreach (ScenePresence pre in presences) + { + ClientView client = (ClientView) pre.ControllingClient; + if (!client.PacketProcessingEnabled) + { + client.Restart(); + client.PacketProcessingEnabled = true; + } + } + } + + // Delete the slave scenes + for(int i=1; i presences = scene.GetScenePresences(); + foreach (ScenePresence pre in presences) + { + ClientView client = (ClientView) pre.ControllingClient; + + // Because data changes by the physics simulation when the client doesn't move, + // if MovementFlag is false, It is necessary to synchronize. + //if(pre.MovementFlag!=0 && client.PacketProcessingEnabled==true) + if(client.PacketProcessingEnabled==true) + { + //m_log.Info("[SPLITSCENE] "+String.Format("Client moving in {0} {1}", scene.RegionInfo.RegionID, pre.AbsolutePosition)); + + for (int i = 0; i < sceneURL.Length; i++) + { + if (i == scene.splitID) + { + continue; + } + + if(isLocalNeighbour[i]) + { + //m_log.Info("[SPLITSCENE] "+"Synchronize ScenePresence (Local) [region:{0}=>{1}, client:{2}]", + // scene.RegionInfo.RegionID, regionPortList[i], pre.UUID.ToString()); + LocalUpdatePhysics(regionPortList[i], pre.UUID, pre.AbsolutePosition, pre.Velocity, pre.PhysicsActor.Flying); + } + else + { + //m_log.Info("[SPLITSCENE] "+"Synchronize ScenePresence (Remote) [region port:{0}, client:{1}, position:{2}, velocity:{3}, flying:{4}]", + // regionPortList[i], pre.UUID.ToString(), pre.AbsolutePosition.ToString(), + // pre.Velocity.ToString(), pre.PhysicsActor.Flying); + + + simMain.XmlRpcCommand(sceneURL[i], "UpdatePhysics", + regionPortList[i], pre.UUID.GetBytes(), + pre.AbsolutePosition.GetBytes(), pre.Velocity.GetBytes(), + pre.PhysicsActor.Flying); + +/* + byte[] buff = new byte[12+12+1]; + + Buffer.BlockCopy(pre.AbsolutePosition.GetBytes(), 0, buff, 0, 12); + Buffer.BlockCopy(pre.Velocity.GetBytes(), 0, buff, 12, 12); + buff[24] = (byte)((pre.PhysicsActor.Flying)?1:0); + + // create header + InternalPacketHeader header = new InternalPacketHeader(); + + header.type = 1; + header.throttlePacketType = 0; + header.numbytes = buff.Length; + header.agent_id = pre.UUID.UUID; + header.region_port = regionPortList[i]; + + //Send + tcpClientList[i].send(header, buff); +*/ + } + } + } +// ++i; + } + } + } + + public bool SynchronizePackets(IScene scene, Packet packet, LLUUID agentID, ThrottleOutPacketType throttlePacketType) + { + if (!isSplit) + { + return false; + } + + Scene localScene = (Scene)scene; + + for (int i = 0; i < sceneURL.Length; i++) + { + if (i == localScene.splitID) + { + continue; + } + + if(isLocalNeighbour[i]) + { + //m_log.Info("[SPLITSCENE] "+"Synchronize Packet (Local) [type:{0}, client:{1}]", + // packet.Type.ToString(), agentID.ToString()); + LocalUpdatePacket(regionPortList[i], agentID, packet, throttlePacketType); + } + else + { + //m_log.Info("[SPLITSCENE] "+"Synchronize Packet (Remote) [type:{0}, client:{1}]", + // packet.Type.ToString(), agentID.ToString()); + // to bytes + byte[] buff = packet.ToBytes(); + + // create header + InternalPacketHeader header = new InternalPacketHeader(); + + header.type = 0; + header.throttlePacketType = (int)throttlePacketType; + header.numbytes = buff.Length; + header.agent_id = agentID.UUID; + header.region_port = regionPortList[i]; + + //Send + tcpClientList[i].send(header, buff); + + PacketPool.Instance.ReturnPacket(packet); + } + } + + return true; + } + + private void LocalUpdatePacket(int regionPort, LLUUID agentID, Packet packet, ThrottleOutPacketType throttlePacketType) + { + Scene scene; + + RegionInfo region = SearchRegionFromPortNum(regionPort); + +// m_log.Info("[SPLITSCENE] "+"LocalUpdatePacket [region port:{0}, client:{1}, packet type:{2}]", +// regionPort, agentID.ToString(), packet.GetType().ToString()); + + if (sceneManager.TryGetScene(region.RegionID, out scene)) + { + ScenePresence pre = scene.GetScenePresences().Find(delegate(ScenePresence x) { return x.UUID == agentID; }); + + if (pre == null) + { + m_log.ErrorFormat("[SPLITSCENE] [LocalUpdatePacket] ScenePresence is missing... ({0})", agentID.ToString()); + return; + } + + if (((ClientView)pre.ControllingClient).PacketProcessingEnabled==true) + { + pre.ControllingClient.OutPacket(packet, throttlePacketType); + } + else + { + PacketPool.Instance.ReturnPacket(packet); + } + } + } + + public void SynchronizePacketRecieve(InternalPacketHeader header, byte[] buff) + { +// m_log.Info("[SPLITSCENE] "+"entering SynchronizePacketRecieve[type={0}]", header.type); + + if (!isSplit) + { + return; + } + + switch (header.type) + { + case 0: + + Packet packet = null; + byte[] zero = new byte[3000]; + int packetEnd = 0; + + // deserialize packet + packetEnd = buff.Length - 1; +// packetEnd = buff.Length; + + try + { + //m_log.Info("[SPLITSCENE] "+"PacketPool.Instance : {0}", (PacketPool.Instance == null)?"null":"not null"); + //m_log.Info("[SPLITSCENE] "+"buff length={0}", buff.Length); + + packet = PacketPool.Instance.GetPacket(buff, ref packetEnd, zero); + + LocalUpdatePacket(header.region_port, new LLUUID(header.agent_id), + packet, (ThrottleOutPacketType)header.throttlePacketType); + } + catch (Exception e) + { + m_log.Error("[SPLITSCENE] "+e.ToString()); + m_log.Error("[SPLITSCENE] "+e.StackTrace); + } + + break; + + case 1: + + int regionPort = header.region_port; + LLUUID scenePresenceID = new LLUUID(header.agent_id); + LLVector3 position = new LLVector3(buff, 0); + LLVector3 velocity = new LLVector3(buff, 12); + bool flying = ((buff[24] == (byte)1)?true:false); + + LocalUpdatePhysics(regionPort, scenePresenceID, position, velocity, flying); + + break; + + default: + m_log.Info("[SPLITSCENE] "+"Invalid type"); + break; + } + +// m_log.Info("[SPLITSCENE] "+"exiting SynchronizePacketRecieve"); + } + } +} diff --git a/ThirdParty/3Di/LoadBalancer/TcpClient.cs b/ThirdParty/3Di/LoadBalancer/TcpClient.cs new file mode 100644 index 0000000..9f62d33 --- /dev/null +++ b/ThirdParty/3Di/LoadBalancer/TcpClient.cs @@ -0,0 +1,240 @@ +/* +* Copyright (c) Contributors, http://opensimulator.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Threading; +using System.Text; +using System.Runtime.Serialization.Formatters.Binary; + +namespace OpenSim.ApplicationPlugins.LoadBalancer { + public class AsynchronousClient { + private static ManualResetEvent connectDone = new ManualResetEvent(false); + private static ManualResetEvent sendDone = new ManualResetEvent(false); + private static ManualResetEvent receiveDone = new ManualResetEvent(false); + private static String response = String.Empty; + + public static Socket StartClient(string hostname, int port) { + try { + IPHostEntry ipHostInfo = Dns.GetHostEntry(hostname); + IPAddress ipAddress = ipHostInfo.AddressList[0]; + IPEndPoint remoteEP = new IPEndPoint(ipAddress, port); + + Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + client.BeginConnect( remoteEP, new AsyncCallback(ConnectCallback), client); + connectDone.WaitOne(); + /* + Send(client,"This is a test"); + sendDone.WaitOne(); + Receive(client); + receiveDone.WaitOne(); + client.Shutdown(SocketShutdown.Both); + client.Close(); + */ + return client; + } catch (Exception e) { + Console.WriteLine(e.ToString()); + throw new Exception("socket error !!"); + } + } + + private static void ConnectCallback(IAsyncResult ar) { + try { + Socket client = (Socket) ar.AsyncState; + client.EndConnect(ar); + Console.WriteLine("Socket connected to {0}", client.RemoteEndPoint.ToString()); + connectDone.Set(); + } catch (Exception e) { + Console.WriteLine(e.ToString()); + } + } + +/* + public static void Receive(Socket client) { + try { + StateObject state = new StateObject(); + state.workSocket = client; + client.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReceiveCallback), state); + } catch (Exception e) { + Console.WriteLine(e.ToString()); + } + } + + private static void ReceiveCallback( IAsyncResult ar ) { + try { + StateObject state = (StateObject) ar.AsyncState; + Socket client = state.workSocket; + + int bytesRead = client.EndReceive(ar); + if (bytesRead > 0) { + state.sb.Append(Encoding.ASCII.GetString(state.buffer,0,bytesRead)); + client.BeginReceive(state.buffer,0,StateObject.BufferSize,0, new AsyncCallback(ReceiveCallback), state); + } else { + if (state.sb.Length > 1) { + response = state.sb.ToString(); + } + receiveDone.Set(); + } + } catch (Exception e) { + Console.WriteLine(e.ToString()); + } + } +*/ + public static void Send(Socket client, byte[] byteData) { + client.BeginSend(byteData, 0, byteData.Length, 0, new AsyncCallback(SendCallback), client); + } + + private static void SendCallback(IAsyncResult ar) { + try { + Socket client = (Socket) ar.AsyncState; + int bytesSent = client.EndSend(ar); + //Console.WriteLine("Sent {0} bytes to server.", bytesSent); + sendDone.Set(); + } catch (Exception e) { + Console.WriteLine(e.ToString()); + } + } + } + +public class InternalPacketHeader +{ + private byte[] buffer = new byte[32]; + public int type; + public int throttlePacketType; + public int numbytes; + public Guid agent_id; + public int region_port; + + public void FromBytes(byte[] bytes) + { + int i = 0; // offset + try + { + this.type = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24)); + this.throttlePacketType = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24)); + this.numbytes = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24)); + this.agent_id = new Guid( + bytes[i++] | (bytes[i++] << 8) | (bytes[i++] << 16) | bytes[i++] << 24, + (short)(bytes[i++] | (bytes[i++] << 8)), + (short)(bytes[i++] | (bytes[i++] << 8)), + bytes[i++], bytes[i++], bytes[i++], bytes[i++], + bytes[i++], bytes[i++], bytes[i++], bytes[i++]); + this.region_port = (int)(bytes[i++] + (bytes[i++] << 8) + (bytes[i++] << 16) + (bytes[i++] << 24)); + } + catch (Exception) + { + throw new Exception("bad format!!!"); + } + } + + public byte[] ToBytes() + { + int i = 0; + this.buffer[i++] = (byte)(this.type % 256); + this.buffer[i++] = (byte)((this.type >> 8) % 256); + this.buffer[i++] = (byte)((this.type >> 16) % 256); + this.buffer[i++] = (byte)((this.type >> 24) % 256); + + this.buffer[i++] = (byte)(this.throttlePacketType % 256); + this.buffer[i++] = (byte)((this.throttlePacketType >> 8) % 256); + this.buffer[i++] = (byte)((this.throttlePacketType >> 16) % 256); + this.buffer[i++] = (byte)((this.throttlePacketType >> 24) % 256); + + this.buffer[i++] = (byte)(this.numbytes % 256); + this.buffer[i++] = (byte)((this.numbytes >> 8) % 256); + this.buffer[i++] = (byte)((this.numbytes >> 16) % 256); + this.buffer[i++] = (byte)((this.numbytes >> 24) % 256); + + // no endian care + Buffer.BlockCopy(agent_id.ToByteArray(), 0, this.buffer, i, 16); i += 16; + + this.buffer[i++] = (byte)(this.region_port % 256); + this.buffer[i++] = (byte)((this.region_port >> 8) % 256); + this.buffer[i++] = (byte)((this.region_port >> 16) % 256); + this.buffer[i++] = (byte)((this.region_port >> 24) % 256); + + return this.buffer; + } +} + public class TcpClient { + + public static int internalPacketHeaderSize = 4*4 + 16*1; + + private string mHostname; + private int mPort; + private Socket mConnection; + public TcpClient(string hostname, int port) { + this.mHostname = hostname; + this.mPort = port; + this.mConnection = null; + } + public void connect() { + this.mConnection = AsynchronousClient.StartClient(mHostname, mPort); + } +/* + public void recevie() { + if (mConnection == null) { + throw new Exception("client not initialized"); + } + try + { + AsynchronousClient.Receive(this.mConnection); + } + catch (Exception e) + { + Console.WriteLine(e.ToString()); + mConnection = null; + } + } +*/ + public void send(InternalPacketHeader header, byte[] packet) { + + lock (this) + { + + if (mConnection == null) { +// throw new Exception("client not initialized"); + connect(); + } + + AsynchronousClient.Send(this.mConnection, header.ToBytes()); + +/* +for (int i = 0; i < 10; i++) +{ + Console.Write(packet[i] + " "); +} +Console.WriteLine(""); +*/ + AsynchronousClient.Send(this.mConnection, packet); + } + } + } +} diff --git a/ThirdParty/3Di/LoadBalancer/TcpServer.cs b/ThirdParty/3Di/LoadBalancer/TcpServer.cs new file mode 100644 index 0000000..ee8bcba --- /dev/null +++ b/ThirdParty/3Di/LoadBalancer/TcpServer.cs @@ -0,0 +1,219 @@ +/* +* Copyright (c) Contributors, http://opensimulator.org/ +* See CONTRIBUTORS.TXT for a full list of copyright holders. +* +* Redistribution and use in source and binary forms, with or without +* modification, are permitted provided that the following conditions are met: +* * Redistributions of source code must retain the above copyright +* notice, this list of conditions and the following disclaimer. +* * Redistributions in binary form must reproduce the above copyright +* notice, this list of conditions and the following disclaimer in the +* documentation and/or other materials provided with the distribution. +* * Neither the name of the OpenSim Project nor the +* names of its contributors may be used to endorse or promote products +* derived from this software without specific prior written permission. +* +* THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY +* EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +* DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY +* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +* LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +* +*/ + +using System; +using System.IO; +using System.Net; +using System.Net.Sockets; +using System.Text; +using System.Threading; +using System.Runtime.Serialization.Formatters.Binary; + +using OpenSim.Framework.Console; + +namespace OpenSim.ApplicationPlugins.LoadBalancer { + + public class StateObject { + public Socket workSocket = null; + public const int BufferSize = 2048; + public byte[] buffer = new byte[BufferSize]; + public MemoryStream ms_ptr = new MemoryStream(); + public InternalPacketHeader header = null; + } + + public class AsynchronousSocketListener { + public static string data = null; + public static ManualResetEvent allDone = new ManualResetEvent(false); + +#region KIRYU + public delegate void PacketRecieveHandler(InternalPacketHeader header, byte[] buff); + public static PacketRecieveHandler PacketHandler = null; +#endregion + + public AsynchronousSocketListener() { } + + public static void StartListening(int port) { + IPHostEntry ipHostInfo = Dns.GetHostEntry(Dns.GetHostName()); + IPAddress ipAddress = ipHostInfo.AddressList[0]; + IPEndPoint localEndPoint = new IPEndPoint(ipAddress, port); + + Socket listener = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp ); + try { + listener.Bind(localEndPoint); + listener.Listen(100); + while (true) { + allDone.Reset(); + listener.BeginAccept( new AsyncCallback(AcceptCallback), listener ); + allDone.WaitOne(); + } + } catch (Exception e) { + Console.WriteLine(e.ToString()); + } + /* + Console.WriteLine("\nPress ENTER to continue..."); + Console.Read(); + */ + } + + public static void AcceptCallback(IAsyncResult ar) { + allDone.Set(); + Socket listener = (Socket) ar.AsyncState; + Socket handler = listener.EndAccept(ar); + StateObject state = new StateObject(); + state.workSocket = handler; + handler.BeginReceive( state.buffer, 0, StateObject.BufferSize, 0, new AsyncCallback(ReadCallback), state); + } + + public static void ReadCallback(IAsyncResult ar) { + String content = String.Empty; + StateObject state = (StateObject) ar.AsyncState; + Socket handler = state.workSocket; + + try + { + + int bytesRead = handler.EndReceive(ar); + + //MainLog.Instance.Verbose("TCPSERVER", "Received packet [{0}]", bytesRead); + + if (bytesRead > 0) { + state.ms_ptr.Write(state.buffer, 0, bytesRead); + } + else + { + //MainLog.Instance.Verbose("TCPSERVER", "Connection terminated"); + return; + } + + long rest_size = state.ms_ptr.Length; + long current_pos = 0; + while (rest_size > TcpClient.internalPacketHeaderSize) { + + if ((state.header == null) && (rest_size >= TcpClient.internalPacketHeaderSize)) + { + //MainLog.Instance.Verbose("TCPSERVER", "Processing header"); + + // reading header + state.header = new InternalPacketHeader(); + + byte[] headerbytes = new byte[TcpClient.internalPacketHeaderSize]; + state.ms_ptr.Position = current_pos; + state.ms_ptr.Read(headerbytes, 0, TcpClient.internalPacketHeaderSize); + state.ms_ptr.Seek(0, SeekOrigin.End); + state.header.FromBytes(headerbytes); + } + + if ((state.header != null) && (rest_size >= state.header.numbytes + TcpClient.internalPacketHeaderSize)) + { + //MainLog.Instance.Verbose("TCPSERVER", "Processing body"); + + // reading body + byte[] packet = new byte[state.header.numbytes]; + state.ms_ptr.Position = current_pos + TcpClient.internalPacketHeaderSize; + state.ms_ptr.Read(packet, 0, state.header.numbytes); + +/* + for(int i=0; i + + + + +Region Monitor GUI, 3Di + + +HEADER +} + +sub screen_footer { + return << "FOOTER"; + + +FOOTER +} + +sub html { + my $grid_info = shift; + my $regions_list = $grid_info->{"sim-profiles"}; + $regions = undef; + foreach(@$regions_list) { + my $ip = $_->{sim_ip} || "UNKNOWN"; + my $port = $_->{sim_port} || "UNKNOWN"; + $regions->{$ip}->{$port} = $_; + if (!$regions->{max_port} || $regions->{max_port} < $port) { + $regions->{max_port} = $port; + } + } + @server_list = keys %$regions; + $max_port = $regions->{max_port}; + my $html = ""; + foreach my $machine (@server_list) { + next if ($machine eq "max_port"); + $html .= &_machine_view($machine, $regions->{$machine}); + } + return $html; +} + +sub _machine_view { + my ($ip, $info) = @_; + my $region_html = ""; + foreach my $region (keys %$info) { + $region_html .= &_region_html($info->{$region}); + } + my $html =<< "MACHINE_HTML"; +

$ip

+$region_html +
+MACHINE_HTML +} + +sub _region_html { + my $region_info = shift; + my $name = $region_info->{name} || "UNKNOWN"; + my $x = $region_info->{x} || -1; + my $y = $region_info->{y} || -1; + my $ip = $region_info->{sim_ip} || "UNKNOWN"; + my $port = $region_info->{sim_port} || "UNKNOWN"; + my $get_scene_presence_filter = $region_info->{get_scene_presence_filter}; + my $get_scene_presence = $region_info->{get_scene_presence}; + my $get_avatar_filter = $region_info->{get_avatar_filter}; + my $get_avatar = $region_info->{get_avatar}; + my $avatar_names = $region_info->{avatar_names}; + my $action_forms = &_action_forms($region_info); + my $html = <<"REGION_HTML"; +$name
+$ip:$port | X: $x Y: $y
+ + + + + + + + + + + + + + + + + + + + + +
get_avatar$get_avatar
get_avatar_filter$get_avatar_filter$avatar_names
get_scene_presence$get_scene_presence
get_scene_presence_filter$get_scene_presence_filter
+$action_forms +REGION_HTML + return $html; +} + +sub _action_forms { + my $region_info = shift; + my $ip = $region_info->{sim_ip}; + my $port = $region_info->{sim_port}; + my $default_input_port = $max_port + 1; + my $move_to_options = ""; + my $split_to_options = ""; + my $merge_ip_options = ""; + foreach(@server_list) { + next if ($_ eq "max_port"); + $merge_ip_options .= "