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

Овечкин Илья #190

Open
wants to merge 7 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
2 changes: 2 additions & 0 deletions ObjectPrinting/ObjectPrinting.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@
</PropertyGroup>

<ItemGroup>
<PackageReference Include="FluentAssertions" Version="6.12.0" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="NUnit" Version="3.12.0" />
<PackageReference Include="NUnit3TestAdapter" Version="4.5.0" />
</ItemGroup>

</Project>
116 changes: 103 additions & 13 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,131 @@
using NUnit.Framework;
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Globalization;
using System.Linq.Expressions;
using System.Collections;

namespace ObjectPrinting
{
public class PrintingConfig<TOwner>

Choose a reason for hiding this comment

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

Не хватает иммутабельности.

Choose a reason for hiding this comment

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

Иммутабельности всё ещё нет. :(
Вот в такой ситуации должно вывести сначала с именем Ivasd, а потом Home, но дважды печатает Home.
image

{
private readonly SerializerConfig configuration;
private readonly Type[] finalTypes = new[]
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan), typeof(Guid)
};

public PrintingConfig()
{
configuration = new SerializerConfig();
}

public PrintingConfig(SerializerConfig configuration)
{
this.configuration = configuration;
}

public PrintingConfig<TOwner> Excluding<Type>()
{
var newConfig = new PrintingConfig<TOwner>(configuration);
newConfig.configuration.excludedTypes.Add(typeof(Type));
return newConfig;
}

public PrintingConfig<TOwner> Excluding<Property>(Expression<Func<TOwner, Property>> memberSelector)
{
var propInfo = ((MemberExpression)memberSelector.Body).Member as PropertyInfo;
var newConfig = new PrintingConfig<TOwner>(configuration);
newConfig.configuration.excludedProperties.Add(propInfo);
return newConfig;
}

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>()
{
var newConfig = new PrintingConfig<TOwner>(configuration);
return new PropertyPrintingConfig<TOwner, TPropType>(newConfig, newConfig.configuration);
}

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>(Expression<Func<TOwner, TPropType>> memberSelector)
{
var propInfo = ((MemberExpression)memberSelector.Body).Member as PropertyInfo;
var newConfig = new PrintingConfig<TOwner>(configuration);
return new PropertyPrintingConfig<TOwner, TPropType>(newConfig, newConfig.configuration, propInfo);
}

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

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

var finalTypes = new[]
var type = obj.GetType();

if (finalTypes.Contains(type))

Choose a reason for hiding this comment

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

В таком случае, получается, что если я принтер настрою на специфический формат инта, а вызову printer.PrintToString(123), то он просто напечатает 123, а не мой специфический формат.

{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan)
};
if (finalTypes.Contains(obj.GetType()))
if(configuration.typeSerialization.TryGetValue(type, out var serializer))
return serializer.DynamicInvoke(obj) + Environment.NewLine;
return obj + Environment.NewLine;
}

if (obj is ICollection collection)
return SerializeCollection(collection, nestingLevel);

configuration.serializedObjects.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 sb = new StringBuilder().Append(type.Name + Environment.NewLine);
var properties = type.GetProperties().Where(propInfo =>
!configuration.excludedProperties.Contains(propInfo) &&
!configuration.excludedTypes.Contains(propInfo.PropertyType));

foreach (var propertyInfo in properties)
{
sb.Append(identation + propertyInfo.Name + " = " +
PrintToString(propertyInfo.GetValue(obj),
nestingLevel + 1));
var propertyValue = propertyInfo.GetValue(obj);
if (configuration.serializedObjects.Contains(propertyValue))
continue;
if (configuration.propertiesSerialization.TryGetValue(propertyInfo, out var propSerializer))
sb.Append(identation + propertyInfo.Name + " = " + propSerializer.DynamicInvoke(propertyValue) + Environment.NewLine);
else
sb.Append(identation + propertyInfo.Name + " = " + PrintToString(propertyValue, nestingLevel + 1));
Comment on lines +94 to +97

Choose a reason for hiding this comment

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

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

}
return sb.ToString();
}

private string SerializeCollection(ICollection collection, int nestingLevel)
{
if (collection is IDictionary dictionary)
return SerializeDictionary(dictionary, nestingLevel);

var sb = new StringBuilder();
foreach (var item in collection)
sb.Append(PrintToString(item, nestingLevel + 1).Trim() + " ");

return $"[ {sb}]" + Environment.NewLine;
}

