Advertisement
Guest User

Untitled

a guest
May 3rd, 2020
342
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 8.15 KB | None | 0 0
  1. /*
  2.  * NuGet:
  3.  *
  4.  * Microsoft.EntityFrameworkCore (3.1.3)
  5.  * Microsoft.EntityFrameworkCore.InMemory (3.1.3)
  6.  * Microsoft.EntityFrameworkCore.Tools (3.1.3)
  7.  */
  8.  
  9. using Microsoft.EntityFrameworkCore;
  10. using Microsoft.Extensions.DependencyInjection;
  11. using System;
  12. using System.Collections.Generic;
  13. using System.Dynamic;
  14. using System.Linq;
  15.  
  16. namespace ConsoleApp48
  17. {
  18.     class Program
  19.     {
  20.         static void Main(string[] args)
  21.         {
  22.             var test = new Test();
  23.             test.TEst1();
  24.  
  25.             Console.ReadKey();
  26.         }
  27.     }
  28.  
  29.     public class Test
  30.     {
  31.         static IEnumerable<string> GetBenchData()
  32.         {
  33.             var rn = Environment.NewLine;
  34.             yield return $"ФИО:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
  35.             yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
  36.             yield return $"ФИО:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Возраст:22";
  37.             yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Полных лет:22";
  38.             yield return $"ФИО:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
  39.             yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Тел.:+78886543422{rn}Возраст:22";
  40.             yield return $"ФИО:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Возраст:22";
  41.             yield return $"Фамилия Имя Отчество:Иванов Иван Иванович{rn}Телефон:+78886543422{rn}Полных лет:22";
  42.         }
  43.  
  44.         public void TEst1()
  45.         {
  46.             foreach (var data in GetBenchData())
  47.             {
  48.                 dynamic obj = new MultiObject(data);
  49.  
  50.                 Console.WriteLine($"FullName: {obj.FullName}, Phone: {obj.Phone}, Age:{obj.Age}");
  51.             }
  52.         }
  53.     }
  54.  
  55.     public class MultiObject : DynamicObject
  56.     {
  57.         private readonly HabraDbContext _context;
  58.         private readonly IRawStringParser _parser;
  59.  
  60.         private readonly Dictionary<string, string> keyValues;
  61.  
  62.         public MultiObject(string rawText)
  63.         {
  64.             _context = IoC.GetService<HabraDbContext>();
  65.             _parser = IoC.GetService<IRawStringParser>();
  66.  
  67.             keyValues = _parser.ParseWithLinq(rawText);
  68.         }
  69.  
  70.         //используется
  71.         public override bool TryGetMember(GetMemberBinder binder, out object result)
  72.         {
  73.             var properties = _context.ContactMapSchemas.Where(x => x.Property == binder.Name).ToDictionary(x => x.Key, x => x.Property);
  74.  
  75.             result = keyValues.FirstOrDefault(x => properties.ContainsKey(x.Key)).Value;
  76.             return true;
  77.         }
  78.  
  79.         //не используется
  80.         public override bool TryConvert(ConvertBinder binder, out object result)
  81.         {
  82.             var properties = _context.ContactMapSchemas.Where(x => x.EntityName == binder.Type.FullName).ToDictionary(x => x.Key, x => x.Property);
  83.  
  84.             result = Activator.CreateInstance(binder.Type);
  85.  
  86.             foreach (var item in keyValues)
  87.             {
  88.                 if (properties.ContainsKey(item.Key))
  89.                 {
  90.                     var prop = result.GetType().GetProperty(properties[item.Key]);
  91.                     prop.SetValue(result, Convert.ChangeType(item.Value, prop.PropertyType));
  92.                 }
  93.             }
  94.  
  95.             return true;
  96.         }
  97.     }
  98.  
  99.  
  100.     #region DB
  101.     public class ContactMapSchema
  102.     {
  103.         public Guid Id { get; set; }
  104.         public string EntityName { get; set; }
  105.         public string Key { get; set; }
  106.         public string Property { get; set; }
  107.     }
  108.  
  109.     public class Contact
  110.     {
  111.         public string FullName { get; set; }
  112.         public string Phone { get; set; }
  113.         public int Age { get; set; }
  114.  
  115.     }
  116.  
  117.     public class HabraDbContext : DbContext
  118.     {
  119.         private static readonly string _contactAssemblyName = typeof(Contact).FullName;
  120.         private static readonly string _contactPhoneAssemblyName = nameof(Contact.Phone);
  121.         private static readonly string _contactFullNameAssemblyName = nameof(Contact.FullName);
  122.         private static readonly string _contactAgeAssemblyName = nameof(Contact.Age);
  123.  
  124.         public DbSet<ContactMapSchema> ContactMapSchemas { get; set; }
  125.  
  126.         public HabraDbContext(DbContextOptions<HabraDbContext> options) : base(options) { Database.EnsureCreated(); }
  127.         protected override void OnModelCreating(ModelBuilder builder)
  128.         {
  129.             base.OnModelCreating(builder);
  130.  
  131.             builder.Entity<ContactMapSchema>().HasKey(x => x.Id);
  132.             builder.Entity<ContactMapSchema>().HasData(
  133.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Телефон", Property = _contactPhoneAssemblyName },
  134.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Контактный телефон", Property = _contactPhoneAssemblyName },
  135.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Тел.", Property = _contactPhoneAssemblyName },
  136.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "ФИО", Property = _contactFullNameAssemblyName },
  137.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Фамилия Имя Отчество", Property = _contactFullNameAssemblyName },
  138.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Имя", Property = _contactFullNameAssemblyName },
  139.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Возраст", Property = _contactAgeAssemblyName },
  140.                 new ContactMapSchema { Id = Guid.NewGuid(), EntityName = _contactAssemblyName, Key = "Полных лет", Property = _contactAgeAssemblyName });
  141.         }
  142.     }
  143.     #endregion
  144.  
  145.     #region Service
  146.     public interface IRawStringParser
  147.     {
  148.         Dictionary<string, string> ParseWithLinq(string rawData, string keyValueDelimiter = ":");
  149.         Dictionary<string, string> ParseWithoutLinq(string rawData, string keyValueDelimiter = ":");
  150.     }
  151.  
  152.     public class DefaultRawStringParser : IRawStringParser
  153.     {
  154.         public Dictionary<string, string> ParseWithLinq(string rawData, string keyValueDelimiter = ":") =>
  155.             rawData?.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
  156.                 .Select(x => x.Split(keyValueDelimiter))
  157.                 .Select(x => x.Length == 2 ? new { Key = x[0], Value = x[1] } : new { Key = "", Value = "" })
  158.                 .Where(x => !string.IsNullOrEmpty(x.Key)).ToDictionary(x => x.Key, x => x.Value) ?? new Dictionary<string, string>();
  159.  
  160.         public Dictionary<string, string> ParseWithoutLinq(string rawData, string keyValueDelimiter = ":")
  161.         {
  162.             var result = new Dictionary<string, string>();
  163.  
  164.             foreach (var row in rawData?.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries))
  165.             {
  166.                 var split = row.Split(keyValueDelimiter);
  167.                 if (split.Length == 2) result.Add(split[0], split[1]);
  168.             }
  169.  
  170.             return result;
  171.         }
  172.     }
  173.  
  174.     public static class IoC
  175.     {
  176.         public static ServiceProvider Provider { get; set; }
  177.  
  178.         static IoC()
  179.         {
  180.             var services = new ServiceCollection();
  181.             services.AddDbContext<HabraDbContext>(x => x.UseInMemoryDatabase(databaseName: "memoryDB"));
  182.             services.AddSingleton<IRawStringParser, DefaultRawStringParser>();
  183.             Provider = services.BuildServiceProvider();
  184.         }
  185.  
  186.         internal static T GetService<T>()
  187.         {
  188.             return Provider.GetService<T>();
  189.         }
  190.     }
  191.     #endregion
  192. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement