Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Шмаков Данил #186

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 11 additions & 15 deletions ObjectPrinting/Helper.cs
Original file line number Diff line number Diff line change
Expand Up @@ -6,29 +6,25 @@ namespace ObjectPrinting
{
public static class Helper
{
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(Expression<Func<TSource, TProperty>> propertyLambda)
public static PropertyInfo GetPropertyInfo<TSource, TProperty>(
Expression<Func<TSource, TProperty>> propertyLambda)
{
if (!(propertyLambda.Body is MemberExpression member))
if (propertyLambda.Body is not MemberExpression member)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a method, not a property.",
propertyLambda.ToString()));
throw new ArgumentException($"Expression '{propertyLambda}' refers to a method, not a property.");
}

if (!(member.Member is PropertyInfo propInfo))
if (member.Member is not PropertyInfo propInfo)
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a field, not a property.",
propertyLambda.ToString()));
throw new ArgumentException($"Expression '{propertyLambda}' refers to a field, not a property.");
}

Type type = typeof(TSource);
if (propInfo.ReflectedType != null && type != propInfo.ReflectedType && !type.IsSubclassOf(propInfo.ReflectedType))
var type = typeof(TSource);
if (propInfo.ReflectedType != null && type != propInfo.ReflectedType &&
!type.IsSubclassOf(propInfo.ReflectedType))
{
throw new ArgumentException(string.Format(
"Expression '{0}' refers to a property that is not from type {1}.",
propertyLambda.ToString(),
type));
throw new ArgumentException(
$"Expression '{propertyLambda}' refers to a property that is not from type {type}.");
}

return propInfo;
Expand Down
6 changes: 1 addition & 5 deletions ObjectPrinting/ObjectPrinting.csproj
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<LangVersion>8</LangVersion>
<LangVersion>latest</LangVersion>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AppendTargetFrameworkToOutputPath>false</AppendTargetFrameworkToOutputPath>
</PropertyGroup>
Expand All @@ -12,8 +12,4 @@
<PackageReference Include="NUnit" Version="3.12.0" />
</ItemGroup>

<ItemGroup>
<Folder Include="Tests\" />
</ItemGroup>

</Project>
295 changes: 147 additions & 148 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -5,170 +5,169 @@
using System.Linq.Expressions;
using System.Reflection;
using System.Text;
using NUnit.Framework;

namespace ObjectPrinting
{
public class PrintingConfig<TOwner> :
IBaseConfig<TOwner>
{
private readonly Type[] finalTypes = new[]
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan), typeof(Guid)
};
public class PrintingConfig<TOwner> :
IBaseConfig<TOwner>
{
private readonly Type[] finalTypes = new[]
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan), typeof(Guid)
};

private readonly HashSet<object> objects;

private List<Type> excludedTypes;
private List<PropertyInfo> excludedProperties;
private readonly List<Type> excludedTypes;
private readonly List<PropertyInfo> excludedProperties;

private Dictionary<Type, Func<object, string>> serializedByType;
private Dictionary<PropertyInfo, Func<object, string>> serializedByPropertyInfo;
private readonly Dictionary<Type, Func<object, string>> serializedByType;
private readonly Dictionary<PropertyInfo, Func<object, string>> serializedByPropertyInfo;

public PrintingConfig()
{
public PrintingConfig()
{
objects = new HashSet<object>();
excludedTypes = new List<Type>();
excludedProperties = new List<PropertyInfo>();
serializedByType = new Dictionary<Type, Func<object, string>>();
serializedByPropertyInfo = new Dictionary<PropertyInfo, Func<object, string>>();
}
excludedProperties = new List<PropertyInfo>();
serializedByType = new Dictionary<Type, Func<object, string>>();
serializedByPropertyInfo = new Dictionary<PropertyInfo, Func<object, string>>();
}

public string PrintToString(TOwner obj)
{
return PrintToString(obj, 0);
}
public string PrintToString(TOwner obj)
{
objects.Clear();
return PrintToString(obj, 0);
}

