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 2 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
29 changes: 29 additions & 0 deletions ObjectPrinting/Config.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System;

namespace ObjectPrinting
{
public class Config

Choose a reason for hiding this comment

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

Какое-то слишком абстрактное название. Конфигов в проекте может быть очень много, плюс некоторые фреймворки используют это названия для конфигов.

{
public HashSet<object> serializedObjects;
public HashSet<Type> excludedTypes;
public HashSet<PropertyInfo> excludedProperties;
public Dictionary<Type, CultureInfo> cultures;
public Dictionary<Type, Delegate> typeSerialization;
public Dictionary<PropertyInfo, Delegate> propertiesSerialization;

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

}

}
}
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>
110 changes: 97 additions & 13 deletions ObjectPrinting/PrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -1,41 +1,125 @@
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 Config configuration;
private readonly Type[] finalTypes;

public PrintingConfig()
{
configuration = new Config();
finalTypes = new[]
{
typeof(int), typeof(double), typeof(float), typeof(string),
typeof(DateTime), typeof(TimeSpan), typeof(Guid)
};
}

public PrintingConfig<TOwner> Excluding<Type>()
{
configuration.excludedTypes.Add(typeof(Type));
return this;
}

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

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>()
{
return new PropertyPrintingConfig<TOwner, TPropType>(this, configuration);
}

public PropertyPrintingConfig<TOwner, TPropType> Printing<TPropType>(Expression<Func<TOwner, TPropType>> memberSelector)
{
var propInfo = ((MemberExpression)memberSelector.Body).Member as PropertyInfo;
return new PropertyPrintingConfig<TOwner, TPropType>(this, 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.cultures.TryGetValue(type, out var culture))
return Convert.ToString(obj, culture) + 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.typeSerialization.TryGetValue(propertyInfo.PropertyType, out var typeSerializer))
sb.Append(identation + propertyInfo.Name + " = " + typeSerializer.DynamicInvoke(propertyValue) + Environment.NewLine);
else if (configuration.propertiesSerialization.TryGetValue(propertyInfo, out var propSerializer))
sb.Append(identation + propertyInfo.Name + " = " + propSerializer.DynamicInvoke(propertyValue) + Environment.NewLine);

Choose a reason for hiding this comment

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

А почему здесь Else if? Почему если мы применили одно, то не можем применить другое?

else
sb.Append(identation + propertyInfo.Name + " = " + PrintToString(propertyValue, nestingLevel + 1));
}
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;
}
}
}
57 changes: 57 additions & 0 deletions ObjectPrinting/PropertyPrintingConfig.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,57 @@
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 Config configuration;
private readonly PropertyInfo propertyInfo;


public PropertyPrintingConfig(PrintingConfig<TOwner> printingConfig, Config 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;
}
configuration.typeSerialization[typeof(TPropType)] = print;
return printingConfig;
}

public PrintingConfig<TOwner> Using(CultureInfo culture)

Choose a reason for hiding this comment

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

В текущей реализации я могу вызвать этот метод на полях, которые к культуре отношения не имеют.
Uploading image.png…

{
configuration.cultures.Add(typeof(TPropType), culture);
return printingConfig;
}

public PrintingConfig<TOwner> ParentConfig => printingConfig;

}
}
23 changes: 23 additions & 0 deletions ObjectPrinting/PropertyPrintingConfigExtensions.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
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;
}

}
}
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