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

Яценко Ирина #198

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

namespace ObjectPrinting
{
public class DataMember
{
public string Name { get; set; }
public Type Type { get; set; }

public Func<object, object> GetValue;
public MemberInfo MemberInfo { get; set; }

public DataMember(FieldInfo fieldInfo)
{
Name = fieldInfo.Name;
GetValue = fieldInfo.GetValue;
Type = fieldInfo.FieldType;
MemberInfo = fieldInfo;
}

public DataMember(PropertyInfo property)
{
Name = property.Name;
GetValue = property.GetValue;
Type = property.PropertyType;
MemberInfo = property;
}
}
}
199 changes: 185 additions & 14 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,212 @@
using System;
Copy link

Choose a reason for hiding this comment

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

Все комменты обсуждаемы - можем обсуждать или в тредах, или в личке в телеге
За количество комментов не парься - это нормально, процесс обучения, повышения скилла, ревью именно для этого и нужно

На пофикшенные комментарии можно ставить реакции или писать пометочки, что и почему

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>

This comment was marked as resolved.

This comment was marked as resolved.

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

private readonly HashSet<FieldInfo> excludedFields = new HashSet<FieldInfo>();

private readonly Dictionary<object, int> complexObjectLinks = new Dictionary<object, int>();
private int maxRecursion = 2;

private readonly HashSet<Type> finalTypes = new HashSet<Type>()
{
typeof(int), typeof(double), typeof(float), typeof(string), typeof(DateTime), typeof(TimeSpan), typeof(Guid)
};

private readonly Dictionary<Type, Func<object, string>> typeSerializesInfos =
new Dictionary<Type, Func<object, string>>();

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


public string PrintToString(TOwner obj)

This comment was marked as resolved.

{
return PrintToString(obj, 0);
}

public PrintingConfig<TOwner> WithMaxRecursion(int maxRecursion)
{
if (maxRecursion < 1)
throw new ArgumentException();
this.maxRecursion = maxRecursion;

return this;
}

public PrintingConfig<TOwner> Exclude<TPropType>(Expression<Func<TOwner, TPropType>> exclude)
{
var memberInfo = GetMemberInfo(exclude);

excludedProperties.Add(memberInfo);

return this;
}

public PrintingConfig<TOwner> SetCulture<TPropType>(CultureInfo culture)
where TPropType : IFormattable
{
return SerializeWith<TPropType>(
p => p.ToString(null, culture));
}

public PrintingConfig<TOwner> SerializeWith<TPropType>(Func<TPropType, string> serialize)
{
Func<object, string> func = p => serialize((TPropType)p);

if (!typeSerializesInfos.ContainsKey(typeof(TPropType)))
typeSerializesInfos[typeof(TPropType)] = func;

return this;
}

public PrintingConfig<TOwner> SerializeWith<TPropType>(
Expression<Func<TOwner, TPropType>> property,
Func<TPropType, string> serialize)
{
var memberInfo = GetMemberInfo(property);
Func<object, string> func = p => serialize((TPropType)p);

membersSerializesInfos[memberInfo] = func;

return this;
}

private static MemberInfo GetMemberInfo<TPropType>(Expression<Func<TOwner, TPropType>> expression)
{
var memberExpression = expression.Body is UnaryExpression unaryExpression
? (MemberExpression)unaryExpression.Operand
: (MemberExpression)expression.Body;

return memberExpression.Member;
}

public PrintingConfig<TOwner> Trim(Expression<Func<TOwner, string>> property, int length)

This comment was marked as resolved.

This comment was marked as resolved.

{
Func<string, string> func = value => value.Length <= length
? value
: value[..length];

return SerializeWith(property, func);
}

public PrintingConfig<TOwner> Trim(int length)
{
Func<string, string> func = value => value.Length <= length
? value
: value[..length];

return SerializeWith(func);
}

public PrintingConfig<TOwner> Exclude<TPropType>()
{
excludedTypes.Add(typeof(TPropType));

return this;
}

private string PrintToString(object obj, int nestingLevel)

This comment was marked as resolved.

This comment was marked as resolved.

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

var finalTypes = new[]
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
};
if (finalTypes.Contains(obj.GetType()))
return obj + Environment.NewLine;

var identation = new string('\t', nestingLevel + 1);
var sb = new StringBuilder();
if (MaxRecursionHasBeenReached(obj))
return $"Maximum recursion has been reached{Environment.NewLine}";

var indentation = string.Intern(new string('\t', nestingLevel + 1));

var type = obj.GetType();
sb.AppendLine(type.Name);
var sb = new StringBuilder().AppendLine(type.Name);


HandleMembers(type, sb, indentation, obj, nestingLevel);




return sb.ToString();
}

private void HandleMembers(Type type, StringBuilder sb, string indentation, object obj, int nestingLevel)
{
foreach (var propertyInfo in type.GetProperties())

This comment was marked as resolved.

{
sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
DataMember data = new DataMember(propertyInfo);

This comment was marked as resolved.

Copy link

Choose a reason for hiding this comment

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

у тебя просто propertyInfo заворачивается в DataMember - зачем? Почему бы не просто передавать MemberInfo в метод

А еще можно сделать финт ушами, чтобы по разному не обрабатывать поля и свойства:

const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Instance;
var fields = type.GetFields(bindingFlags);
var properties = type.GetProperties(bindingFlags);

return fields.Concat<MemberInfo>(properties);


HandleMember(sb, data, obj, indentation, nestingLevel);
}

foreach (var fieldInfo in type.GetFields())
{
DataMember data = new DataMember(fieldInfo);

HandleMember(sb, data, obj, indentation, nestingLevel);
}
return sb.ToString();
}

