1
0

Removed DNS dependency, added ReflectionExtensions.

This commit is contained in:
2022-09-18 22:54:32 +02:00
parent ba8dd516e6
commit 36ddaf02ad
9 changed files with 135 additions and 48 deletions

View File

@@ -6,7 +6,7 @@
<AssemblyName>AMWD.Common</AssemblyName>
<RootNamespace>AMWD.Common</RootNamespace>
<NrtRevisionFormat>{semvertag:main}{!:~dirty}</NrtRevisionFormat>
<NrtRevisionFormat>{semvertag:main}{!:-dirty}</NrtRevisionFormat>
<AppendTargetFrameworkToOutputPath>true</AppendTargetFrameworkToOutputPath>
<CopyRefAssembliesToPublishDirectory>false</CopyRefAssembliesToPublishDirectory>
@@ -33,19 +33,22 @@
<PackageLicenseExpression>MIT</PackageLicenseExpression>
</PropertyGroup>
<PropertyGroup Condition="'$(CI)' == 'true'">
<PropertyGroup Condition="'$(GITLAB_CI)' == 'true'">
<ContinuousIntegrationBuild>true</ContinuousIntegrationBuild>
</PropertyGroup>
<ItemGroup Condition="'$(GITLAB_CI)' == 'true'">
<SourceLinkGitLabHost Include="git.am-wd.de" Version="$(CI_SERVER_VERSION)" />
<PackageReference Include="Microsoft.SourceLink.GitLab" Version="1.1.1" PrivateAssets="all" />
</ItemGroup>
<ItemGroup>
<None Include="../icon.png" Pack="true" PackagePath="/" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Dns" Version="7.0.0" />
<PackageReference Include="MessagePack" Version="2.4.35" />
<PackageReference Include="Microsoft.AspNetCore.HttpOverrides" Version="2.2.0" />
<PackageReference Include="Microsoft.SourceLink.GitLab" Version="1.1.1" PrivateAssets="all" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="Unclassified.DeepConvert" Version="1.4.0" />
<PackageReference Include="Unclassified.NetRevisionTask" Version="0.4.3">

View File

@@ -0,0 +1,42 @@
using System.Reflection;
using System.Threading.Tasks;
namespace AMWD.Common.Extensions
{
/// <summary>
/// Extension methods for <see cref="System.Reflection"/>.
/// </summary>
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public static class ReflectionExtensions
{
/// <summary>
/// Calls a method from it's reflection asynchronously without result.
/// </summary>
/// <param name="methodInfo">The <see cref="MethodInfo"/> to call on an object.</param>
/// <param name="obj">The reflected instance to call the method on.</param>
/// <param name="parameters">The parameters of the called method.</param>
/// <returns>An awaitable <see cref="Task"/>.</returns>
public static async Task CallAsync(this MethodInfo methodInfo, object obj, params object[] parameters)
{
var task = (Task)methodInfo.Invoke(obj, parameters);
await task.ConfigureAwait(false);
}
/// <summary>
/// Invokes a method from it's reflection asynchronously with a result.
/// </summary>
/// <typeparam name="TResult">The result type, that is expected (and casted to).</typeparam>
/// <param name="methodInfo">The <see cref="MethodInfo"/> to invoke on an object.</param>
/// <param name="obj">The reflected instance to invoke the method on.</param>
/// <param name="parameters">The parameters of the called method.</param>
/// <returns>An awaitable <see cref="Task"/> with result.</returns>
public static async Task<TResult> InvokeAsync<TResult>(this MethodInfo methodInfo, object obj, params object[] parameters)
{
var task = (Task)methodInfo.Invoke(obj, parameters);
await task.ConfigureAwait(false);
var resultPropertyInfo = task.GetType().GetProperty("Result");
return (TResult)resultPropertyInfo.GetValue(task);
}
}
}

View File