private string PrintToString(object obj, int nestingLevel)
{
//TODO apply configurations
if (obj == null)
return "null" + Environment.NewLine;
private string PrintToString(object obj, int nestingLevel)
{
if (obj == null)
return "null" + Environment.NewLine;

if (finalTypes.Contains(obj.GetType()))
return obj + Environment.NewLine;
if (finalTypes.Contains(obj.GetType()))
return obj + Environment.NewLine;

if (objects.Contains(obj))
return "cycled" + Environment.NewLine;
objects.Add(obj);

var identation = new string('\t', nestingLevel + 1);
var sb = new StringBuilder();
var type = obj.GetType();
sb.AppendLine(type.Name);
foreach (var propertyInfo in type.GetProperties())
{
var propType = propertyInfo.PropertyType;
if (excludedProperties.Contains(propertyInfo) || excludedTypes.Contains(propType))
continue;

if (serializedByPropertyInfo.ContainsKey(propertyInfo))
{
var serializedValue = serializedByPropertyInfo[propertyInfo](propertyInfo.GetValue(obj));
sb.Append(identation + propertyInfo.Name + " = " + serializedValue);
continue;
}

if (serializedByType.ContainsKey(propType))
{
var serializedValue = serializedByType[propType](propertyInfo.GetValue(obj));
sb.Append(identation + propertyInfo.Name + " = " + serializedValue);
continue;
}

if (propType.BaseType == typeof(Array) || propType.GetInterfaces().Contains(typeof(IList)))
{
sb.Append(identation + propertyInfo.Name + ": ");
sb.Append(SerializeListElements(propertyInfo.GetValue(obj), nestingLevel + 1));
continue;
}

if (propType.GetInterfaces().Contains(typeof(IDictionary)))
{
sb.Append(identation + propertyInfo.Name + ": ");
sb.Append(SerializeDictionaryElements(propertyInfo.GetValue(obj), nestingLevel + 1));
continue;
}

sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
}

return sb.ToString();
}

private string SerializeDictionaryElements(object obj, int nesting)
{
var sb = new StringBuilder();
var dictionary = obj as IDictionary;
var identation = new string('\t', nesting + 1);
if (dictionary == null || dictionary.Keys.Count == 0)
return "<empty>" + Environment.NewLine;
sb.Append(Environment.NewLine);
var index = 1;
foreach (var element in dictionary.Keys)
{
sb.AppendLine(identation + index++ + " element:");
sb.Append(identation + "\tKey: " + PrintToString(element, nesting + 2));
sb.Append(identation + "\tValue: " + PrintToString(dictionary[element], nesting + 2));
}

return sb.ToString();
}

private string SerializeListElements(object obj, int nesting)
{
var sb = new StringBuilder();
var list = obj as IEnumerable;
var identation = new string('\t', nesting + 1);
if (list == null || !list.Cast<object>().Any())
return "<empty>" + Environment.NewLine;
sb.Append(Environment.NewLine);
var index = 1;
foreach (var element in list)
{
sb.Append(identation + index++ + ": " + PrintToString(element, nesting + 1));
}

return sb.ToString();
}

public IBaseConfig<TOwner> Exclude<TArg>(Expression<Func<TOwner, TArg>> f)
{
var configuratedProperty = Helper.GetPropertyInfo(f);
excludedProperties.Add(configuratedProperty);
return this;
}

public IBaseConfig<TOwner> Exclude<T>()
{
excludedTypes.Add(typeof(T));
return this;
}

TypeConfig<TOwner, TArg> IBaseConfig<TOwner>.Printing<TArg>()
{
var configuratedType = typeof(TArg);
return new TypeConfig<TOwner, TArg>(this, configuratedType);
}

public PropertyConfig<TOwner, TArg> Printing<TArg>(Expression<Func<TOwner, TArg>> f)
{
var configuratedProperty = Helper.GetPropertyInfo(f);
return new PropertyConfig<TOwner, TArg>(this, configuratedProperty);
}

public void AddPropertySerialization<TProperty>(Func<TProperty, string> f, PropertyInfo configuratedProperty)
{
serializedByPropertyInfo.Add(configuratedProperty, obj => f((TProperty)obj));
}

public void AddTypeSerialization<TProperty>(Func<TProperty, string> f, Type configuratedType)
{
serializedByType.Add(configuratedType, obj => f((TProperty)obj));
}
}
var identation = new string('\t', nestingLevel + 1);
var sb = new StringBuilder();
var type = obj.GetType();
sb.AppendLine(type.Name);
foreach (var propertyInfo in type.GetProperties())
{
var propType = propertyInfo.PropertyType;

if (excludedProperties.Contains(propertyInfo) || excludedTypes.Contains(propType))
continue;

if (serializedByPropertyInfo.TryGetValue(propertyInfo, out var propertySerialization))
{
var serializedValue = propertySerialization(propertyInfo.GetValue(obj));
sb.Append(identation + propertyInfo.Name + " = " + serializedValue);
continue;
}

if (serializedByType.TryGetValue(propType, out var typeSerialization))
{
var serializedValue = typeSerialization(propertyInfo.GetValue(obj));
sb.Append(identation + propertyInfo.Name + " = " + serializedValue);
continue;
}

if (propType.GetInterfaces().Contains(typeof(IList)))
{
sb.Append(identation + propertyInfo.Name + ": ");
sb.Append(SerializeListElements(propertyInfo.GetValue(obj), nestingLevel + 1));
continue;
}

if (propType.GetInterfaces().Contains(typeof(IDictionary)))
{
sb.Append(identation + propertyInfo.Name + ": ");
sb.Append(SerializeDictionaryElements(propertyInfo.GetValue(obj), nestingLevel + 1));
continue;
}

sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
}