private string SerializeDictionary(IDictionary dictionary, int nestingLevel)
{
var sb = new StringBuilder();
var identation = new string('\t', nestingLevel);
sb.Append(identation + "{" + Environment.NewLine);
foreach (DictionaryEntry keyValuePair in dictionary)
{
identation = new string('\t', nestingLevel + 1);
sb.Append(identation + "[" + PrintToString(keyValuePair.Key, nestingLevel + 1).Trim() + " - ");
sb.Append(PrintToString(keyValuePair.Value, 0).Trim());
sb.Append("],");
sb.Append(Environment.NewLine);
}

return sb + "}" + Environment.NewLine;
}
}
}
50 changes: 50 additions & 0 deletions ObjectPrinting/PropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
using NUnit.Framework;
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Globalization;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace ObjectPrinting
{
public class PropertyPrintingConfig<TOwner, TPropType>
{
private readonly PrintingConfig<TOwner> printingConfig;
private readonly SerializerConfig configuration;
private readonly PropertyInfo propertyInfo;


public PropertyPrintingConfig(PrintingConfig<TOwner> printingConfig, SerializerConfig configuration, PropertyInfo propertyInfo = null)
{
this.printingConfig = printingConfig;
this.configuration = configuration;
this.propertyInfo = propertyInfo;
}

public PrintingConfig<TOwner> Using(Func<TPropType, string> print)
{
if (propertyInfo == null)
{
if (!configuration.typeSerialization.ContainsKey(typeof(TPropType)))
configuration.typeSerialization.Add(typeof(TPropType), print);
else
configuration.typeSerialization[typeof(TPropType)] = print;
}
else
{
if (!configuration.propertiesSerialization.ContainsKey(propertyInfo))
configuration.propertiesSerialization.Add(propertyInfo, print);
else
configuration.propertiesSerialization[propertyInfo] = print;
}
return printingConfig;
}

public PrintingConfig<TOwner> ParentConfig => printingConfig;

}
}
37 changes: 37 additions & 0 deletions ObjectPrinting/PropertyPrintingConfigExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
using NUnit.Framework;
using System;
using System.Linq;
using System.Text;
using System.Collections.Generic;
using System.Reflection;
using System.Globalization;
using System.Linq.Expressions;
using Newtonsoft.Json.Linq;
using System.Text.RegularExpressions;

namespace ObjectPrinting
{
public static class PropertyPrintingConfigExtensions
{
public static PrintingConfig<TOwner> TrimmedToLength<TOwner>(this PropertyPrintingConfig<TOwner, string> propConfig, int maxLen)
{
propConfig.Using(property => property.Substring(0,Math.Min(maxLen, property.Length)).ToString());
return propConfig.ParentConfig;
}

public static PrintingConfig<TOwner> Using<TOwner>(this PropertyPrintingConfig<TOwner, DateTime> propConfig, CultureInfo culture)
{
return propConfig.Using(x => x.ToString(culture));
}

public static PrintingConfig<TOwner> Using<TOwner>(this PropertyPrintingConfig<TOwner, double> propConfig, CultureInfo culture)
{
return propConfig.Using(x => x.ToString(culture));
}

public static PrintingConfig<TOwner> Using<TOwner>(this PropertyPrintingConfig<TOwner, float> propConfig, CultureInfo culture)
{
return propConfig.Using(x => x.ToString(culture));
}
}
}
27 changes: 27 additions & 0 deletions ObjectPrinting/SerializerConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System;

namespace ObjectPrinting
{
public class SerializerConfig
{
public HashSet<object> serializedObjects;
public HashSet<Type> excludedTypes;
public HashSet<PropertyInfo> excludedProperties;
public Dictionary<Type, Delegate> typeSerialization;
public Dictionary<PropertyInfo, Delegate> propertiesSerialization;

public SerializerConfig()
{
serializedObjects = new HashSet<object>();
excludedTypes = new HashSet<Type>();
excludedProperties = new HashSet<PropertyInfo>();
typeSerialization = new Dictionary<Type, Delegate>();
propertiesSerialization = new Dictionary<PropertyInfo, Delegate>();

}

}
}
10 changes: 0 additions & 10 deletions ObjectPrinting/Solved/ObjectExtensions.cs

This file was deleted.

10 changes: 0 additions & 10 deletions ObjectPrinting/Solved/ObjectPrinter.cs

This file was deleted.

62 changes: 0 additions & 62 deletions ObjectPrinting/Solved/PrintingConfig.cs

This file was deleted.

32 changes: 0 additions & 32 deletions ObjectPrinting/Solved/PropertyPrintingConfig.cs

This file was deleted.

Loading