private void HandleMember(StringBuilder sb, DataMember member, object obj, string indentation, int nestingLevel)

This comment was marked as resolved.

{
if (excludedProperties.Any(memberInfo => memberInfo.Name == member.Name) ||
excludedTypes.Contains(member.Type))
return;

if (membersSerializesInfos.TryGetValue(member.MemberInfo, out var serializeMember))
{
sb.Append(GetSerializedString(obj, member, indentation, serializeMember));
return;
}

if (typeSerializesInfos.TryGetValue(member.Type, out var serializeType))
{
sb.Append(GetSerializedString(obj, member, indentation, serializeType));
return;
}

sb.Append(
GetSerializedString(
obj,
member,
indentation,
(value) => PrintToString(
value,
nestingLevel + 1),
false));
}


private bool MaxRecursionHasBeenReached(object obj)
{
complexObjectLinks.TryAdd(obj, 0);
complexObjectLinks[obj]++;

return complexObjectLinks[obj] == maxRecursion;
}

private string GetSerializedString(
object obj,
DataMember memberInfo,
string indentation,
Func<object, string> serializeMember,
bool needNewLine = true)
{
var serializedString = serializeMember(memberInfo.GetValue(obj));
var stringEnd = needNewLine ? Environment.NewLine : string.Empty;

return $"{indentation}{memberInfo.Name} = {serializedString}{stringEnd}";
}
}
}
27 changes: 0 additions & 27 deletions ObjectPrinting/Tests/ObjectPrinterAcceptanceTests.cs

This file was deleted.

93 changes: 93 additions & 0 deletions ObjectPrintingTests/ObjectPrinterAcceptanceTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
using System.Globalization;
using FluentAssertions;
using NUnit.Framework;
using ObjectPrinting;

namespace ObjectPrintingTests
{
[TestFixture]
public class ObjectPrinterAcceptanceTests

This comment was marked as resolved.

This comment was marked as resolved.

{
[Test]
public void ShouldExcludeMember_WhenItsTypeSpecified()
{
var person = new Person { Name = "Alex", Age = 19 };

var printer = ObjectPrinter.For<Person>();
printer.Exclude(p => p.Age)
.Exclude<double>();

var s1 = printer.PrintToString(person);
s1.Should().Be(
"Person\r\n\tId = 00000000-0000-0000-0000-000000000000\r\n\tName = Alex\r\n\tSubPerson = null\r\n\tPublicField = null\r\n");
}

[Test]
public void ShouldUseTrimming_WhenItsSpecifiedForType()
{
var person = new Person { Name = "Petr", Age = 20, Height = 180 };
var printer = ObjectPrinter.For<Person>();

var s1 = printer.Trim(p => p.Name, 1).PrintToString(person);

s1.Should().Be(
"Person\r\n\tId = 00000000-0000-0000-0000-000000000000\r\n\tName = P\r\n\tHeight = 180\r\n\tAge = 20\r\n\tSubPerson = null\r\n\tPublicField = null\r\n");
}

[Test]
public void ShouldSerializeMember_WithGivenFunc()
{
var person = new Person { Name = "Petr", Age = 20, Height = 180 };
var printer = ObjectPrinter.For<Person>();

var s1 = printer.SerializeWith(p => p.Age, age => (age + 1000).ToString()).PrintToString(person);

s1.Should().Be(
"Person\r\n\tId = 00000000-0000-0000-0000-000000000000\r\n\tName = Petr\r\n\tHeight = 180\r\n\tAge = 1020\r\n\tSubPerson = null\r\n\tPublicField = null\r\n");
}

[Test]
public void SetCulture_ShouldAddedCultureInfo()
{
var person = new Person { Name = "Petr", Age = 20, Height = 180.5 };
var printer = ObjectPrinter.For<Person>();

var s1 = printer.SetCulture<double>(CultureInfo.InvariantCulture).PrintToString(person);

s1.Should().Be(
"Person\r\n\tId = 00000000-0000-0000-0000-000000000000\r\n\tName = Petr\r\n\tHeight = 180.5\r\n\tAge = 20\r\n\tSubPerson = null\r\n\tPublicField = null\r\n");
}

[Test]
public void WhenCyclicLinksWasFound_ShouldPrintWithRecursionLimit()
{
var person = new Person { Name = "Petr", Age = 20, Height = 180, SubPerson = new SubPerson() };
person.SubPerson.Age = 15;
person.SubPerson.Person = person;
var printer = ObjectPrinter.For<Person>();

var s1 = printer.PrintToString(person);

s1.Should().Be(
"Person\r\n\tId = 00000000-0000-0000-0000-000000000000\r\n\tName = Petr\r\n\tHeight = 180\r\n\tAge = 20\r\n\tSubPerson = SubPerson\r\n\t\tPerson = Maximum recursion has been reached\r\n\t\tAge = 15\r\n\tPublicField = null\r\n");
}

[Test]
public void WhenPassNull_ShouldReturnNullString()
{
var printer = ObjectPrinter.For<Person>();
var s1 = printer.PrintToString(null);

s1.Should().Be("null\r\n");
}

[Test]
public void WhenPassFinalType_ShouldReturnStringRepresentationOfThisType()
{
var printer = ObjectPrinter.For<int>();
var s1 = printer.PrintToString(1);

s1.Should().Be("1\r\n");
}
}
}
Loading