return sb.ToString();
}

private string SerializeDictionaryElements(object obj, int nesting)
{
var sb = new StringBuilder();
var dictionary = obj as IDictionary;
var identation = new string('\t', nesting + 1);
if (dictionary == null || dictionary.Keys.Count == 0)
return "<empty>" + Environment.NewLine;
sb.Append(Environment.NewLine);
var index = 0;
foreach (var element in dictionary.Keys)
{
sb.AppendLine(identation + index++ + " element:");
sb.Append(identation + "\tKey: " + PrintToString(element, nesting + 2));
sb.Append(identation + "\tValue: " + PrintToString(dictionary[element], nesting + 2));
}

return sb.ToString();
}

private string SerializeListElements(object obj, int nesting)
{
var sb = new StringBuilder();
var list = obj as IEnumerable;
var identation = new string('\t', nesting + 1);
if (list == null || !list.Cast<object>().Any())
return "<empty>" + Environment.NewLine;
sb.Append(Environment.NewLine);
var index = 0;
foreach (var element in list)
{
sb.Append(identation + index++ + ": " + PrintToString(element, nesting + 1));
}

return sb.ToString();
}

public IBaseConfig<TOwner> Exclude<TArg>(Expression<Func<TOwner, TArg>> f)
{
var configuratedProperty = Helper.GetPropertyInfo(f);
excludedProperties.Add(configuratedProperty);
return this;
}

public IBaseConfig<TOwner> Exclude<T>()
{
excludedTypes.Add(typeof(T));
return this;
}

public TypeConfig<TOwner, TArg> Printing<TArg>()
{
var configuratedType = typeof(TArg);
return new TypeConfig<TOwner, TArg>(this, configuratedType);
}

public PropertyConfig<TOwner, TArg> Printing<TArg>(Expression<Func<TOwner, TArg>> f)
{
var configuratedProperty = Helper.GetPropertyInfo(f);
return new PropertyConfig<TOwner, TArg>(this, configuratedProperty);
}

public void AddPropertySerialization<TProperty>(Func<TProperty, string> f, PropertyInfo configuratedProperty)
{
serializedByPropertyInfo.Add(configuratedProperty, obj => f((TProperty)obj));
}

public void AddTypeSerialization<TProperty>(Func<TProperty, string> f, Type configuratedType)
{
serializedByType.Add(configuratedType, obj => f((TProperty)obj));
}
}
}
Loading