@@ -1,13 +1,14 @@
using System.Collections.Generic;
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using DNS.Client;
using DNS.Protocol;
using AMWD.Common.Extensions;
namespace System
{
@@ -150,47 +151,67 @@ namespace System
/// You can enhance the check by requesting the MX record of the domain.
/// </remarks>
/// <param name="email">The email address as string to validate.</param>
/// <param name="checkRecordExists">A value indicating whether to resolve a MX record (Google DNS is used).</param>
/// <param name="checkForDnsRecord">A value indicating whether to resolve a MX record (Google DNS is used).</param>
/// <returns><c>true</c> when the email address is valid, other wise <c>false</c>.</returns>
public static bool IsValidEmailAddress(this string email, bool checkRecordExists = false)
=> email.IsValidEmailAddress(checkRecordExists ? new[] { new IPEndPoint(IPAddress.Parse("8.8.8.8"), 53) } : null);
public static bool IsValidEmailAddress(this string email, bool checkForDnsRecord = false)
=> email.IsValidEmailAddress(checkForDnsRecord ? new[] { new IPEndPoint(IPAddress.Parse("8.8.8.8"), 53) } : null);
/// <summary>
/// Checks whether the given <see cref="string"/> is a valid <see cref="MailAddress"/>.
/// </summary>
/// <remarks>
/// The check is enhanced by a request for MX records on the defined <paramref name="nameservers"/>.
/// <br/>
/// The DNS resolution is only used when the DNS NuGet package is available.
/// See: https://www.nuget.org/packages/DNS/7.0.0
/// </remarks>
/// <param name="email">The email address as string to validate.</param>
/// <param name="emailAddress">The email address as string to validate.</param>
/// <param name="nameservers">A list of <see cref="IPEndPoint"/>s of nameservers.</param>
/// <returns><c>true</c> when the email address is valid, other wise <c>false</c>.</returns>
public static bool IsValidEmailAddress(this string email, IEnumerable<IPEndPoint> nameservers)
public static bool IsValidEmailAddress(this string emailAddress, IEnumerable<IPEndPoint> nameservers)
{
try
{
var mailAddress = new MailAddress(email);
bool isValid = mailAddress.Address == email;
var mailAddress = new MailAddress(emailAddress);
bool isValid = mailAddress.Address == emailAddress;
if (isValid && nameservers?.Any() == true)
{
var dnsClientType = Type.GetType("DNS.Client.DnsClient, DNS");
if (dnsClientType == null)
throw new DllNotFoundException("The DNS NuGet package is required: https://www.nuget.org/packages/DNS/7.0.0");
var recordTypeType = Type.GetType("DNS.Protocol.RecordType, DNS");
var resolveMethodInfo = dnsClientType.GetMethod("Resolve", new[] { typeof(string), recordTypeType, typeof(CancellationToken) });
bool exists = false;
foreach (var nameserver in nameservers)
{
var client = new DnsClient(nameserver);
var waitTask = Task.Run(async () => await client.Resolve(mailAddress.Host, RecordType.MX));
object dnsClient = Activator.CreateInstance(dnsClientType, new object[] { nameserver });
var waitTask = Task.Run(async () => await resolveMethodInfo.InvokeAsync<object>(dnsClient, new object[] { mailAddress.Host, 15, CancellationToken.None })); // 15 = MX Record
waitTask.Wait();
var response = waitTask.Result;
object response = waitTask.Result;
waitTask.Dispose();
if (response.ResponseCode != ResponseCode.NoError)
int responseCode = (int)response.GetType().GetProperty("ResponseCode").GetValue(response);
if (responseCode != 0)
continue;
exists = response.AnswerRecords
.Where(r => r.Type == RecordType.MX)
.Any();
object list = response.GetType().GetProperty("AnswerRecords").GetValue(response);
foreach (object item in (list as IEnumerable))
{
int type = (int)item.GetType().GetProperty("Type").GetValue(item);
if (type == 15)
{
exists = true;
break;
}
}
break;
if (exists)
break;
}
isValid &= exists;