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 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
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;
}
}
}
91 changes: 65 additions & 26 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,9 @@ public class PrintingConfig<TOwner>
{
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;

Expand Down Expand Up @@ -61,7 +64,8 @@ public PrintingConfig<TOwner> SerializeWith<TPropType>(Func<TPropType, string> s
{
Func<object, string> func = p => serialize((TPropType)p);

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

return this;
}
Expand Down Expand Up @@ -96,7 +100,7 @@ public PrintingConfig<TOwner> Trim(Expression<Func<TOwner, string>> property, in
return SerializeWith(property, func);
}

public PrintingConfig<TOwner> Trim(int length) //
public PrintingConfig<TOwner> Trim(int length)
{
Func<string, string> func = value => value.Length <= length
? value
Expand Down Expand Up @@ -128,32 +132,62 @@ private string PrintToString(object obj, int nestingLevel)
var type = obj.GetType();
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.

{
if (excludedProperties.Any(memberInfo => memberInfo.Name == propertyInfo.Name) ||
excludedTypes.Contains(propertyInfo.PropertyType))
continue;

if (membersSerializesInfos.TryGetValue(propertyInfo, out var serializeMember))
{
sb.Append(GetSerializedString(obj, propertyInfo, indentation, serializeMember));
continue;
}

if (typeSerializesInfos.TryGetValue(propertyInfo.PropertyType, out var serializeType))
{
sb.Append(GetSerializedString(obj, propertyInfo, indentation, serializeType));
continue;
}

sb.Append($"{indentation}{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);
}

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

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

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);
Expand All @@ -162,12 +196,17 @@ private bool MaxRecursionHasBeenReached(object obj)
return complexObjectLinks[obj] == maxRecursion;
}

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

return $"{indentation}{propertyInfo.Name} = {serializedString}{Environment.NewLine}";
return $"{indentation}{memberInfo.Name} = {serializedString}{stringEnd}";
}

}
}
46 changes: 5 additions & 41 deletions ObjectPrintingTests/ObjectPrinterAcceptanceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,12 @@
using FluentAssertions;
using NUnit.Framework;
using ObjectPrinting;
using ObjectPrinting.Tests;

namespace ObjectPrintingTests
{
[TestFixture]
public class ObjectPrinterAcceptanceTests

This comment was marked as resolved.

This comment was marked as resolved.

{
[Test]
public void Demo()
{
var person = new Person { Name = "Alex", Age = 19, Height = 180.5, SubPerson = new SubPerson() };
person.SubPerson.Age = 15;
person.SubPerson.Person = person;

var printer = ObjectPrinter.For<Person>();

//Исключение из сериализации свойства/ поля определенного типа
//Альтернативный способ сериализации для определенного типа
//Для всех типов, имеющих культуру, есть возможность ее указать
//printer.Exclude<double>()
// .SerializeWith(p => p.Age, age => (age + 1000).ToString())
// .SetCulture<double>(CultureInfo.InvariantCulture)
// .SerializeWith<string>((p) => p.ToUpper())
// .Trim<string>(p => p.Name, 1)
// .Exclude(p => p.Name)
// .


//Корректная обработка циклических ссылок между объектами(не должны приводить к StackOverflowException)
}

[Test]
public void DoSomething_WhenSomething()
{
var person = new Person { Name = "Alex", Age = 19 };
var printer = ObjectPrinter.For<Person>();

printer.SerializeWith(p => p.Name, n => $"{n} :))")
.Trim(p => p.Name, 1)
.Trim(1);
}

[Test]
public void ShouldExcludeMember_WhenItsTypeSpecified()
{
Expand All @@ -55,7 +19,7 @@ public void ShouldExcludeMember_WhenItsTypeSpecified()

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");
"Person\r\n\tId = 00000000-0000-0000-0000-000000000000\r\n\tName = Alex\r\n\tSubPerson = null\r\n\tPublicField = null\r\n");
}

[Test]
Expand All @@ -67,7 +31,7 @@ public void ShouldUseTrimming_WhenItsSpecifiedForType()
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");
"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]
Expand All @@ -79,7 +43,7 @@ public void ShouldSerializeMember_WithGivenFunc()
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");
"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]
Expand All @@ -91,7 +55,7 @@ public void SetCulture_ShouldAddedCultureInfo()
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");
"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]
Expand All @@ -105,7 +69,7 @@ public void WhenCyclicLinksWasFound_ShouldPrintWithRecursionLimit()
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");
"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]
Expand Down
2 changes: 1 addition & 1 deletion ObjectPrintingTests/Person.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
using System;

namespace ObjectPrinting.Tests
namespace ObjectPrintingTests
{
public class Person
{
Expand Down
4 changes: 1 addition & 3 deletions ObjectPrintingTests/SubPerson.cs
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
using System;

namespace ObjectPrinting.Tests
namespace ObjectPrintingTests
{
public class SubPerson
{
Expand Down