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

Зубакин Ренат #196

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
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
17 changes: 17 additions & 0 deletions ObjectPrinting/Extensions/ObjectExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
using System;

namespace ObjectPrinting.Extensions
{
public static class ObjectExtensions
{
public static string PrintToString<T>(this T obj)
{
return ObjectPrinter.For<T>().PrintToString(obj);
}

public static string PrintToString<T>(this T obj, Func<PrintingConfig<T>,PrintingConfig<T>> func)
{
return func(ObjectPrinter.For<T>()).PrintToString(obj);
}
}
}
11 changes: 11 additions & 0 deletions ObjectPrinting/Extensions/PropertyPrintingConfigExtension.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
namespace ObjectPrinting.Extensions
{
public static class PropertyPrintingConfigExtension
{
public static PrintingConfig<TOwner> TrimmedStringProperty<TOwner>(
this PropertyPrintingConfig<TOwner, string> printingConfig, int length)
{
return printingConfig.SetSerializer(str => str.Length <= length ? str : str.Substring(0, length));
}
}
}
1 change: 1 addition & 0 deletions ObjectPrinting/ObjectPrinting.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="5.10.3" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
</ItemGroup>
Expand Down
185 changes: 169 additions & 16 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,194 @@
using System;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Text;

namespace ObjectPrinting
{
public class PrintingConfig<TOwner>
{
private static readonly HashSet<Type> FinalTypes = new HashSet<Type>()
{
typeof(int),
typeof(double),
typeof(float),
typeof(string),
typeof(DateTime),
typeof(TimeSpan),
typeof(Guid)
};

private readonly HashSet<Type> excludedTypes = new HashSet<Type>();
private readonly HashSet<MemberInfo> excludedProperty = new HashSet<MemberInfo>();

private readonly Dictionary<MemberInfo, Func<object,string>> customPropertySerialize =
new Dictionary<MemberInfo, Func<object,string>>();

private readonly Dictionary<Type, Func<object,string>> customTypeSerializers = new Dictionary<Type, Func<object,string>>();
private readonly HashSet<object> visitedObjects = new HashSet<object>();


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

private string PrintToString(object obj, int nestingLevel)
{
var builder = new StringBuilder();

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Кадется лишнее поле

//TODO apply configurations
if (obj == null)
return "null" + Environment.NewLine;
return "null";

if (visitedObjects.Contains(obj))
{
return $"Cycling references";
}

//visitedObjects.Add(obj);

if (FinalTypes.Contains(obj.GetType()))
return obj.ToString();

if (obj is IDictionary dictionary)
{
return PrintToStringIDictionary(dictionary, nestingLevel + 1);
}

if (obj is IEnumerable collection)
{
return PrintToStringIEnumerable(collection, nestingLevel + 1);
}

var finalTypes = new[]
return PrintToStringProperties(obj, nestingLevel + 1);
}

private string PrintToStringProperties(object obj, int nestingLevel)
{
var identation = new string('\t', nestingLevel);
var builder = new StringBuilder();
var objType = obj.GetType();
builder.Append($"{objType.Name}");
visitedObjects.Add(obj);
foreach (var propertyInfo in GetIncludedProperties(objType))
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
};
if (finalTypes.Contains(obj.GetType()))
return obj + Environment.NewLine;
var value = propertyInfo.GetValue(obj);
var customSerializeStr = TryUseCustomSerializer(value, propertyInfo, out var str)
? str
: PrintToString(value, nestingLevel + 1);
builder.Append('\n' + identation + propertyInfo.Name + " = " + customSerializeStr);
}
visitedObjects.Remove(obj);
return builder.ToString();
}

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())
private string PrintToStringIEnumerable(IEnumerable collection, int nestingLevel)
{
var identation = new string('\t', nestingLevel);
var builder = new StringBuilder();
visitedObjects.Add(collection);
foreach (var item in collection)
{
sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
builder.Append('\n' + identation + PrintToString(item, nestingLevel + 1));
}
return sb.ToString();

visitedObjects.Remove(collection);
return builder.ToString();
}

private string PrintToStringIDictionary(IDictionary dictionary, int nestingLevel)
{
var identation = new string('\t', nestingLevel);
var builder = new StringBuilder();

visitedObjects.Add(dictionary);

foreach (var key in dictionary.Keys)
{
builder.Append('\n' + identation + PrintToString(key, nestingLevel + 1) + " = " +
PrintToString(dictionary[key], nestingLevel + 1));
}

visitedObjects.Remove(dictionary);
return builder.ToString();
}

private bool TryUseCustomSerializer(object value, PropertyInfo propertyInfo, out string str)
{
str = null;
if (customPropertySerialize.ContainsKey(propertyInfo))
{
str = (string)customPropertySerialize[propertyInfo].DynamicInvoke(value);
return true;
}

var type = propertyInfo.PropertyType;
if (customTypeSerializers.ContainsKey(propertyInfo.PropertyType))
{
str = (string)customTypeSerializers[propertyInfo.PropertyType].DynamicInvoke(value);
return true;
}

return false;
}

private IEnumerable<PropertyInfo> GetIncludedProperties(Type type)
{
return type.GetRuntimeProperties().Where(p => !IsExclude(p));
}

private bool IsExclude(PropertyInfo member)
{
return excludedTypes.Contains(member.PropertyType) || excludedProperty.Contains(member);
}

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

public PrintingConfig<TOwner> Exclude<TProperty>(Expression<Func<TOwner, TProperty>> func)
{
var memberInfo = func.Body as MemberExpression;
if (memberInfo == null)
throw new ArgumentException();
excludedProperty.Add(memberInfo.Member);
return this;
}


public PrintingConfig<TOwner> SetCustomTypeSerializer<TType>(Func<TType, string> serializer)
{
customTypeSerializers[typeof(TType)] = obj =>serializer((TType)obj);
return this;
}

public PropertyPrintingConfig<TOwner, TProperty> SerializeByProperty<TProperty>(
Expression<Func<TOwner, TProperty>> func)
{
var memberInfo = func.Body as MemberExpression;
if (memberInfo == null)
throw new ArgumentException();
return new PropertyPrintingConfig<TOwner, TProperty>(this, memberInfo.Member);
}

public PrintingConfig<TOwner> SetCustomPropertySerializer<TProperty>(MemberInfo property,
Func<TProperty, string> serializer)
{
customPropertySerialize[property] = obj =>serializer((TProperty)obj);
return this;
}

public PrintingConfig<TOwner> SetCulture<TType>(string format, CultureInfo culture)
where TType : IFormattable

{
return SetCustomTypeSerializer((TType obj) => obj.ToString(format, culture));
}
}
}
23 changes: 23 additions & 0 deletions ObjectPrinting/PropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
using System;
using System.Reflection;

namespace ObjectPrinting
{
public class PropertyPrintingConfig<TOwner, TProperty>
{
private readonly PrintingConfig<TOwner> printingConfig;
private readonly MemberInfo property;

public PropertyPrintingConfig(PrintingConfig<TOwner> printingConfig, MemberInfo property)
{
this.printingConfig = printingConfig;
this.property = property;
}

public PrintingConfig<TOwner> SetSerializer(Func<TProperty, string> serializer)
{
printingConfig.SetCustomPropertySerializer(property, serializer);
return printingConfig;
}
}
}
Loading