当前位置:网站首页>Newbe.ObjectVisitor Example 1
Newbe.ObjectVisitor Example 1
2020-11-08 20:18:00 【Newbe36524】
We have added some scenarios and practice instructions that can be used to implement the functions of the library .
Transform the database link string into a data model , Or format the data model as a link string .
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 { get; set; } = null!;
public ushort? Port { get; set; } = null!;
public string Username { get; set; } = null!;
public string Password { get; set; } = null!;
public int? MaxPoolSize { get; set; } = 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, object? value, 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<string, string>>
ConnectionStringConstructor
=
default(DataConnectionModel)!
.V()
.WithExtendObject<DataConnectionModel, Dictionary<string, string>>()
.ForEach(context => SetValueIfFound(context))
.Cache();
private static void SetValueIfFound(
IObjectVisitorContext<DataConnectionModel, Dictionary<string, string>, 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;
}
}
}
} |
Replace the fields that meet the mobile phone number format in the object with ciphertext , Avoid sensitive information output .
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 { get; set; } = null!;
public string Phone { get; set; } = null!;
public string Password { get; set; } = null!;
}
}
} |
Will be realized IEnumerable<int>
The sum of all properties of .
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 { get; set; }
}
public class TestModel
{
public int[] List1 { get; set; } = null!;
public IEnumerable<int> List2 { get; set; } = null!;
public List<int> List3 { get; set; } = null!;
public HashSet<int> List4 { get; set; } = null!;
}
}
} |
Release notes
- Newbe.ObjectVisitor 0.2.10 Release , More colorful
- Newbe.ObjectVisitor 0.1.4 Release , The initial release
Use samples
Share with others
- Looking for better performance dynamics Getter and Setter programme
- Looking for a smaller immutable dictionary with better performance
GitHub Project address :https://github.com/newbe36524/Newbe.ObjectVisitor
Gitee Project address :https://gitee.com/yks/Newbe.ObjectVisitor
- The author of this article : newbe36524
- Link to this article : https://www.newbe.pro/Newbe.ObjectVisitor/Example-1/
- Copyright notice : All articles in this blog except special statement , All adopt BY-NC-SA license agreement . Reprint please indicate the source !
版权声明
本文为[Newbe36524]所创,转载请带上原文链接,感谢
边栏推荐
- 动态规划设计:最大子数组
- 经典动态规划:最长公共子序列
- One minute comprehensive understanding of forsage smart contract global shared Ethereum matrix plan
- 选择排序
- CountDownLatch 瞬间炸裂!同基于 AQS,凭什么 CyclicBarrier 可以这么秀?
- Opencv solves the problem of ippicv download failure_ 2019_ lnx_ intel64_ general_ 20180723.tgz offline Download
- [cloud service] there are so many ECS instances on alicloud server, how to select the type? Best practice note
- 线程池运用不当的一次线上事故
- 不是程序员,代码也不能太丑!python官方书写规范:任何人都该了解的 pep8
- MongoDB增删改查操作
猜你喜欢
Awk implements SQL like join operation
构造回文的最小插入次数
给大家介绍下,这是我的流程图软件 —— draw.io
寻找性能更优秀的不可变小字典
. net core cross platform resource monitoring library and dotnet tool
解决go get下载包失败问题
IT industry salary has been far ahead! Ten years later, is the programmer still a high paying profession?
动态规划设计:最大子数组
An online accident caused by improper use of thread pool
CountDownLatch 瞬间炸裂!同基于 AQS,凭什么 CyclicBarrier 可以这么秀?
随机推荐
Express framework
Looking for a small immutable dictionary with better performance
Opencv solves the problem of ippicv download failure_ 2019_ lnx_ intel64_ general_ 20180723.tgz offline Download
微信小程序相关
(O) Analysis of service manager (1) BinderInternal.getContextObject
接口测试用例思路总结
MongoDB增删改查操作
RSA非对称加密算法
Solution to cross domain problem of front end separation
How to deploy pytorch lightning model to production
Creating a text cloud or label cloud in Python
Introduction and application of swagger
单例模式的五种设计方案
200人的程序员面试经验,都在这里了
Infix expression to suffix expression
Proficient in high concurrency and multithreading, but can't use ThreadLocal?
Summary: in October, more investment management strategies have come to the new overseas defi project!
Using fastai to develop and deploy image classifier application
Using GaN based oversampling technique to improve the accuracy of model for mortality prediction of unbalanced covid-19
经典动态规划:最长公共子序列