提交 8547807b 编写于 作者: 麦壳饼's avatar 麦壳饼

"D:\GitHub\IoTSharp\IoTSharp\GitVersion.yml"

上级 0ba378b4
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
namespace Uixe.Extensions
{
public static class DataExtension
{
public static string ToISO8601(this System.DateTime time) => time.ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:sssZ");
public static T ToJson<T>(this IDataReader dataReader) where T : class
{
return dataReader.ToJson().ToObject<T>();
}
public static JArray ToJson(this IDataReader dataReader)
{
JArray jArray = new JArray();
try
{
while (dataReader.Read())
{
JObject jObject = new JObject();
for (int i = 0; i < dataReader.FieldCount; i++)
{
try
{
string strKey = dataReader.GetName(i);
if (dataReader[i] != DBNull.Value)
{
object obj = Convert.ChangeType(dataReader[i], dataReader.GetFieldType(i));
jObject.Add(strKey, JToken.FromObject(obj));
}
}
catch (Exception)
{
}
}
jArray.Add(jObject);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return jArray;
}
public static JArray ToJson(this DataTable dt)
{
JArray jArray = new JArray();
try
{
for (int il = 0; il < dt.Rows.Count; il++)
{
JObject jObject = new JObject();
for (int i = 0; i < dt.Columns.Count; i++)
{
try
{
string strKey = dt.Columns[i].ColumnName;
if (dt.Rows[il].ItemArray[i] != DBNull.Value)
{
object obj = Convert.ChangeType(dt.Rows[il].ItemArray[i], dt.Columns[i].DataType);
jObject.Add(strKey, JToken.FromObject(obj));
}
}
catch (Exception)
{
}
}
jArray.Add(jObject);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return jArray;
}
public static List<T> ToList<T>(this DataTable dt) where T : class
{
List<T> jArray = new List<T>();
var prs = typeof(T).GetProperties();
try
{
for (int il = 0; il < dt.Rows.Count; il++)
{
T jObject = Activator.CreateInstance<T>();
for (int i = 0; i < dt.Columns.Count; i++)
{
try
{
string strKey = dt.Columns[i].ColumnName;
if (dt.Rows[il].ItemArray[i] != DBNull.Value)
{
object obj = Convert.ChangeType(dt.Rows[il].ItemArray[i], dt.Columns[i].DataType);
var p = prs.FirstOrDefault(px => px.Name.ToLower() == strKey.ToLower());
if (p != null)
{
SetValue(jObject, dt.Columns[i].DataType, obj, p);
}
}
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
jArray.Add(jObject);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return jArray;
}
public static List<T> ToList<T>(this IDataReader dataReader) where T : class
{
List<T> jArray = new List<T>();
var prs = typeof(T).GetProperties();
try
{
while (dataReader.Read())
{
T jObject = Activator.CreateInstance<T>();
for (int i = 0; i < dataReader.FieldCount; i++)
{
try
{
string strKey = dataReader.GetName(i);
if (dataReader[i] != DBNull.Value)
{
var ft = dataReader.GetFieldType(i);
var _v = dataReader[i];
object obj = Convert.ChangeType(_v, ft);
var p = prs.FirstOrDefault(px => px.Name.ToLower() == strKey.ToLower());
if (p != null)
{
SetValue(jObject, ft, obj, p);
}
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
jArray.Add(jObject);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return jArray;
}
private static void SetValue<T>(T jObject, Type ft, object obj, System.Reflection.PropertyInfo p) where T : class
{
if (p.PropertyType == ft)
{
p.SetValue(jObject, obj);
}
else if (p.PropertyType == typeof(DateTime) && ft == typeof(string))
{
if (DateTime.TryParse((string)obj, out DateTime dt))
{
p.SetValue(jObject, dt);
}
}
else
{
p.SetValue(jObject, Convert.ChangeType(obj, p.PropertyType));
}
}
}
}
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace IoTSharp.Extensions
{
public static class FileExtension
{
public static string GetSHA1(this FileInfo s)
{
string result = string.Empty;
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] retval = sha1.ComputeHash(s.ReadAllBytes());
result = BitConverter.ToString(retval).Replace("-", "");
return result;
}
public static string GetMd5Sum(this FileInfo s)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
string t2 = BitConverter.ToString(md5.ComputeHash(s.ReadAllBytes()));
t2 = t2.Replace("-", "");
return t2;
}
public static byte[] ReadAllBytes(this FileInfo fi) => File.ReadAllBytes(fi.FullName);
public static byte[] ReadBytes(this FileInfo fi, int count) => ReadBytes(fi, 0, count);
public static byte[] ReadBytes(this FileInfo fi, int offset, int count)
{
byte[] buffer = new byte[count];
using (var fs = fi.OpenRead())
{
fs.Read(buffer, offset, count);
}
return buffer;
}
public static void WriteAllText(this FileInfo fi, string contents) => File.WriteAllText(fi.FullName, contents);
public static bool Exists(this FileInfo fi) => File.Exists(fi.FullName);
public static void Delete(this FileInfo fi) => File.Delete(fi.FullName);
public static string ReadAllText(this FileInfo fi) => File.ReadAllText(fi.FullName);
public static void WriteAllBytes(this FileInfo fi, byte[] bytes) => File.WriteAllBytes(fi.FullName, bytes);
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.0</TargetFramework>
<TargetFramework>netstandard2.1</TargetFramework>
<GeneratePackageOnBuild>true</GeneratePackageOnBuild>
<PackageProjectUrl>https://github.com/IoTSharp/IoTSharp/tree/master/IoTSharp.Extensions</PackageProjectUrl>
<RepositoryUrl>https://github.com/IoTSharp/IoTSharp</RepositoryUrl>
......@@ -10,15 +10,12 @@
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.Extensions.Configuration.Json" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.WindowsServices" Version="3.0.0" />
<PackageReference Include="GitVersionTask" Version="5.1.1">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.Extensions.DependencyInjection.Abstractions" Version="3.0.0" />
<PackageReference Include="Newtonsoft.Json" Version="12.0.2" />
<PackageReference Include="System.Text.Encoding.CodePages" Version="4.6.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
<PackageReference Include="Microsoft.Extensions.Hosting.Abstractions" Version="3.0.0" />
<PackageReference Include="Microsoft.AspNetCore.Hosting.WindowsServices" Version="3.0.0" />
</ItemGroup>
</Project>
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
namespace IoTSharp.Extensions
{
public static class JsonExtensions
{
public static T ToJson<T>(this IDataReader dataReader) where T : class
{
return dataReader.ToJson().ToObject<T>();
}
public static List<T> ToList<T>(this IDataReader dataReader) where T : class
{
return dataReader.ToJson().ToObject<List<T>>();
}
public static JArray ToJson(this IDataReader dataReader)
{
JArray jArray = new JArray();
try
{
while (dataReader.Read())
{
JObject jObject = new JObject();
for (int i = 0; i < dataReader.FieldCount; i++)
{
try
{
string strKey = dataReader.GetName(i);
if (dataReader[i] != DBNull.Value)
{
object obj = Convert.ChangeType(dataReader[i], dataReader.GetFieldType(i));
jObject.Add(strKey, JToken.FromObject(obj));
}
}
catch (Exception)
{
}
}
jArray.Add(jObject);
}
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
return jArray;
}
}
}
......@@ -2,150 +2,21 @@
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Hosting.WindowsServices;
using Microsoft.Extensions.Configuration;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
namespace IoTSharp.Extensions
{
public static class MiscExtensions
{
public static IWebHostBuilder UseJsonToSettings(this IWebHostBuilder hostBuilder, string filename)
{
return hostBuilder.ConfigureAppConfiguration(builder =>
{
try
{
if (System.IO.File.Exists(filename))
{
builder.AddJsonFile(filename, true);
}
}
catch (System.Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
});
}
public static IHostBuilder ConfigureWindowsServices(this IHostBuilder hostBuilder)
{
bool IsWindowsService = false;
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
{
using (var process = GetParent(Process.GetCurrentProcess()))
{
IsWindowsService = process != null && process.ProcessName == "services";
}
}
if (Environment.CommandLine.Contains("--usebasedirectory") || (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) && IsWindowsService))
{
hostBuilder.UseContentRoot(AppContext.BaseDirectory);
System.IO.Directory.SetCurrentDirectory(AppContext.BaseDirectory);
hostBuilder.UseWindowsService();
}
return hostBuilder;
}
private static Process GetParent(Process child)
{
var parentId = 0;
var handle = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
if (handle == IntPtr.Zero)
{
return null;
}
var processInfo = new PROCESSENTRY32
{
dwSize = (uint)Marshal.SizeOf(typeof(PROCESSENTRY32))
};
if (!Process32First(handle, ref processInfo))
{
return null;
}
do
{
if (child.Id == processInfo.th32ProcessID)
{
parentId = (int)processInfo.th32ParentProcessID;
}
} while (parentId == 0 && Process32Next(handle, ref processInfo));
if (parentId > 0)
{
return Process.GetProcessById(parentId);
}
return null;
}
private static uint TH32CS_SNAPPROCESS = 2;
[DllImport("kernel32.dll")]
public static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[DllImport("kernel32.dll", SetLastError = true)]
public static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessID);
[DllImport("kernel32.dll")]
public static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe);
[StructLayout(LayoutKind.Sequential)]
public struct PROCESSENTRY32
{
public uint dwSize;
public uint cntUsage;
public uint th32ProcessID;
public IntPtr th32DefaultHeapID;
public uint th32ModuleID;
public uint cntThreads;
public uint th32ParentProcessID;
public int pcPriClassBase;
public uint dwFlags;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szExeFile;
}
public static string MD5Sum(this string text) => BitConverter.ToString(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(text))).Replace("-", "");
public static Task Forget(this Task task)
{
return Task.CompletedTask;
}
public static Task StartSTATask(this TaskFactory task, Action action)
{
var tcs = new TaskCompletionSource<object>();
var thread = new Thread(() =>
{
try
{
action();
tcs.SetResult(new object());
}
catch (Exception e)
{
tcs.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
public static T GetRequiredService<T>(this IServiceScopeFactory scopeFactor) =>
scopeFactor.CreateScope().ServiceProvider.GetRequiredService<T>();
......
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace IoTSharp.Extensions
{
public static class StringExtension
{
public static string ToTitleCase(this string str)
{
return System.Threading.Thread.CurrentThread.CurrentCulture.TextInfo.ToTitleCase(str.ToLower());
}
public static string Left(this string str, int length)
{
str = (str ?? string.Empty);
return str.Substring(0, Math.Min(length, str.Length));
}
public static string Right(this string str, int length)
{
str = (str ?? string.Empty);
return (str.Length >= length)
? str.Substring(str.Length - length, length)
: str;
}
public static char[] Right(this char[] str, int length)
{
return str.Skip(str.Length - length).Take(length).ToArray();
}
public static char[] Left(this char[] str, int length)
{
return str.Take(length).ToArray();
}
public static byte[] Right(this byte[] str, int length)
{
return str.Skip(str.Length - length).Take(length).ToArray();
}
public static byte[] Left(this byte[] str, int length)
{
return str.Take(length).ToArray();
}
}
}
using System;
using System.Threading;
using System.Threading.Tasks;
namespace IoTSharp.Extensions
{
public static class TaskExtension
{
public static Task StartSTATask(this TaskFactory task, Action action)
{
var tcs = new TaskCompletionSource<object>();
var thread = new Thread(() =>
{
try
{
action();
tcs.SetResult(new object());
}
catch (Exception e)
{
tcs.SetException(e);
}
});
thread.SetApartmentState(ApartmentState.STA);
thread.Start();
return tcs.Task;
}
public static Task Forget(this Task task)
{
return Task.CompletedTask;
}
}
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册