Newbe.ObjectVisitor 样例1

将数据库链接字符串转型为数据模型,或者将数据模型格式化为链接字符串。

using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using FluentAssertions;
using NUnit.Framework;

namespace Newbe.ObjectVisitor.Tests
{
    public class DataConnectionModelTest
    {
        public const string ConnectionStringValue =
            "Host=www.newbe.pro;Port=36524;Username=newbe36524;Password=newbe.pro;";

        [Test]
        public void JoinToString()
        {
            var model = new DataConnectionModel
            {
                Host = "www.newbe.pro",
                Port = 36524,
                Username = "newbe36524",
                Password = "newbe.pro",
            };
            var connectionString = model.ToString();

            connectionString.Should().Be(ConnectionStringValue);
        }

        [Test]
        public void BuildFromString()
        {
            var model = DataConnectionModel.FromString(ConnectionStringValue);
            var expected = new DataConnectionModel
            {
                Host = "www.newbe.pro",
                Port = 36524,
                Username = "newbe36524",
                Password = "newbe.pro",
            };
            model.Should().BeEquivalentTo(expected);
        }


        public class DataConnectionModel
        {
            public string Host { getset; } = null!;
            public ushort? Port { getset; } = null!;
            public string Username { getset; } = null!;
            public string Password { getset; } = null!;
            public int? MaxPoolSize { getset; } = null!;

            private static readonly ICachedObjectVisitor<DataConnectionModel, StringBuilder> ConnectionStringBuilder =
                default(DataConnectionModel)!
                    .V()
                    .WithExtendObject<DataConnectionModel, StringBuilder>()
                    .ForEach((name, value, sb) => AppendValueIfNotNull(name, value, sb))
                    .Cache();

            private static void AppendValueIfNotNull(string name, objectvalue, StringBuilder sb)
            {
                if (value != null)
                {
                    sb.Append($"{name}={value};");
                }
            }

            public override string ToString()
            {
                var sb = new StringBuilder();
                ConnectionStringBuilder.Run(this, sb);
                return sb.ToString();
            }

            private static readonly ICachedObjectVisitor<DataConnectionModel, Dictionary<stringstring>>
                ConnectionStringConstructor
                    =
                    default(DataConnectionModel)!
                        .V()
                        .WithExtendObject<DataConnectionModel, Dictionary<stringstring>>()
                        .ForEach(context => SetValueIfFound(context))
                        .Cache();

            private static void SetValueIfFound(
                IObjectVisitorContext<DataConnectionModel, Dictionary<stringstring>, object> c
)

            {
                if (c.ExtendObject.TryGetValue(c.Name, out var stringValue))
                {
                    TypeConverter conv = TypeDescriptor.GetConverter(c.PropertyInfo.PropertyType);
                    c.Value = conv.ConvertFrom(stringValue)!;
                }
            }

            public static DataConnectionModel FromString(string connectionString)
            {
                var dic = connectionString.Split(';')
                    .Where(x => !string.IsNullOrEmpty(x))
                    .Select(x => x.Split('='))
                    .ToDictionary(x => x[0], x => x[1]);
                var re = new DataConnectionModel();
                ConnectionStringConstructor.Run(re, dic);
                return re;
            }
        }
    }
}

将对象中满足手机号码格式的字段替换为密文,避免敏感信息输出。

using System.Text.RegularExpressions;
using FluentAssertions;
using NUnit.Framework;

namespace Newbe.ObjectVisitor.Tests
{
    public class ChangePasswordTest
    {
        [Test]
        public void CoverSensitiveDataTest()
        {
            // here is a model
            var userModel = new UserModel
            {
                Username = "newbe36524",
                Password = "newbe.pro",
                Phone = "12345678901"
            };

            // create a data visitor to cover sensitive data
            var visitor = userModel.V()
                .ForEach<UserModel, string>(x => CoverSensitiveData(x))
                .Cache();

            visitor.Run(userModel);

            var expected = new UserModel
            {
                Username = "newbe36524",
                Password = "***",
                Phone = "123****8901",
            };
            userModel.Should().BeEquivalentTo(expected);
        }

        private void CoverSensitiveData(IObjectVisitorContext<UserModel, string> c)
        {
            var value = c.Value;
            if (!string.IsNullOrEmpty(value))
            {
                c.Value = Regex.Replace(value"(\d{3})\d{4}(\d{4})""$1****$2");
            }

            if (c.Name == nameof(UserModel.Password))
            {
                c.Value = "***";
            }
        }

        public class UserModel
        {
            public string Username { getset; } = null!;
            public string Phone { getset; } = null!;
            public string Password { getset; } = null!;
        }
    }
}

将实现了 IEnumerable<int> 的所有属性求和。

using System.Collections.Generic;
using System.Linq;
using FluentAssertions;
using NUnit.Framework;

namespace Newbe.ObjectVisitor.Tests
{
    public class EnumerableTest
    {
        [Test]
        public void NameAndValue()
        {
            var model = new TestModel
            {
                List1 = new[] {1},
                List2 = new[] {2},
                List3 = new List<int> {3},
                List4 = new HashSet<int> {4}
            };
            var sumBag = new SumBag();
            var visitor = model.V()
                .WithExtendObject(sumBag)
                .ForEach<TestModel, SumBag, IEnumerable<int>>((name, value, bag) => Sum(bag, value),
                    x => x.IsOrImplOf<IEnumerable<int>>())
                .Cache();
            visitor.Run(model, sumBag);
            sumBag.Sum.Should().Be(10);
        }

        private static void Sum(SumBag bag, IEnumerable<int> data)
        {
            bag.Sum += data.Sum();
        }

        public class SumBag
        {
            public int Sum { getset; }
        }

        public class TestModel
        {
            public int[] List1 { getset; } = null!;
            public IEnumerable<int> List2 { getset; } = null!;
            public List<int> List3 { getset; } = null!;
            public HashSet<int> List4 { getset; } = null!;
        }
    }
}


原文始发于微信公众号(newbe技术专栏):Newbe.ObjectVisitor 样例1

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/68261.html

(0)
newbe的头像newbebm

相关推荐

发表回复

登录后才能评论
极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!