-
Notifications
You must be signed in to change notification settings - Fork 252
Косторной Дмитрий #223
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
Open
Kostornoj-Dmitrij
wants to merge
13
commits into
kontur-courses:master
Choose a base branch
from
Kostornoj-Dmitrij:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Косторной Дмитрий #223
Changes from all commits
Commits
Show all changes
13 commits
Select commit
Hold shift + click to select a range
db042a5
Базовая настройка проекта, исключил предложенный тестовый файл
Kostornoj-Dmitrij 01a6a67
Создание проекта для тестов
Kostornoj-Dmitrij d29703d
Тесты + вспомогательные классы для них
Kostornoj-Dmitrij a8e70c9
Расширения и основной класс для ObjectPrinter
Kostornoj-Dmitrij a6a6328
Основная логика сериализатора
Kostornoj-Dmitrij af4664a
Add verified files because forgot
Kostornoj-Dmitrij 6e5b2f7
Удалил папку тестов и Solved из ObjectOrinting и ненужные зависимости.
Kostornoj-Dmitrij 4136bfa
Удалил папку Solved из ObjectPrinting
Kostornoj-Dmitrij d604940
Добавил константу для разделителя, интерполяцию вместо конкатенации
Kostornoj-Dmitrij c0dcf83
Разделил подготовку к тестам и проверки. Добавил тесты на исключения
Kostornoj-Dmitrij b3fe665
Обновил verified файлы
Kostornoj-Dmitrij 2972683
Добавил обработку исключений, сериализацию типов объектов коллекций
Kostornoj-Dmitrij 5212f0e
Изменил конкатенацию на использование StringBuilder
Kostornoj-Dmitrij File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| using System; | ||
| using ObjectPrinting.Interfaces; | ||
|
|
||
| namespace ObjectPrinting.Extensions; | ||
|
|
||
| public static class ObjectPrinterExtensions | ||
| { | ||
| public static string? Serialize<TSerialize>(this IObjectPrinter printer, TSerialize obj) => | ||
| printer.For<TSerialize>().PrintToString(obj); | ||
|
|
||
| public static string? Serialize<TSerialize>(this IObjectPrinter printer, TSerialize obj, | ||
| Func<ObjectPrinterSettings<TSerialize>, ObjectPrinterSettings<TSerialize>> config) => | ||
| config(printer.For<TSerialize>()).PrintToString(obj); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,6 @@ | ||
| namespace ObjectPrinting.Interfaces; | ||
|
|
||
| public interface IObjectPrinter | ||
| { | ||
| ObjectPrinterSettings<T> For<T>(); | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,10 +1,11 @@ | ||
| namespace ObjectPrinting | ||
| using ObjectPrinting.Interfaces; | ||
|
|
||
| namespace ObjectPrinting; | ||
|
|
||
| public class ObjectPrinter : IObjectPrinter | ||
| { | ||
| public class ObjectPrinter | ||
| public ObjectPrinterSettings<T> For<T>() | ||
| { | ||
| public static PrintingConfig<T> For<T>() | ||
| { | ||
| return new PrintingConfig<T>(); | ||
| } | ||
| return new ObjectPrinterSettings<T>(); | ||
| } | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,219 @@ | ||
| using System; | ||
| using System.Text; | ||
| using System.Reflection; | ||
| using System.Collections; | ||
| using System.Linq.Expressions; | ||
| using System.Collections.Generic; | ||
|
|
||
| namespace ObjectPrinting; | ||
|
|
||
| public class ObjectPrinterSettings<TOwner> | ||
| { | ||
| private readonly HashSet<Type> finalTypes = | ||
| [ | ||
| typeof(bool), typeof(byte), typeof(int), typeof(double), typeof(float), typeof(char), typeof(string), | ||
| typeof(DateTime), typeof(TimeSpan), typeof(Guid) | ||
| ]; | ||
|
|
||
| private readonly HashSet<Type> excludedTypes = []; | ||
| private readonly HashSet<MemberInfo> excludedProperties = []; | ||
| private readonly HashSet<object> processedObjects = new(ReferenceEqualityComparer.Instance); | ||
| private readonly Dictionary<Type, IFormatProvider> typeCulture = []; | ||
| private readonly Dictionary<Type, Func<object, string>> typeSerializers = []; | ||
| private readonly Dictionary<MemberInfo, Func<object, string>> propertySerializers = []; | ||
| private int? maxStringLength; | ||
| private const int MaxCollectionItems = 100; | ||
| private const char IndentChar = '\t'; | ||
|
|
||
| public ObjectPrinterSettings<TOwner> Exclude<T>() | ||
| { | ||
| excludedTypes.Add(typeof(T)); | ||
| return this; | ||
| } | ||
|
|
||
| public ObjectPrinterSettings<TOwner> Exclude<T>(Expression<Func<TOwner, T>> propertyExpression) | ||
| { | ||
| var propertyName = GetPropertyInfo(propertyExpression); | ||
| excludedProperties.Add(propertyName); | ||
| return this; | ||
| } | ||
|
|
||
| public ObjectPrinterSettings<TOwner> SetCustomSerialization<T>(Func<T, string> serializer) | ||
| { | ||
| typeSerializers[typeof(T)] = obj => | ||
| { | ||
| try | ||
| { | ||
| return serializer((T)obj); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| return $"[Error serializing type '{typeof(T).Name}']: {ex.Message}"; | ||
| } | ||
| }; | ||
| return this; | ||
| } | ||
|
|
||
| public ObjectPrinterSettings<TOwner> SetCustomSerialization<T>(Expression<Func<TOwner, T>> propertyExpression, Func<T, string> serializer) | ||
| { | ||
| var propertyName = GetPropertyInfo(propertyExpression); | ||
| propertySerializers[propertyName] = obj => | ||
| { | ||
| try | ||
| { | ||
| return serializer((T)obj); | ||
| } | ||
| catch (Exception ex) | ||
| { | ||
| return $"[Error serializing property '{propertyName.Name}']: {ex.Message}"; | ||
| } | ||
| }; | ||
| return this; | ||
| } | ||
|
|
||
| public ObjectPrinterSettings<TOwner> SetCulture<T>(IFormatProvider culture, string? format = null) where T : IFormattable | ||
| { | ||
| typeCulture[typeof(T)] = culture; | ||
| if (!string.IsNullOrEmpty(format)) | ||
| typeSerializers[typeof(T)] = obj => ((IFormattable)obj).ToString(format, culture); | ||
| return this; | ||
| } | ||
|
|
||
| public ObjectPrinterSettings<TOwner> TrimStringsToLength(int maxLength) | ||
| { | ||
| maxStringLength = maxLength; | ||
| return this; | ||
| } | ||
|
|
||
| public string? PrintToString(TOwner obj) => PrintToString(obj, 0); | ||
|
|
||
| private string? PrintToString(object? obj, int nestingLevel) | ||
| { | ||
| if (obj == null) | ||
| return AppendNewLine("null"); | ||
|
|
||
| if (processedObjects.Contains(obj)) | ||
| return AppendNewLine("[Circular Reference]"); | ||
|
|
||
| if (TrySerializeFinalType(obj, out var result)) | ||
| return result; | ||
|
|
||
| return TrySerializeCollection(obj, nestingLevel, out var collectionResult) ? collectionResult : SerializeComplexType(obj, nestingLevel); | ||
| } | ||
|
|
||
| private bool TrySerializeCollection(object obj, int nestingLevel, out string? collectionResult) | ||
| { | ||
| if (obj is IEnumerable enumerable) | ||
| { | ||
| var text = new StringBuilder(); | ||
| var pad = new string(IndentChar, nestingLevel + 1); | ||
| var count = 0; | ||
|
|
||
| text.AppendLine($"({obj.GetType().Name}):"); | ||
| foreach (var item in enumerable) | ||
| { | ||
| if (count++ >= MaxCollectionItems) | ||
| { | ||
| text.Append($"{pad}... (truncated)"); | ||
| break; | ||
| } | ||
|
|
||
| var elementType = item?.GetType().Name ?? "unknown"; | ||
|
|
||
| text.Append($"{pad}({elementType}):{PrintToString(item, nestingLevel + 1)}"); | ||
| } | ||
|
|
||
| collectionResult = text.ToString(); | ||
| return true; | ||
| } | ||
|
|
||
| collectionResult = null; | ||
| return false; | ||
| } | ||
|
|
||
| private bool TrySerializeFinalType(object obj, out string? result) | ||
| { | ||
| var type = obj.GetType(); | ||
| if (finalTypes.Contains(type)) | ||
| { | ||
| result = (obj switch | ||
| { | ||
| IFormattable formattable when typeCulture.ContainsKey(type) => | ||
| formattable.ToString("G", typeCulture[type]), | ||
| string str => Trim(str), | ||
| _ => obj.ToString() | ||
| })!; | ||
|
|
||
| result = AppendNewLine(result); | ||
| return true; | ||
| } | ||
| result = null; | ||
| return false; | ||
| } | ||
|
|
||
| private string Trim(string str) | ||
| { | ||
| if (maxStringLength.HasValue && str.Length > maxStringLength) | ||
| return str[..maxStringLength.Value]; | ||
| return str; | ||
| } | ||
|
|
||
| private string SerializeComplexType(object obj, int nestingLevel) | ||
| { | ||
| processedObjects.Add(obj); | ||
| try | ||
| { | ||
| var pad = new string(IndentChar, nestingLevel + 1); | ||
| var text = new StringBuilder(); | ||
| var type = obj.GetType(); | ||
| text.AppendLine(type.Name); | ||
|
|
||
| foreach (var property in type.GetProperties()) | ||
| { | ||
| if (excludedTypes.Contains(property.PropertyType) || excludedProperties.Contains(property)) | ||
| continue; | ||
|
|
||
| var value = property.GetValue(obj); | ||
| var serializedValue = SerializeProperty(property, value, nestingLevel + 1); | ||
| text.Append($"{pad}{property.Name} = {serializedValue}"); | ||
| } | ||
|
|
||
| return text.ToString(); | ||
| } | ||
| finally | ||
| { | ||
| processedObjects.Remove(obj); | ||
| } | ||
| } | ||
|
|
||
| private string? SerializeProperty(PropertyInfo property, object? value, int nestingLevel) | ||
| { | ||
|
|
||
| if (propertySerializers.TryGetValue(property, out var propertySerializer)) | ||
| return AppendNewLine(propertySerializer(value!)); | ||
|
|
||
| if (typeSerializers.TryGetValue(property.PropertyType, out var typeSerializer)) | ||
| return AppendNewLine(typeSerializer(value!)); | ||
|
|
||
| return PrintToString(value, nestingLevel); | ||
|
|
||
| } | ||
|
|
||
| private static MemberInfo GetPropertyInfo<T>(Expression<Func<TOwner, T>> propertyExpression) | ||
| { | ||
| if (propertyExpression.Body is not MemberExpression member) | ||
| throw new ArgumentException("Expression must be a property access.", nameof(propertyExpression)); | ||
| return member.Member; | ||
| } | ||
|
|
||
| private static string AppendNewLine(string? text) | ||
| { | ||
| if (text != null && text.EndsWith(Environment.NewLine)) | ||
| return text; | ||
|
|
||
| var result = new StringBuilder(text); | ||
| result.Append(Environment.NewLine); | ||
|
|
||
| return result.ToString(); | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
This file was deleted.
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
This comment was marked as resolved.
Sorry, something went wrong.
Uh oh!
There was an error while loading. Please reload this page.