349 lines
13 KiB
C#
349 lines
13 KiB
C#
/*
|
|
* DynamORM - Dynamic Object-Relational Mapping library.
|
|
* Copyright (c) 2012-2026, Grzegorz Russek (grzegorz.russek@gmail.com)
|
|
* All rights reserved.
|
|
*
|
|
* 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.
|
|
*
|
|
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "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 COPYRIGHT HOLDER OR 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.Linq;
|
|
using System.Reflection;
|
|
using DynamORM.Mapper;
|
|
using DynamORM.Objects;
|
|
|
|
namespace DynamORM.Helpers
|
|
{
|
|
internal static class DynamicProcedureResultBinder
|
|
{
|
|
private sealed class ResultPropertyBinding
|
|
{
|
|
public ProcedureResultAttribute Attribute { get; set; }
|
|
public PropertyInfo Property { get; set; }
|
|
}
|
|
|
|
internal static bool IsProcedureContract(object item)
|
|
{
|
|
return item is IProcedureParameters;
|
|
}
|
|
|
|
internal static Type GetDeclaredResultType(object item)
|
|
{
|
|
if (item == null)
|
|
return null;
|
|
|
|
Type iface = item.GetType().GetInterfaces()
|
|
.FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IProcedureParameters<>));
|
|
|
|
return iface == null ? null : iface.GetGenericArguments()[0];
|
|
}
|
|
|
|
internal static bool HasDeclaredResultBinding(Type resultType)
|
|
{
|
|
return resultType != null &&
|
|
(typeof(IProcedureResultReader).IsAssignableFrom(resultType) || GetResultPropertyBindings(resultType).Count > 0);
|
|
}
|
|
|
|
internal static object CreateDeclaredResult(Type resultType)
|
|
{
|
|
if (resultType == null)
|
|
return null;
|
|
|
|
DynamicTypeMap mapper = DynamicMapperCache.GetMapper(resultType);
|
|
if (mapper != null)
|
|
return mapper.Creator();
|
|
|
|
return Activator.CreateInstance(resultType);
|
|
}
|
|
|
|
internal static object ReadDeclaredResult(Type resultType, IDataReader reader)
|
|
{
|
|
if (!HasDeclaredResultBinding(resultType))
|
|
throw new InvalidOperationException(string.Format("Type '{0}' does not declare a supported procedure result binding.", resultType == null ? "<null>" : resultType.FullName));
|
|
|
|
object instance = CreateDeclaredResult(resultType);
|
|
|
|
IList<ResultPropertyBinding> bindings = GetResultPropertyBindings(resultType);
|
|
if (bindings.Count > 0)
|
|
BindResultProperties(instance, reader, bindings);
|
|
else
|
|
((IProcedureResultReader)instance).ReadResults(reader);
|
|
|
|
return instance;
|
|
}
|
|
|
|
internal static object BindPayload(Type resultType, string mainResultName, object mainResult, IDictionary<string, object> returnValues, object existing = null)
|
|
{
|
|
if (resultType == null)
|
|
return existing ?? returnValues.ToDynamic();
|
|
|
|
Dictionary<string, object> payload = new Dictionary<string, object>();
|
|
|
|
if (mainResultName != null)
|
|
payload[mainResultName] = mainResult == DBNull.Value ? null : mainResult;
|
|
|
|
if (returnValues != null)
|
|
foreach (KeyValuePair<string, object> item in returnValues)
|
|
payload[item.Key] = item.Value == DBNull.Value ? null : item.Value;
|
|
|
|
DynamicTypeMap mapper = DynamicMapperCache.GetMapper(resultType);
|
|
if (mapper != null)
|
|
return mapper.Map(payload.ToDynamic(), existing ?? mapper.Creator());
|
|
|
|
if (existing != null)
|
|
return existing;
|
|
|
|
return payload.ToDynamic();
|
|
}
|
|
|
|
private static IList<ResultPropertyBinding> GetResultPropertyBindings(Type resultType)
|
|
{
|
|
return resultType.GetProperties(BindingFlags.Instance | BindingFlags.Public)
|
|
.Where(x => x.CanWrite && x.GetIndexParameters().Length == 0)
|
|
.Select(x => new ResultPropertyBinding
|
|
{
|
|
Property = x,
|
|
Attribute = x.GetCustomAttributes(typeof(ProcedureResultAttribute), true).Cast<ProcedureResultAttribute>().FirstOrDefault()
|
|
})
|
|
.Where(x => x.Attribute != null)
|
|
.OrderBy(x => x.Attribute.ResultIndex)
|
|
.ThenBy(x => x.Property.MetadataToken)
|
|
.ToList();
|
|
}
|
|
|
|
private static void BindResultProperties(object instance, IDataReader reader, IList<ResultPropertyBinding> bindings)
|
|
{
|
|
ValidateBindings(instance.GetType(), bindings);
|
|
|
|
int currentIndex = 0;
|
|
bool hasCurrent = true;
|
|
|
|
for (int i = 0; i < bindings.Count; i++)
|
|
{
|
|
ResultPropertyBinding binding = bindings[i];
|
|
while (hasCurrent && currentIndex < binding.Attribute.ResultIndex)
|
|
{
|
|
hasCurrent = reader.NextResult();
|
|
currentIndex++;
|
|
}
|
|
|
|
if (!hasCurrent || currentIndex != binding.Attribute.ResultIndex)
|
|
break;
|
|
|
|
object value = ReadResultValue(binding.Property.PropertyType, binding.Attribute, reader);
|
|
binding.Property.SetValue(instance, value, null);
|
|
|
|
if (i + 1 < bindings.Count)
|
|
{
|
|
hasCurrent = reader.NextResult();
|
|
currentIndex++;
|
|
}
|
|
}
|
|
}
|
|
|
|
private static void ValidateBindings(Type resultType, IList<ResultPropertyBinding> bindings)
|
|
{
|
|
var duplicates = bindings.GroupBy(x => x.Attribute.ResultIndex).FirstOrDefault(x => x.Count() > 1);
|
|
if (duplicates != null)
|
|
throw new InvalidOperationException(string.Format("Type '{0}' defines multiple ProcedureResultAttribute bindings for result index {1}.", resultType.FullName, duplicates.Key));
|
|
}
|
|
|
|
private static object ReadResultValue(Type propertyType, ProcedureResultAttribute attr, IDataReader reader)
|
|
{
|
|
Type elementType;
|
|
|
|
if (propertyType == typeof(DataTable))
|
|
return reader.ToDataTable(string.IsNullOrEmpty(attr.Name) ? null : attr.Name);
|
|
|
|
if (TryGetEnumerableElementType(propertyType, out elementType))
|
|
{
|
|
if (elementType == typeof(object))
|
|
return reader.EnumerateReader().ToList();
|
|
|
|
if (elementType.IsValueType || elementType == typeof(string) || elementType == typeof(Guid))
|
|
return ReadSimpleList(propertyType, elementType, attr, reader);
|
|
|
|
return ReadComplexList(propertyType, elementType, reader);
|
|
}
|
|
|
|
if (propertyType.IsValueType || propertyType == typeof(string) || propertyType == typeof(Guid))
|
|
return ReadSimpleValue(propertyType, attr, reader);
|
|
|
|
return ReadComplexValue(propertyType, reader);
|
|
}
|
|
|
|
private static object ReadSimpleValue(Type propertyType, ProcedureResultAttribute attr, IDataReader reader)
|
|
{
|
|
object value = null;
|
|
int ordinal = -1;
|
|
bool haveRow = false;
|
|
|
|
while (reader.Read())
|
|
{
|
|
if (!haveRow)
|
|
{
|
|
ordinal = GetOrdinal(reader, attr);
|
|
value = reader.IsDBNull(ordinal) ? null : reader[ordinal];
|
|
haveRow = true;
|
|
}
|
|
}
|
|
|
|
if (!haveRow || value == null)
|
|
return propertyType.GetDefaultValue();
|
|
|
|
if (propertyType == typeof(Guid))
|
|
{
|
|
Guid g;
|
|
if (Guid.TryParse(value.ToString(), out g))
|
|
return g;
|
|
return propertyType.GetDefaultValue();
|
|
}
|
|
|
|
return propertyType.CastObject(value);
|
|
}
|
|
|
|
private static object ReadSimpleList(Type propertyType, Type elementType, ProcedureResultAttribute attr, IDataReader reader)
|
|
{
|
|
Type listType = typeof(List<>).MakeGenericType(elementType);
|
|
var list = (System.Collections.IList)Activator.CreateInstance(listType);
|
|
int ordinal = -1;
|
|
bool initialized = false;
|
|
|
|
while (reader.Read())
|
|
{
|
|
if (!initialized)
|
|
{
|
|
ordinal = GetOrdinal(reader, attr);
|
|
initialized = true;
|
|
}
|
|
|
|
if (reader.IsDBNull(ordinal))
|
|
{
|
|
list.Add(elementType.GetDefaultValue());
|
|
continue;
|
|
}
|
|
|
|
object value = reader[ordinal];
|
|
if (elementType == typeof(Guid))
|
|
{
|
|
Guid g;
|
|
list.Add(Guid.TryParse(value.ToString(), out g) ? (object)g : elementType.GetDefaultValue());
|
|
}
|
|
else
|
|
list.Add(elementType.CastObject(value));
|
|
}
|
|
|
|
if (propertyType.IsArray)
|
|
{
|
|
Array array = Array.CreateInstance(elementType, list.Count);
|
|
list.CopyTo(array, 0);
|
|
return array;
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
private static object ReadComplexValue(Type propertyType, IDataReader reader)
|
|
{
|
|
object value = null;
|
|
bool haveRow = false;
|
|
|
|
while (reader.Read())
|
|
{
|
|
if (!haveRow)
|
|
{
|
|
value = (reader.RowToDynamic() as object).Map(propertyType);
|
|
haveRow = true;
|
|
}
|
|
}
|
|
|
|
return value;
|
|
}
|
|
|
|
private static object ReadComplexList(Type propertyType, Type elementType, IDataReader reader)
|
|
{
|
|
Type listType = typeof(List<>).MakeGenericType(elementType);
|
|
var list = (System.Collections.IList)Activator.CreateInstance(listType);
|
|
|
|
while (reader.Read())
|
|
list.Add((reader.RowToDynamic() as object).Map(elementType));
|
|
|
|
if (propertyType.IsArray)
|
|
{
|
|
Array array = Array.CreateInstance(elementType, list.Count);
|
|
list.CopyTo(array, 0);
|
|
return array;
|
|
}
|
|
|
|
return list;
|
|
}
|
|
|
|
private static bool TryGetEnumerableElementType(Type type, out Type elementType)
|
|
{
|
|
elementType = null;
|
|
|
|
if (type == typeof(string) || type == typeof(byte[]))
|
|
return false;
|
|
|
|
if (type.IsArray)
|
|
{
|
|
elementType = type.GetElementType();
|
|
return true;
|
|
}
|
|
|
|
if (type.IsGenericType)
|
|
{
|
|
Type generic = type.GetGenericTypeDefinition();
|
|
if (generic == typeof(List<>) || generic == typeof(IList<>) || generic == typeof(IEnumerable<>))
|
|
{
|
|
elementType = type.GetGenericArguments()[0];
|
|
return true;
|
|
}
|
|
}
|
|
|
|
Type enumerableInterface = type.GetInterfaces().FirstOrDefault(x => x.IsGenericType && x.GetGenericTypeDefinition() == typeof(IEnumerable<>));
|
|
if (enumerableInterface != null)
|
|
{
|
|
elementType = enumerableInterface.GetGenericArguments()[0];
|
|
return true;
|
|
}
|
|
|
|
return false;
|
|
}
|
|
|
|
private static int GetOrdinal(IDataReader reader, ProcedureResultAttribute attr)
|
|
{
|
|
if (attr == null || string.IsNullOrEmpty(attr.ColumnName))
|
|
return 0;
|
|
|
|
int ordinal = reader.GetOrdinal(attr.ColumnName);
|
|
if (ordinal < 0)
|
|
throw new IndexOutOfRangeException(attr.ColumnName);
|
|
|
|
return ordinal;
|
|
}
|
|
}
|
|
}
|